aarch64 - Set the mode for the unspec in speculation_tracker insn.
[platform/upstream/linaro-gcc.git] / gcc / builtins.c
1 /* Expand builtin functions.
2    Copyright (C) 1988-2016 Free Software Foundation, Inc.
3
4 This file is part of GCC.
5
6 GCC is free software; you can redistribute it and/or modify it under
7 the terms of the GNU General Public License as published by the Free
8 Software Foundation; either version 3, or (at your option) any later
9 version.
10
11 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
12 WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with GCC; see the file COPYING3.  If not see
18 <http://www.gnu.org/licenses/>.  */
19
20 /* Legacy warning!  Please add no further builtin simplifications here
21    (apart from pure constant folding) - builtin simplifications should go
22    to match.pd or gimple-fold.c instead.  */
23
24 #include "config.h"
25 #include "system.h"
26 #include "coretypes.h"
27 #include "backend.h"
28 #include "target.h"
29 #include "rtl.h"
30 #include "tree.h"
31 #include "memmodel.h"
32 #include "gimple.h"
33 #include "predict.h"
34 #include "tm_p.h"
35 #include "stringpool.h"
36 #include "tree-ssanames.h"
37 #include "expmed.h"
38 #include "optabs.h"
39 #include "emit-rtl.h"
40 #include "recog.h"
41 #include "diagnostic-core.h"
42 #include "alias.h"
43 #include "fold-const.h"
44 #include "fold-const-call.h"
45 #include "stor-layout.h"
46 #include "calls.h"
47 #include "varasm.h"
48 #include "tree-object-size.h"
49 #include "realmpfr.h"
50 #include "cfgrtl.h"
51 #include "except.h"
52 #include "dojump.h"
53 #include "explow.h"
54 #include "stmt.h"
55 #include "expr.h"
56 #include "libfuncs.h"
57 #include "output.h"
58 #include "typeclass.h"
59 #include "langhooks.h"
60 #include "value-prof.h"
61 #include "builtins.h"
62 #include "asan.h"
63 #include "cilk.h"
64 #include "tree-chkp.h"
65 #include "rtl-chkp.h"
66 #include "internal-fn.h"
67 #include "case-cfn-macros.h"
68
69
70 struct target_builtins default_target_builtins;
71 #if SWITCHABLE_TARGET
72 struct target_builtins *this_target_builtins = &default_target_builtins;
73 #endif
74
75 /* Define the names of the builtin function types and codes.  */
76 const char *const built_in_class_names[BUILT_IN_LAST]
77   = {"NOT_BUILT_IN", "BUILT_IN_FRONTEND", "BUILT_IN_MD", "BUILT_IN_NORMAL"};
78
79 #define DEF_BUILTIN(X, N, C, T, LT, B, F, NA, AT, IM, COND) #X,
80 const char * built_in_names[(int) END_BUILTINS] =
81 {
82 #include "builtins.def"
83 };
84
85 /* Setup an array of builtin_info_type, make sure each element decl is
86    initialized to NULL_TREE.  */
87 builtin_info_type builtin_info[(int)END_BUILTINS];
88
89 /* Non-zero if __builtin_constant_p should be folded right away.  */
90 bool force_folding_builtin_constant_p;
91
92 static rtx c_readstr (const char *, machine_mode);
93 static int target_char_cast (tree, char *);
94 static rtx get_memory_rtx (tree, tree);
95 static int apply_args_size (void);
96 static int apply_result_size (void);
97 static rtx result_vector (int, rtx);
98 static void expand_builtin_prefetch (tree);
99 static rtx expand_builtin_apply_args (void);
100 static rtx expand_builtin_apply_args_1 (void);
101 static rtx expand_builtin_apply (rtx, rtx, rtx);
102 static void expand_builtin_return (rtx);
103 static enum type_class type_to_class (tree);
104 static rtx expand_builtin_classify_type (tree);
105 static rtx expand_builtin_mathfn_3 (tree, rtx, rtx);
106 static rtx expand_builtin_mathfn_ternary (tree, rtx, rtx);
107 static rtx expand_builtin_interclass_mathfn (tree, rtx);
108 static rtx expand_builtin_sincos (tree);
109 static rtx expand_builtin_cexpi (tree, rtx);
110 static rtx expand_builtin_int_roundingfn (tree, rtx);
111 static rtx expand_builtin_int_roundingfn_2 (tree, rtx);
112 static rtx expand_builtin_next_arg (void);
113 static rtx expand_builtin_va_start (tree);
114 static rtx expand_builtin_va_end (tree);
115 static rtx expand_builtin_va_copy (tree);
116 static rtx expand_builtin_strcmp (tree, rtx);
117 static rtx expand_builtin_strncmp (tree, rtx, machine_mode);
118 static rtx builtin_memcpy_read_str (void *, HOST_WIDE_INT, machine_mode);
119 static rtx expand_builtin_memcpy (tree, rtx);
120 static rtx expand_builtin_memcpy_with_bounds (tree, rtx);
121 static rtx expand_builtin_memcpy_args (tree, tree, tree, rtx, tree);
122 static rtx expand_builtin_mempcpy (tree, rtx, machine_mode);
123 static rtx expand_builtin_mempcpy_with_bounds (tree, rtx, machine_mode);
124 static rtx expand_builtin_mempcpy_args (tree, tree, tree, rtx,
125                                         machine_mode, int, tree);
126 static rtx expand_builtin_strcpy (tree, rtx);
127 static rtx expand_builtin_strcpy_args (tree, tree, rtx);
128 static rtx expand_builtin_stpcpy (tree, rtx, machine_mode);
129 static rtx expand_builtin_strncpy (tree, rtx);
130 static rtx builtin_memset_gen_str (void *, HOST_WIDE_INT, machine_mode);
131 static rtx expand_builtin_memset (tree, rtx, machine_mode);
132 static rtx expand_builtin_memset_with_bounds (tree, rtx, machine_mode);
133 static rtx expand_builtin_memset_args (tree, tree, tree, rtx, machine_mode, tree);
134 static rtx expand_builtin_bzero (tree);
135 static rtx expand_builtin_strlen (tree, rtx, machine_mode);
136 static rtx expand_builtin_alloca (tree, bool);
137 static rtx expand_builtin_unop (machine_mode, tree, rtx, rtx, optab);
138 static rtx expand_builtin_frame_address (tree, tree);
139 static tree stabilize_va_list_loc (location_t, tree, int);
140 static rtx expand_builtin_expect (tree, rtx);
141 static tree fold_builtin_constant_p (tree);
142 static tree fold_builtin_classify_type (tree);
143 static tree fold_builtin_strlen (location_t, tree, tree);
144 static tree fold_builtin_inf (location_t, tree, int);
145 static tree rewrite_call_expr (location_t, tree, int, tree, int, ...);
146 static bool validate_arg (const_tree, enum tree_code code);
147 static rtx expand_builtin_fabs (tree, rtx, rtx);
148 static rtx expand_builtin_signbit (tree, rtx);
149 static tree fold_builtin_strchr (location_t, tree, tree, tree);
150 static tree fold_builtin_memchr (location_t, tree, tree, tree, tree);
151 static tree fold_builtin_memcmp (location_t, tree, tree, tree);
152 static tree fold_builtin_strcmp (location_t, tree, tree);
153 static tree fold_builtin_strncmp (location_t, tree, tree, tree);
154 static tree fold_builtin_isascii (location_t, tree);
155 static tree fold_builtin_toascii (location_t, tree);
156 static tree fold_builtin_isdigit (location_t, tree);
157 static tree fold_builtin_fabs (location_t, tree, tree);
158 static tree fold_builtin_abs (location_t, tree, tree);
159 static tree fold_builtin_unordered_cmp (location_t, tree, tree, tree, enum tree_code,
160                                         enum tree_code);
161 static tree fold_builtin_0 (location_t, tree);
162 static tree fold_builtin_1 (location_t, tree, tree);
163 static tree fold_builtin_2 (location_t, tree, tree, tree);
164 static tree fold_builtin_3 (location_t, tree, tree, tree, tree);
165 static tree fold_builtin_varargs (location_t, tree, tree*, int);
166
167 static tree fold_builtin_strpbrk (location_t, tree, tree, tree);
168 static tree fold_builtin_strstr (location_t, tree, tree, tree);
169 static tree fold_builtin_strrchr (location_t, tree, tree, tree);
170 static tree fold_builtin_strspn (location_t, tree, tree);
171 static tree fold_builtin_strcspn (location_t, tree, tree);
172
173 static rtx expand_builtin_object_size (tree);
174 static rtx expand_builtin_memory_chk (tree, rtx, machine_mode,
175                                       enum built_in_function);
176 static void maybe_emit_chk_warning (tree, enum built_in_function);
177 static void maybe_emit_sprintf_chk_warning (tree, enum built_in_function);
178 static void maybe_emit_free_warning (tree);
179 static tree fold_builtin_object_size (tree, tree);
180
181 unsigned HOST_WIDE_INT target_newline;
182 unsigned HOST_WIDE_INT target_percent;
183 static unsigned HOST_WIDE_INT target_c;
184 static unsigned HOST_WIDE_INT target_s;
185 char target_percent_c[3];
186 char target_percent_s[3];
187 char target_percent_s_newline[4];
188 static tree do_mpfr_remquo (tree, tree, tree);
189 static tree do_mpfr_lgamma_r (tree, tree, tree);
190 static void expand_builtin_sync_synchronize (void);
191
192 /* Return true if NAME starts with __builtin_ or __sync_.  */
193
194 static bool
195 is_builtin_name (const char *name)
196 {
197   if (strncmp (name, "__builtin_", 10) == 0)
198     return true;
199   if (strncmp (name, "__sync_", 7) == 0)
200     return true;
201   if (strncmp (name, "__atomic_", 9) == 0)
202     return true;
203   if (flag_cilkplus 
204       && (!strcmp (name, "__cilkrts_detach")   
205           || !strcmp (name, "__cilkrts_pop_frame")))
206     return true;
207   return false;
208 }
209
210
211 /* Return true if DECL is a function symbol representing a built-in.  */
212
213 bool
214 is_builtin_fn (tree decl)
215 {
216   return TREE_CODE (decl) == FUNCTION_DECL && DECL_BUILT_IN (decl);
217 }
218
219 /* Return true if NODE should be considered for inline expansion regardless
220    of the optimization level.  This means whenever a function is invoked with
221    its "internal" name, which normally contains the prefix "__builtin".  */
222
223 bool
224 called_as_built_in (tree node)
225 {
226   /* Note that we must use DECL_NAME, not DECL_ASSEMBLER_NAME_SET_P since
227      we want the name used to call the function, not the name it
228      will have. */
229   const char *name = IDENTIFIER_POINTER (DECL_NAME (node));
230   return is_builtin_name (name);
231 }
232
233 /* Compute values M and N such that M divides (address of EXP - N) and such
234    that N < M.  If these numbers can be determined, store M in alignp and N in
235    *BITPOSP and return true.  Otherwise return false and store BITS_PER_UNIT to
236    *alignp and any bit-offset to *bitposp.
237
238    Note that the address (and thus the alignment) computed here is based
239    on the address to which a symbol resolves, whereas DECL_ALIGN is based
240    on the address at which an object is actually located.  These two
241    addresses are not always the same.  For example, on ARM targets,
242    the address &foo of a Thumb function foo() has the lowest bit set,
243    whereas foo() itself starts on an even address.
244
245    If ADDR_P is true we are taking the address of the memory reference EXP
246    and thus cannot rely on the access taking place.  */
247
248 static bool
249 get_object_alignment_2 (tree exp, unsigned int *alignp,
250                         unsigned HOST_WIDE_INT *bitposp, bool addr_p)
251 {
252   HOST_WIDE_INT bitsize, bitpos;
253   tree offset;
254   machine_mode mode;
255   int unsignedp, reversep, volatilep;
256   unsigned int align = BITS_PER_UNIT;
257   bool known_alignment = false;
258
259   /* Get the innermost object and the constant (bitpos) and possibly
260      variable (offset) offset of the access.  */
261   exp = get_inner_reference (exp, &bitsize, &bitpos, &offset, &mode,
262                              &unsignedp, &reversep, &volatilep, true);
263
264   /* Extract alignment information from the innermost object and
265      possibly adjust bitpos and offset.  */
266   if (TREE_CODE (exp) == FUNCTION_DECL)
267     {
268       /* Function addresses can encode extra information besides their
269          alignment.  However, if TARGET_PTRMEMFUNC_VBIT_LOCATION
270          allows the low bit to be used as a virtual bit, we know
271          that the address itself must be at least 2-byte aligned.  */
272       if (TARGET_PTRMEMFUNC_VBIT_LOCATION == ptrmemfunc_vbit_in_pfn)
273         align = 2 * BITS_PER_UNIT;
274     }
275   else if (TREE_CODE (exp) == LABEL_DECL)
276     ;
277   else if (TREE_CODE (exp) == CONST_DECL)
278     {
279       /* The alignment of a CONST_DECL is determined by its initializer.  */
280       exp = DECL_INITIAL (exp);
281       align = TYPE_ALIGN (TREE_TYPE (exp));
282       if (CONSTANT_CLASS_P (exp))
283         align = (unsigned) CONSTANT_ALIGNMENT (exp, align);
284
285       known_alignment = true;
286     }
287   else if (DECL_P (exp))
288     {
289       align = DECL_ALIGN (exp);
290       known_alignment = true;
291     }
292   else if (TREE_CODE (exp) == VIEW_CONVERT_EXPR)
293     {
294       align = TYPE_ALIGN (TREE_TYPE (exp));
295     }
296   else if (TREE_CODE (exp) == INDIRECT_REF
297            || TREE_CODE (exp) == MEM_REF
298            || TREE_CODE (exp) == TARGET_MEM_REF)
299     {
300       tree addr = TREE_OPERAND (exp, 0);
301       unsigned ptr_align;
302       unsigned HOST_WIDE_INT ptr_bitpos;
303       unsigned HOST_WIDE_INT ptr_bitmask = ~0;
304
305       /* If the address is explicitely aligned, handle that.  */
306       if (TREE_CODE (addr) == BIT_AND_EXPR
307           && TREE_CODE (TREE_OPERAND (addr, 1)) == INTEGER_CST)
308         {
309           ptr_bitmask = TREE_INT_CST_LOW (TREE_OPERAND (addr, 1));
310           ptr_bitmask *= BITS_PER_UNIT;
311           align = ptr_bitmask & -ptr_bitmask;
312           addr = TREE_OPERAND (addr, 0);
313         }
314
315       known_alignment
316         = get_pointer_alignment_1 (addr, &ptr_align, &ptr_bitpos);
317       align = MAX (ptr_align, align);
318
319       /* Re-apply explicit alignment to the bitpos.  */
320       ptr_bitpos &= ptr_bitmask;
321
322       /* The alignment of the pointer operand in a TARGET_MEM_REF
323          has to take the variable offset parts into account.  */
324       if (TREE_CODE (exp) == TARGET_MEM_REF)
325         {
326           if (TMR_INDEX (exp))
327             {
328               unsigned HOST_WIDE_INT step = 1;
329               if (TMR_STEP (exp))
330                 step = TREE_INT_CST_LOW (TMR_STEP (exp));
331               align = MIN (align, (step & -step) * BITS_PER_UNIT);
332             }
333           if (TMR_INDEX2 (exp))
334             align = BITS_PER_UNIT;
335           known_alignment = false;
336         }
337
338       /* When EXP is an actual memory reference then we can use
339          TYPE_ALIGN of a pointer indirection to derive alignment.
340          Do so only if get_pointer_alignment_1 did not reveal absolute
341          alignment knowledge and if using that alignment would
342          improve the situation.  */
343       if (!addr_p && !known_alignment
344           && TYPE_ALIGN (TREE_TYPE (exp)) > align)
345         align = TYPE_ALIGN (TREE_TYPE (exp));
346       else
347         {
348           /* Else adjust bitpos accordingly.  */
349           bitpos += ptr_bitpos;
350           if (TREE_CODE (exp) == MEM_REF
351               || TREE_CODE (exp) == TARGET_MEM_REF)
352             bitpos += mem_ref_offset (exp).to_short_addr () * BITS_PER_UNIT;
353         }
354     }
355   else if (TREE_CODE (exp) == STRING_CST)
356     {
357       /* STRING_CST are the only constant objects we allow to be not
358          wrapped inside a CONST_DECL.  */
359       align = TYPE_ALIGN (TREE_TYPE (exp));
360       if (CONSTANT_CLASS_P (exp))
361         align = (unsigned) CONSTANT_ALIGNMENT (exp, align);
362
363       known_alignment = true;
364     }
365
366   /* If there is a non-constant offset part extract the maximum
367      alignment that can prevail.  */
368   if (offset)
369     {
370       unsigned int trailing_zeros = tree_ctz (offset);
371       if (trailing_zeros < HOST_BITS_PER_INT)
372         {
373           unsigned int inner = (1U << trailing_zeros) * BITS_PER_UNIT;
374           if (inner)
375             align = MIN (align, inner);
376         }
377     }
378
379   *alignp = align;
380   *bitposp = bitpos & (*alignp - 1);
381   return known_alignment;
382 }
383
384 /* For a memory reference expression EXP compute values M and N such that M
385    divides (&EXP - N) and such that N < M.  If these numbers can be determined,
386    store M in alignp and N in *BITPOSP and return true.  Otherwise return false
387    and store BITS_PER_UNIT to *alignp and any bit-offset to *bitposp.  */
388
389 bool
390 get_object_alignment_1 (tree exp, unsigned int *alignp,
391                         unsigned HOST_WIDE_INT *bitposp)
392 {
393   return get_object_alignment_2 (exp, alignp, bitposp, false);
394 }
395
396 /* Return the alignment in bits of EXP, an object.  */
397
398 unsigned int
399 get_object_alignment (tree exp)
400 {
401   unsigned HOST_WIDE_INT bitpos = 0;
402   unsigned int align;
403
404   get_object_alignment_1 (exp, &align, &bitpos);
405
406   /* align and bitpos now specify known low bits of the pointer.
407      ptr & (align - 1) == bitpos.  */
408
409   if (bitpos != 0)
410     align = (bitpos & -bitpos);
411   return align;
412 }
413
414 /* For a pointer valued expression EXP compute values M and N such that M
415    divides (EXP - N) and such that N < M.  If these numbers can be determined,
416    store M in alignp and N in *BITPOSP and return true.  Return false if
417    the results are just a conservative approximation.
418
419    If EXP is not a pointer, false is returned too.  */
420
421 bool
422 get_pointer_alignment_1 (tree exp, unsigned int *alignp,
423                          unsigned HOST_WIDE_INT *bitposp)
424 {
425   STRIP_NOPS (exp);
426
427   if (TREE_CODE (exp) == ADDR_EXPR)
428     return get_object_alignment_2 (TREE_OPERAND (exp, 0),
429                                    alignp, bitposp, true);
430   else if (TREE_CODE (exp) == POINTER_PLUS_EXPR)
431     {
432       unsigned int align;
433       unsigned HOST_WIDE_INT bitpos;
434       bool res = get_pointer_alignment_1 (TREE_OPERAND (exp, 0),
435                                           &align, &bitpos);
436       if (TREE_CODE (TREE_OPERAND (exp, 1)) == INTEGER_CST)
437         bitpos += TREE_INT_CST_LOW (TREE_OPERAND (exp, 1)) * BITS_PER_UNIT;
438       else
439         {
440           unsigned int trailing_zeros = tree_ctz (TREE_OPERAND (exp, 1));
441           if (trailing_zeros < HOST_BITS_PER_INT)
442             {
443               unsigned int inner = (1U << trailing_zeros) * BITS_PER_UNIT;
444               if (inner)
445                 align = MIN (align, inner);
446             }
447         }
448       *alignp = align;
449       *bitposp = bitpos & (align - 1);
450       return res;
451     }
452   else if (TREE_CODE (exp) == SSA_NAME
453            && POINTER_TYPE_P (TREE_TYPE (exp)))
454     {
455       unsigned int ptr_align, ptr_misalign;
456       struct ptr_info_def *pi = SSA_NAME_PTR_INFO (exp);
457
458       if (pi && get_ptr_info_alignment (pi, &ptr_align, &ptr_misalign))
459         {
460           *bitposp = ptr_misalign * BITS_PER_UNIT;
461           *alignp = ptr_align * BITS_PER_UNIT;
462           /* Make sure to return a sensible alignment when the multiplication
463              by BITS_PER_UNIT overflowed.  */
464           if (*alignp == 0)
465             *alignp = 1u << (HOST_BITS_PER_INT - 1);
466           /* We cannot really tell whether this result is an approximation.  */
467           return false;
468         }
469       else
470         {
471           *bitposp = 0;
472           *alignp = BITS_PER_UNIT;
473           return false;
474         }
475     }
476   else if (TREE_CODE (exp) == INTEGER_CST)
477     {
478       *alignp = BIGGEST_ALIGNMENT;
479       *bitposp = ((TREE_INT_CST_LOW (exp) * BITS_PER_UNIT)
480                   & (BIGGEST_ALIGNMENT - 1));
481       return true;
482     }
483
484   *bitposp = 0;
485   *alignp = BITS_PER_UNIT;
486   return false;
487 }
488
489 /* Return the alignment in bits of EXP, a pointer valued expression.
490    The alignment returned is, by default, the alignment of the thing that
491    EXP points to.  If it is not a POINTER_TYPE, 0 is returned.
492
493    Otherwise, look at the expression to see if we can do better, i.e., if the
494    expression is actually pointing at an object whose alignment is tighter.  */
495
496 unsigned int
497 get_pointer_alignment (tree exp)
498 {
499   unsigned HOST_WIDE_INT bitpos = 0;
500   unsigned int align;
501
502   get_pointer_alignment_1 (exp, &align, &bitpos);
503
504   /* align and bitpos now specify known low bits of the pointer.
505      ptr & (align - 1) == bitpos.  */
506
507   if (bitpos != 0)
508     align = (bitpos & -bitpos);
509
510   return align;
511 }
512
513 /* Compute the length of a C string.  TREE_STRING_LENGTH is not the right
514    way, because it could contain a zero byte in the middle.
515    TREE_STRING_LENGTH is the size of the character array, not the string.
516
517    ONLY_VALUE should be nonzero if the result is not going to be emitted
518    into the instruction stream and zero if it is going to be expanded.
519    E.g. with i++ ? "foo" : "bar", if ONLY_VALUE is nonzero, constant 3
520    is returned, otherwise NULL, since
521    len = c_strlen (src, 1); if (len) expand_expr (len, ...); would not
522    evaluate the side-effects.
523
524    If ONLY_VALUE is two then we do not emit warnings about out-of-bound
525    accesses.  Note that this implies the result is not going to be emitted
526    into the instruction stream.
527
528    The value returned is of type `ssizetype'.
529
530    Unfortunately, string_constant can't access the values of const char
531    arrays with initializers, so neither can we do so here.  */
532
533 tree
534 c_strlen (tree src, int only_value)
535 {
536   tree offset_node;
537   HOST_WIDE_INT offset;
538   int max;
539   const char *ptr;
540   location_t loc;
541
542   STRIP_NOPS (src);
543   if (TREE_CODE (src) == COND_EXPR
544       && (only_value || !TREE_SIDE_EFFECTS (TREE_OPERAND (src, 0))))
545     {
546       tree len1, len2;
547
548       len1 = c_strlen (TREE_OPERAND (src, 1), only_value);
549       len2 = c_strlen (TREE_OPERAND (src, 2), only_value);
550       if (tree_int_cst_equal (len1, len2))
551         return len1;
552     }
553
554   if (TREE_CODE (src) == COMPOUND_EXPR
555       && (only_value || !TREE_SIDE_EFFECTS (TREE_OPERAND (src, 0))))
556     return c_strlen (TREE_OPERAND (src, 1), only_value);
557
558   loc = EXPR_LOC_OR_LOC (src, input_location);
559
560   src = string_constant (src, &offset_node);
561   if (src == 0)
562     return NULL_TREE;
563
564   max = TREE_STRING_LENGTH (src) - 1;
565   ptr = TREE_STRING_POINTER (src);
566
567   if (offset_node && TREE_CODE (offset_node) != INTEGER_CST)
568     {
569       /* If the string has an internal zero byte (e.g., "foo\0bar"), we can't
570          compute the offset to the following null if we don't know where to
571          start searching for it.  */
572       int i;
573
574       for (i = 0; i < max; i++)
575         if (ptr[i] == 0)
576           return NULL_TREE;
577
578       /* We don't know the starting offset, but we do know that the string
579          has no internal zero bytes.  We can assume that the offset falls
580          within the bounds of the string; otherwise, the programmer deserves
581          what he gets.  Subtract the offset from the length of the string,
582          and return that.  This would perhaps not be valid if we were dealing
583          with named arrays in addition to literal string constants.  */
584
585       return size_diffop_loc (loc, size_int (max), offset_node);
586     }
587
588   /* We have a known offset into the string.  Start searching there for
589      a null character if we can represent it as a single HOST_WIDE_INT.  */
590   if (offset_node == 0)
591     offset = 0;
592   else if (! tree_fits_shwi_p (offset_node))
593     offset = -1;
594   else
595     offset = tree_to_shwi (offset_node);
596
597   /* If the offset is known to be out of bounds, warn, and call strlen at
598      runtime.  */
599   if (offset < 0 || offset > max)
600     {
601      /* Suppress multiple warnings for propagated constant strings.  */
602       if (only_value != 2
603           && !TREE_NO_WARNING (src))
604         {
605           warning_at (loc, 0, "offset outside bounds of constant string");
606           TREE_NO_WARNING (src) = 1;
607         }
608       return NULL_TREE;
609     }
610
611   /* Use strlen to search for the first zero byte.  Since any strings
612      constructed with build_string will have nulls appended, we win even
613      if we get handed something like (char[4])"abcd".
614
615      Since OFFSET is our starting index into the string, no further
616      calculation is needed.  */
617   return ssize_int (strlen (ptr + offset));
618 }
619
620 /* Return a constant integer corresponding to target reading
621    GET_MODE_BITSIZE (MODE) bits from string constant STR.  */
622
623 static rtx
624 c_readstr (const char *str, machine_mode mode)
625 {
626   HOST_WIDE_INT ch;
627   unsigned int i, j;
628   HOST_WIDE_INT tmp[MAX_BITSIZE_MODE_ANY_INT / HOST_BITS_PER_WIDE_INT];
629
630   gcc_assert (GET_MODE_CLASS (mode) == MODE_INT);
631   unsigned int len = (GET_MODE_PRECISION (mode) + HOST_BITS_PER_WIDE_INT - 1)
632     / HOST_BITS_PER_WIDE_INT;
633
634   gcc_assert (len <= MAX_BITSIZE_MODE_ANY_INT / HOST_BITS_PER_WIDE_INT);
635   for (i = 0; i < len; i++)
636     tmp[i] = 0;
637
638   ch = 1;
639   for (i = 0; i < GET_MODE_SIZE (mode); i++)
640     {
641       j = i;
642       if (WORDS_BIG_ENDIAN)
643         j = GET_MODE_SIZE (mode) - i - 1;
644       if (BYTES_BIG_ENDIAN != WORDS_BIG_ENDIAN
645           && GET_MODE_SIZE (mode) >= UNITS_PER_WORD)
646         j = j + UNITS_PER_WORD - 2 * (j % UNITS_PER_WORD) - 1;
647       j *= BITS_PER_UNIT;
648
649       if (ch)
650         ch = (unsigned char) str[i];
651       tmp[j / HOST_BITS_PER_WIDE_INT] |= ch << (j % HOST_BITS_PER_WIDE_INT);
652     }
653
654   wide_int c = wide_int::from_array (tmp, len, GET_MODE_PRECISION (mode));
655   return immed_wide_int_const (c, mode);
656 }
657
658 /* Cast a target constant CST to target CHAR and if that value fits into
659    host char type, return zero and put that value into variable pointed to by
660    P.  */
661
662 static int
663 target_char_cast (tree cst, char *p)
664 {
665   unsigned HOST_WIDE_INT val, hostval;
666
667   if (TREE_CODE (cst) != INTEGER_CST
668       || CHAR_TYPE_SIZE > HOST_BITS_PER_WIDE_INT)
669     return 1;
670
671   /* Do not care if it fits or not right here.  */
672   val = TREE_INT_CST_LOW (cst);
673
674   if (CHAR_TYPE_SIZE < HOST_BITS_PER_WIDE_INT)
675     val &= (((unsigned HOST_WIDE_INT) 1) << CHAR_TYPE_SIZE) - 1;
676
677   hostval = val;
678   if (HOST_BITS_PER_CHAR < HOST_BITS_PER_WIDE_INT)
679     hostval &= (((unsigned HOST_WIDE_INT) 1) << HOST_BITS_PER_CHAR) - 1;
680
681   if (val != hostval)
682     return 1;
683
684   *p = hostval;
685   return 0;
686 }
687
688 /* Similar to save_expr, but assumes that arbitrary code is not executed
689    in between the multiple evaluations.  In particular, we assume that a
690    non-addressable local variable will not be modified.  */
691
692 static tree
693 builtin_save_expr (tree exp)
694 {
695   if (TREE_CODE (exp) == SSA_NAME
696       || (TREE_ADDRESSABLE (exp) == 0
697           && (TREE_CODE (exp) == PARM_DECL
698               || (TREE_CODE (exp) == VAR_DECL && !TREE_STATIC (exp)))))
699     return exp;
700
701   return save_expr (exp);
702 }
703
704 /* Given TEM, a pointer to a stack frame, follow the dynamic chain COUNT
705    times to get the address of either a higher stack frame, or a return
706    address located within it (depending on FNDECL_CODE).  */
707
708 static rtx
709 expand_builtin_return_addr (enum built_in_function fndecl_code, int count)
710 {
711   int i;
712   rtx tem = INITIAL_FRAME_ADDRESS_RTX;
713   if (tem == NULL_RTX)
714     {
715       /* For a zero count with __builtin_return_address, we don't care what
716          frame address we return, because target-specific definitions will
717          override us.  Therefore frame pointer elimination is OK, and using
718          the soft frame pointer is OK.
719
720          For a nonzero count, or a zero count with __builtin_frame_address,
721          we require a stable offset from the current frame pointer to the
722          previous one, so we must use the hard frame pointer, and
723          we must disable frame pointer elimination.  */
724       if (count == 0 && fndecl_code == BUILT_IN_RETURN_ADDRESS)
725         tem = frame_pointer_rtx;
726       else
727         {
728           tem = hard_frame_pointer_rtx;
729
730           /* Tell reload not to eliminate the frame pointer.  */
731           crtl->accesses_prior_frames = 1;
732         }
733     }
734
735   if (count > 0)
736     SETUP_FRAME_ADDRESSES ();
737
738   /* On the SPARC, the return address is not in the frame, it is in a
739      register.  There is no way to access it off of the current frame
740      pointer, but it can be accessed off the previous frame pointer by
741      reading the value from the register window save area.  */
742   if (RETURN_ADDR_IN_PREVIOUS_FRAME && fndecl_code == BUILT_IN_RETURN_ADDRESS)
743     count--;
744
745   /* Scan back COUNT frames to the specified frame.  */
746   for (i = 0; i < count; i++)
747     {
748       /* Assume the dynamic chain pointer is in the word that the
749          frame address points to, unless otherwise specified.  */
750       tem = DYNAMIC_CHAIN_ADDRESS (tem);
751       tem = memory_address (Pmode, tem);
752       tem = gen_frame_mem (Pmode, tem);
753       tem = copy_to_reg (tem);
754     }
755
756   /* For __builtin_frame_address, return what we've got.  But, on
757      the SPARC for example, we may have to add a bias.  */
758   if (fndecl_code == BUILT_IN_FRAME_ADDRESS)
759     return FRAME_ADDR_RTX (tem);
760
761   /* For __builtin_return_address, get the return address from that frame.  */
762 #ifdef RETURN_ADDR_RTX
763   tem = RETURN_ADDR_RTX (count, tem);
764 #else
765   tem = memory_address (Pmode,
766                         plus_constant (Pmode, tem, GET_MODE_SIZE (Pmode)));
767   tem = gen_frame_mem (Pmode, tem);
768 #endif
769   return tem;
770 }
771
772 /* Alias set used for setjmp buffer.  */
773 static alias_set_type setjmp_alias_set = -1;
774
775 /* Construct the leading half of a __builtin_setjmp call.  Control will
776    return to RECEIVER_LABEL.  This is also called directly by the SJLJ
777    exception handling code.  */
778
779 void
780 expand_builtin_setjmp_setup (rtx buf_addr, rtx receiver_label)
781 {
782   machine_mode sa_mode = STACK_SAVEAREA_MODE (SAVE_NONLOCAL);
783   rtx stack_save;
784   rtx mem;
785
786   if (setjmp_alias_set == -1)
787     setjmp_alias_set = new_alias_set ();
788
789   buf_addr = convert_memory_address (Pmode, buf_addr);
790
791   buf_addr = force_reg (Pmode, force_operand (buf_addr, NULL_RTX));
792
793   /* We store the frame pointer and the address of receiver_label in
794      the buffer and use the rest of it for the stack save area, which
795      is machine-dependent.  */
796
797   mem = gen_rtx_MEM (Pmode, buf_addr);
798   set_mem_alias_set (mem, setjmp_alias_set);
799   emit_move_insn (mem, targetm.builtin_setjmp_frame_value ());
800
801   mem = gen_rtx_MEM (Pmode, plus_constant (Pmode, buf_addr,
802                                            GET_MODE_SIZE (Pmode))),
803   set_mem_alias_set (mem, setjmp_alias_set);
804
805   emit_move_insn (validize_mem (mem),
806                   force_reg (Pmode, gen_rtx_LABEL_REF (Pmode, receiver_label)));
807
808   stack_save = gen_rtx_MEM (sa_mode,
809                             plus_constant (Pmode, buf_addr,
810                                            2 * GET_MODE_SIZE (Pmode)));
811   set_mem_alias_set (stack_save, setjmp_alias_set);
812   emit_stack_save (SAVE_NONLOCAL, &stack_save);
813
814   /* If there is further processing to do, do it.  */
815   if (targetm.have_builtin_setjmp_setup ())
816     emit_insn (targetm.gen_builtin_setjmp_setup (buf_addr));
817
818   /* We have a nonlocal label.   */
819   cfun->has_nonlocal_label = 1;
820 }
821
822 /* Construct the trailing part of a __builtin_setjmp call.  This is
823    also called directly by the SJLJ exception handling code.
824    If RECEIVER_LABEL is NULL, instead contruct a nonlocal goto handler.  */
825
826 void
827 expand_builtin_setjmp_receiver (rtx receiver_label)
828 {
829   rtx chain;
830
831   /* Mark the FP as used when we get here, so we have to make sure it's
832      marked as used by this function.  */
833   emit_use (hard_frame_pointer_rtx);
834
835   /* Mark the static chain as clobbered here so life information
836      doesn't get messed up for it.  */
837   chain = targetm.calls.static_chain (current_function_decl, true);
838   if (chain && REG_P (chain))
839     emit_clobber (chain);
840
841   /* Now put in the code to restore the frame pointer, and argument
842      pointer, if needed.  */
843   if (! targetm.have_nonlocal_goto ())
844     {
845       /* First adjust our frame pointer to its actual value.  It was
846          previously set to the start of the virtual area corresponding to
847          the stacked variables when we branched here and now needs to be
848          adjusted to the actual hardware fp value.
849
850          Assignments to virtual registers are converted by
851          instantiate_virtual_regs into the corresponding assignment
852          to the underlying register (fp in this case) that makes
853          the original assignment true.
854          So the following insn will actually be decrementing fp by
855          STARTING_FRAME_OFFSET.  */
856       emit_move_insn (virtual_stack_vars_rtx, hard_frame_pointer_rtx);
857
858       /* Restoring the frame pointer also modifies the hard frame pointer.
859          Mark it used (so that the previous assignment remains live once
860          the frame pointer is eliminated) and clobbered (to represent the
861          implicit update from the assignment).  */
862       emit_use (hard_frame_pointer_rtx);
863       emit_clobber (hard_frame_pointer_rtx);
864     }
865
866   if (!HARD_FRAME_POINTER_IS_ARG_POINTER && fixed_regs[ARG_POINTER_REGNUM])
867     {
868 #ifdef ELIMINABLE_REGS
869       /* If the argument pointer can be eliminated in favor of the
870          frame pointer, we don't need to restore it.  We assume here
871          that if such an elimination is present, it can always be used.
872          This is the case on all known machines; if we don't make this
873          assumption, we do unnecessary saving on many machines.  */
874       size_t i;
875       static const struct elims {const int from, to;} elim_regs[] = ELIMINABLE_REGS;
876
877       for (i = 0; i < ARRAY_SIZE (elim_regs); i++)
878         if (elim_regs[i].from == ARG_POINTER_REGNUM
879             && elim_regs[i].to == HARD_FRAME_POINTER_REGNUM)
880           break;
881
882       if (i == ARRAY_SIZE (elim_regs))
883 #endif
884         {
885           /* Now restore our arg pointer from the address at which it
886              was saved in our stack frame.  */
887           emit_move_insn (crtl->args.internal_arg_pointer,
888                           copy_to_reg (get_arg_pointer_save_area ()));
889         }
890     }
891
892   if (receiver_label != NULL && targetm.have_builtin_setjmp_receiver ())
893     emit_insn (targetm.gen_builtin_setjmp_receiver (receiver_label));
894   else if (targetm.have_nonlocal_goto_receiver ())
895     emit_insn (targetm.gen_nonlocal_goto_receiver ());
896   else
897     { /* Nothing */ }
898
899   /* We must not allow the code we just generated to be reordered by
900      scheduling.  Specifically, the update of the frame pointer must
901      happen immediately, not later.  */
902   emit_insn (gen_blockage ());
903 }
904
905 /* __builtin_longjmp is passed a pointer to an array of five words (not
906    all will be used on all machines).  It operates similarly to the C
907    library function of the same name, but is more efficient.  Much of
908    the code below is copied from the handling of non-local gotos.  */
909
910 static void
911 expand_builtin_longjmp (rtx buf_addr, rtx value)
912 {
913   rtx fp, lab, stack;
914   rtx_insn *insn, *last;
915   machine_mode sa_mode = STACK_SAVEAREA_MODE (SAVE_NONLOCAL);
916
917   /* DRAP is needed for stack realign if longjmp is expanded to current
918      function  */
919   if (SUPPORTS_STACK_ALIGNMENT)
920     crtl->need_drap = true;
921
922   if (setjmp_alias_set == -1)
923     setjmp_alias_set = new_alias_set ();
924
925   buf_addr = convert_memory_address (Pmode, buf_addr);
926
927   buf_addr = force_reg (Pmode, buf_addr);
928
929   /* We require that the user must pass a second argument of 1, because
930      that is what builtin_setjmp will return.  */
931   gcc_assert (value == const1_rtx);
932
933   last = get_last_insn ();
934   if (targetm.have_builtin_longjmp ())
935     emit_insn (targetm.gen_builtin_longjmp (buf_addr));
936   else
937     {
938       fp = gen_rtx_MEM (Pmode, buf_addr);
939       lab = gen_rtx_MEM (Pmode, plus_constant (Pmode, buf_addr,
940                                                GET_MODE_SIZE (Pmode)));
941
942       stack = gen_rtx_MEM (sa_mode, plus_constant (Pmode, buf_addr,
943                                                    2 * GET_MODE_SIZE (Pmode)));
944       set_mem_alias_set (fp, setjmp_alias_set);
945       set_mem_alias_set (lab, setjmp_alias_set);
946       set_mem_alias_set (stack, setjmp_alias_set);
947
948       /* Pick up FP, label, and SP from the block and jump.  This code is
949          from expand_goto in stmt.c; see there for detailed comments.  */
950       if (targetm.have_nonlocal_goto ())
951         /* We have to pass a value to the nonlocal_goto pattern that will
952            get copied into the static_chain pointer, but it does not matter
953            what that value is, because builtin_setjmp does not use it.  */
954         emit_insn (targetm.gen_nonlocal_goto (value, lab, stack, fp));
955       else
956         {
957           lab = copy_to_reg (lab);
958
959           emit_clobber (gen_rtx_MEM (BLKmode, gen_rtx_SCRATCH (VOIDmode)));
960           emit_clobber (gen_rtx_MEM (BLKmode, hard_frame_pointer_rtx));
961
962           emit_move_insn (hard_frame_pointer_rtx, fp);
963           emit_stack_restore (SAVE_NONLOCAL, stack);
964
965           emit_use (hard_frame_pointer_rtx);
966           emit_use (stack_pointer_rtx);
967           emit_indirect_jump (lab);
968         }
969     }
970
971   /* Search backwards and mark the jump insn as a non-local goto.
972      Note that this precludes the use of __builtin_longjmp to a
973      __builtin_setjmp target in the same function.  However, we've
974      already cautioned the user that these functions are for
975      internal exception handling use only.  */
976   for (insn = get_last_insn (); insn; insn = PREV_INSN (insn))
977     {
978       gcc_assert (insn != last);
979
980       if (JUMP_P (insn))
981         {
982           add_reg_note (insn, REG_NON_LOCAL_GOTO, const0_rtx);
983           break;
984         }
985       else if (CALL_P (insn))
986         break;
987     }
988 }
989
990 static inline bool
991 more_const_call_expr_args_p (const const_call_expr_arg_iterator *iter)
992 {
993   return (iter->i < iter->n);
994 }
995
996 /* This function validates the types of a function call argument list
997    against a specified list of tree_codes.  If the last specifier is a 0,
998    that represents an ellipses, otherwise the last specifier must be a
999    VOID_TYPE.  */
1000
1001 static bool
1002 validate_arglist (const_tree callexpr, ...)
1003 {
1004   enum tree_code code;
1005   bool res = 0;
1006   va_list ap;
1007   const_call_expr_arg_iterator iter;
1008   const_tree arg;
1009
1010   va_start (ap, callexpr);
1011   init_const_call_expr_arg_iterator (callexpr, &iter);
1012
1013   do
1014     {
1015       code = (enum tree_code) va_arg (ap, int);
1016       switch (code)
1017         {
1018         case 0:
1019           /* This signifies an ellipses, any further arguments are all ok.  */
1020           res = true;
1021           goto end;
1022         case VOID_TYPE:
1023           /* This signifies an endlink, if no arguments remain, return
1024              true, otherwise return false.  */
1025           res = !more_const_call_expr_args_p (&iter);
1026           goto end;
1027         default:
1028           /* If no parameters remain or the parameter's code does not
1029              match the specified code, return false.  Otherwise continue
1030              checking any remaining arguments.  */
1031           arg = next_const_call_expr_arg (&iter);
1032           if (!validate_arg (arg, code))
1033             goto end;
1034           break;
1035         }
1036     }
1037   while (1);
1038
1039   /* We need gotos here since we can only have one VA_CLOSE in a
1040      function.  */
1041  end: ;
1042   va_end (ap);
1043
1044   return res;
1045 }
1046
1047 /* Expand a call to __builtin_nonlocal_goto.  We're passed the target label
1048    and the address of the save area.  */
1049
1050 static rtx
1051 expand_builtin_nonlocal_goto (tree exp)
1052 {
1053   tree t_label, t_save_area;
1054   rtx r_label, r_save_area, r_fp, r_sp;
1055   rtx_insn *insn;
1056
1057   if (!validate_arglist (exp, POINTER_TYPE, POINTER_TYPE, VOID_TYPE))
1058     return NULL_RTX;
1059
1060   t_label = CALL_EXPR_ARG (exp, 0);
1061   t_save_area = CALL_EXPR_ARG (exp, 1);
1062
1063   r_label = expand_normal (t_label);
1064   r_label = convert_memory_address (Pmode, r_label);
1065   r_save_area = expand_normal (t_save_area);
1066   r_save_area = convert_memory_address (Pmode, r_save_area);
1067   /* Copy the address of the save location to a register just in case it was
1068      based on the frame pointer.   */
1069   r_save_area = copy_to_reg (r_save_area);
1070   r_fp = gen_rtx_MEM (Pmode, r_save_area);
1071   r_sp = gen_rtx_MEM (STACK_SAVEAREA_MODE (SAVE_NONLOCAL),
1072                       plus_constant (Pmode, r_save_area,
1073                                      GET_MODE_SIZE (Pmode)));
1074
1075   crtl->has_nonlocal_goto = 1;
1076
1077   /* ??? We no longer need to pass the static chain value, afaik.  */
1078   if (targetm.have_nonlocal_goto ())
1079     emit_insn (targetm.gen_nonlocal_goto (const0_rtx, r_label, r_sp, r_fp));
1080   else
1081     {
1082       r_label = copy_to_reg (r_label);
1083
1084       emit_clobber (gen_rtx_MEM (BLKmode, gen_rtx_SCRATCH (VOIDmode)));
1085       emit_clobber (gen_rtx_MEM (BLKmode, hard_frame_pointer_rtx));
1086
1087       /* Restore frame pointer for containing function.  */
1088       emit_move_insn (hard_frame_pointer_rtx, r_fp);
1089       emit_stack_restore (SAVE_NONLOCAL, r_sp);
1090
1091       /* USE of hard_frame_pointer_rtx added for consistency;
1092          not clear if really needed.  */
1093       emit_use (hard_frame_pointer_rtx);
1094       emit_use (stack_pointer_rtx);
1095
1096       /* If the architecture is using a GP register, we must
1097          conservatively assume that the target function makes use of it.
1098          The prologue of functions with nonlocal gotos must therefore
1099          initialize the GP register to the appropriate value, and we
1100          must then make sure that this value is live at the point
1101          of the jump.  (Note that this doesn't necessarily apply
1102          to targets with a nonlocal_goto pattern; they are free
1103          to implement it in their own way.  Note also that this is
1104          a no-op if the GP register is a global invariant.)  */
1105       if ((unsigned) PIC_OFFSET_TABLE_REGNUM != INVALID_REGNUM
1106           && fixed_regs[PIC_OFFSET_TABLE_REGNUM])
1107         emit_use (pic_offset_table_rtx);
1108
1109       emit_indirect_jump (r_label);
1110     }
1111
1112   /* Search backwards to the jump insn and mark it as a
1113      non-local goto.  */
1114   for (insn = get_last_insn (); insn; insn = PREV_INSN (insn))
1115     {
1116       if (JUMP_P (insn))
1117         {
1118           add_reg_note (insn, REG_NON_LOCAL_GOTO, const0_rtx);
1119           break;
1120         }
1121       else if (CALL_P (insn))
1122         break;
1123     }
1124
1125   return const0_rtx;
1126 }
1127
1128 /* __builtin_update_setjmp_buf is passed a pointer to an array of five words
1129    (not all will be used on all machines) that was passed to __builtin_setjmp.
1130    It updates the stack pointer in that block to the current value.  This is
1131    also called directly by the SJLJ exception handling code.  */
1132
1133 void
1134 expand_builtin_update_setjmp_buf (rtx buf_addr)
1135 {
1136   machine_mode sa_mode = STACK_SAVEAREA_MODE (SAVE_NONLOCAL);
1137   rtx stack_save
1138     = gen_rtx_MEM (sa_mode,
1139                    memory_address
1140                    (sa_mode,
1141                     plus_constant (Pmode, buf_addr,
1142                                    2 * GET_MODE_SIZE (Pmode))));
1143
1144   emit_stack_save (SAVE_NONLOCAL, &stack_save);
1145 }
1146
1147 /* Expand a call to __builtin_prefetch.  For a target that does not support
1148    data prefetch, evaluate the memory address argument in case it has side
1149    effects.  */
1150
1151 static void
1152 expand_builtin_prefetch (tree exp)
1153 {
1154   tree arg0, arg1, arg2;
1155   int nargs;
1156   rtx op0, op1, op2;
1157
1158   if (!validate_arglist (exp, POINTER_TYPE, 0))
1159     return;
1160
1161   arg0 = CALL_EXPR_ARG (exp, 0);
1162
1163   /* Arguments 1 and 2 are optional; argument 1 (read/write) defaults to
1164      zero (read) and argument 2 (locality) defaults to 3 (high degree of
1165      locality).  */
1166   nargs = call_expr_nargs (exp);
1167   if (nargs > 1)
1168     arg1 = CALL_EXPR_ARG (exp, 1);
1169   else
1170     arg1 = integer_zero_node;
1171   if (nargs > 2)
1172     arg2 = CALL_EXPR_ARG (exp, 2);
1173   else
1174     arg2 = integer_three_node;
1175
1176   /* Argument 0 is an address.  */
1177   op0 = expand_expr (arg0, NULL_RTX, Pmode, EXPAND_NORMAL);
1178
1179   /* Argument 1 (read/write flag) must be a compile-time constant int.  */
1180   if (TREE_CODE (arg1) != INTEGER_CST)
1181     {
1182       error ("second argument to %<__builtin_prefetch%> must be a constant");
1183       arg1 = integer_zero_node;
1184     }
1185   op1 = expand_normal (arg1);
1186   /* Argument 1 must be either zero or one.  */
1187   if (INTVAL (op1) != 0 && INTVAL (op1) != 1)
1188     {
1189       warning (0, "invalid second argument to %<__builtin_prefetch%>;"
1190                " using zero");
1191       op1 = const0_rtx;
1192     }
1193
1194   /* Argument 2 (locality) must be a compile-time constant int.  */
1195   if (TREE_CODE (arg2) != INTEGER_CST)
1196     {
1197       error ("third argument to %<__builtin_prefetch%> must be a constant");
1198       arg2 = integer_zero_node;
1199     }
1200   op2 = expand_normal (arg2);
1201   /* Argument 2 must be 0, 1, 2, or 3.  */
1202   if (INTVAL (op2) < 0 || INTVAL (op2) > 3)
1203     {
1204       warning (0, "invalid third argument to %<__builtin_prefetch%>; using zero");
1205       op2 = const0_rtx;
1206     }
1207
1208   if (targetm.have_prefetch ())
1209     {
1210       struct expand_operand ops[3];
1211
1212       create_address_operand (&ops[0], op0);
1213       create_integer_operand (&ops[1], INTVAL (op1));
1214       create_integer_operand (&ops[2], INTVAL (op2));
1215       if (maybe_expand_insn (targetm.code_for_prefetch, 3, ops))
1216         return;
1217     }
1218
1219   /* Don't do anything with direct references to volatile memory, but
1220      generate code to handle other side effects.  */
1221   if (!MEM_P (op0) && side_effects_p (op0))
1222     emit_insn (op0);
1223 }
1224
1225 /* Get a MEM rtx for expression EXP which is the address of an operand
1226    to be used in a string instruction (cmpstrsi, movmemsi, ..).  LEN is
1227    the maximum length of the block of memory that might be accessed or
1228    NULL if unknown.  */
1229
1230 static rtx
1231 get_memory_rtx (tree exp, tree len)
1232 {
1233   tree orig_exp = exp;
1234   rtx addr, mem;
1235
1236   /* When EXP is not resolved SAVE_EXPR, MEM_ATTRS can be still derived
1237      from its expression, for expr->a.b only <variable>.a.b is recorded.  */
1238   if (TREE_CODE (exp) == SAVE_EXPR && !SAVE_EXPR_RESOLVED_P (exp))
1239     exp = TREE_OPERAND (exp, 0);
1240
1241   addr = expand_expr (orig_exp, NULL_RTX, ptr_mode, EXPAND_NORMAL);
1242   mem = gen_rtx_MEM (BLKmode, memory_address (BLKmode, addr));
1243
1244   /* Get an expression we can use to find the attributes to assign to MEM.
1245      First remove any nops.  */
1246   while (CONVERT_EXPR_P (exp)
1247          && POINTER_TYPE_P (TREE_TYPE (TREE_OPERAND (exp, 0))))
1248     exp = TREE_OPERAND (exp, 0);
1249
1250   /* Build a MEM_REF representing the whole accessed area as a byte blob,
1251      (as builtin stringops may alias with anything).  */
1252   exp = fold_build2 (MEM_REF,
1253                      build_array_type (char_type_node,
1254                                        build_range_type (sizetype,
1255                                                          size_one_node, len)),
1256                      exp, build_int_cst (ptr_type_node, 0));
1257
1258   /* If the MEM_REF has no acceptable address, try to get the base object
1259      from the original address we got, and build an all-aliasing
1260      unknown-sized access to that one.  */
1261   if (is_gimple_mem_ref_addr (TREE_OPERAND (exp, 0)))
1262     set_mem_attributes (mem, exp, 0);
1263   else if (TREE_CODE (TREE_OPERAND (exp, 0)) == ADDR_EXPR
1264            && (exp = get_base_address (TREE_OPERAND (TREE_OPERAND (exp, 0),
1265                                                      0))))
1266     {
1267       exp = build_fold_addr_expr (exp);
1268       exp = fold_build2 (MEM_REF,
1269                          build_array_type (char_type_node,
1270                                            build_range_type (sizetype,
1271                                                              size_zero_node,
1272                                                              NULL)),
1273                          exp, build_int_cst (ptr_type_node, 0));
1274       set_mem_attributes (mem, exp, 0);
1275     }
1276   set_mem_alias_set (mem, 0);
1277   return mem;
1278 }
1279 \f
1280 /* Built-in functions to perform an untyped call and return.  */
1281
1282 #define apply_args_mode \
1283   (this_target_builtins->x_apply_args_mode)
1284 #define apply_result_mode \
1285   (this_target_builtins->x_apply_result_mode)
1286
1287 /* Return the size required for the block returned by __builtin_apply_args,
1288    and initialize apply_args_mode.  */
1289
1290 static int
1291 apply_args_size (void)
1292 {
1293   static int size = -1;
1294   int align;
1295   unsigned int regno;
1296   machine_mode mode;
1297
1298   /* The values computed by this function never change.  */
1299   if (size < 0)
1300     {
1301       /* The first value is the incoming arg-pointer.  */
1302       size = GET_MODE_SIZE (Pmode);
1303
1304       /* The second value is the structure value address unless this is
1305          passed as an "invisible" first argument.  */
1306       if (targetm.calls.struct_value_rtx (cfun ? TREE_TYPE (cfun->decl) : 0, 0))
1307         size += GET_MODE_SIZE (Pmode);
1308
1309       for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
1310         if (FUNCTION_ARG_REGNO_P (regno))
1311           {
1312             mode = targetm.calls.get_raw_arg_mode (regno);
1313
1314             gcc_assert (mode != VOIDmode);
1315
1316             align = GET_MODE_ALIGNMENT (mode) / BITS_PER_UNIT;
1317             if (size % align != 0)
1318               size = CEIL (size, align) * align;
1319             size += GET_MODE_SIZE (mode);
1320             apply_args_mode[regno] = mode;
1321           }
1322         else
1323           {
1324             apply_args_mode[regno] = VOIDmode;
1325           }
1326     }
1327   return size;
1328 }
1329
1330 /* Return the size required for the block returned by __builtin_apply,
1331    and initialize apply_result_mode.  */
1332
1333 static int
1334 apply_result_size (void)
1335 {
1336   static int size = -1;
1337   int align, regno;
1338   machine_mode mode;
1339
1340   /* The values computed by this function never change.  */
1341   if (size < 0)
1342     {
1343       size = 0;
1344
1345       for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
1346         if (targetm.calls.function_value_regno_p (regno))
1347           {
1348             mode = targetm.calls.get_raw_result_mode (regno);
1349
1350             gcc_assert (mode != VOIDmode);
1351
1352             align = GET_MODE_ALIGNMENT (mode) / BITS_PER_UNIT;
1353             if (size % align != 0)
1354               size = CEIL (size, align) * align;
1355             size += GET_MODE_SIZE (mode);
1356             apply_result_mode[regno] = mode;
1357           }
1358         else
1359           apply_result_mode[regno] = VOIDmode;
1360
1361       /* Allow targets that use untyped_call and untyped_return to override
1362          the size so that machine-specific information can be stored here.  */
1363 #ifdef APPLY_RESULT_SIZE
1364       size = APPLY_RESULT_SIZE;
1365 #endif
1366     }
1367   return size;
1368 }
1369
1370 /* Create a vector describing the result block RESULT.  If SAVEP is true,
1371    the result block is used to save the values; otherwise it is used to
1372    restore the values.  */
1373
1374 static rtx
1375 result_vector (int savep, rtx result)
1376 {
1377   int regno, size, align, nelts;
1378   machine_mode mode;
1379   rtx reg, mem;
1380   rtx *savevec = XALLOCAVEC (rtx, FIRST_PSEUDO_REGISTER);
1381
1382   size = nelts = 0;
1383   for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
1384     if ((mode = apply_result_mode[regno]) != VOIDmode)
1385       {
1386         align = GET_MODE_ALIGNMENT (mode) / BITS_PER_UNIT;
1387         if (size % align != 0)
1388           size = CEIL (size, align) * align;
1389         reg = gen_rtx_REG (mode, savep ? regno : INCOMING_REGNO (regno));
1390         mem = adjust_address (result, mode, size);
1391         savevec[nelts++] = (savep
1392                             ? gen_rtx_SET (mem, reg)
1393                             : gen_rtx_SET (reg, mem));
1394         size += GET_MODE_SIZE (mode);
1395       }
1396   return gen_rtx_PARALLEL (VOIDmode, gen_rtvec_v (nelts, savevec));
1397 }
1398
1399 /* Save the state required to perform an untyped call with the same
1400    arguments as were passed to the current function.  */
1401
1402 static rtx
1403 expand_builtin_apply_args_1 (void)
1404 {
1405   rtx registers, tem;
1406   int size, align, regno;
1407   machine_mode mode;
1408   rtx struct_incoming_value = targetm.calls.struct_value_rtx (cfun ? TREE_TYPE (cfun->decl) : 0, 1);
1409
1410   /* Create a block where the arg-pointer, structure value address,
1411      and argument registers can be saved.  */
1412   registers = assign_stack_local (BLKmode, apply_args_size (), -1);
1413
1414   /* Walk past the arg-pointer and structure value address.  */
1415   size = GET_MODE_SIZE (Pmode);
1416   if (targetm.calls.struct_value_rtx (cfun ? TREE_TYPE (cfun->decl) : 0, 0))
1417     size += GET_MODE_SIZE (Pmode);
1418
1419   /* Save each register used in calling a function to the block.  */
1420   for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
1421     if ((mode = apply_args_mode[regno]) != VOIDmode)
1422       {
1423         align = GET_MODE_ALIGNMENT (mode) / BITS_PER_UNIT;
1424         if (size % align != 0)
1425           size = CEIL (size, align) * align;
1426
1427         tem = gen_rtx_REG (mode, INCOMING_REGNO (regno));
1428
1429         emit_move_insn (adjust_address (registers, mode, size), tem);
1430         size += GET_MODE_SIZE (mode);
1431       }
1432
1433   /* Save the arg pointer to the block.  */
1434   tem = copy_to_reg (crtl->args.internal_arg_pointer);
1435   /* We need the pointer as the caller actually passed them to us, not
1436      as we might have pretended they were passed.  Make sure it's a valid
1437      operand, as emit_move_insn isn't expected to handle a PLUS.  */
1438   if (STACK_GROWS_DOWNWARD)
1439     tem
1440       = force_operand (plus_constant (Pmode, tem,
1441                                       crtl->args.pretend_args_size),
1442                        NULL_RTX);
1443   emit_move_insn (adjust_address (registers, Pmode, 0), tem);
1444
1445   size = GET_MODE_SIZE (Pmode);
1446
1447   /* Save the structure value address unless this is passed as an
1448      "invisible" first argument.  */
1449   if (struct_incoming_value)
1450     {
1451       emit_move_insn (adjust_address (registers, Pmode, size),
1452                       copy_to_reg (struct_incoming_value));
1453       size += GET_MODE_SIZE (Pmode);
1454     }
1455
1456   /* Return the address of the block.  */
1457   return copy_addr_to_reg (XEXP (registers, 0));
1458 }
1459
1460 /* __builtin_apply_args returns block of memory allocated on
1461    the stack into which is stored the arg pointer, structure
1462    value address, static chain, and all the registers that might
1463    possibly be used in performing a function call.  The code is
1464    moved to the start of the function so the incoming values are
1465    saved.  */
1466
1467 static rtx
1468 expand_builtin_apply_args (void)
1469 {
1470   /* Don't do __builtin_apply_args more than once in a function.
1471      Save the result of the first call and reuse it.  */
1472   if (apply_args_value != 0)
1473     return apply_args_value;
1474   {
1475     /* When this function is called, it means that registers must be
1476        saved on entry to this function.  So we migrate the
1477        call to the first insn of this function.  */
1478     rtx temp;
1479
1480     start_sequence ();
1481     temp = expand_builtin_apply_args_1 ();
1482     rtx_insn *seq = get_insns ();
1483     end_sequence ();
1484
1485     apply_args_value = temp;
1486
1487     /* Put the insns after the NOTE that starts the function.
1488        If this is inside a start_sequence, make the outer-level insn
1489        chain current, so the code is placed at the start of the
1490        function.  If internal_arg_pointer is a non-virtual pseudo,
1491        it needs to be placed after the function that initializes
1492        that pseudo.  */
1493     push_topmost_sequence ();
1494     if (REG_P (crtl->args.internal_arg_pointer)
1495         && REGNO (crtl->args.internal_arg_pointer) > LAST_VIRTUAL_REGISTER)
1496       emit_insn_before (seq, parm_birth_insn);
1497     else
1498       emit_insn_before (seq, NEXT_INSN (entry_of_function ()));
1499     pop_topmost_sequence ();
1500     return temp;
1501   }
1502 }
1503
1504 /* Perform an untyped call and save the state required to perform an
1505    untyped return of whatever value was returned by the given function.  */
1506
1507 static rtx
1508 expand_builtin_apply (rtx function, rtx arguments, rtx argsize)
1509 {
1510   int size, align, regno;
1511   machine_mode mode;
1512   rtx incoming_args, result, reg, dest, src;
1513   rtx_call_insn *call_insn;
1514   rtx old_stack_level = 0;
1515   rtx call_fusage = 0;
1516   rtx struct_value = targetm.calls.struct_value_rtx (cfun ? TREE_TYPE (cfun->decl) : 0, 0);
1517
1518   arguments = convert_memory_address (Pmode, arguments);
1519
1520   /* Create a block where the return registers can be saved.  */
1521   result = assign_stack_local (BLKmode, apply_result_size (), -1);
1522
1523   /* Fetch the arg pointer from the ARGUMENTS block.  */
1524   incoming_args = gen_reg_rtx (Pmode);
1525   emit_move_insn (incoming_args, gen_rtx_MEM (Pmode, arguments));
1526   if (!STACK_GROWS_DOWNWARD)
1527     incoming_args = expand_simple_binop (Pmode, MINUS, incoming_args, argsize,
1528                                          incoming_args, 0, OPTAB_LIB_WIDEN);
1529
1530   /* Push a new argument block and copy the arguments.  Do not allow
1531      the (potential) memcpy call below to interfere with our stack
1532      manipulations.  */
1533   do_pending_stack_adjust ();
1534   NO_DEFER_POP;
1535
1536   /* Save the stack with nonlocal if available.  */
1537   if (targetm.have_save_stack_nonlocal ())
1538     emit_stack_save (SAVE_NONLOCAL, &old_stack_level);
1539   else
1540     emit_stack_save (SAVE_BLOCK, &old_stack_level);
1541
1542   /* Allocate a block of memory onto the stack and copy the memory
1543      arguments to the outgoing arguments address.  We can pass TRUE
1544      as the 4th argument because we just saved the stack pointer
1545      and will restore it right after the call.  */
1546   allocate_dynamic_stack_space (argsize, 0, BIGGEST_ALIGNMENT, true);
1547
1548   /* Set DRAP flag to true, even though allocate_dynamic_stack_space
1549      may have already set current_function_calls_alloca to true.
1550      current_function_calls_alloca won't be set if argsize is zero,
1551      so we have to guarantee need_drap is true here.  */
1552   if (SUPPORTS_STACK_ALIGNMENT)
1553     crtl->need_drap = true;
1554
1555   dest = virtual_outgoing_args_rtx;
1556   if (!STACK_GROWS_DOWNWARD)
1557     {
1558       if (CONST_INT_P (argsize))
1559         dest = plus_constant (Pmode, dest, -INTVAL (argsize));
1560       else
1561         dest = gen_rtx_PLUS (Pmode, dest, negate_rtx (Pmode, argsize));
1562     }
1563   dest = gen_rtx_MEM (BLKmode, dest);
1564   set_mem_align (dest, PARM_BOUNDARY);
1565   src = gen_rtx_MEM (BLKmode, incoming_args);
1566   set_mem_align (src, PARM_BOUNDARY);
1567   emit_block_move (dest, src, argsize, BLOCK_OP_NORMAL);
1568
1569   /* Refer to the argument block.  */
1570   apply_args_size ();
1571   arguments = gen_rtx_MEM (BLKmode, arguments);
1572   set_mem_align (arguments, PARM_BOUNDARY);
1573
1574   /* Walk past the arg-pointer and structure value address.  */
1575   size = GET_MODE_SIZE (Pmode);
1576   if (struct_value)
1577     size += GET_MODE_SIZE (Pmode);
1578
1579   /* Restore each of the registers previously saved.  Make USE insns
1580      for each of these registers for use in making the call.  */
1581   for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
1582     if ((mode = apply_args_mode[regno]) != VOIDmode)
1583       {
1584         align = GET_MODE_ALIGNMENT (mode) / BITS_PER_UNIT;
1585         if (size % align != 0)
1586           size = CEIL (size, align) * align;
1587         reg = gen_rtx_REG (mode, regno);
1588         emit_move_insn (reg, adjust_address (arguments, mode, size));
1589         use_reg (&call_fusage, reg);
1590         size += GET_MODE_SIZE (mode);
1591       }
1592
1593   /* Restore the structure value address unless this is passed as an
1594      "invisible" first argument.  */
1595   size = GET_MODE_SIZE (Pmode);
1596   if (struct_value)
1597     {
1598       rtx value = gen_reg_rtx (Pmode);
1599       emit_move_insn (value, adjust_address (arguments, Pmode, size));
1600       emit_move_insn (struct_value, value);
1601       if (REG_P (struct_value))
1602         use_reg (&call_fusage, struct_value);
1603       size += GET_MODE_SIZE (Pmode);
1604     }
1605
1606   /* All arguments and registers used for the call are set up by now!  */
1607   function = prepare_call_address (NULL, function, NULL, &call_fusage, 0, 0);
1608
1609   /* Ensure address is valid.  SYMBOL_REF is already valid, so no need,
1610      and we don't want to load it into a register as an optimization,
1611      because prepare_call_address already did it if it should be done.  */
1612   if (GET_CODE (function) != SYMBOL_REF)
1613     function = memory_address (FUNCTION_MODE, function);
1614
1615   /* Generate the actual call instruction and save the return value.  */
1616   if (targetm.have_untyped_call ())
1617     {
1618       rtx mem = gen_rtx_MEM (FUNCTION_MODE, function);
1619       emit_call_insn (targetm.gen_untyped_call (mem, result,
1620                                                 result_vector (1, result)));
1621     }
1622   else if (targetm.have_call_value ())
1623     {
1624       rtx valreg = 0;
1625
1626       /* Locate the unique return register.  It is not possible to
1627          express a call that sets more than one return register using
1628          call_value; use untyped_call for that.  In fact, untyped_call
1629          only needs to save the return registers in the given block.  */
1630       for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
1631         if ((mode = apply_result_mode[regno]) != VOIDmode)
1632           {
1633             gcc_assert (!valreg); /* have_untyped_call required.  */
1634
1635             valreg = gen_rtx_REG (mode, regno);
1636           }
1637
1638       emit_insn (targetm.gen_call_value (valreg,
1639                                          gen_rtx_MEM (FUNCTION_MODE, function),
1640                                          const0_rtx, NULL_RTX, const0_rtx));
1641
1642       emit_move_insn (adjust_address (result, GET_MODE (valreg), 0), valreg);
1643     }
1644   else
1645     gcc_unreachable ();
1646
1647   /* Find the CALL insn we just emitted, and attach the register usage
1648      information.  */
1649   call_insn = last_call_insn ();
1650   add_function_usage_to (call_insn, call_fusage);
1651
1652   /* Restore the stack.  */
1653   if (targetm.have_save_stack_nonlocal ())
1654     emit_stack_restore (SAVE_NONLOCAL, old_stack_level);
1655   else
1656     emit_stack_restore (SAVE_BLOCK, old_stack_level);
1657   fixup_args_size_notes (call_insn, get_last_insn (), 0);
1658
1659   OK_DEFER_POP;
1660
1661   /* Return the address of the result block.  */
1662   result = copy_addr_to_reg (XEXP (result, 0));
1663   return convert_memory_address (ptr_mode, result);
1664 }
1665
1666 /* Perform an untyped return.  */
1667
1668 static void
1669 expand_builtin_return (rtx result)
1670 {
1671   int size, align, regno;
1672   machine_mode mode;
1673   rtx reg;
1674   rtx_insn *call_fusage = 0;
1675
1676   result = convert_memory_address (Pmode, result);
1677
1678   apply_result_size ();
1679   result = gen_rtx_MEM (BLKmode, result);
1680
1681   if (targetm.have_untyped_return ())
1682     {
1683       rtx vector = result_vector (0, result);
1684       emit_jump_insn (targetm.gen_untyped_return (result, vector));
1685       emit_barrier ();
1686       return;
1687     }
1688
1689   /* Restore the return value and note that each value is used.  */
1690   size = 0;
1691   for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
1692     if ((mode = apply_result_mode[regno]) != VOIDmode)
1693       {
1694         align = GET_MODE_ALIGNMENT (mode) / BITS_PER_UNIT;
1695         if (size % align != 0)
1696           size = CEIL (size, align) * align;
1697         reg = gen_rtx_REG (mode, INCOMING_REGNO (regno));
1698         emit_move_insn (reg, adjust_address (result, mode, size));
1699
1700         push_to_sequence (call_fusage);
1701         emit_use (reg);
1702         call_fusage = get_insns ();
1703         end_sequence ();
1704         size += GET_MODE_SIZE (mode);
1705       }
1706
1707   /* Put the USE insns before the return.  */
1708   emit_insn (call_fusage);
1709
1710   /* Return whatever values was restored by jumping directly to the end
1711      of the function.  */
1712   expand_naked_return ();
1713 }
1714
1715 /* Used by expand_builtin_classify_type and fold_builtin_classify_type.  */
1716
1717 static enum type_class
1718 type_to_class (tree type)
1719 {
1720   switch (TREE_CODE (type))
1721     {
1722     case VOID_TYPE:        return void_type_class;
1723     case INTEGER_TYPE:     return integer_type_class;
1724     case ENUMERAL_TYPE:    return enumeral_type_class;
1725     case BOOLEAN_TYPE:     return boolean_type_class;
1726     case POINTER_TYPE:     return pointer_type_class;
1727     case REFERENCE_TYPE:   return reference_type_class;
1728     case OFFSET_TYPE:      return offset_type_class;
1729     case REAL_TYPE:        return real_type_class;
1730     case COMPLEX_TYPE:     return complex_type_class;
1731     case FUNCTION_TYPE:    return function_type_class;
1732     case METHOD_TYPE:      return method_type_class;
1733     case RECORD_TYPE:      return record_type_class;
1734     case UNION_TYPE:
1735     case QUAL_UNION_TYPE:  return union_type_class;
1736     case ARRAY_TYPE:       return (TYPE_STRING_FLAG (type)
1737                                    ? string_type_class : array_type_class);
1738     case LANG_TYPE:        return lang_type_class;
1739     default:               return no_type_class;
1740     }
1741 }
1742
1743 /* Expand a call EXP to __builtin_classify_type.  */
1744
1745 static rtx
1746 expand_builtin_classify_type (tree exp)
1747 {
1748   if (call_expr_nargs (exp))
1749     return GEN_INT (type_to_class (TREE_TYPE (CALL_EXPR_ARG (exp, 0))));
1750   return GEN_INT (no_type_class);
1751 }
1752
1753 /* This helper macro, meant to be used in mathfn_built_in below,
1754    determines which among a set of three builtin math functions is
1755    appropriate for a given type mode.  The `F' and `L' cases are
1756    automatically generated from the `double' case.  */
1757 #define CASE_MATHFN(MATHFN) \
1758   CASE_CFN_##MATHFN: \
1759   fcode = BUILT_IN_##MATHFN; fcodef = BUILT_IN_##MATHFN##F ; \
1760   fcodel = BUILT_IN_##MATHFN##L ; break;
1761 /* Similar to above, but appends _R after any F/L suffix.  */
1762 #define CASE_MATHFN_REENT(MATHFN) \
1763   case CFN_BUILT_IN_##MATHFN##_R: \
1764   case CFN_BUILT_IN_##MATHFN##F_R: \
1765   case CFN_BUILT_IN_##MATHFN##L_R: \
1766   fcode = BUILT_IN_##MATHFN##_R; fcodef = BUILT_IN_##MATHFN##F_R ; \
1767   fcodel = BUILT_IN_##MATHFN##L_R ; break;
1768
1769 /* Return a function equivalent to FN but operating on floating-point
1770    values of type TYPE, or END_BUILTINS if no such function exists.
1771    This is purely an operation on function codes; it does not guarantee
1772    that the target actually has an implementation of the function.  */
1773
1774 static built_in_function
1775 mathfn_built_in_2 (tree type, combined_fn fn)
1776 {
1777   built_in_function fcode, fcodef, fcodel;
1778
1779   switch (fn)
1780     {
1781     CASE_MATHFN (ACOS)
1782     CASE_MATHFN (ACOSH)
1783     CASE_MATHFN (ASIN)
1784     CASE_MATHFN (ASINH)
1785     CASE_MATHFN (ATAN)
1786     CASE_MATHFN (ATAN2)
1787     CASE_MATHFN (ATANH)
1788     CASE_MATHFN (CBRT)
1789     CASE_MATHFN (CEIL)
1790     CASE_MATHFN (CEXPI)
1791     CASE_MATHFN (COPYSIGN)
1792     CASE_MATHFN (COS)
1793     CASE_MATHFN (COSH)
1794     CASE_MATHFN (DREM)
1795     CASE_MATHFN (ERF)
1796     CASE_MATHFN (ERFC)
1797     CASE_MATHFN (EXP)
1798     CASE_MATHFN (EXP10)
1799     CASE_MATHFN (EXP2)
1800     CASE_MATHFN (EXPM1)
1801     CASE_MATHFN (FABS)
1802     CASE_MATHFN (FDIM)
1803     CASE_MATHFN (FLOOR)
1804     CASE_MATHFN (FMA)
1805     CASE_MATHFN (FMAX)
1806     CASE_MATHFN (FMIN)
1807     CASE_MATHFN (FMOD)
1808     CASE_MATHFN (FREXP)
1809     CASE_MATHFN (GAMMA)
1810     CASE_MATHFN_REENT (GAMMA) /* GAMMA_R */
1811     CASE_MATHFN (HUGE_VAL)
1812     CASE_MATHFN (HYPOT)
1813     CASE_MATHFN (ILOGB)
1814     CASE_MATHFN (ICEIL)
1815     CASE_MATHFN (IFLOOR)
1816     CASE_MATHFN (INF)
1817     CASE_MATHFN (IRINT)
1818     CASE_MATHFN (IROUND)
1819     CASE_MATHFN (ISINF)
1820     CASE_MATHFN (J0)
1821     CASE_MATHFN (J1)
1822     CASE_MATHFN (JN)
1823     CASE_MATHFN (LCEIL)
1824     CASE_MATHFN (LDEXP)
1825     CASE_MATHFN (LFLOOR)
1826     CASE_MATHFN (LGAMMA)
1827     CASE_MATHFN_REENT (LGAMMA) /* LGAMMA_R */
1828     CASE_MATHFN (LLCEIL)
1829     CASE_MATHFN (LLFLOOR)
1830     CASE_MATHFN (LLRINT)
1831     CASE_MATHFN (LLROUND)
1832     CASE_MATHFN (LOG)
1833     CASE_MATHFN (LOG10)
1834     CASE_MATHFN (LOG1P)
1835     CASE_MATHFN (LOG2)
1836     CASE_MATHFN (LOGB)
1837     CASE_MATHFN (LRINT)
1838     CASE_MATHFN (LROUND)
1839     CASE_MATHFN (MODF)
1840     CASE_MATHFN (NAN)
1841     CASE_MATHFN (NANS)
1842     CASE_MATHFN (NEARBYINT)
1843     CASE_MATHFN (NEXTAFTER)
1844     CASE_MATHFN (NEXTTOWARD)
1845     CASE_MATHFN (POW)
1846     CASE_MATHFN (POWI)
1847     CASE_MATHFN (POW10)
1848     CASE_MATHFN (REMAINDER)
1849     CASE_MATHFN (REMQUO)
1850     CASE_MATHFN (RINT)
1851     CASE_MATHFN (ROUND)
1852     CASE_MATHFN (SCALB)
1853     CASE_MATHFN (SCALBLN)
1854     CASE_MATHFN (SCALBN)
1855     CASE_MATHFN (SIGNBIT)
1856     CASE_MATHFN (SIGNIFICAND)
1857     CASE_MATHFN (SIN)
1858     CASE_MATHFN (SINCOS)
1859     CASE_MATHFN (SINH)
1860     CASE_MATHFN (SQRT)
1861     CASE_MATHFN (TAN)
1862     CASE_MATHFN (TANH)
1863     CASE_MATHFN (TGAMMA)
1864     CASE_MATHFN (TRUNC)
1865     CASE_MATHFN (Y0)
1866     CASE_MATHFN (Y1)
1867     CASE_MATHFN (YN)
1868
1869     default:
1870       return END_BUILTINS;
1871     }
1872
1873   if (TYPE_MAIN_VARIANT (type) == double_type_node)
1874     return fcode;
1875   else if (TYPE_MAIN_VARIANT (type) == float_type_node)
1876     return fcodef;
1877   else if (TYPE_MAIN_VARIANT (type) == long_double_type_node)
1878     return fcodel;
1879   else
1880     return END_BUILTINS;
1881 }
1882
1883 /* Return mathematic function equivalent to FN but operating directly on TYPE,
1884    if available.  If IMPLICIT_P is true use the implicit builtin declaration,
1885    otherwise use the explicit declaration.  If we can't do the conversion,
1886    return null.  */
1887
1888 static tree
1889 mathfn_built_in_1 (tree type, combined_fn fn, bool implicit_p)
1890 {
1891   built_in_function fcode2 = mathfn_built_in_2 (type, fn);
1892   if (fcode2 == END_BUILTINS)
1893     return NULL_TREE;
1894
1895   if (implicit_p && !builtin_decl_implicit_p (fcode2))
1896     return NULL_TREE;
1897
1898   return builtin_decl_explicit (fcode2);
1899 }
1900
1901 /* Like mathfn_built_in_1, but always use the implicit array.  */
1902
1903 tree
1904 mathfn_built_in (tree type, combined_fn fn)
1905 {
1906   return mathfn_built_in_1 (type, fn, /*implicit=*/ 1);
1907 }
1908
1909 /* Like mathfn_built_in_1, but take a built_in_function and
1910    always use the implicit array.  */
1911
1912 tree
1913 mathfn_built_in (tree type, enum built_in_function fn)
1914 {
1915   return mathfn_built_in_1 (type, as_combined_fn (fn), /*implicit=*/ 1);
1916 }
1917
1918 /* If BUILT_IN_NORMAL function FNDECL has an associated internal function,
1919    return its code, otherwise return IFN_LAST.  Note that this function
1920    only tests whether the function is defined in internals.def, not whether
1921    it is actually available on the target.  */
1922
1923 internal_fn
1924 associated_internal_fn (tree fndecl)
1925 {
1926   gcc_checking_assert (DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL);
1927   tree return_type = TREE_TYPE (TREE_TYPE (fndecl));
1928   switch (DECL_FUNCTION_CODE (fndecl))
1929     {
1930 #define DEF_INTERNAL_FLT_FN(NAME, FLAGS, OPTAB, TYPE) \
1931     CASE_FLT_FN (BUILT_IN_##NAME): return IFN_##NAME;
1932 #define DEF_INTERNAL_INT_FN(NAME, FLAGS, OPTAB, TYPE) \
1933     CASE_INT_FN (BUILT_IN_##NAME): return IFN_##NAME;
1934 #include "internal-fn.def"
1935
1936     CASE_FLT_FN (BUILT_IN_POW10):
1937       return IFN_EXP10;
1938
1939     CASE_FLT_FN (BUILT_IN_DREM):
1940       return IFN_REMAINDER;
1941
1942     CASE_FLT_FN (BUILT_IN_SCALBN):
1943     CASE_FLT_FN (BUILT_IN_SCALBLN):
1944       if (REAL_MODE_FORMAT (TYPE_MODE (return_type))->b == 2)
1945         return IFN_LDEXP;
1946       return IFN_LAST;
1947
1948     default:
1949       return IFN_LAST;
1950     }
1951 }
1952
1953 /* If CALL is a call to a BUILT_IN_NORMAL function that could be replaced
1954    on the current target by a call to an internal function, return the
1955    code of that internal function, otherwise return IFN_LAST.  The caller
1956    is responsible for ensuring that any side-effects of the built-in
1957    call are dealt with correctly.  E.g. if CALL sets errno, the caller
1958    must decide that the errno result isn't needed or make it available
1959    in some other way.  */
1960
1961 internal_fn
1962 replacement_internal_fn (gcall *call)
1963 {
1964   if (gimple_call_builtin_p (call, BUILT_IN_NORMAL))
1965     {
1966       internal_fn ifn = associated_internal_fn (gimple_call_fndecl (call));
1967       if (ifn != IFN_LAST)
1968         {
1969           tree_pair types = direct_internal_fn_types (ifn, call);
1970           optimization_type opt_type = bb_optimization_type (gimple_bb (call));
1971           if (direct_internal_fn_supported_p (ifn, types, opt_type))
1972             return ifn;
1973         }
1974     }
1975   return IFN_LAST;
1976 }
1977
1978 /* Expand a call to the builtin trinary math functions (fma).
1979    Return NULL_RTX if a normal call should be emitted rather than expanding the
1980    function in-line.  EXP is the expression that is a call to the builtin
1981    function; if convenient, the result should be placed in TARGET.
1982    SUBTARGET may be used as the target for computing one of EXP's
1983    operands.  */
1984
1985 static rtx
1986 expand_builtin_mathfn_ternary (tree exp, rtx target, rtx subtarget)
1987 {
1988   optab builtin_optab;
1989   rtx op0, op1, op2, result;
1990   rtx_insn *insns;
1991   tree fndecl = get_callee_fndecl (exp);
1992   tree arg0, arg1, arg2;
1993   machine_mode mode;
1994
1995   if (!validate_arglist (exp, REAL_TYPE, REAL_TYPE, REAL_TYPE, VOID_TYPE))
1996     return NULL_RTX;
1997
1998   arg0 = CALL_EXPR_ARG (exp, 0);
1999   arg1 = CALL_EXPR_ARG (exp, 1);
2000   arg2 = CALL_EXPR_ARG (exp, 2);
2001
2002   switch (DECL_FUNCTION_CODE (fndecl))
2003     {
2004     CASE_FLT_FN (BUILT_IN_FMA):
2005       builtin_optab = fma_optab; break;
2006     default:
2007       gcc_unreachable ();
2008     }
2009
2010   /* Make a suitable register to place result in.  */
2011   mode = TYPE_MODE (TREE_TYPE (exp));
2012
2013   /* Before working hard, check whether the instruction is available.  */
2014   if (optab_handler (builtin_optab, mode) == CODE_FOR_nothing)
2015     return NULL_RTX;
2016
2017   result = gen_reg_rtx (mode);
2018
2019   /* Always stabilize the argument list.  */
2020   CALL_EXPR_ARG (exp, 0) = arg0 = builtin_save_expr (arg0);
2021   CALL_EXPR_ARG (exp, 1) = arg1 = builtin_save_expr (arg1);
2022   CALL_EXPR_ARG (exp, 2) = arg2 = builtin_save_expr (arg2);
2023
2024   op0 = expand_expr (arg0, subtarget, VOIDmode, EXPAND_NORMAL);
2025   op1 = expand_normal (arg1);
2026   op2 = expand_normal (arg2);
2027
2028   start_sequence ();
2029
2030   /* Compute into RESULT.
2031      Set RESULT to wherever the result comes back.  */
2032   result = expand_ternary_op (mode, builtin_optab, op0, op1, op2,
2033                               result, 0);
2034
2035   /* If we were unable to expand via the builtin, stop the sequence
2036      (without outputting the insns) and call to the library function
2037      with the stabilized argument list.  */
2038   if (result == 0)
2039     {
2040       end_sequence ();
2041       return expand_call (exp, target, target == const0_rtx);
2042     }
2043
2044   /* Output the entire sequence.  */
2045   insns = get_insns ();
2046   end_sequence ();
2047   emit_insn (insns);
2048
2049   return result;
2050 }
2051
2052 /* Expand a call to the builtin sin and cos math functions.
2053    Return NULL_RTX if a normal call should be emitted rather than expanding the
2054    function in-line.  EXP is the expression that is a call to the builtin
2055    function; if convenient, the result should be placed in TARGET.
2056    SUBTARGET may be used as the target for computing one of EXP's
2057    operands.  */
2058
2059 static rtx
2060 expand_builtin_mathfn_3 (tree exp, rtx target, rtx subtarget)
2061 {
2062   optab builtin_optab;
2063   rtx op0;
2064   rtx_insn *insns;
2065   tree fndecl = get_callee_fndecl (exp);
2066   machine_mode mode;
2067   tree arg;
2068
2069   if (!validate_arglist (exp, REAL_TYPE, VOID_TYPE))
2070     return NULL_RTX;
2071
2072   arg = CALL_EXPR_ARG (exp, 0);
2073
2074   switch (DECL_FUNCTION_CODE (fndecl))
2075     {
2076     CASE_FLT_FN (BUILT_IN_SIN):
2077     CASE_FLT_FN (BUILT_IN_COS):
2078       builtin_optab = sincos_optab; break;
2079     default:
2080       gcc_unreachable ();
2081     }
2082
2083   /* Make a suitable register to place result in.  */
2084   mode = TYPE_MODE (TREE_TYPE (exp));
2085
2086   /* Check if sincos insn is available, otherwise fallback
2087      to sin or cos insn.  */
2088   if (optab_handler (builtin_optab, mode) == CODE_FOR_nothing)
2089     switch (DECL_FUNCTION_CODE (fndecl))
2090       {
2091       CASE_FLT_FN (BUILT_IN_SIN):
2092         builtin_optab = sin_optab; break;
2093       CASE_FLT_FN (BUILT_IN_COS):
2094         builtin_optab = cos_optab; break;
2095       default:
2096         gcc_unreachable ();
2097       }
2098
2099   /* Before working hard, check whether the instruction is available.  */
2100   if (optab_handler (builtin_optab, mode) != CODE_FOR_nothing)
2101     {
2102       rtx result = gen_reg_rtx (mode);
2103
2104       /* Wrap the computation of the argument in a SAVE_EXPR, as we may
2105          need to expand the argument again.  This way, we will not perform
2106          side-effects more the once.  */
2107       CALL_EXPR_ARG (exp, 0) = arg = builtin_save_expr (arg);
2108
2109       op0 = expand_expr (arg, subtarget, VOIDmode, EXPAND_NORMAL);
2110
2111       start_sequence ();
2112
2113       /* Compute into RESULT.
2114          Set RESULT to wherever the result comes back.  */
2115       if (builtin_optab == sincos_optab)
2116         {
2117           int ok;
2118
2119           switch (DECL_FUNCTION_CODE (fndecl))
2120             {
2121             CASE_FLT_FN (BUILT_IN_SIN):
2122               ok = expand_twoval_unop (builtin_optab, op0, 0, result, 0);
2123               break;
2124             CASE_FLT_FN (BUILT_IN_COS):
2125               ok = expand_twoval_unop (builtin_optab, op0, result, 0, 0);
2126               break;
2127             default:
2128               gcc_unreachable ();
2129             }
2130           gcc_assert (ok);
2131         }
2132       else
2133         result = expand_unop (mode, builtin_optab, op0, result, 0);
2134
2135       if (result != 0)
2136         {
2137           /* Output the entire sequence.  */
2138           insns = get_insns ();
2139           end_sequence ();
2140           emit_insn (insns);
2141           return result;
2142         }
2143
2144       /* If we were unable to expand via the builtin, stop the sequence
2145          (without outputting the insns) and call to the library function
2146          with the stabilized argument list.  */
2147       end_sequence ();
2148     }
2149
2150   return expand_call (exp, target, target == const0_rtx);
2151 }
2152
2153 /* Given an interclass math builtin decl FNDECL and it's argument ARG
2154    return an RTL instruction code that implements the functionality.
2155    If that isn't possible or available return CODE_FOR_nothing.  */
2156
2157 static enum insn_code
2158 interclass_mathfn_icode (tree arg, tree fndecl)
2159 {
2160   bool errno_set = false;
2161   optab builtin_optab = unknown_optab;
2162   machine_mode mode;
2163
2164   switch (DECL_FUNCTION_CODE (fndecl))
2165     {
2166     CASE_FLT_FN (BUILT_IN_ILOGB):
2167       errno_set = true; builtin_optab = ilogb_optab; break;
2168     CASE_FLT_FN (BUILT_IN_ISINF):
2169       builtin_optab = isinf_optab; break;
2170     case BUILT_IN_ISNORMAL:
2171     case BUILT_IN_ISFINITE:
2172     CASE_FLT_FN (BUILT_IN_FINITE):
2173     case BUILT_IN_FINITED32:
2174     case BUILT_IN_FINITED64:
2175     case BUILT_IN_FINITED128:
2176     case BUILT_IN_ISINFD32:
2177     case BUILT_IN_ISINFD64:
2178     case BUILT_IN_ISINFD128:
2179       /* These builtins have no optabs (yet).  */
2180       break;
2181     default:
2182       gcc_unreachable ();
2183     }
2184
2185   /* There's no easy way to detect the case we need to set EDOM.  */
2186   if (flag_errno_math && errno_set)
2187     return CODE_FOR_nothing;
2188
2189   /* Optab mode depends on the mode of the input argument.  */
2190   mode = TYPE_MODE (TREE_TYPE (arg));
2191
2192   if (builtin_optab)
2193     return optab_handler (builtin_optab, mode);
2194   return CODE_FOR_nothing;
2195 }
2196
2197 /* Expand a call to one of the builtin math functions that operate on
2198    floating point argument and output an integer result (ilogb, isinf,
2199    isnan, etc).
2200    Return 0 if a normal call should be emitted rather than expanding the
2201    function in-line.  EXP is the expression that is a call to the builtin
2202    function; if convenient, the result should be placed in TARGET.  */
2203
2204 static rtx
2205 expand_builtin_interclass_mathfn (tree exp, rtx target)
2206 {
2207   enum insn_code icode = CODE_FOR_nothing;
2208   rtx op0;
2209   tree fndecl = get_callee_fndecl (exp);
2210   machine_mode mode;
2211   tree arg;
2212
2213   if (!validate_arglist (exp, REAL_TYPE, VOID_TYPE))
2214     return NULL_RTX;
2215
2216   arg = CALL_EXPR_ARG (exp, 0);
2217   icode = interclass_mathfn_icode (arg, fndecl);
2218   mode = TYPE_MODE (TREE_TYPE (arg));
2219
2220   if (icode != CODE_FOR_nothing)
2221     {
2222       struct expand_operand ops[1];
2223       rtx_insn *last = get_last_insn ();
2224       tree orig_arg = arg;
2225
2226       /* Wrap the computation of the argument in a SAVE_EXPR, as we may
2227          need to expand the argument again.  This way, we will not perform
2228          side-effects more the once.  */
2229       CALL_EXPR_ARG (exp, 0) = arg = builtin_save_expr (arg);
2230
2231       op0 = expand_expr (arg, NULL_RTX, VOIDmode, EXPAND_NORMAL);
2232
2233       if (mode != GET_MODE (op0))
2234         op0 = convert_to_mode (mode, op0, 0);
2235
2236       create_output_operand (&ops[0], target, TYPE_MODE (TREE_TYPE (exp)));
2237       if (maybe_legitimize_operands (icode, 0, 1, ops)
2238           && maybe_emit_unop_insn (icode, ops[0].value, op0, UNKNOWN))
2239         return ops[0].value;
2240
2241       delete_insns_since (last);
2242       CALL_EXPR_ARG (exp, 0) = orig_arg;
2243     }
2244
2245   return NULL_RTX;
2246 }
2247
2248 /* Expand a call to the builtin sincos math function.
2249    Return NULL_RTX if a normal call should be emitted rather than expanding the
2250    function in-line.  EXP is the expression that is a call to the builtin
2251    function.  */
2252
2253 static rtx
2254 expand_builtin_sincos (tree exp)
2255 {
2256   rtx op0, op1, op2, target1, target2;
2257   machine_mode mode;
2258   tree arg, sinp, cosp;
2259   int result;
2260   location_t loc = EXPR_LOCATION (exp);
2261   tree alias_type, alias_off;
2262
2263   if (!validate_arglist (exp, REAL_TYPE,
2264                          POINTER_TYPE, POINTER_TYPE, VOID_TYPE))
2265     return NULL_RTX;
2266
2267   arg = CALL_EXPR_ARG (exp, 0);
2268   sinp = CALL_EXPR_ARG (exp, 1);
2269   cosp = CALL_EXPR_ARG (exp, 2);
2270
2271   /* Make a suitable register to place result in.  */
2272   mode = TYPE_MODE (TREE_TYPE (arg));
2273
2274   /* Check if sincos insn is available, otherwise emit the call.  */
2275   if (optab_handler (sincos_optab, mode) == CODE_FOR_nothing)
2276     return NULL_RTX;
2277
2278   target1 = gen_reg_rtx (mode);
2279   target2 = gen_reg_rtx (mode);
2280
2281   op0 = expand_normal (arg);
2282   alias_type = build_pointer_type_for_mode (TREE_TYPE (arg), ptr_mode, true);
2283   alias_off = build_int_cst (alias_type, 0);
2284   op1 = expand_normal (fold_build2_loc (loc, MEM_REF, TREE_TYPE (arg),
2285                                         sinp, alias_off));
2286   op2 = expand_normal (fold_build2_loc (loc, MEM_REF, TREE_TYPE (arg),
2287                                         cosp, alias_off));
2288
2289   /* Compute into target1 and target2.
2290      Set TARGET to wherever the result comes back.  */
2291   result = expand_twoval_unop (sincos_optab, op0, target2, target1, 0);
2292   gcc_assert (result);
2293
2294   /* Move target1 and target2 to the memory locations indicated
2295      by op1 and op2.  */
2296   emit_move_insn (op1, target1);
2297   emit_move_insn (op2, target2);
2298
2299   return const0_rtx;
2300 }
2301
2302 /* Expand a call to the internal cexpi builtin to the sincos math function.
2303    EXP is the expression that is a call to the builtin function; if convenient,
2304    the result should be placed in TARGET.  */
2305
2306 static rtx
2307 expand_builtin_cexpi (tree exp, rtx target)
2308 {
2309   tree fndecl = get_callee_fndecl (exp);
2310   tree arg, type;
2311   machine_mode mode;
2312   rtx op0, op1, op2;
2313   location_t loc = EXPR_LOCATION (exp);
2314
2315   if (!validate_arglist (exp, REAL_TYPE, VOID_TYPE))
2316     return NULL_RTX;
2317
2318   arg = CALL_EXPR_ARG (exp, 0);
2319   type = TREE_TYPE (arg);
2320   mode = TYPE_MODE (TREE_TYPE (arg));
2321
2322   /* Try expanding via a sincos optab, fall back to emitting a libcall
2323      to sincos or cexp.  We are sure we have sincos or cexp because cexpi
2324      is only generated from sincos, cexp or if we have either of them.  */
2325   if (optab_handler (sincos_optab, mode) != CODE_FOR_nothing)
2326     {
2327       op1 = gen_reg_rtx (mode);
2328       op2 = gen_reg_rtx (mode);
2329
2330       op0 = expand_expr (arg, NULL_RTX, VOIDmode, EXPAND_NORMAL);
2331
2332       /* Compute into op1 and op2.  */
2333       expand_twoval_unop (sincos_optab, op0, op2, op1, 0);
2334     }
2335   else if (targetm.libc_has_function (function_sincos))
2336     {
2337       tree call, fn = NULL_TREE;
2338       tree top1, top2;
2339       rtx op1a, op2a;
2340
2341       if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPIF)
2342         fn = builtin_decl_explicit (BUILT_IN_SINCOSF);
2343       else if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPI)
2344         fn = builtin_decl_explicit (BUILT_IN_SINCOS);
2345       else if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPIL)
2346         fn = builtin_decl_explicit (BUILT_IN_SINCOSL);
2347       else
2348         gcc_unreachable ();
2349
2350       op1 = assign_temp (TREE_TYPE (arg), 1, 1);
2351       op2 = assign_temp (TREE_TYPE (arg), 1, 1);
2352       op1a = copy_addr_to_reg (XEXP (op1, 0));
2353       op2a = copy_addr_to_reg (XEXP (op2, 0));
2354       top1 = make_tree (build_pointer_type (TREE_TYPE (arg)), op1a);
2355       top2 = make_tree (build_pointer_type (TREE_TYPE (arg)), op2a);
2356
2357       /* Make sure not to fold the sincos call again.  */
2358       call = build1 (ADDR_EXPR, build_pointer_type (TREE_TYPE (fn)), fn);
2359       expand_normal (build_call_nary (TREE_TYPE (TREE_TYPE (fn)),
2360                                       call, 3, arg, top1, top2));
2361     }
2362   else
2363     {
2364       tree call, fn = NULL_TREE, narg;
2365       tree ctype = build_complex_type (type);
2366
2367       if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPIF)
2368         fn = builtin_decl_explicit (BUILT_IN_CEXPF);
2369       else if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPI)
2370         fn = builtin_decl_explicit (BUILT_IN_CEXP);
2371       else if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPIL)
2372         fn = builtin_decl_explicit (BUILT_IN_CEXPL);
2373       else
2374         gcc_unreachable ();
2375
2376       /* If we don't have a decl for cexp create one.  This is the
2377          friendliest fallback if the user calls __builtin_cexpi
2378          without full target C99 function support.  */
2379       if (fn == NULL_TREE)
2380         {
2381           tree fntype;
2382           const char *name = NULL;
2383
2384           if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPIF)
2385             name = "cexpf";
2386           else if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPI)
2387             name = "cexp";
2388           else if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPIL)
2389             name = "cexpl";
2390
2391           fntype = build_function_type_list (ctype, ctype, NULL_TREE);
2392           fn = build_fn_decl (name, fntype);
2393         }
2394
2395       narg = fold_build2_loc (loc, COMPLEX_EXPR, ctype,
2396                           build_real (type, dconst0), arg);
2397
2398       /* Make sure not to fold the cexp call again.  */
2399       call = build1 (ADDR_EXPR, build_pointer_type (TREE_TYPE (fn)), fn);
2400       return expand_expr (build_call_nary (ctype, call, 1, narg),
2401                           target, VOIDmode, EXPAND_NORMAL);
2402     }
2403
2404   /* Now build the proper return type.  */
2405   return expand_expr (build2 (COMPLEX_EXPR, build_complex_type (type),
2406                               make_tree (TREE_TYPE (arg), op2),
2407                               make_tree (TREE_TYPE (arg), op1)),
2408                       target, VOIDmode, EXPAND_NORMAL);
2409 }
2410
2411 /* Conveniently construct a function call expression.  FNDECL names the
2412    function to be called, N is the number of arguments, and the "..."
2413    parameters are the argument expressions.  Unlike build_call_exr
2414    this doesn't fold the call, hence it will always return a CALL_EXPR.  */
2415
2416 static tree
2417 build_call_nofold_loc (location_t loc, tree fndecl, int n, ...)
2418 {
2419   va_list ap;
2420   tree fntype = TREE_TYPE (fndecl);
2421   tree fn = build1 (ADDR_EXPR, build_pointer_type (fntype), fndecl);
2422
2423   va_start (ap, n);
2424   fn = build_call_valist (TREE_TYPE (fntype), fn, n, ap);
2425   va_end (ap);
2426   SET_EXPR_LOCATION (fn, loc);
2427   return fn;
2428 }
2429
2430 /* Expand a call to one of the builtin rounding functions gcc defines
2431    as an extension (lfloor and lceil).  As these are gcc extensions we
2432    do not need to worry about setting errno to EDOM.
2433    If expanding via optab fails, lower expression to (int)(floor(x)).
2434    EXP is the expression that is a call to the builtin function;
2435    if convenient, the result should be placed in TARGET.  */
2436
2437 static rtx
2438 expand_builtin_int_roundingfn (tree exp, rtx target)
2439 {
2440   convert_optab builtin_optab;
2441   rtx op0, tmp;
2442   rtx_insn *insns;
2443   tree fndecl = get_callee_fndecl (exp);
2444   enum built_in_function fallback_fn;
2445   tree fallback_fndecl;
2446   machine_mode mode;
2447   tree arg;
2448
2449   if (!validate_arglist (exp, REAL_TYPE, VOID_TYPE))
2450     gcc_unreachable ();
2451
2452   arg = CALL_EXPR_ARG (exp, 0);
2453
2454   switch (DECL_FUNCTION_CODE (fndecl))
2455     {
2456     CASE_FLT_FN (BUILT_IN_ICEIL):
2457     CASE_FLT_FN (BUILT_IN_LCEIL):
2458     CASE_FLT_FN (BUILT_IN_LLCEIL):
2459       builtin_optab = lceil_optab;
2460       fallback_fn = BUILT_IN_CEIL;
2461       break;
2462
2463     CASE_FLT_FN (BUILT_IN_IFLOOR):
2464     CASE_FLT_FN (BUILT_IN_LFLOOR):
2465     CASE_FLT_FN (BUILT_IN_LLFLOOR):
2466       builtin_optab = lfloor_optab;
2467       fallback_fn = BUILT_IN_FLOOR;
2468       break;
2469
2470     default:
2471       gcc_unreachable ();
2472     }
2473
2474   /* Make a suitable register to place result in.  */
2475   mode = TYPE_MODE (TREE_TYPE (exp));
2476
2477   target = gen_reg_rtx (mode);
2478
2479   /* Wrap the computation of the argument in a SAVE_EXPR, as we may
2480      need to expand the argument again.  This way, we will not perform
2481      side-effects more the once.  */
2482   CALL_EXPR_ARG (exp, 0) = arg = builtin_save_expr (arg);
2483
2484   op0 = expand_expr (arg, NULL, VOIDmode, EXPAND_NORMAL);
2485
2486   start_sequence ();
2487
2488   /* Compute into TARGET.  */
2489   if (expand_sfix_optab (target, op0, builtin_optab))
2490     {
2491       /* Output the entire sequence.  */
2492       insns = get_insns ();
2493       end_sequence ();
2494       emit_insn (insns);
2495       return target;
2496     }
2497
2498   /* If we were unable to expand via the builtin, stop the sequence
2499      (without outputting the insns).  */
2500   end_sequence ();
2501
2502   /* Fall back to floating point rounding optab.  */
2503   fallback_fndecl = mathfn_built_in (TREE_TYPE (arg), fallback_fn);
2504
2505   /* For non-C99 targets we may end up without a fallback fndecl here
2506      if the user called __builtin_lfloor directly.  In this case emit
2507      a call to the floor/ceil variants nevertheless.  This should result
2508      in the best user experience for not full C99 targets.  */
2509   if (fallback_fndecl == NULL_TREE)
2510     {
2511       tree fntype;
2512       const char *name = NULL;
2513
2514       switch (DECL_FUNCTION_CODE (fndecl))
2515         {
2516         case BUILT_IN_ICEIL:
2517         case BUILT_IN_LCEIL:
2518         case BUILT_IN_LLCEIL:
2519           name = "ceil";
2520           break;
2521         case BUILT_IN_ICEILF:
2522         case BUILT_IN_LCEILF:
2523         case BUILT_IN_LLCEILF:
2524           name = "ceilf";
2525           break;
2526         case BUILT_IN_ICEILL:
2527         case BUILT_IN_LCEILL:
2528         case BUILT_IN_LLCEILL:
2529           name = "ceill";
2530           break;
2531         case BUILT_IN_IFLOOR:
2532         case BUILT_IN_LFLOOR:
2533         case BUILT_IN_LLFLOOR:
2534           name = "floor";
2535           break;
2536         case BUILT_IN_IFLOORF:
2537         case BUILT_IN_LFLOORF:
2538         case BUILT_IN_LLFLOORF:
2539           name = "floorf";
2540           break;
2541         case BUILT_IN_IFLOORL:
2542         case BUILT_IN_LFLOORL:
2543         case BUILT_IN_LLFLOORL:
2544           name = "floorl";
2545           break;
2546         default:
2547           gcc_unreachable ();
2548         }
2549
2550       fntype = build_function_type_list (TREE_TYPE (arg),
2551                                          TREE_TYPE (arg), NULL_TREE);
2552       fallback_fndecl = build_fn_decl (name, fntype);
2553     }
2554
2555   exp = build_call_nofold_loc (EXPR_LOCATION (exp), fallback_fndecl, 1, arg);
2556
2557   tmp = expand_normal (exp);
2558   tmp = maybe_emit_group_store (tmp, TREE_TYPE (exp));
2559
2560   /* Truncate the result of floating point optab to integer
2561      via expand_fix ().  */
2562   target = gen_reg_rtx (mode);
2563   expand_fix (target, tmp, 0);
2564
2565   return target;
2566 }
2567
2568 /* Expand a call to one of the builtin math functions doing integer
2569    conversion (lrint).
2570    Return 0 if a normal call should be emitted rather than expanding the
2571    function in-line.  EXP is the expression that is a call to the builtin
2572    function; if convenient, the result should be placed in TARGET.  */
2573
2574 static rtx
2575 expand_builtin_int_roundingfn_2 (tree exp, rtx target)
2576 {
2577   convert_optab builtin_optab;
2578   rtx op0;
2579   rtx_insn *insns;
2580   tree fndecl = get_callee_fndecl (exp);
2581   tree arg;
2582   machine_mode mode;
2583   enum built_in_function fallback_fn = BUILT_IN_NONE;
2584
2585   if (!validate_arglist (exp, REAL_TYPE, VOID_TYPE))
2586      gcc_unreachable ();
2587
2588   arg = CALL_EXPR_ARG (exp, 0);
2589
2590   switch (DECL_FUNCTION_CODE (fndecl))
2591     {
2592     CASE_FLT_FN (BUILT_IN_IRINT):
2593       fallback_fn = BUILT_IN_LRINT;
2594       gcc_fallthrough ();
2595     CASE_FLT_FN (BUILT_IN_LRINT):
2596     CASE_FLT_FN (BUILT_IN_LLRINT):
2597       builtin_optab = lrint_optab;
2598       break;
2599
2600     CASE_FLT_FN (BUILT_IN_IROUND):
2601       fallback_fn = BUILT_IN_LROUND;
2602       gcc_fallthrough ();
2603     CASE_FLT_FN (BUILT_IN_LROUND):
2604     CASE_FLT_FN (BUILT_IN_LLROUND):
2605       builtin_optab = lround_optab;
2606       break;
2607
2608     default:
2609       gcc_unreachable ();
2610     }
2611
2612   /* There's no easy way to detect the case we need to set EDOM.  */
2613   if (flag_errno_math && fallback_fn == BUILT_IN_NONE)
2614     return NULL_RTX;
2615
2616   /* Make a suitable register to place result in.  */
2617   mode = TYPE_MODE (TREE_TYPE (exp));
2618
2619   /* There's no easy way to detect the case we need to set EDOM.  */
2620   if (!flag_errno_math)
2621     {
2622       rtx result = gen_reg_rtx (mode);
2623
2624       /* Wrap the computation of the argument in a SAVE_EXPR, as we may
2625          need to expand the argument again.  This way, we will not perform
2626          side-effects more the once.  */
2627       CALL_EXPR_ARG (exp, 0) = arg = builtin_save_expr (arg);
2628
2629       op0 = expand_expr (arg, NULL, VOIDmode, EXPAND_NORMAL);
2630
2631       start_sequence ();
2632
2633       if (expand_sfix_optab (result, op0, builtin_optab))
2634         {
2635           /* Output the entire sequence.  */
2636           insns = get_insns ();
2637           end_sequence ();
2638           emit_insn (insns);
2639           return result;
2640         }
2641
2642       /* If we were unable to expand via the builtin, stop the sequence
2643          (without outputting the insns) and call to the library function
2644          with the stabilized argument list.  */
2645       end_sequence ();
2646     }
2647
2648   if (fallback_fn != BUILT_IN_NONE)
2649     {
2650       /* Fall back to rounding to long int.  Use implicit_p 0 - for non-C99
2651          targets, (int) round (x) should never be transformed into
2652          BUILT_IN_IROUND and if __builtin_iround is called directly, emit
2653          a call to lround in the hope that the target provides at least some
2654          C99 functions.  This should result in the best user experience for
2655          not full C99 targets.  */
2656       tree fallback_fndecl = mathfn_built_in_1
2657         (TREE_TYPE (arg), as_combined_fn (fallback_fn), 0);
2658
2659       exp = build_call_nofold_loc (EXPR_LOCATION (exp),
2660                                    fallback_fndecl, 1, arg);
2661
2662       target = expand_call (exp, NULL_RTX, target == const0_rtx);
2663       target = maybe_emit_group_store (target, TREE_TYPE (exp));
2664       return convert_to_mode (mode, target, 0);
2665     }
2666
2667   return expand_call (exp, target, target == const0_rtx);
2668 }
2669
2670 /* Expand a call to the powi built-in mathematical function.  Return NULL_RTX if
2671    a normal call should be emitted rather than expanding the function
2672    in-line.  EXP is the expression that is a call to the builtin
2673    function; if convenient, the result should be placed in TARGET.  */
2674
2675 static rtx
2676 expand_builtin_powi (tree exp, rtx target)
2677 {
2678   tree arg0, arg1;
2679   rtx op0, op1;
2680   machine_mode mode;
2681   machine_mode mode2;
2682
2683   if (! validate_arglist (exp, REAL_TYPE, INTEGER_TYPE, VOID_TYPE))
2684     return NULL_RTX;
2685
2686   arg0 = CALL_EXPR_ARG (exp, 0);
2687   arg1 = CALL_EXPR_ARG (exp, 1);
2688   mode = TYPE_MODE (TREE_TYPE (exp));
2689
2690   /* Emit a libcall to libgcc.  */
2691
2692   /* Mode of the 2nd argument must match that of an int.  */
2693   mode2 = mode_for_size (INT_TYPE_SIZE, MODE_INT, 0);
2694
2695   if (target == NULL_RTX)
2696     target = gen_reg_rtx (mode);
2697
2698   op0 = expand_expr (arg0, NULL_RTX, mode, EXPAND_NORMAL);
2699   if (GET_MODE (op0) != mode)
2700     op0 = convert_to_mode (mode, op0, 0);
2701   op1 = expand_expr (arg1, NULL_RTX, mode2, EXPAND_NORMAL);
2702   if (GET_MODE (op1) != mode2)
2703     op1 = convert_to_mode (mode2, op1, 0);
2704
2705   target = emit_library_call_value (optab_libfunc (powi_optab, mode),
2706                                     target, LCT_CONST, mode, 2,
2707                                     op0, mode, op1, mode2);
2708
2709   return target;
2710 }
2711
2712 /* Expand expression EXP which is a call to the strlen builtin.  Return
2713    NULL_RTX if we failed the caller should emit a normal call, otherwise
2714    try to get the result in TARGET, if convenient.  */
2715
2716 static rtx
2717 expand_builtin_strlen (tree exp, rtx target,
2718                        machine_mode target_mode)
2719 {
2720   if (!validate_arglist (exp, POINTER_TYPE, VOID_TYPE))
2721     return NULL_RTX;
2722   else
2723     {
2724       struct expand_operand ops[4];
2725       rtx pat;
2726       tree len;
2727       tree src = CALL_EXPR_ARG (exp, 0);
2728       rtx src_reg;
2729       rtx_insn *before_strlen;
2730       machine_mode insn_mode = target_mode;
2731       enum insn_code icode = CODE_FOR_nothing;
2732       unsigned int align;
2733
2734       /* If the length can be computed at compile-time, return it.  */
2735       len = c_strlen (src, 0);
2736       if (len)
2737         return expand_expr (len, target, target_mode, EXPAND_NORMAL);
2738
2739       /* If the length can be computed at compile-time and is constant
2740          integer, but there are side-effects in src, evaluate
2741          src for side-effects, then return len.
2742          E.g. x = strlen (i++ ? "xfoo" + 1 : "bar");
2743          can be optimized into: i++; x = 3;  */
2744       len = c_strlen (src, 1);
2745       if (len && TREE_CODE (len) == INTEGER_CST)
2746         {
2747           expand_expr (src, const0_rtx, VOIDmode, EXPAND_NORMAL);
2748           return expand_expr (len, target, target_mode, EXPAND_NORMAL);
2749         }
2750
2751       align = get_pointer_alignment (src) / BITS_PER_UNIT;
2752
2753       /* If SRC is not a pointer type, don't do this operation inline.  */
2754       if (align == 0)
2755         return NULL_RTX;
2756
2757       /* Bail out if we can't compute strlen in the right mode.  */
2758       while (insn_mode != VOIDmode)
2759         {
2760           icode = optab_handler (strlen_optab, insn_mode);
2761           if (icode != CODE_FOR_nothing)
2762             break;
2763
2764           insn_mode = GET_MODE_WIDER_MODE (insn_mode);
2765         }
2766       if (insn_mode == VOIDmode)
2767         return NULL_RTX;
2768
2769       /* Make a place to hold the source address.  We will not expand
2770          the actual source until we are sure that the expansion will
2771          not fail -- there are trees that cannot be expanded twice.  */
2772       src_reg = gen_reg_rtx (Pmode);
2773
2774       /* Mark the beginning of the strlen sequence so we can emit the
2775          source operand later.  */
2776       before_strlen = get_last_insn ();
2777
2778       create_output_operand (&ops[0], target, insn_mode);
2779       create_fixed_operand (&ops[1], gen_rtx_MEM (BLKmode, src_reg));
2780       create_integer_operand (&ops[2], 0);
2781       create_integer_operand (&ops[3], align);
2782       if (!maybe_expand_insn (icode, 4, ops))
2783         return NULL_RTX;
2784
2785       /* Now that we are assured of success, expand the source.  */
2786       start_sequence ();
2787       pat = expand_expr (src, src_reg, Pmode, EXPAND_NORMAL);
2788       if (pat != src_reg)
2789         {
2790 #ifdef POINTERS_EXTEND_UNSIGNED
2791           if (GET_MODE (pat) != Pmode)
2792             pat = convert_to_mode (Pmode, pat,
2793                                    POINTERS_EXTEND_UNSIGNED);
2794 #endif
2795           emit_move_insn (src_reg, pat);
2796         }
2797       pat = get_insns ();
2798       end_sequence ();
2799
2800       if (before_strlen)
2801         emit_insn_after (pat, before_strlen);
2802       else
2803         emit_insn_before (pat, get_insns ());
2804
2805       /* Return the value in the proper mode for this function.  */
2806       if (GET_MODE (ops[0].value) == target_mode)
2807         target = ops[0].value;
2808       else if (target != 0)
2809         convert_move (target, ops[0].value, 0);
2810       else
2811         target = convert_to_mode (target_mode, ops[0].value, 0);
2812
2813       return target;
2814     }
2815 }
2816
2817 /* Callback routine for store_by_pieces.  Read GET_MODE_BITSIZE (MODE)
2818    bytes from constant string DATA + OFFSET and return it as target
2819    constant.  */
2820
2821 static rtx
2822 builtin_memcpy_read_str (void *data, HOST_WIDE_INT offset,
2823                          machine_mode mode)
2824 {
2825   const char *str = (const char *) data;
2826
2827   gcc_assert (offset >= 0
2828               && ((unsigned HOST_WIDE_INT) offset + GET_MODE_SIZE (mode)
2829                   <= strlen (str) + 1));
2830
2831   return c_readstr (str + offset, mode);
2832 }
2833
2834 /* LEN specify length of the block of memcpy/memset operation.
2835    Figure out its range and put it into MIN_SIZE/MAX_SIZE. 
2836    In some cases we can make very likely guess on max size, then we
2837    set it into PROBABLE_MAX_SIZE.  */
2838
2839 static void
2840 determine_block_size (tree len, rtx len_rtx,
2841                       unsigned HOST_WIDE_INT *min_size,
2842                       unsigned HOST_WIDE_INT *max_size,
2843                       unsigned HOST_WIDE_INT *probable_max_size)
2844 {
2845   if (CONST_INT_P (len_rtx))
2846     {
2847       *min_size = *max_size = *probable_max_size = UINTVAL (len_rtx);
2848       return;
2849     }
2850   else
2851     {
2852       wide_int min, max;
2853       enum value_range_type range_type = VR_UNDEFINED;
2854
2855       /* Determine bounds from the type.  */
2856       if (tree_fits_uhwi_p (TYPE_MIN_VALUE (TREE_TYPE (len))))
2857         *min_size = tree_to_uhwi (TYPE_MIN_VALUE (TREE_TYPE (len)));
2858       else
2859         *min_size = 0;
2860       if (tree_fits_uhwi_p (TYPE_MAX_VALUE (TREE_TYPE (len))))
2861         *probable_max_size = *max_size
2862           = tree_to_uhwi (TYPE_MAX_VALUE (TREE_TYPE (len)));
2863       else
2864         *probable_max_size = *max_size = GET_MODE_MASK (GET_MODE (len_rtx));
2865
2866       if (TREE_CODE (len) == SSA_NAME)
2867         range_type = get_range_info (len, &min, &max);
2868       if (range_type == VR_RANGE)
2869         {
2870           if (wi::fits_uhwi_p (min) && *min_size < min.to_uhwi ())
2871             *min_size = min.to_uhwi ();
2872           if (wi::fits_uhwi_p (max) && *max_size > max.to_uhwi ())
2873             *probable_max_size = *max_size = max.to_uhwi ();
2874         }
2875       else if (range_type == VR_ANTI_RANGE)
2876         {
2877           /* Anti range 0...N lets us to determine minimal size to N+1.  */
2878           if (min == 0)
2879             {
2880               if (wi::fits_uhwi_p (max) && max.to_uhwi () + 1 != 0)
2881                 *min_size = max.to_uhwi () + 1;
2882             }
2883           /* Code like
2884
2885              int n;
2886              if (n < 100)
2887                memcpy (a, b, n)
2888
2889              Produce anti range allowing negative values of N.  We still
2890              can use the information and make a guess that N is not negative.
2891              */
2892           else if (!wi::leu_p (max, 1 << 30) && wi::fits_uhwi_p (min))
2893             *probable_max_size = min.to_uhwi () - 1;
2894         }
2895     }
2896   gcc_checking_assert (*max_size <=
2897                        (unsigned HOST_WIDE_INT)
2898                           GET_MODE_MASK (GET_MODE (len_rtx)));
2899 }
2900
2901 /* Helper function to do the actual work for expand_builtin_memcpy.  */
2902
2903 static rtx
2904 expand_builtin_memcpy_args (tree dest, tree src, tree len, rtx target, tree exp)
2905 {
2906   const char *src_str;
2907   unsigned int src_align = get_pointer_alignment (src);
2908   unsigned int dest_align = get_pointer_alignment (dest);
2909   rtx dest_mem, src_mem, dest_addr, len_rtx;
2910   HOST_WIDE_INT expected_size = -1;
2911   unsigned int expected_align = 0;
2912   unsigned HOST_WIDE_INT min_size;
2913   unsigned HOST_WIDE_INT max_size;
2914   unsigned HOST_WIDE_INT probable_max_size;
2915
2916   /* If DEST is not a pointer type, call the normal function.  */
2917   if (dest_align == 0)
2918     return NULL_RTX;
2919
2920   /* If either SRC is not a pointer type, don't do this
2921      operation in-line.  */
2922   if (src_align == 0)
2923     return NULL_RTX;
2924
2925   if (currently_expanding_gimple_stmt)
2926     stringop_block_profile (currently_expanding_gimple_stmt,
2927                             &expected_align, &expected_size);
2928
2929   if (expected_align < dest_align)
2930     expected_align = dest_align;
2931   dest_mem = get_memory_rtx (dest, len);
2932   set_mem_align (dest_mem, dest_align);
2933   len_rtx = expand_normal (len);
2934   determine_block_size (len, len_rtx, &min_size, &max_size,
2935                         &probable_max_size);
2936   src_str = c_getstr (src);
2937
2938   /* If SRC is a string constant and block move would be done
2939      by pieces, we can avoid loading the string from memory
2940      and only stored the computed constants.  */
2941   if (src_str
2942       && CONST_INT_P (len_rtx)
2943       && (unsigned HOST_WIDE_INT) INTVAL (len_rtx) <= strlen (src_str) + 1
2944       && can_store_by_pieces (INTVAL (len_rtx), builtin_memcpy_read_str,
2945                               CONST_CAST (char *, src_str),
2946                               dest_align, false))
2947     {
2948       dest_mem = store_by_pieces (dest_mem, INTVAL (len_rtx),
2949                                   builtin_memcpy_read_str,
2950                                   CONST_CAST (char *, src_str),
2951                                   dest_align, false, 0);
2952       dest_mem = force_operand (XEXP (dest_mem, 0), target);
2953       dest_mem = convert_memory_address (ptr_mode, dest_mem);
2954       return dest_mem;
2955     }
2956
2957   src_mem = get_memory_rtx (src, len);
2958   set_mem_align (src_mem, src_align);
2959
2960   /* Copy word part most expediently.  */
2961   dest_addr = emit_block_move_hints (dest_mem, src_mem, len_rtx,
2962                                      CALL_EXPR_TAILCALL (exp)
2963                                      ? BLOCK_OP_TAILCALL : BLOCK_OP_NORMAL,
2964                                      expected_align, expected_size,
2965                                      min_size, max_size, probable_max_size);
2966
2967   if (dest_addr == 0)
2968     {
2969       dest_addr = force_operand (XEXP (dest_mem, 0), target);
2970       dest_addr = convert_memory_address (ptr_mode, dest_addr);
2971     }
2972
2973   return dest_addr;
2974 }
2975
2976 /* Expand a call EXP to the memcpy builtin.
2977    Return NULL_RTX if we failed, the caller should emit a normal call,
2978    otherwise try to get the result in TARGET, if convenient (and in
2979    mode MODE if that's convenient).  */
2980
2981 static rtx
2982 expand_builtin_memcpy (tree exp, rtx target)
2983 {
2984   if (!validate_arglist (exp,
2985                          POINTER_TYPE, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
2986     return NULL_RTX;
2987   else
2988     {
2989       tree dest = CALL_EXPR_ARG (exp, 0);
2990       tree src = CALL_EXPR_ARG (exp, 1);
2991       tree len = CALL_EXPR_ARG (exp, 2);
2992       return expand_builtin_memcpy_args (dest, src, len, target, exp);
2993     }
2994 }
2995
2996 /* Expand an instrumented call EXP to the memcpy builtin.
2997    Return NULL_RTX if we failed, the caller should emit a normal call,
2998    otherwise try to get the result in TARGET, if convenient (and in
2999    mode MODE if that's convenient).  */
3000
3001 static rtx
3002 expand_builtin_memcpy_with_bounds (tree exp, rtx target)
3003 {
3004   if (!validate_arglist (exp,
3005                          POINTER_TYPE, POINTER_BOUNDS_TYPE,
3006                          POINTER_TYPE, POINTER_BOUNDS_TYPE,
3007                          INTEGER_TYPE, VOID_TYPE))
3008     return NULL_RTX;
3009   else
3010     {
3011       tree dest = CALL_EXPR_ARG (exp, 0);
3012       tree src = CALL_EXPR_ARG (exp, 2);
3013       tree len = CALL_EXPR_ARG (exp, 4);
3014       rtx res = expand_builtin_memcpy_args (dest, src, len, target, exp);
3015
3016       /* Return src bounds with the result.  */
3017       if (res)
3018         {
3019           rtx bnd = force_reg (targetm.chkp_bound_mode (),
3020                                expand_normal (CALL_EXPR_ARG (exp, 1)));
3021           res = chkp_join_splitted_slot (res, bnd);
3022         }
3023       return res;
3024     }
3025 }
3026
3027 /* Expand a call EXP to the mempcpy builtin.
3028    Return NULL_RTX if we failed; the caller should emit a normal call,
3029    otherwise try to get the result in TARGET, if convenient (and in
3030    mode MODE if that's convenient).  If ENDP is 0 return the
3031    destination pointer, if ENDP is 1 return the end pointer ala
3032    mempcpy, and if ENDP is 2 return the end pointer minus one ala
3033    stpcpy.  */
3034
3035 static rtx
3036 expand_builtin_mempcpy (tree exp, rtx target, machine_mode mode)
3037 {
3038   if (!validate_arglist (exp,
3039                          POINTER_TYPE, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
3040     return NULL_RTX;
3041   else
3042     {
3043       tree dest = CALL_EXPR_ARG (exp, 0);
3044       tree src = CALL_EXPR_ARG (exp, 1);
3045       tree len = CALL_EXPR_ARG (exp, 2);
3046       return expand_builtin_mempcpy_args (dest, src, len,
3047                                           target, mode, /*endp=*/ 1,
3048                                           exp);
3049     }
3050 }
3051
3052 /* Expand an instrumented call EXP to the mempcpy builtin.
3053    Return NULL_RTX if we failed, the caller should emit a normal call,
3054    otherwise try to get the result in TARGET, if convenient (and in
3055    mode MODE if that's convenient).  */
3056
3057 static rtx
3058 expand_builtin_mempcpy_with_bounds (tree exp, rtx target, machine_mode mode)
3059 {
3060   if (!validate_arglist (exp,
3061                          POINTER_TYPE, POINTER_BOUNDS_TYPE,
3062                          POINTER_TYPE, POINTER_BOUNDS_TYPE,
3063                          INTEGER_TYPE, VOID_TYPE))
3064     return NULL_RTX;
3065   else
3066     {
3067       tree dest = CALL_EXPR_ARG (exp, 0);
3068       tree src = CALL_EXPR_ARG (exp, 2);
3069       tree len = CALL_EXPR_ARG (exp, 4);
3070       rtx res = expand_builtin_mempcpy_args (dest, src, len, target,
3071                                              mode, 1, exp);
3072
3073       /* Return src bounds with the result.  */
3074       if (res)
3075         {
3076           rtx bnd = force_reg (targetm.chkp_bound_mode (),
3077                                expand_normal (CALL_EXPR_ARG (exp, 1)));
3078           res = chkp_join_splitted_slot (res, bnd);
3079         }
3080       return res;
3081     }
3082 }
3083
3084 /* Helper function to do the actual work for expand_builtin_mempcpy.  The
3085    arguments to the builtin_mempcpy call DEST, SRC, and LEN are broken out
3086    so that this can also be called without constructing an actual CALL_EXPR.
3087    The other arguments and return value are the same as for
3088    expand_builtin_mempcpy.  */
3089
3090 static rtx
3091 expand_builtin_mempcpy_args (tree dest, tree src, tree len,
3092                              rtx target, machine_mode mode, int endp,
3093                              tree orig_exp)
3094 {
3095   tree fndecl = get_callee_fndecl (orig_exp);
3096
3097     /* If return value is ignored, transform mempcpy into memcpy.  */
3098   if (target == const0_rtx
3099       && DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CHKP_MEMPCPY_NOBND_NOCHK_CHKP
3100       && builtin_decl_implicit_p (BUILT_IN_CHKP_MEMCPY_NOBND_NOCHK_CHKP))
3101     {
3102       tree fn = builtin_decl_implicit (BUILT_IN_CHKP_MEMCPY_NOBND_NOCHK_CHKP);
3103       tree result = build_call_nofold_loc (UNKNOWN_LOCATION, fn, 3,
3104                                            dest, src, len);
3105       return expand_expr (result, target, mode, EXPAND_NORMAL);
3106     }
3107   else if (target == const0_rtx
3108            && builtin_decl_implicit_p (BUILT_IN_MEMCPY))
3109     {
3110       tree fn = builtin_decl_implicit (BUILT_IN_MEMCPY);
3111       tree result = build_call_nofold_loc (UNKNOWN_LOCATION, fn, 3,
3112                                            dest, src, len);
3113       return expand_expr (result, target, mode, EXPAND_NORMAL);
3114     }
3115   else
3116     {
3117       const char *src_str;
3118       unsigned int src_align = get_pointer_alignment (src);
3119       unsigned int dest_align = get_pointer_alignment (dest);
3120       rtx dest_mem, src_mem, len_rtx;
3121
3122       /* If either SRC or DEST is not a pointer type, don't do this
3123          operation in-line.  */
3124       if (dest_align == 0 || src_align == 0)
3125         return NULL_RTX;
3126
3127       /* If LEN is not constant, call the normal function.  */
3128       if (! tree_fits_uhwi_p (len))
3129         return NULL_RTX;
3130
3131       len_rtx = expand_normal (len);
3132       src_str = c_getstr (src);
3133
3134       /* If SRC is a string constant and block move would be done
3135          by pieces, we can avoid loading the string from memory
3136          and only stored the computed constants.  */
3137       if (src_str
3138           && CONST_INT_P (len_rtx)
3139           && (unsigned HOST_WIDE_INT) INTVAL (len_rtx) <= strlen (src_str) + 1
3140           && can_store_by_pieces (INTVAL (len_rtx), builtin_memcpy_read_str,
3141                                   CONST_CAST (char *, src_str),
3142                                   dest_align, false))
3143         {
3144           dest_mem = get_memory_rtx (dest, len);
3145           set_mem_align (dest_mem, dest_align);
3146           dest_mem = store_by_pieces (dest_mem, INTVAL (len_rtx),
3147                                       builtin_memcpy_read_str,
3148                                       CONST_CAST (char *, src_str),
3149                                       dest_align, false, endp);
3150           dest_mem = force_operand (XEXP (dest_mem, 0), NULL_RTX);
3151           dest_mem = convert_memory_address (ptr_mode, dest_mem);
3152           return dest_mem;
3153         }
3154
3155       if (CONST_INT_P (len_rtx)
3156           && can_move_by_pieces (INTVAL (len_rtx),
3157                                  MIN (dest_align, src_align)))
3158         {
3159           dest_mem = get_memory_rtx (dest, len);
3160           set_mem_align (dest_mem, dest_align);
3161           src_mem = get_memory_rtx (src, len);
3162           set_mem_align (src_mem, src_align);
3163           dest_mem = move_by_pieces (dest_mem, src_mem, INTVAL (len_rtx),
3164                                      MIN (dest_align, src_align), endp);
3165           dest_mem = force_operand (XEXP (dest_mem, 0), NULL_RTX);
3166           dest_mem = convert_memory_address (ptr_mode, dest_mem);
3167           return dest_mem;
3168         }
3169
3170       return NULL_RTX;
3171     }
3172 }
3173
3174 /* Expand into a movstr instruction, if one is available.  Return NULL_RTX if
3175    we failed, the caller should emit a normal call, otherwise try to
3176    get the result in TARGET, if convenient.  If ENDP is 0 return the
3177    destination pointer, if ENDP is 1 return the end pointer ala
3178    mempcpy, and if ENDP is 2 return the end pointer minus one ala
3179    stpcpy.  */
3180
3181 static rtx
3182 expand_movstr (tree dest, tree src, rtx target, int endp)
3183 {
3184   struct expand_operand ops[3];
3185   rtx dest_mem;
3186   rtx src_mem;
3187
3188   if (!targetm.have_movstr ())
3189     return NULL_RTX;
3190
3191   dest_mem = get_memory_rtx (dest, NULL);
3192   src_mem = get_memory_rtx (src, NULL);
3193   if (!endp)
3194     {
3195       target = force_reg (Pmode, XEXP (dest_mem, 0));
3196       dest_mem = replace_equiv_address (dest_mem, target);
3197     }
3198
3199   create_output_operand (&ops[0], endp ? target : NULL_RTX, Pmode);
3200   create_fixed_operand (&ops[1], dest_mem);
3201   create_fixed_operand (&ops[2], src_mem);
3202   if (!maybe_expand_insn (targetm.code_for_movstr, 3, ops))
3203     return NULL_RTX;
3204
3205   if (endp && target != const0_rtx)
3206     {
3207       target = ops[0].value;
3208       /* movstr is supposed to set end to the address of the NUL
3209          terminator.  If the caller requested a mempcpy-like return value,
3210          adjust it.  */
3211       if (endp == 1)
3212         {
3213           rtx tem = plus_constant (GET_MODE (target),
3214                                    gen_lowpart (GET_MODE (target), target), 1);
3215           emit_move_insn (target, force_operand (tem, NULL_RTX));
3216         }
3217     }
3218   return target;
3219 }
3220
3221 /* Expand expression EXP, which is a call to the strcpy builtin.  Return
3222    NULL_RTX if we failed the caller should emit a normal call, otherwise
3223    try to get the result in TARGET, if convenient (and in mode MODE if that's
3224    convenient).  */
3225
3226 static rtx
3227 expand_builtin_strcpy (tree exp, rtx target)
3228 {
3229   if (validate_arglist (exp, POINTER_TYPE, POINTER_TYPE, VOID_TYPE))
3230    {
3231      tree dest = CALL_EXPR_ARG (exp, 0);
3232      tree src = CALL_EXPR_ARG (exp, 1);
3233      return expand_builtin_strcpy_args (dest, src, target);
3234    }
3235    return NULL_RTX;
3236 }
3237
3238 /* Helper function to do the actual work for expand_builtin_strcpy.  The
3239    arguments to the builtin_strcpy call DEST and SRC are broken out
3240    so that this can also be called without constructing an actual CALL_EXPR.
3241    The other arguments and return value are the same as for
3242    expand_builtin_strcpy.  */
3243
3244 static rtx
3245 expand_builtin_strcpy_args (tree dest, tree src, rtx target)
3246 {
3247   return expand_movstr (dest, src, target, /*endp=*/0);
3248 }
3249
3250 /* Expand a call EXP to the stpcpy builtin.
3251    Return NULL_RTX if we failed the caller should emit a normal call,
3252    otherwise try to get the result in TARGET, if convenient (and in
3253    mode MODE if that's convenient).  */
3254
3255 static rtx
3256 expand_builtin_stpcpy (tree exp, rtx target, machine_mode mode)
3257 {
3258   tree dst, src;
3259   location_t loc = EXPR_LOCATION (exp);
3260
3261   if (!validate_arglist (exp, POINTER_TYPE, POINTER_TYPE, VOID_TYPE))
3262     return NULL_RTX;
3263
3264   dst = CALL_EXPR_ARG (exp, 0);
3265   src = CALL_EXPR_ARG (exp, 1);
3266
3267   /* If return value is ignored, transform stpcpy into strcpy.  */
3268   if (target == const0_rtx && builtin_decl_implicit (BUILT_IN_STRCPY))
3269     {
3270       tree fn = builtin_decl_implicit (BUILT_IN_STRCPY);
3271       tree result = build_call_nofold_loc (loc, fn, 2, dst, src);
3272       return expand_expr (result, target, mode, EXPAND_NORMAL);
3273     }
3274   else
3275     {
3276       tree len, lenp1;
3277       rtx ret;
3278
3279       /* Ensure we get an actual string whose length can be evaluated at
3280          compile-time, not an expression containing a string.  This is
3281          because the latter will potentially produce pessimized code
3282          when used to produce the return value.  */
3283       if (! c_getstr (src) || ! (len = c_strlen (src, 0)))
3284         return expand_movstr (dst, src, target, /*endp=*/2);
3285
3286       lenp1 = size_binop_loc (loc, PLUS_EXPR, len, ssize_int (1));
3287       ret = expand_builtin_mempcpy_args (dst, src, lenp1,
3288                                          target, mode, /*endp=*/2,
3289                                          exp);
3290
3291       if (ret)
3292         return ret;
3293
3294       if (TREE_CODE (len) == INTEGER_CST)
3295         {
3296           rtx len_rtx = expand_normal (len);
3297
3298           if (CONST_INT_P (len_rtx))
3299             {
3300               ret = expand_builtin_strcpy_args (dst, src, target);
3301
3302               if (ret)
3303                 {
3304                   if (! target)
3305                     {
3306                       if (mode != VOIDmode)
3307                         target = gen_reg_rtx (mode);
3308                       else
3309                         target = gen_reg_rtx (GET_MODE (ret));
3310                     }
3311                   if (GET_MODE (target) != GET_MODE (ret))
3312                     ret = gen_lowpart (GET_MODE (target), ret);
3313
3314                   ret = plus_constant (GET_MODE (ret), ret, INTVAL (len_rtx));
3315                   ret = emit_move_insn (target, force_operand (ret, NULL_RTX));
3316                   gcc_assert (ret);
3317
3318                   return target;
3319                 }
3320             }
3321         }
3322
3323       return expand_movstr (dst, src, target, /*endp=*/2);
3324     }
3325 }
3326
3327 /* Callback routine for store_by_pieces.  Read GET_MODE_BITSIZE (MODE)
3328    bytes from constant string DATA + OFFSET and return it as target
3329    constant.  */
3330
3331 rtx
3332 builtin_strncpy_read_str (void *data, HOST_WIDE_INT offset,
3333                           machine_mode mode)
3334 {
3335   const char *str = (const char *) data;
3336
3337   if ((unsigned HOST_WIDE_INT) offset > strlen (str))
3338     return const0_rtx;
3339
3340   return c_readstr (str + offset, mode);
3341 }
3342
3343 /* Expand expression EXP, which is a call to the strncpy builtin.  Return
3344    NULL_RTX if we failed the caller should emit a normal call.  */
3345
3346 static rtx
3347 expand_builtin_strncpy (tree exp, rtx target)
3348 {
3349   location_t loc = EXPR_LOCATION (exp);
3350
3351   if (validate_arglist (exp,
3352                         POINTER_TYPE, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
3353     {
3354       tree dest = CALL_EXPR_ARG (exp, 0);
3355       tree src = CALL_EXPR_ARG (exp, 1);
3356       tree len = CALL_EXPR_ARG (exp, 2);
3357       tree slen = c_strlen (src, 1);
3358
3359       /* We must be passed a constant len and src parameter.  */
3360       if (!tree_fits_uhwi_p (len) || !slen || !tree_fits_uhwi_p (slen))
3361         return NULL_RTX;
3362
3363       slen = size_binop_loc (loc, PLUS_EXPR, slen, ssize_int (1));
3364
3365       /* We're required to pad with trailing zeros if the requested
3366          len is greater than strlen(s2)+1.  In that case try to
3367          use store_by_pieces, if it fails, punt.  */
3368       if (tree_int_cst_lt (slen, len))
3369         {
3370           unsigned int dest_align = get_pointer_alignment (dest);
3371           const char *p = c_getstr (src);
3372           rtx dest_mem;
3373
3374           if (!p || dest_align == 0 || !tree_fits_uhwi_p (len)
3375               || !can_store_by_pieces (tree_to_uhwi (len),
3376                                        builtin_strncpy_read_str,
3377                                        CONST_CAST (char *, p),
3378                                        dest_align, false))
3379             return NULL_RTX;
3380
3381           dest_mem = get_memory_rtx (dest, len);
3382           store_by_pieces (dest_mem, tree_to_uhwi (len),
3383                            builtin_strncpy_read_str,
3384                            CONST_CAST (char *, p), dest_align, false, 0);
3385           dest_mem = force_operand (XEXP (dest_mem, 0), target);
3386           dest_mem = convert_memory_address (ptr_mode, dest_mem);
3387           return dest_mem;
3388         }
3389     }
3390   return NULL_RTX;
3391 }
3392
3393 /* Callback routine for store_by_pieces.  Read GET_MODE_BITSIZE (MODE)
3394    bytes from constant string DATA + OFFSET and return it as target
3395    constant.  */
3396
3397 rtx
3398 builtin_memset_read_str (void *data, HOST_WIDE_INT offset ATTRIBUTE_UNUSED,
3399                          machine_mode mode)
3400 {
3401   const char *c = (const char *) data;
3402   char *p = XALLOCAVEC (char, GET_MODE_SIZE (mode));
3403
3404   memset (p, *c, GET_MODE_SIZE (mode));
3405
3406   return c_readstr (p, mode);
3407 }
3408
3409 /* Callback routine for store_by_pieces.  Return the RTL of a register
3410    containing GET_MODE_SIZE (MODE) consecutive copies of the unsigned
3411    char value given in the RTL register data.  For example, if mode is
3412    4 bytes wide, return the RTL for 0x01010101*data.  */
3413
3414 static rtx
3415 builtin_memset_gen_str (void *data, HOST_WIDE_INT offset ATTRIBUTE_UNUSED,
3416                         machine_mode mode)
3417 {
3418   rtx target, coeff;
3419   size_t size;
3420   char *p;
3421
3422   size = GET_MODE_SIZE (mode);
3423   if (size == 1)
3424     return (rtx) data;
3425
3426   p = XALLOCAVEC (char, size);
3427   memset (p, 1, size);
3428   coeff = c_readstr (p, mode);
3429
3430   target = convert_to_mode (mode, (rtx) data, 1);
3431   target = expand_mult (mode, target, coeff, NULL_RTX, 1);
3432   return force_reg (mode, target);
3433 }
3434
3435 /* Expand expression EXP, which is a call to the memset builtin.  Return
3436    NULL_RTX if we failed the caller should emit a normal call, otherwise
3437    try to get the result in TARGET, if convenient (and in mode MODE if that's
3438    convenient).  */
3439
3440 static rtx
3441 expand_builtin_memset (tree exp, rtx target, machine_mode mode)
3442 {
3443   if (!validate_arglist (exp,
3444                          POINTER_TYPE, INTEGER_TYPE, INTEGER_TYPE, VOID_TYPE))
3445     return NULL_RTX;
3446   else
3447     {
3448       tree dest = CALL_EXPR_ARG (exp, 0);
3449       tree val = CALL_EXPR_ARG (exp, 1);
3450       tree len = CALL_EXPR_ARG (exp, 2);
3451       return expand_builtin_memset_args (dest, val, len, target, mode, exp);
3452     }
3453 }
3454
3455 /* Expand expression EXP, which is an instrumented call to the memset builtin.
3456    Return NULL_RTX if we failed the caller should emit a normal call, otherwise
3457    try to get the result in TARGET, if convenient (and in mode MODE if that's
3458    convenient).  */
3459
3460 static rtx
3461 expand_builtin_memset_with_bounds (tree exp, rtx target, machine_mode mode)
3462 {
3463   if (!validate_arglist (exp,
3464                          POINTER_TYPE, POINTER_BOUNDS_TYPE,
3465                          INTEGER_TYPE, INTEGER_TYPE, VOID_TYPE))
3466     return NULL_RTX;
3467   else
3468     {
3469       tree dest = CALL_EXPR_ARG (exp, 0);
3470       tree val = CALL_EXPR_ARG (exp, 2);
3471       tree len = CALL_EXPR_ARG (exp, 3);
3472       rtx res = expand_builtin_memset_args (dest, val, len, target, mode, exp);
3473
3474       /* Return src bounds with the result.  */
3475       if (res)
3476         {
3477           rtx bnd = force_reg (targetm.chkp_bound_mode (),
3478                                expand_normal (CALL_EXPR_ARG (exp, 1)));
3479           res = chkp_join_splitted_slot (res, bnd);
3480         }
3481       return res;
3482     }
3483 }
3484
3485 /* Helper function to do the actual work for expand_builtin_memset.  The
3486    arguments to the builtin_memset call DEST, VAL, and LEN are broken out
3487    so that this can also be called without constructing an actual CALL_EXPR.
3488    The other arguments and return value are the same as for
3489    expand_builtin_memset.  */
3490
3491 static rtx
3492 expand_builtin_memset_args (tree dest, tree val, tree len,
3493                             rtx target, machine_mode mode, tree orig_exp)
3494 {
3495   tree fndecl, fn;
3496   enum built_in_function fcode;
3497   machine_mode val_mode;
3498   char c;
3499   unsigned int dest_align;
3500   rtx dest_mem, dest_addr, len_rtx;
3501   HOST_WIDE_INT expected_size = -1;
3502   unsigned int expected_align = 0;
3503   unsigned HOST_WIDE_INT min_size;
3504   unsigned HOST_WIDE_INT max_size;
3505   unsigned HOST_WIDE_INT probable_max_size;
3506
3507   dest_align = get_pointer_alignment (dest);
3508
3509   /* If DEST is not a pointer type, don't do this operation in-line.  */
3510   if (dest_align == 0)
3511     return NULL_RTX;
3512
3513   if (currently_expanding_gimple_stmt)
3514     stringop_block_profile (currently_expanding_gimple_stmt,
3515                             &expected_align, &expected_size);
3516
3517   if (expected_align < dest_align)
3518     expected_align = dest_align;
3519
3520   /* If the LEN parameter is zero, return DEST.  */
3521   if (integer_zerop (len))
3522     {
3523       /* Evaluate and ignore VAL in case it has side-effects.  */
3524       expand_expr (val, const0_rtx, VOIDmode, EXPAND_NORMAL);
3525       return expand_expr (dest, target, mode, EXPAND_NORMAL);
3526     }
3527
3528   /* Stabilize the arguments in case we fail.  */
3529   dest = builtin_save_expr (dest);
3530   val = builtin_save_expr (val);
3531   len = builtin_save_expr (len);
3532
3533   len_rtx = expand_normal (len);
3534   determine_block_size (len, len_rtx, &min_size, &max_size,
3535                         &probable_max_size);
3536   dest_mem = get_memory_rtx (dest, len);
3537   val_mode = TYPE_MODE (unsigned_char_type_node);
3538
3539   if (TREE_CODE (val) != INTEGER_CST)
3540     {
3541       rtx val_rtx;
3542
3543       val_rtx = expand_normal (val);
3544       val_rtx = convert_to_mode (val_mode, val_rtx, 0);
3545
3546       /* Assume that we can memset by pieces if we can store
3547        * the coefficients by pieces (in the required modes).
3548        * We can't pass builtin_memset_gen_str as that emits RTL.  */
3549       c = 1;
3550       if (tree_fits_uhwi_p (len)
3551           && can_store_by_pieces (tree_to_uhwi (len),
3552                                   builtin_memset_read_str, &c, dest_align,
3553                                   true))
3554         {
3555           val_rtx = force_reg (val_mode, val_rtx);
3556           store_by_pieces (dest_mem, tree_to_uhwi (len),
3557                            builtin_memset_gen_str, val_rtx, dest_align,
3558                            true, 0);
3559         }
3560       else if (!set_storage_via_setmem (dest_mem, len_rtx, val_rtx,
3561                                         dest_align, expected_align,
3562                                         expected_size, min_size, max_size,
3563                                         probable_max_size))
3564         goto do_libcall;
3565
3566       dest_mem = force_operand (XEXP (dest_mem, 0), NULL_RTX);
3567       dest_mem = convert_memory_address (ptr_mode, dest_mem);
3568       return dest_mem;
3569     }
3570
3571   if (target_char_cast (val, &c))
3572     goto do_libcall;
3573
3574   if (c)
3575     {
3576       if (tree_fits_uhwi_p (len)
3577           && can_store_by_pieces (tree_to_uhwi (len),
3578                                   builtin_memset_read_str, &c, dest_align,
3579                                   true))
3580         store_by_pieces (dest_mem, tree_to_uhwi (len),
3581                          builtin_memset_read_str, &c, dest_align, true, 0);
3582       else if (!set_storage_via_setmem (dest_mem, len_rtx,
3583                                         gen_int_mode (c, val_mode),
3584                                         dest_align, expected_align,
3585                                         expected_size, min_size, max_size,
3586                                         probable_max_size))
3587         goto do_libcall;
3588
3589       dest_mem = force_operand (XEXP (dest_mem, 0), NULL_RTX);
3590       dest_mem = convert_memory_address (ptr_mode, dest_mem);
3591       return dest_mem;
3592     }
3593
3594   set_mem_align (dest_mem, dest_align);
3595   dest_addr = clear_storage_hints (dest_mem, len_rtx,
3596                                    CALL_EXPR_TAILCALL (orig_exp)
3597                                    ? BLOCK_OP_TAILCALL : BLOCK_OP_NORMAL,
3598                                    expected_align, expected_size,
3599                                    min_size, max_size,
3600                                    probable_max_size);
3601
3602   if (dest_addr == 0)
3603     {
3604       dest_addr = force_operand (XEXP (dest_mem, 0), NULL_RTX);
3605       dest_addr = convert_memory_address (ptr_mode, dest_addr);
3606     }
3607
3608   return dest_addr;
3609
3610  do_libcall:
3611   fndecl = get_callee_fndecl (orig_exp);
3612   fcode = DECL_FUNCTION_CODE (fndecl);
3613   if (fcode == BUILT_IN_MEMSET
3614       || fcode == BUILT_IN_CHKP_MEMSET_NOBND_NOCHK_CHKP)
3615     fn = build_call_nofold_loc (EXPR_LOCATION (orig_exp), fndecl, 3,
3616                                 dest, val, len);
3617   else if (fcode == BUILT_IN_BZERO)
3618     fn = build_call_nofold_loc (EXPR_LOCATION (orig_exp), fndecl, 2,
3619                                 dest, len);
3620   else
3621     gcc_unreachable ();
3622   gcc_assert (TREE_CODE (fn) == CALL_EXPR);
3623   CALL_EXPR_TAILCALL (fn) = CALL_EXPR_TAILCALL (orig_exp);
3624   return expand_call (fn, target, target == const0_rtx);
3625 }
3626
3627 /* Expand expression EXP, which is a call to the bzero builtin.  Return
3628    NULL_RTX if we failed the caller should emit a normal call.  */
3629
3630 static rtx
3631 expand_builtin_bzero (tree exp)
3632 {
3633   tree dest, size;
3634   location_t loc = EXPR_LOCATION (exp);
3635
3636   if (!validate_arglist (exp, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
3637     return NULL_RTX;
3638
3639   dest = CALL_EXPR_ARG (exp, 0);
3640   size = CALL_EXPR_ARG (exp, 1);
3641
3642   /* New argument list transforming bzero(ptr x, int y) to
3643      memset(ptr x, int 0, size_t y).   This is done this way
3644      so that if it isn't expanded inline, we fallback to
3645      calling bzero instead of memset.  */
3646
3647   return expand_builtin_memset_args (dest, integer_zero_node,
3648                                      fold_convert_loc (loc,
3649                                                        size_type_node, size),
3650                                      const0_rtx, VOIDmode, exp);
3651 }
3652
3653 /* Try to expand cmpstr operation ICODE with the given operands.
3654    Return the result rtx on success, otherwise return null.  */
3655
3656 static rtx
3657 expand_cmpstr (insn_code icode, rtx target, rtx arg1_rtx, rtx arg2_rtx,
3658                HOST_WIDE_INT align)
3659 {
3660   machine_mode insn_mode = insn_data[icode].operand[0].mode;
3661
3662   if (target && (!REG_P (target) || HARD_REGISTER_P (target)))
3663     target = NULL_RTX;
3664
3665   struct expand_operand ops[4];
3666   create_output_operand (&ops[0], target, insn_mode);
3667   create_fixed_operand (&ops[1], arg1_rtx);
3668   create_fixed_operand (&ops[2], arg2_rtx);
3669   create_integer_operand (&ops[3], align);
3670   if (maybe_expand_insn (icode, 4, ops))
3671     return ops[0].value;
3672   return NULL_RTX;
3673 }
3674
3675 /* Try to expand cmpstrn or cmpmem operation ICODE with the given operands.
3676    ARG3_TYPE is the type of ARG3_RTX.  Return the result rtx on success,
3677    otherwise return null.  */
3678
3679 static rtx
3680 expand_cmpstrn_or_cmpmem (insn_code icode, rtx target, rtx arg1_rtx,
3681                           rtx arg2_rtx, tree arg3_type, rtx arg3_rtx,
3682                           HOST_WIDE_INT align)
3683 {
3684   machine_mode insn_mode = insn_data[icode].operand[0].mode;
3685
3686   if (target && (!REG_P (target) || HARD_REGISTER_P (target)))
3687     target = NULL_RTX;
3688
3689   struct expand_operand ops[5];
3690   create_output_operand (&ops[0], target, insn_mode);
3691   create_fixed_operand (&ops[1], arg1_rtx);
3692   create_fixed_operand (&ops[2], arg2_rtx);
3693   create_convert_operand_from (&ops[3], arg3_rtx, TYPE_MODE (arg3_type),
3694                                TYPE_UNSIGNED (arg3_type));
3695   create_integer_operand (&ops[4], align);
3696   if (maybe_expand_insn (icode, 5, ops))
3697     return ops[0].value;
3698   return NULL_RTX;
3699 }
3700
3701 /* Expand expression EXP, which is a call to the memcmp built-in function.
3702    Return NULL_RTX if we failed and the caller should emit a normal call,
3703    otherwise try to get the result in TARGET, if convenient.  */
3704
3705 static rtx
3706 expand_builtin_memcmp (tree exp, rtx target)
3707 {
3708   if (!validate_arglist (exp,
3709                          POINTER_TYPE, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
3710     return NULL_RTX;
3711
3712   /* Note: The cmpstrnsi pattern, if it exists, is not suitable for
3713      implementing memcmp because it will stop if it encounters two
3714      zero bytes.  */
3715   insn_code icode = direct_optab_handler (cmpmem_optab, SImode);
3716   if (icode == CODE_FOR_nothing)
3717     return NULL_RTX;
3718
3719   tree arg1 = CALL_EXPR_ARG (exp, 0);
3720   tree arg2 = CALL_EXPR_ARG (exp, 1);
3721   tree len = CALL_EXPR_ARG (exp, 2);
3722
3723   unsigned int arg1_align = get_pointer_alignment (arg1) / BITS_PER_UNIT;
3724   unsigned int arg2_align = get_pointer_alignment (arg2) / BITS_PER_UNIT;
3725
3726   /* If we don't have POINTER_TYPE, call the function.  */
3727   if (arg1_align == 0 || arg2_align == 0)
3728     return NULL_RTX;
3729
3730   machine_mode mode = TYPE_MODE (TREE_TYPE (exp));
3731   location_t loc = EXPR_LOCATION (exp);
3732   rtx arg1_rtx = get_memory_rtx (arg1, len);
3733   rtx arg2_rtx = get_memory_rtx (arg2, len);
3734   rtx arg3_rtx = expand_normal (fold_convert_loc (loc, sizetype, len));
3735
3736   /* Set MEM_SIZE as appropriate.  */
3737   if (CONST_INT_P (arg3_rtx))
3738     {
3739       set_mem_size (arg1_rtx, INTVAL (arg3_rtx));
3740       set_mem_size (arg2_rtx, INTVAL (arg3_rtx));
3741     }
3742
3743   rtx result = expand_cmpstrn_or_cmpmem (icode, target, arg1_rtx, arg2_rtx,
3744                                          TREE_TYPE (len), arg3_rtx,
3745                                          MIN (arg1_align, arg2_align));
3746   if (result)
3747     {
3748       /* Return the value in the proper mode for this function.  */
3749       if (GET_MODE (result) == mode)
3750         return result;
3751
3752       if (target != 0)
3753         {
3754           convert_move (target, result, 0);
3755           return target;
3756         }
3757
3758       return convert_to_mode (mode, result, 0);
3759     }
3760
3761   result = target;
3762   if (! (result != 0
3763          && REG_P (result) && GET_MODE (result) == mode
3764          && REGNO (result) >= FIRST_PSEUDO_REGISTER))
3765     result = gen_reg_rtx (mode);
3766
3767   emit_library_call_value (memcmp_libfunc, result, LCT_PURE,
3768                            TYPE_MODE (integer_type_node), 3,
3769                            XEXP (arg1_rtx, 0), Pmode,
3770                            XEXP (arg2_rtx, 0), Pmode,
3771                            convert_to_mode (TYPE_MODE (sizetype), arg3_rtx,
3772                                             TYPE_UNSIGNED (sizetype)),
3773                            TYPE_MODE (sizetype));
3774   return result;
3775 }
3776
3777 /* Expand expression EXP, which is a call to the strcmp builtin.  Return NULL_RTX
3778    if we failed the caller should emit a normal call, otherwise try to get
3779    the result in TARGET, if convenient.  */
3780
3781 static rtx
3782 expand_builtin_strcmp (tree exp, ATTRIBUTE_UNUSED rtx target)
3783 {
3784   if (!validate_arglist (exp, POINTER_TYPE, POINTER_TYPE, VOID_TYPE))
3785     return NULL_RTX;
3786
3787   insn_code cmpstr_icode = direct_optab_handler (cmpstr_optab, SImode);
3788   insn_code cmpstrn_icode = direct_optab_handler (cmpstrn_optab, SImode);
3789   if (cmpstr_icode != CODE_FOR_nothing || cmpstrn_icode != CODE_FOR_nothing)
3790     {
3791       rtx arg1_rtx, arg2_rtx;
3792       tree fndecl, fn;
3793       tree arg1 = CALL_EXPR_ARG (exp, 0);
3794       tree arg2 = CALL_EXPR_ARG (exp, 1);
3795       rtx result = NULL_RTX;
3796
3797       unsigned int arg1_align = get_pointer_alignment (arg1) / BITS_PER_UNIT;
3798       unsigned int arg2_align = get_pointer_alignment (arg2) / BITS_PER_UNIT;
3799
3800       /* If we don't have POINTER_TYPE, call the function.  */
3801       if (arg1_align == 0 || arg2_align == 0)
3802         return NULL_RTX;
3803
3804       /* Stabilize the arguments in case gen_cmpstr(n)si fail.  */
3805       arg1 = builtin_save_expr (arg1);
3806       arg2 = builtin_save_expr (arg2);
3807
3808       arg1_rtx = get_memory_rtx (arg1, NULL);
3809       arg2_rtx = get_memory_rtx (arg2, NULL);
3810
3811       /* Try to call cmpstrsi.  */
3812       if (cmpstr_icode != CODE_FOR_nothing)
3813         result = expand_cmpstr (cmpstr_icode, target, arg1_rtx, arg2_rtx,
3814                                 MIN (arg1_align, arg2_align));
3815
3816       /* Try to determine at least one length and call cmpstrnsi.  */
3817       if (!result && cmpstrn_icode != CODE_FOR_nothing)
3818         {
3819           tree len;
3820           rtx arg3_rtx;
3821
3822           tree len1 = c_strlen (arg1, 1);
3823           tree len2 = c_strlen (arg2, 1);
3824
3825           if (len1)
3826             len1 = size_binop (PLUS_EXPR, ssize_int (1), len1);
3827           if (len2)
3828             len2 = size_binop (PLUS_EXPR, ssize_int (1), len2);
3829
3830           /* If we don't have a constant length for the first, use the length
3831              of the second, if we know it.  We don't require a constant for
3832              this case; some cost analysis could be done if both are available
3833              but neither is constant.  For now, assume they're equally cheap,
3834              unless one has side effects.  If both strings have constant lengths,
3835              use the smaller.  */
3836
3837           if (!len1)
3838             len = len2;
3839           else if (!len2)
3840             len = len1;
3841           else if (TREE_SIDE_EFFECTS (len1))
3842             len = len2;
3843           else if (TREE_SIDE_EFFECTS (len2))
3844             len = len1;
3845           else if (TREE_CODE (len1) != INTEGER_CST)
3846             len = len2;
3847           else if (TREE_CODE (len2) != INTEGER_CST)
3848             len = len1;
3849           else if (tree_int_cst_lt (len1, len2))
3850             len = len1;
3851           else
3852             len = len2;
3853
3854           /* If both arguments have side effects, we cannot optimize.  */
3855           if (len && !TREE_SIDE_EFFECTS (len))
3856             {
3857               arg3_rtx = expand_normal (len);
3858               result = expand_cmpstrn_or_cmpmem
3859                 (cmpstrn_icode, target, arg1_rtx, arg2_rtx, TREE_TYPE (len),
3860                  arg3_rtx, MIN (arg1_align, arg2_align));
3861             }
3862         }
3863
3864       if (result)
3865         {
3866           /* Return the value in the proper mode for this function.  */
3867           machine_mode mode = TYPE_MODE (TREE_TYPE (exp));
3868           if (GET_MODE (result) == mode)
3869             return result;
3870           if (target == 0)
3871             return convert_to_mode (mode, result, 0);
3872           convert_move (target, result, 0);
3873           return target;
3874         }
3875
3876       /* Expand the library call ourselves using a stabilized argument
3877          list to avoid re-evaluating the function's arguments twice.  */
3878       fndecl = get_callee_fndecl (exp);
3879       fn = build_call_nofold_loc (EXPR_LOCATION (exp), fndecl, 2, arg1, arg2);
3880       gcc_assert (TREE_CODE (fn) == CALL_EXPR);
3881       CALL_EXPR_TAILCALL (fn) = CALL_EXPR_TAILCALL (exp);
3882       return expand_call (fn, target, target == const0_rtx);
3883     }
3884   return NULL_RTX;
3885 }
3886
3887 /* Expand expression EXP, which is a call to the strncmp builtin. Return
3888    NULL_RTX if we failed the caller should emit a normal call, otherwise try to get
3889    the result in TARGET, if convenient.  */
3890
3891 static rtx
3892 expand_builtin_strncmp (tree exp, ATTRIBUTE_UNUSED rtx target,
3893                         ATTRIBUTE_UNUSED machine_mode mode)
3894 {
3895   location_t loc ATTRIBUTE_UNUSED = EXPR_LOCATION (exp);
3896
3897   if (!validate_arglist (exp,
3898                          POINTER_TYPE, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
3899     return NULL_RTX;
3900
3901   /* If c_strlen can determine an expression for one of the string
3902      lengths, and it doesn't have side effects, then emit cmpstrnsi
3903      using length MIN(strlen(string)+1, arg3).  */
3904   insn_code cmpstrn_icode = direct_optab_handler (cmpstrn_optab, SImode);
3905   if (cmpstrn_icode != CODE_FOR_nothing)
3906   {
3907     tree len, len1, len2;
3908     rtx arg1_rtx, arg2_rtx, arg3_rtx;
3909     rtx result;
3910     tree fndecl, fn;
3911     tree arg1 = CALL_EXPR_ARG (exp, 0);
3912     tree arg2 = CALL_EXPR_ARG (exp, 1);
3913     tree arg3 = CALL_EXPR_ARG (exp, 2);
3914
3915     unsigned int arg1_align = get_pointer_alignment (arg1) / BITS_PER_UNIT;
3916     unsigned int arg2_align = get_pointer_alignment (arg2) / BITS_PER_UNIT;
3917
3918     len1 = c_strlen (arg1, 1);
3919     len2 = c_strlen (arg2, 1);
3920
3921     if (len1)
3922       len1 = size_binop_loc (loc, PLUS_EXPR, ssize_int (1), len1);
3923     if (len2)
3924       len2 = size_binop_loc (loc, PLUS_EXPR, ssize_int (1), len2);
3925
3926     /* If we don't have a constant length for the first, use the length
3927        of the second, if we know it.  We don't require a constant for
3928        this case; some cost analysis could be done if both are available
3929        but neither is constant.  For now, assume they're equally cheap,
3930        unless one has side effects.  If both strings have constant lengths,
3931        use the smaller.  */
3932
3933     if (!len1)
3934       len = len2;
3935     else if (!len2)
3936       len = len1;
3937     else if (TREE_SIDE_EFFECTS (len1))
3938       len = len2;
3939     else if (TREE_SIDE_EFFECTS (len2))
3940       len = len1;
3941     else if (TREE_CODE (len1) != INTEGER_CST)
3942       len = len2;
3943     else if (TREE_CODE (len2) != INTEGER_CST)
3944       len = len1;
3945     else if (tree_int_cst_lt (len1, len2))
3946       len = len1;
3947     else
3948       len = len2;
3949
3950     /* If both arguments have side effects, we cannot optimize.  */
3951     if (!len || TREE_SIDE_EFFECTS (len))
3952       return NULL_RTX;
3953
3954     /* The actual new length parameter is MIN(len,arg3).  */
3955     len = fold_build2_loc (loc, MIN_EXPR, TREE_TYPE (len), len,
3956                        fold_convert_loc (loc, TREE_TYPE (len), arg3));
3957
3958     /* If we don't have POINTER_TYPE, call the function.  */
3959     if (arg1_align == 0 || arg2_align == 0)
3960       return NULL_RTX;
3961
3962     /* Stabilize the arguments in case gen_cmpstrnsi fails.  */
3963     arg1 = builtin_save_expr (arg1);
3964     arg2 = builtin_save_expr (arg2);
3965     len = builtin_save_expr (len);
3966
3967     arg1_rtx = get_memory_rtx (arg1, len);
3968     arg2_rtx = get_memory_rtx (arg2, len);
3969     arg3_rtx = expand_normal (len);
3970     result = expand_cmpstrn_or_cmpmem (cmpstrn_icode, target, arg1_rtx,
3971                                        arg2_rtx, TREE_TYPE (len), arg3_rtx,
3972                                        MIN (arg1_align, arg2_align));
3973     if (result)
3974       {
3975         /* Return the value in the proper mode for this function.  */
3976         mode = TYPE_MODE (TREE_TYPE (exp));
3977         if (GET_MODE (result) == mode)
3978           return result;
3979         if (target == 0)
3980           return convert_to_mode (mode, result, 0);
3981         convert_move (target, result, 0);
3982         return target;
3983       }
3984
3985     /* Expand the library call ourselves using a stabilized argument
3986        list to avoid re-evaluating the function's arguments twice.  */
3987     fndecl = get_callee_fndecl (exp);
3988     fn = build_call_nofold_loc (EXPR_LOCATION (exp), fndecl, 3,
3989                                 arg1, arg2, len);
3990     gcc_assert (TREE_CODE (fn) == CALL_EXPR);
3991     CALL_EXPR_TAILCALL (fn) = CALL_EXPR_TAILCALL (exp);
3992     return expand_call (fn, target, target == const0_rtx);
3993   }
3994   return NULL_RTX;
3995 }
3996
3997 /* Expand a call to __builtin_saveregs, generating the result in TARGET,
3998    if that's convenient.  */
3999
4000 rtx
4001 expand_builtin_saveregs (void)
4002 {
4003   rtx val;
4004   rtx_insn *seq;
4005
4006   /* Don't do __builtin_saveregs more than once in a function.
4007      Save the result of the first call and reuse it.  */
4008   if (saveregs_value != 0)
4009     return saveregs_value;
4010
4011   /* When this function is called, it means that registers must be
4012      saved on entry to this function.  So we migrate the call to the
4013      first insn of this function.  */
4014
4015   start_sequence ();
4016
4017   /* Do whatever the machine needs done in this case.  */
4018   val = targetm.calls.expand_builtin_saveregs ();
4019
4020   seq = get_insns ();
4021   end_sequence ();
4022
4023   saveregs_value = val;
4024
4025   /* Put the insns after the NOTE that starts the function.  If this
4026      is inside a start_sequence, make the outer-level insn chain current, so
4027      the code is placed at the start of the function.  */
4028   push_topmost_sequence ();
4029   emit_insn_after (seq, entry_of_function ());
4030   pop_topmost_sequence ();
4031
4032   return val;
4033 }
4034
4035 /* Expand a call to __builtin_next_arg.  */
4036
4037 static rtx
4038 expand_builtin_next_arg (void)
4039 {
4040   /* Checking arguments is already done in fold_builtin_next_arg
4041      that must be called before this function.  */
4042   return expand_binop (ptr_mode, add_optab,
4043                        crtl->args.internal_arg_pointer,
4044                        crtl->args.arg_offset_rtx,
4045                        NULL_RTX, 0, OPTAB_LIB_WIDEN);
4046 }
4047
4048 /* Make it easier for the backends by protecting the valist argument
4049    from multiple evaluations.  */
4050
4051 static tree
4052 stabilize_va_list_loc (location_t loc, tree valist, int needs_lvalue)
4053 {
4054   tree vatype = targetm.canonical_va_list_type (TREE_TYPE (valist));
4055
4056   /* The current way of determining the type of valist is completely
4057      bogus.  We should have the information on the va builtin instead.  */
4058   if (!vatype)
4059     vatype = targetm.fn_abi_va_list (cfun->decl);
4060
4061   if (TREE_CODE (vatype) == ARRAY_TYPE)
4062     {
4063       if (TREE_SIDE_EFFECTS (valist))
4064         valist = save_expr (valist);
4065
4066       /* For this case, the backends will be expecting a pointer to
4067          vatype, but it's possible we've actually been given an array
4068          (an actual TARGET_CANONICAL_VA_LIST_TYPE (valist)).
4069          So fix it.  */
4070       if (TREE_CODE (TREE_TYPE (valist)) == ARRAY_TYPE)
4071         {
4072           tree p1 = build_pointer_type (TREE_TYPE (vatype));
4073           valist = build_fold_addr_expr_with_type_loc (loc, valist, p1);
4074         }
4075     }
4076   else
4077     {
4078       tree pt = build_pointer_type (vatype);
4079
4080       if (! needs_lvalue)
4081         {
4082           if (! TREE_SIDE_EFFECTS (valist))
4083             return valist;
4084
4085           valist = fold_build1_loc (loc, ADDR_EXPR, pt, valist);
4086           TREE_SIDE_EFFECTS (valist) = 1;
4087         }
4088
4089       if (TREE_SIDE_EFFECTS (valist))
4090         valist = save_expr (valist);
4091       valist = fold_build2_loc (loc, MEM_REF,
4092                                 vatype, valist, build_int_cst (pt, 0));
4093     }
4094
4095   return valist;
4096 }
4097
4098 /* The "standard" definition of va_list is void*.  */
4099
4100 tree
4101 std_build_builtin_va_list (void)
4102 {
4103   return ptr_type_node;
4104 }
4105
4106 /* The "standard" abi va_list is va_list_type_node.  */
4107
4108 tree
4109 std_fn_abi_va_list (tree fndecl ATTRIBUTE_UNUSED)
4110 {
4111   return va_list_type_node;
4112 }
4113
4114 /* The "standard" type of va_list is va_list_type_node.  */
4115
4116 tree
4117 std_canonical_va_list_type (tree type)
4118 {
4119   tree wtype, htype;
4120
4121   if (INDIRECT_REF_P (type))
4122     type = TREE_TYPE (type);
4123   else if (POINTER_TYPE_P (type) && POINTER_TYPE_P (TREE_TYPE (type)))
4124     type = TREE_TYPE (type);
4125   wtype = va_list_type_node;
4126   htype = type;
4127   /* Treat structure va_list types.  */
4128   if (TREE_CODE (wtype) == RECORD_TYPE && POINTER_TYPE_P (htype))
4129     htype = TREE_TYPE (htype);
4130   else if (TREE_CODE (wtype) == ARRAY_TYPE)
4131     {
4132       /* If va_list is an array type, the argument may have decayed
4133          to a pointer type, e.g. by being passed to another function.
4134          In that case, unwrap both types so that we can compare the
4135          underlying records.  */
4136       if (TREE_CODE (htype) == ARRAY_TYPE
4137           || POINTER_TYPE_P (htype))
4138         {
4139           wtype = TREE_TYPE (wtype);
4140           htype = TREE_TYPE (htype);
4141         }
4142     }
4143   if (TYPE_MAIN_VARIANT (wtype) == TYPE_MAIN_VARIANT (htype))
4144     return va_list_type_node;
4145
4146   return NULL_TREE;
4147 }
4148
4149 /* The "standard" implementation of va_start: just assign `nextarg' to
4150    the variable.  */
4151
4152 void
4153 std_expand_builtin_va_start (tree valist, rtx nextarg)
4154 {
4155   rtx va_r = expand_expr (valist, NULL_RTX, VOIDmode, EXPAND_WRITE);
4156   convert_move (va_r, nextarg, 0);
4157
4158   /* We do not have any valid bounds for the pointer, so
4159      just store zero bounds for it.  */
4160   if (chkp_function_instrumented_p (current_function_decl))
4161     chkp_expand_bounds_reset_for_mem (valist,
4162                                       make_tree (TREE_TYPE (valist),
4163                                                  nextarg));
4164 }
4165
4166 /* Expand EXP, a call to __builtin_va_start.  */
4167
4168 static rtx
4169 expand_builtin_va_start (tree exp)
4170 {
4171   rtx nextarg;
4172   tree valist;
4173   location_t loc = EXPR_LOCATION (exp);
4174
4175   if (call_expr_nargs (exp) < 2)
4176     {
4177       error_at (loc, "too few arguments to function %<va_start%>");
4178       return const0_rtx;
4179     }
4180
4181   if (fold_builtin_next_arg (exp, true))
4182     return const0_rtx;
4183
4184   nextarg = expand_builtin_next_arg ();
4185   valist = stabilize_va_list_loc (loc, CALL_EXPR_ARG (exp, 0), 1);
4186
4187   if (targetm.expand_builtin_va_start)
4188     targetm.expand_builtin_va_start (valist, nextarg);
4189   else
4190     std_expand_builtin_va_start (valist, nextarg);
4191
4192   return const0_rtx;
4193 }
4194
4195 /* Expand EXP, a call to __builtin_va_end.  */
4196
4197 static rtx
4198 expand_builtin_va_end (tree exp)
4199 {
4200   tree valist = CALL_EXPR_ARG (exp, 0);
4201
4202   /* Evaluate for side effects, if needed.  I hate macros that don't
4203      do that.  */
4204   if (TREE_SIDE_EFFECTS (valist))
4205     expand_expr (valist, const0_rtx, VOIDmode, EXPAND_NORMAL);
4206
4207   return const0_rtx;
4208 }
4209
4210 /* Expand EXP, a call to __builtin_va_copy.  We do this as a
4211    builtin rather than just as an assignment in stdarg.h because of the
4212    nastiness of array-type va_list types.  */
4213
4214 static rtx
4215 expand_builtin_va_copy (tree exp)
4216 {
4217   tree dst, src, t;
4218   location_t loc = EXPR_LOCATION (exp);
4219
4220   dst = CALL_EXPR_ARG (exp, 0);
4221   src = CALL_EXPR_ARG (exp, 1);
4222
4223   dst = stabilize_va_list_loc (loc, dst, 1);
4224   src = stabilize_va_list_loc (loc, src, 0);
4225
4226   gcc_assert (cfun != NULL && cfun->decl != NULL_TREE);
4227
4228   if (TREE_CODE (targetm.fn_abi_va_list (cfun->decl)) != ARRAY_TYPE)
4229     {
4230       t = build2 (MODIFY_EXPR, targetm.fn_abi_va_list (cfun->decl), dst, src);
4231       TREE_SIDE_EFFECTS (t) = 1;
4232       expand_expr (t, const0_rtx, VOIDmode, EXPAND_NORMAL);
4233     }
4234   else
4235     {
4236       rtx dstb, srcb, size;
4237
4238       /* Evaluate to pointers.  */
4239       dstb = expand_expr (dst, NULL_RTX, Pmode, EXPAND_NORMAL);
4240       srcb = expand_expr (src, NULL_RTX, Pmode, EXPAND_NORMAL);
4241       size = expand_expr (TYPE_SIZE_UNIT (targetm.fn_abi_va_list (cfun->decl)),
4242                   NULL_RTX, VOIDmode, EXPAND_NORMAL);
4243
4244       dstb = convert_memory_address (Pmode, dstb);
4245       srcb = convert_memory_address (Pmode, srcb);
4246
4247       /* "Dereference" to BLKmode memories.  */
4248       dstb = gen_rtx_MEM (BLKmode, dstb);
4249       set_mem_alias_set (dstb, get_alias_set (TREE_TYPE (TREE_TYPE (dst))));
4250       set_mem_align (dstb, TYPE_ALIGN (targetm.fn_abi_va_list (cfun->decl)));
4251       srcb = gen_rtx_MEM (BLKmode, srcb);
4252       set_mem_alias_set (srcb, get_alias_set (TREE_TYPE (TREE_TYPE (src))));
4253       set_mem_align (srcb, TYPE_ALIGN (targetm.fn_abi_va_list (cfun->decl)));
4254
4255       /* Copy.  */
4256       emit_block_move (dstb, srcb, size, BLOCK_OP_NORMAL);
4257     }
4258
4259   return const0_rtx;
4260 }
4261
4262 /* Expand a call to one of the builtin functions __builtin_frame_address or
4263    __builtin_return_address.  */
4264
4265 static rtx
4266 expand_builtin_frame_address (tree fndecl, tree exp)
4267 {
4268   /* The argument must be a nonnegative integer constant.
4269      It counts the number of frames to scan up the stack.
4270      The value is either the frame pointer value or the return
4271      address saved in that frame.  */
4272   if (call_expr_nargs (exp) == 0)
4273     /* Warning about missing arg was already issued.  */
4274     return const0_rtx;
4275   else if (! tree_fits_uhwi_p (CALL_EXPR_ARG (exp, 0)))
4276     {
4277       error ("invalid argument to %qD", fndecl);
4278       return const0_rtx;
4279     }
4280   else
4281     {
4282       /* Number of frames to scan up the stack.  */
4283       unsigned HOST_WIDE_INT count = tree_to_uhwi (CALL_EXPR_ARG (exp, 0));
4284
4285       rtx tem = expand_builtin_return_addr (DECL_FUNCTION_CODE (fndecl), count);
4286
4287       /* Some ports cannot access arbitrary stack frames.  */
4288       if (tem == NULL)
4289         {
4290           warning (0, "unsupported argument to %qD", fndecl);
4291           return const0_rtx;
4292         }
4293
4294       if (count)
4295         {
4296           /* Warn since no effort is made to ensure that any frame
4297              beyond the current one exists or can be safely reached.  */
4298           warning (OPT_Wframe_address, "calling %qD with "
4299                    "a nonzero argument is unsafe", fndecl);
4300         }
4301
4302       /* For __builtin_frame_address, return what we've got.  */
4303       if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_FRAME_ADDRESS)
4304         return tem;
4305
4306       if (!REG_P (tem)
4307           && ! CONSTANT_P (tem))
4308         tem = copy_addr_to_reg (tem);
4309       return tem;
4310     }
4311 }
4312
4313 /* Expand EXP, a call to the alloca builtin.  Return NULL_RTX if we
4314    failed and the caller should emit a normal call.  CANNOT_ACCUMULATE
4315    is the same as for allocate_dynamic_stack_space.  */
4316
4317 static rtx
4318 expand_builtin_alloca (tree exp, bool cannot_accumulate)
4319 {
4320   rtx op0;
4321   rtx result;
4322   bool valid_arglist;
4323   unsigned int align;
4324   bool alloca_with_align = (DECL_FUNCTION_CODE (get_callee_fndecl (exp))
4325                             == BUILT_IN_ALLOCA_WITH_ALIGN);
4326
4327   valid_arglist
4328     = (alloca_with_align
4329        ? validate_arglist (exp, INTEGER_TYPE, INTEGER_TYPE, VOID_TYPE)
4330        : validate_arglist (exp, INTEGER_TYPE, VOID_TYPE));
4331
4332   if (!valid_arglist)
4333     return NULL_RTX;
4334
4335   /* Compute the argument.  */
4336   op0 = expand_normal (CALL_EXPR_ARG (exp, 0));
4337
4338   /* Compute the alignment.  */
4339   align = (alloca_with_align
4340            ? TREE_INT_CST_LOW (CALL_EXPR_ARG (exp, 1))
4341            : BIGGEST_ALIGNMENT);
4342
4343   /* Allocate the desired space.  */
4344   result = allocate_dynamic_stack_space (op0, 0, align, cannot_accumulate);
4345   result = convert_memory_address (ptr_mode, result);
4346
4347   return result;
4348 }
4349
4350 /* Expand a call to bswap builtin in EXP.
4351    Return NULL_RTX if a normal call should be emitted rather than expanding the
4352    function in-line.  If convenient, the result should be placed in TARGET.
4353    SUBTARGET may be used as the target for computing one of EXP's operands.  */
4354
4355 static rtx
4356 expand_builtin_bswap (machine_mode target_mode, tree exp, rtx target,
4357                       rtx subtarget)
4358 {
4359   tree arg;
4360   rtx op0;
4361
4362   if (!validate_arglist (exp, INTEGER_TYPE, VOID_TYPE))
4363     return NULL_RTX;
4364
4365   arg = CALL_EXPR_ARG (exp, 0);
4366   op0 = expand_expr (arg,
4367                      subtarget && GET_MODE (subtarget) == target_mode
4368                      ? subtarget : NULL_RTX,
4369                      target_mode, EXPAND_NORMAL);
4370   if (GET_MODE (op0) != target_mode)
4371     op0 = convert_to_mode (target_mode, op0, 1);
4372
4373   target = expand_unop (target_mode, bswap_optab, op0, target, 1);
4374
4375   gcc_assert (target);
4376
4377   return convert_to_mode (target_mode, target, 1);
4378 }
4379
4380 /* Expand a call to a unary builtin in EXP.
4381    Return NULL_RTX if a normal call should be emitted rather than expanding the
4382    function in-line.  If convenient, the result should be placed in TARGET.
4383    SUBTARGET may be used as the target for computing one of EXP's operands.  */
4384
4385 static rtx
4386 expand_builtin_unop (machine_mode target_mode, tree exp, rtx target,
4387                      rtx subtarget, optab op_optab)
4388 {
4389   rtx op0;
4390
4391   if (!validate_arglist (exp, INTEGER_TYPE, VOID_TYPE))
4392     return NULL_RTX;
4393
4394   /* Compute the argument.  */
4395   op0 = expand_expr (CALL_EXPR_ARG (exp, 0),
4396                      (subtarget
4397                       && (TYPE_MODE (TREE_TYPE (CALL_EXPR_ARG (exp, 0)))
4398                           == GET_MODE (subtarget))) ? subtarget : NULL_RTX,
4399                      VOIDmode, EXPAND_NORMAL);
4400   /* Compute op, into TARGET if possible.
4401      Set TARGET to wherever the result comes back.  */
4402   target = expand_unop (TYPE_MODE (TREE_TYPE (CALL_EXPR_ARG (exp, 0))),
4403                         op_optab, op0, target, op_optab != clrsb_optab);
4404   gcc_assert (target);
4405
4406   return convert_to_mode (target_mode, target, 0);
4407 }
4408
4409 /* Expand a call to __builtin_expect.  We just return our argument
4410    as the builtin_expect semantic should've been already executed by
4411    tree branch prediction pass. */
4412
4413 static rtx
4414 expand_builtin_expect (tree exp, rtx target)
4415 {
4416   tree arg;
4417
4418   if (call_expr_nargs (exp) < 2)
4419     return const0_rtx;
4420   arg = CALL_EXPR_ARG (exp, 0);
4421
4422   target = expand_expr (arg, target, VOIDmode, EXPAND_NORMAL);
4423   /* When guessing was done, the hints should be already stripped away.  */
4424   gcc_assert (!flag_guess_branch_prob
4425               || optimize == 0 || seen_error ());
4426   return target;
4427 }
4428
4429 /* Expand a call to __builtin_assume_aligned.  We just return our first
4430    argument as the builtin_assume_aligned semantic should've been already
4431    executed by CCP.  */
4432
4433 static rtx
4434 expand_builtin_assume_aligned (tree exp, rtx target)
4435 {
4436   if (call_expr_nargs (exp) < 2)
4437     return const0_rtx;
4438   target = expand_expr (CALL_EXPR_ARG (exp, 0), target, VOIDmode,
4439                         EXPAND_NORMAL);
4440   gcc_assert (!TREE_SIDE_EFFECTS (CALL_EXPR_ARG (exp, 1))
4441               && (call_expr_nargs (exp) < 3
4442                   || !TREE_SIDE_EFFECTS (CALL_EXPR_ARG (exp, 2))));
4443   return target;
4444 }
4445
4446 void
4447 expand_builtin_trap (void)
4448 {
4449   if (targetm.have_trap ())
4450     {
4451       rtx_insn *insn = emit_insn (targetm.gen_trap ());
4452       /* For trap insns when not accumulating outgoing args force
4453          REG_ARGS_SIZE note to prevent crossjumping of calls with
4454          different args sizes.  */
4455       if (!ACCUMULATE_OUTGOING_ARGS)
4456         add_reg_note (insn, REG_ARGS_SIZE, GEN_INT (stack_pointer_delta));
4457     }
4458   else
4459     emit_library_call (abort_libfunc, LCT_NORETURN, VOIDmode, 0);
4460   emit_barrier ();
4461 }
4462
4463 /* Expand a call to __builtin_unreachable.  We do nothing except emit
4464    a barrier saying that control flow will not pass here.
4465
4466    It is the responsibility of the program being compiled to ensure
4467    that control flow does never reach __builtin_unreachable.  */
4468 static void
4469 expand_builtin_unreachable (void)
4470 {
4471   emit_barrier ();
4472 }
4473
4474 /* Expand EXP, a call to fabs, fabsf or fabsl.
4475    Return NULL_RTX if a normal call should be emitted rather than expanding
4476    the function inline.  If convenient, the result should be placed
4477    in TARGET.  SUBTARGET may be used as the target for computing
4478    the operand.  */
4479
4480 static rtx
4481 expand_builtin_fabs (tree exp, rtx target, rtx subtarget)
4482 {
4483   machine_mode mode;
4484   tree arg;
4485   rtx op0;
4486
4487   if (!validate_arglist (exp, REAL_TYPE, VOID_TYPE))
4488     return NULL_RTX;
4489
4490   arg = CALL_EXPR_ARG (exp, 0);
4491   CALL_EXPR_ARG (exp, 0) = arg = builtin_save_expr (arg);
4492   mode = TYPE_MODE (TREE_TYPE (arg));
4493   op0 = expand_expr (arg, subtarget, VOIDmode, EXPAND_NORMAL);
4494   return expand_abs (mode, op0, target, 0, safe_from_p (target, arg, 1));
4495 }
4496
4497 /* Expand EXP, a call to copysign, copysignf, or copysignl.
4498    Return NULL is a normal call should be emitted rather than expanding the
4499    function inline.  If convenient, the result should be placed in TARGET.
4500    SUBTARGET may be used as the target for computing the operand.  */
4501
4502 static rtx
4503 expand_builtin_copysign (tree exp, rtx target, rtx subtarget)
4504 {
4505   rtx op0, op1;
4506   tree arg;
4507
4508   if (!validate_arglist (exp, REAL_TYPE, REAL_TYPE, VOID_TYPE))
4509     return NULL_RTX;
4510
4511   arg = CALL_EXPR_ARG (exp, 0);
4512   op0 = expand_expr (arg, subtarget, VOIDmode, EXPAND_NORMAL);
4513
4514   arg = CALL_EXPR_ARG (exp, 1);
4515   op1 = expand_normal (arg);
4516
4517   return expand_copysign (op0, op1, target);
4518 }
4519
4520 /* Expand a call to __builtin___clear_cache.  */
4521
4522 static rtx
4523 expand_builtin___clear_cache (tree exp)
4524 {
4525   if (!targetm.code_for_clear_cache)
4526     {
4527 #ifdef CLEAR_INSN_CACHE
4528       /* There is no "clear_cache" insn, and __clear_cache() in libgcc
4529          does something.  Just do the default expansion to a call to
4530          __clear_cache().  */
4531       return NULL_RTX;
4532 #else
4533       /* There is no "clear_cache" insn, and __clear_cache() in libgcc
4534          does nothing.  There is no need to call it.  Do nothing.  */
4535       return const0_rtx;
4536 #endif /* CLEAR_INSN_CACHE */
4537     }
4538
4539   /* We have a "clear_cache" insn, and it will handle everything.  */
4540   tree begin, end;
4541   rtx begin_rtx, end_rtx;
4542
4543   /* We must not expand to a library call.  If we did, any
4544      fallback library function in libgcc that might contain a call to
4545      __builtin___clear_cache() would recurse infinitely.  */
4546   if (!validate_arglist (exp, POINTER_TYPE, POINTER_TYPE, VOID_TYPE))
4547     {
4548       error ("both arguments to %<__builtin___clear_cache%> must be pointers");
4549       return const0_rtx;
4550     }
4551
4552   if (targetm.have_clear_cache ())
4553     {
4554       struct expand_operand ops[2];
4555
4556       begin = CALL_EXPR_ARG (exp, 0);
4557       begin_rtx = expand_expr (begin, NULL_RTX, Pmode, EXPAND_NORMAL);
4558
4559       end = CALL_EXPR_ARG (exp, 1);
4560       end_rtx = expand_expr (end, NULL_RTX, Pmode, EXPAND_NORMAL);
4561
4562       create_address_operand (&ops[0], begin_rtx);
4563       create_address_operand (&ops[1], end_rtx);
4564       if (maybe_expand_insn (targetm.code_for_clear_cache, 2, ops))
4565         return const0_rtx;
4566     }
4567   return const0_rtx;
4568 }
4569
4570 /* Given a trampoline address, make sure it satisfies TRAMPOLINE_ALIGNMENT.  */
4571
4572 static rtx
4573 round_trampoline_addr (rtx tramp)
4574 {
4575   rtx temp, addend, mask;
4576
4577   /* If we don't need too much alignment, we'll have been guaranteed
4578      proper alignment by get_trampoline_type.  */
4579   if (TRAMPOLINE_ALIGNMENT <= STACK_BOUNDARY)
4580     return tramp;
4581
4582   /* Round address up to desired boundary.  */
4583   temp = gen_reg_rtx (Pmode);
4584   addend = gen_int_mode (TRAMPOLINE_ALIGNMENT / BITS_PER_UNIT - 1, Pmode);
4585   mask = gen_int_mode (-TRAMPOLINE_ALIGNMENT / BITS_PER_UNIT, Pmode);
4586
4587   temp  = expand_simple_binop (Pmode, PLUS, tramp, addend,
4588                                temp, 0, OPTAB_LIB_WIDEN);
4589   tramp = expand_simple_binop (Pmode, AND, temp, mask,
4590                                temp, 0, OPTAB_LIB_WIDEN);
4591
4592   return tramp;
4593 }
4594
4595 static rtx
4596 expand_builtin_init_trampoline (tree exp, bool onstack)
4597 {
4598   tree t_tramp, t_func, t_chain;
4599   rtx m_tramp, r_tramp, r_chain, tmp;
4600
4601   if (!validate_arglist (exp, POINTER_TYPE, POINTER_TYPE,
4602                          POINTER_TYPE, VOID_TYPE))
4603     return NULL_RTX;
4604
4605   t_tramp = CALL_EXPR_ARG (exp, 0);
4606   t_func = CALL_EXPR_ARG (exp, 1);
4607   t_chain = CALL_EXPR_ARG (exp, 2);
4608
4609   r_tramp = expand_normal (t_tramp);
4610   m_tramp = gen_rtx_MEM (BLKmode, r_tramp);
4611   MEM_NOTRAP_P (m_tramp) = 1;
4612
4613   /* If ONSTACK, the TRAMP argument should be the address of a field
4614      within the local function's FRAME decl.  Either way, let's see if
4615      we can fill in the MEM_ATTRs for this memory.  */
4616   if (TREE_CODE (t_tramp) == ADDR_EXPR)
4617     set_mem_attributes (m_tramp, TREE_OPERAND (t_tramp, 0), true);
4618
4619   /* Creator of a heap trampoline is responsible for making sure the
4620      address is aligned to at least STACK_BOUNDARY.  Normally malloc
4621      will ensure this anyhow.  */
4622   tmp = round_trampoline_addr (r_tramp);
4623   if (tmp != r_tramp)
4624     {
4625       m_tramp = change_address (m_tramp, BLKmode, tmp);
4626       set_mem_align (m_tramp, TRAMPOLINE_ALIGNMENT);
4627       set_mem_size (m_tramp, TRAMPOLINE_SIZE);
4628     }
4629
4630   /* The FUNC argument should be the address of the nested function.
4631      Extract the actual function decl to pass to the hook.  */
4632   gcc_assert (TREE_CODE (t_func) == ADDR_EXPR);
4633   t_func = TREE_OPERAND (t_func, 0);
4634   gcc_assert (TREE_CODE (t_func) == FUNCTION_DECL);
4635
4636   r_chain = expand_normal (t_chain);
4637
4638   /* Generate insns to initialize the trampoline.  */
4639   targetm.calls.trampoline_init (m_tramp, t_func, r_chain);
4640
4641   if (onstack)
4642     {
4643       trampolines_created = 1;
4644
4645       warning_at (DECL_SOURCE_LOCATION (t_func), OPT_Wtrampolines,
4646                   "trampoline generated for nested function %qD", t_func);
4647     }
4648
4649   return const0_rtx;
4650 }
4651
4652 static rtx
4653 expand_builtin_adjust_trampoline (tree exp)
4654 {
4655   rtx tramp;
4656
4657   if (!validate_arglist (exp, POINTER_TYPE, VOID_TYPE))
4658     return NULL_RTX;
4659
4660   tramp = expand_normal (CALL_EXPR_ARG (exp, 0));
4661   tramp = round_trampoline_addr (tramp);
4662   if (targetm.calls.trampoline_adjust_address)
4663     tramp = targetm.calls.trampoline_adjust_address (tramp);
4664
4665   return tramp;
4666 }
4667
4668 /* Expand the call EXP to the built-in signbit, signbitf or signbitl
4669    function.  The function first checks whether the back end provides
4670    an insn to implement signbit for the respective mode.  If not, it
4671    checks whether the floating point format of the value is such that
4672    the sign bit can be extracted.  If that is not the case, error out.
4673    EXP is the expression that is a call to the builtin function; if
4674    convenient, the result should be placed in TARGET.  */
4675 static rtx
4676 expand_builtin_signbit (tree exp, rtx target)
4677 {
4678   const struct real_format *fmt;
4679   machine_mode fmode, imode, rmode;
4680   tree arg;
4681   int word, bitpos;
4682   enum insn_code icode;
4683   rtx temp;
4684   location_t loc = EXPR_LOCATION (exp);
4685
4686   if (!validate_arglist (exp, REAL_TYPE, VOID_TYPE))
4687     return NULL_RTX;
4688
4689   arg = CALL_EXPR_ARG (exp, 0);
4690   fmode = TYPE_MODE (TREE_TYPE (arg));
4691   rmode = TYPE_MODE (TREE_TYPE (exp));
4692   fmt = REAL_MODE_FORMAT (fmode);
4693
4694   arg = builtin_save_expr (arg);
4695
4696   /* Expand the argument yielding a RTX expression. */
4697   temp = expand_normal (arg);
4698
4699   /* Check if the back end provides an insn that handles signbit for the
4700      argument's mode. */
4701   icode = optab_handler (signbit_optab, fmode);
4702   if (icode != CODE_FOR_nothing)
4703     {
4704       rtx_insn *last = get_last_insn ();
4705       target = gen_reg_rtx (TYPE_MODE (TREE_TYPE (exp)));
4706       if (maybe_emit_unop_insn (icode, target, temp, UNKNOWN))
4707         return target;
4708       delete_insns_since (last);
4709     }
4710
4711   /* For floating point formats without a sign bit, implement signbit
4712      as "ARG < 0.0".  */
4713   bitpos = fmt->signbit_ro;
4714   if (bitpos < 0)
4715   {
4716     /* But we can't do this if the format supports signed zero.  */
4717     gcc_assert (!fmt->has_signed_zero || !HONOR_SIGNED_ZEROS (fmode));
4718
4719     arg = fold_build2_loc (loc, LT_EXPR, TREE_TYPE (exp), arg,
4720                        build_real (TREE_TYPE (arg), dconst0));
4721     return expand_expr (arg, target, VOIDmode, EXPAND_NORMAL);
4722   }
4723
4724   if (GET_MODE_SIZE (fmode) <= UNITS_PER_WORD)
4725     {
4726       imode = int_mode_for_mode (fmode);
4727       gcc_assert (imode != BLKmode);
4728       temp = gen_lowpart (imode, temp);
4729     }
4730   else
4731     {
4732       imode = word_mode;
4733       /* Handle targets with different FP word orders.  */
4734       if (FLOAT_WORDS_BIG_ENDIAN)
4735         word = (GET_MODE_BITSIZE (fmode) - bitpos) / BITS_PER_WORD;
4736       else
4737         word = bitpos / BITS_PER_WORD;
4738       temp = operand_subword_force (temp, word, fmode);
4739       bitpos = bitpos % BITS_PER_WORD;
4740     }
4741
4742   /* Force the intermediate word_mode (or narrower) result into a
4743      register.  This avoids attempting to create paradoxical SUBREGs
4744      of floating point modes below.  */
4745   temp = force_reg (imode, temp);
4746
4747   /* If the bitpos is within the "result mode" lowpart, the operation
4748      can be implement with a single bitwise AND.  Otherwise, we need
4749      a right shift and an AND.  */
4750
4751   if (bitpos < GET_MODE_BITSIZE (rmode))
4752     {
4753       wide_int mask = wi::set_bit_in_zero (bitpos, GET_MODE_PRECISION (rmode));
4754
4755       if (GET_MODE_SIZE (imode) > GET_MODE_SIZE (rmode))
4756         temp = gen_lowpart (rmode, temp);
4757       temp = expand_binop (rmode, and_optab, temp,
4758                            immed_wide_int_const (mask, rmode),
4759                            NULL_RTX, 1, OPTAB_LIB_WIDEN);
4760     }
4761   else
4762     {
4763       /* Perform a logical right shift to place the signbit in the least
4764          significant bit, then truncate the result to the desired mode
4765          and mask just this bit.  */
4766       temp = expand_shift (RSHIFT_EXPR, imode, temp, bitpos, NULL_RTX, 1);
4767       temp = gen_lowpart (rmode, temp);
4768       temp = expand_binop (rmode, and_optab, temp, const1_rtx,
4769                            NULL_RTX, 1, OPTAB_LIB_WIDEN);
4770     }
4771
4772   return temp;
4773 }
4774
4775 /* Expand fork or exec calls.  TARGET is the desired target of the
4776    call.  EXP is the call. FN is the
4777    identificator of the actual function.  IGNORE is nonzero if the
4778    value is to be ignored.  */
4779
4780 static rtx
4781 expand_builtin_fork_or_exec (tree fn, tree exp, rtx target, int ignore)
4782 {
4783   tree id, decl;
4784   tree call;
4785
4786   /* If we are not profiling, just call the function.  */
4787   if (!profile_arc_flag)
4788     return NULL_RTX;
4789
4790   /* Otherwise call the wrapper.  This should be equivalent for the rest of
4791      compiler, so the code does not diverge, and the wrapper may run the
4792      code necessary for keeping the profiling sane.  */
4793
4794   switch (DECL_FUNCTION_CODE (fn))
4795     {
4796     case BUILT_IN_FORK:
4797       id = get_identifier ("__gcov_fork");
4798       break;
4799
4800     case BUILT_IN_EXECL:
4801       id = get_identifier ("__gcov_execl");
4802       break;
4803
4804     case BUILT_IN_EXECV:
4805       id = get_identifier ("__gcov_execv");
4806       break;
4807
4808     case BUILT_IN_EXECLP:
4809       id = get_identifier ("__gcov_execlp");
4810       break;
4811
4812     case BUILT_IN_EXECLE:
4813       id = get_identifier ("__gcov_execle");
4814       break;
4815
4816     case BUILT_IN_EXECVP:
4817       id = get_identifier ("__gcov_execvp");
4818       break;
4819
4820     case BUILT_IN_EXECVE:
4821       id = get_identifier ("__gcov_execve");
4822       break;
4823
4824     default:
4825       gcc_unreachable ();
4826     }
4827
4828   decl = build_decl (DECL_SOURCE_LOCATION (fn),
4829                      FUNCTION_DECL, id, TREE_TYPE (fn));
4830   DECL_EXTERNAL (decl) = 1;
4831   TREE_PUBLIC (decl) = 1;
4832   DECL_ARTIFICIAL (decl) = 1;
4833   TREE_NOTHROW (decl) = 1;
4834   DECL_VISIBILITY (decl) = VISIBILITY_DEFAULT;
4835   DECL_VISIBILITY_SPECIFIED (decl) = 1;
4836   call = rewrite_call_expr (EXPR_LOCATION (exp), exp, 0, decl, 0);
4837   return expand_call (call, target, ignore);
4838  }
4839
4840
4841 \f
4842 /* Reconstitute a mode for a __sync intrinsic operation.  Since the type of
4843    the pointer in these functions is void*, the tree optimizers may remove
4844    casts.  The mode computed in expand_builtin isn't reliable either, due
4845    to __sync_bool_compare_and_swap.
4846
4847    FCODE_DIFF should be fcode - base, where base is the FOO_1 code for the
4848    group of builtins.  This gives us log2 of the mode size.  */
4849
4850 static inline machine_mode
4851 get_builtin_sync_mode (int fcode_diff)
4852 {
4853   /* The size is not negotiable, so ask not to get BLKmode in return
4854      if the target indicates that a smaller size would be better.  */
4855   return mode_for_size (BITS_PER_UNIT << fcode_diff, MODE_INT, 0);
4856 }
4857
4858 /* Expand the memory expression LOC and return the appropriate memory operand
4859    for the builtin_sync operations.  */
4860
4861 static rtx
4862 get_builtin_sync_mem (tree loc, machine_mode mode)
4863 {
4864   rtx addr, mem;
4865
4866   addr = expand_expr (loc, NULL_RTX, ptr_mode, EXPAND_SUM);
4867   addr = convert_memory_address (Pmode, addr);
4868
4869   /* Note that we explicitly do not want any alias information for this
4870      memory, so that we kill all other live memories.  Otherwise we don't
4871      satisfy the full barrier semantics of the intrinsic.  */
4872   mem = validize_mem (gen_rtx_MEM (mode, addr));
4873
4874   /* The alignment needs to be at least according to that of the mode.  */
4875   set_mem_align (mem, MAX (GET_MODE_ALIGNMENT (mode),
4876                            get_pointer_alignment (loc)));
4877   set_mem_alias_set (mem, ALIAS_SET_MEMORY_BARRIER);
4878   MEM_VOLATILE_P (mem) = 1;
4879
4880   return mem;
4881 }
4882
4883 /* Make sure an argument is in the right mode.
4884    EXP is the tree argument. 
4885    MODE is the mode it should be in.  */
4886
4887 static rtx
4888 expand_expr_force_mode (tree exp, machine_mode mode)
4889 {
4890   rtx val;
4891   machine_mode old_mode;
4892
4893   val = expand_expr (exp, NULL_RTX, mode, EXPAND_NORMAL);
4894   /* If VAL is promoted to a wider mode, convert it back to MODE.  Take care
4895      of CONST_INTs, where we know the old_mode only from the call argument.  */
4896
4897   old_mode = GET_MODE (val);
4898   if (old_mode == VOIDmode)
4899     old_mode = TYPE_MODE (TREE_TYPE (exp));
4900   val = convert_modes (mode, old_mode, val, 1);
4901   return val;
4902 }
4903
4904
4905 /* Expand the __sync_xxx_and_fetch and __sync_fetch_and_xxx intrinsics.
4906    EXP is the CALL_EXPR.  CODE is the rtx code
4907    that corresponds to the arithmetic or logical operation from the name;
4908    an exception here is that NOT actually means NAND.  TARGET is an optional
4909    place for us to store the results; AFTER is true if this is the
4910    fetch_and_xxx form.  */
4911
4912 static rtx
4913 expand_builtin_sync_operation (machine_mode mode, tree exp,
4914                                enum rtx_code code, bool after,
4915                                rtx target)
4916 {
4917   rtx val, mem;
4918   location_t loc = EXPR_LOCATION (exp);
4919
4920   if (code == NOT && warn_sync_nand)
4921     {
4922       tree fndecl = get_callee_fndecl (exp);
4923       enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
4924
4925       static bool warned_f_a_n, warned_n_a_f;
4926
4927       switch (fcode)
4928         {
4929         case BUILT_IN_SYNC_FETCH_AND_NAND_1:
4930         case BUILT_IN_SYNC_FETCH_AND_NAND_2:
4931         case BUILT_IN_SYNC_FETCH_AND_NAND_4:
4932         case BUILT_IN_SYNC_FETCH_AND_NAND_8:
4933         case BUILT_IN_SYNC_FETCH_AND_NAND_16:
4934           if (warned_f_a_n)
4935             break;
4936
4937           fndecl = builtin_decl_implicit (BUILT_IN_SYNC_FETCH_AND_NAND_N);
4938           inform (loc, "%qD changed semantics in GCC 4.4", fndecl);
4939           warned_f_a_n = true;
4940           break;
4941
4942         case BUILT_IN_SYNC_NAND_AND_FETCH_1:
4943         case BUILT_IN_SYNC_NAND_AND_FETCH_2:
4944         case BUILT_IN_SYNC_NAND_AND_FETCH_4:
4945         case BUILT_IN_SYNC_NAND_AND_FETCH_8:
4946         case BUILT_IN_SYNC_NAND_AND_FETCH_16:
4947           if (warned_n_a_f)
4948             break;
4949
4950          fndecl = builtin_decl_implicit (BUILT_IN_SYNC_NAND_AND_FETCH_N);
4951           inform (loc, "%qD changed semantics in GCC 4.4", fndecl);
4952           warned_n_a_f = true;
4953           break;
4954
4955         default:
4956           gcc_unreachable ();
4957         }
4958     }
4959
4960   /* Expand the operands.  */
4961   mem = get_builtin_sync_mem (CALL_EXPR_ARG (exp, 0), mode);
4962   val = expand_expr_force_mode (CALL_EXPR_ARG (exp, 1), mode);
4963
4964   return expand_atomic_fetch_op (target, mem, val, code, MEMMODEL_SYNC_SEQ_CST,
4965                                  after);
4966 }
4967
4968 /* Expand the __sync_val_compare_and_swap and __sync_bool_compare_and_swap
4969    intrinsics. EXP is the CALL_EXPR.  IS_BOOL is
4970    true if this is the boolean form.  TARGET is a place for us to store the
4971    results; this is NOT optional if IS_BOOL is true.  */
4972
4973 static rtx
4974 expand_builtin_compare_and_swap (machine_mode mode, tree exp,
4975                                  bool is_bool, rtx target)
4976 {
4977   rtx old_val, new_val, mem;
4978   rtx *pbool, *poval;
4979
4980   /* Expand the operands.  */
4981   mem = get_builtin_sync_mem (CALL_EXPR_ARG (exp, 0), mode);
4982   old_val = expand_expr_force_mode (CALL_EXPR_ARG (exp, 1), mode);
4983   new_val = expand_expr_force_mode (CALL_EXPR_ARG (exp, 2), mode);
4984
4985   pbool = poval = NULL;
4986   if (target != const0_rtx)
4987     {
4988       if (is_bool)
4989         pbool = &target;
4990       else
4991         poval = &target;
4992     }
4993   if (!expand_atomic_compare_and_swap (pbool, poval, mem, old_val, new_val,
4994                                        false, MEMMODEL_SYNC_SEQ_CST,
4995                                        MEMMODEL_SYNC_SEQ_CST))
4996     return NULL_RTX;
4997
4998   return target;
4999 }
5000
5001 /* Expand the __sync_lock_test_and_set intrinsic.  Note that the most
5002    general form is actually an atomic exchange, and some targets only
5003    support a reduced form with the second argument being a constant 1.
5004    EXP is the CALL_EXPR; TARGET is an optional place for us to store
5005    the results.  */
5006
5007 static rtx
5008 expand_builtin_sync_lock_test_and_set (machine_mode mode, tree exp,
5009                                        rtx target)
5010 {
5011   rtx val, mem;
5012
5013   /* Expand the operands.  */
5014   mem = get_builtin_sync_mem (CALL_EXPR_ARG (exp, 0), mode);
5015   val = expand_expr_force_mode (CALL_EXPR_ARG (exp, 1), mode);
5016
5017   return expand_sync_lock_test_and_set (target, mem, val);
5018 }
5019
5020 /* Expand the __sync_lock_release intrinsic.  EXP is the CALL_EXPR.  */
5021
5022 static void
5023 expand_builtin_sync_lock_release (machine_mode mode, tree exp)
5024 {
5025   rtx mem;
5026
5027   /* Expand the operands.  */
5028   mem = get_builtin_sync_mem (CALL_EXPR_ARG (exp, 0), mode);
5029
5030   expand_atomic_store (mem, const0_rtx, MEMMODEL_SYNC_RELEASE, true);
5031 }
5032
5033 /* Given an integer representing an ``enum memmodel'', verify its
5034    correctness and return the memory model enum.  */
5035
5036 static enum memmodel
5037 get_memmodel (tree exp)
5038 {
5039   rtx op;
5040   unsigned HOST_WIDE_INT val;
5041   source_location loc
5042     = expansion_point_location_if_in_system_header (input_location);
5043
5044   /* If the parameter is not a constant, it's a run time value so we'll just
5045      convert it to MEMMODEL_SEQ_CST to avoid annoying runtime checking.  */
5046   if (TREE_CODE (exp) != INTEGER_CST)
5047     return MEMMODEL_SEQ_CST;
5048
5049   op = expand_normal (exp);
5050
5051   val = INTVAL (op);
5052   if (targetm.memmodel_check)
5053     val = targetm.memmodel_check (val);
5054   else if (val & ~MEMMODEL_MASK)
5055     {
5056       warning_at (loc, OPT_Winvalid_memory_model,
5057                   "unknown architecture specifier in memory model to builtin");
5058       return MEMMODEL_SEQ_CST;
5059     }
5060
5061   /* Should never see a user explicit SYNC memodel model, so >= LAST works. */
5062   if (memmodel_base (val) >= MEMMODEL_LAST)
5063     {
5064       warning_at (loc, OPT_Winvalid_memory_model,
5065                   "invalid memory model argument to builtin");
5066       return MEMMODEL_SEQ_CST;
5067     }
5068
5069   /* Workaround for Bugzilla 59448. GCC doesn't track consume properly, so
5070      be conservative and promote consume to acquire.  */
5071   if (val == MEMMODEL_CONSUME)
5072     val = MEMMODEL_ACQUIRE;
5073
5074   return (enum memmodel) val;
5075 }
5076
5077 /* Expand the __atomic_exchange intrinsic:
5078         TYPE __atomic_exchange (TYPE *object, TYPE desired, enum memmodel)
5079    EXP is the CALL_EXPR.
5080    TARGET is an optional place for us to store the results.  */
5081
5082 static rtx
5083 expand_builtin_atomic_exchange (machine_mode mode, tree exp, rtx target)
5084 {
5085   rtx val, mem;
5086   enum memmodel model;
5087
5088   model = get_memmodel (CALL_EXPR_ARG (exp, 2));
5089
5090   if (!flag_inline_atomics)
5091     return NULL_RTX;
5092
5093   /* Expand the operands.  */
5094   mem = get_builtin_sync_mem (CALL_EXPR_ARG (exp, 0), mode);
5095   val = expand_expr_force_mode (CALL_EXPR_ARG (exp, 1), mode);
5096
5097   return expand_atomic_exchange (target, mem, val, model);
5098 }
5099
5100 /* Expand the __atomic_compare_exchange intrinsic:
5101         bool __atomic_compare_exchange (TYPE *object, TYPE *expect, 
5102                                         TYPE desired, BOOL weak, 
5103                                         enum memmodel success,
5104                                         enum memmodel failure)
5105    EXP is the CALL_EXPR.
5106    TARGET is an optional place for us to store the results.  */
5107
5108 static rtx
5109 expand_builtin_atomic_compare_exchange (machine_mode mode, tree exp, 
5110                                         rtx target)
5111 {
5112   rtx expect, desired, mem, oldval;
5113   rtx_code_label *label;
5114   enum memmodel success, failure;
5115   tree weak;
5116   bool is_weak;
5117   source_location loc
5118     = expansion_point_location_if_in_system_header (input_location);
5119
5120   success = get_memmodel (CALL_EXPR_ARG (exp, 4));
5121   failure = get_memmodel (CALL_EXPR_ARG (exp, 5));
5122
5123   if (failure > success)
5124     {
5125       warning_at (loc, OPT_Winvalid_memory_model,
5126                   "failure memory model cannot be stronger than success "
5127                   "memory model for %<__atomic_compare_exchange%>");
5128       success = MEMMODEL_SEQ_CST;
5129     }
5130  
5131   if (is_mm_release (failure) || is_mm_acq_rel (failure))
5132     {
5133       warning_at (loc, OPT_Winvalid_memory_model,
5134                   "invalid failure memory model for "
5135                   "%<__atomic_compare_exchange%>");
5136       failure = MEMMODEL_SEQ_CST;
5137       success = MEMMODEL_SEQ_CST;
5138     }
5139
5140  
5141   if (!flag_inline_atomics)
5142     return NULL_RTX;
5143
5144   /* Expand the operands.  */
5145   mem = get_builtin_sync_mem (CALL_EXPR_ARG (exp, 0), mode);
5146
5147   expect = expand_normal (CALL_EXPR_ARG (exp, 1));
5148   expect = convert_memory_address (Pmode, expect);
5149   expect = gen_rtx_MEM (mode, expect);
5150   desired = expand_expr_force_mode (CALL_EXPR_ARG (exp, 2), mode);
5151
5152   weak = CALL_EXPR_ARG (exp, 3);
5153   is_weak = false;
5154   if (tree_fits_shwi_p (weak) && tree_to_shwi (weak) != 0)
5155     is_weak = true;
5156
5157   if (target == const0_rtx)
5158     target = NULL;
5159
5160   /* Lest the rtl backend create a race condition with an imporoper store
5161      to memory, always create a new pseudo for OLDVAL.  */
5162   oldval = NULL;
5163
5164   if (!expand_atomic_compare_and_swap (&target, &oldval, mem, expect, desired,
5165                                        is_weak, success, failure))
5166     return NULL_RTX;
5167
5168   /* Conditionally store back to EXPECT, lest we create a race condition
5169      with an improper store to memory.  */
5170   /* ??? With a rearrangement of atomics at the gimple level, we can handle
5171      the normal case where EXPECT is totally private, i.e. a register.  At
5172      which point the store can be unconditional.  */
5173   label = gen_label_rtx ();
5174   emit_cmp_and_jump_insns (target, const0_rtx, NE, NULL,
5175                            GET_MODE (target), 1, label);
5176   emit_move_insn (expect, oldval);
5177   emit_label (label);
5178
5179   return target;
5180 }
5181
5182 /* Expand the __atomic_load intrinsic:
5183         TYPE __atomic_load (TYPE *object, enum memmodel)
5184    EXP is the CALL_EXPR.
5185    TARGET is an optional place for us to store the results.  */
5186
5187 static rtx
5188 expand_builtin_atomic_load (machine_mode mode, tree exp, rtx target)
5189 {
5190   rtx mem;
5191   enum memmodel model;
5192
5193   model = get_memmodel (CALL_EXPR_ARG (exp, 1));
5194   if (is_mm_release (model) || is_mm_acq_rel (model))
5195     {
5196       source_location loc
5197         = expansion_point_location_if_in_system_header (input_location);
5198       warning_at (loc, OPT_Winvalid_memory_model,
5199                   "invalid memory model for %<__atomic_load%>");
5200       model = MEMMODEL_SEQ_CST;
5201     }
5202
5203   if (!flag_inline_atomics)
5204     return NULL_RTX;
5205
5206   /* Expand the operand.  */
5207   mem = get_builtin_sync_mem (CALL_EXPR_ARG (exp, 0), mode);
5208
5209   return expand_atomic_load (target, mem, model);
5210 }
5211
5212
5213 /* Expand the __atomic_store intrinsic:
5214         void __atomic_store (TYPE *object, TYPE desired, enum memmodel)
5215    EXP is the CALL_EXPR.
5216    TARGET is an optional place for us to store the results.  */
5217
5218 static rtx
5219 expand_builtin_atomic_store (machine_mode mode, tree exp)
5220 {
5221   rtx mem, val;
5222   enum memmodel model;
5223
5224   model = get_memmodel (CALL_EXPR_ARG (exp, 2));
5225   if (!(is_mm_relaxed (model) || is_mm_seq_cst (model)
5226         || is_mm_release (model)))
5227     {
5228       source_location loc
5229         = expansion_point_location_if_in_system_header (input_location);
5230       warning_at (loc, OPT_Winvalid_memory_model,
5231                   "invalid memory model for %<__atomic_store%>");
5232       model = MEMMODEL_SEQ_CST;
5233     }
5234
5235   if (!flag_inline_atomics)
5236     return NULL_RTX;
5237
5238   /* Expand the operands.  */
5239   mem = get_builtin_sync_mem (CALL_EXPR_ARG (exp, 0), mode);
5240   val = expand_expr_force_mode (CALL_EXPR_ARG (exp, 1), mode);
5241
5242   return expand_atomic_store (mem, val, model, false);
5243 }
5244
5245 /* Expand the __atomic_fetch_XXX intrinsic:
5246         TYPE __atomic_fetch_XXX (TYPE *object, TYPE val, enum memmodel)
5247    EXP is the CALL_EXPR.
5248    TARGET is an optional place for us to store the results.
5249    CODE is the operation, PLUS, MINUS, ADD, XOR, or IOR.
5250    FETCH_AFTER is true if returning the result of the operation.
5251    FETCH_AFTER is false if returning the value before the operation.
5252    IGNORE is true if the result is not used.
5253    EXT_CALL is the correct builtin for an external call if this cannot be
5254    resolved to an instruction sequence.  */
5255
5256 static rtx
5257 expand_builtin_atomic_fetch_op (machine_mode mode, tree exp, rtx target,
5258                                 enum rtx_code code, bool fetch_after,
5259                                 bool ignore, enum built_in_function ext_call)
5260 {
5261   rtx val, mem, ret;
5262   enum memmodel model;
5263   tree fndecl;
5264   tree addr;
5265
5266   model = get_memmodel (CALL_EXPR_ARG (exp, 2));
5267
5268   /* Expand the operands.  */
5269   mem = get_builtin_sync_mem (CALL_EXPR_ARG (exp, 0), mode);
5270   val = expand_expr_force_mode (CALL_EXPR_ARG (exp, 1), mode);
5271
5272   /* Only try generating instructions if inlining is turned on.  */
5273   if (flag_inline_atomics)
5274     {
5275       ret = expand_atomic_fetch_op (target, mem, val, code, model, fetch_after);
5276       if (ret)
5277         return ret;
5278     }
5279
5280   /* Return if a different routine isn't needed for the library call.  */
5281   if (ext_call == BUILT_IN_NONE)
5282     return NULL_RTX;
5283
5284   /* Change the call to the specified function.  */
5285   fndecl = get_callee_fndecl (exp);
5286   addr = CALL_EXPR_FN (exp);
5287   STRIP_NOPS (addr);
5288
5289   gcc_assert (TREE_OPERAND (addr, 0) == fndecl);
5290   TREE_OPERAND (addr, 0) = builtin_decl_explicit (ext_call);
5291
5292   /* Expand the call here so we can emit trailing code.  */
5293   ret = expand_call (exp, target, ignore);
5294
5295   /* Replace the original function just in case it matters.  */
5296   TREE_OPERAND (addr, 0) = fndecl;
5297
5298   /* Then issue the arithmetic correction to return the right result.  */
5299   if (!ignore)
5300     {
5301       if (code == NOT)
5302         {
5303           ret = expand_simple_binop (mode, AND, ret, val, NULL_RTX, true,
5304                                      OPTAB_LIB_WIDEN);
5305           ret = expand_simple_unop (mode, NOT, ret, target, true);
5306         }
5307       else
5308         ret = expand_simple_binop (mode, code, ret, val, target, true,
5309                                    OPTAB_LIB_WIDEN);
5310     }
5311   return ret;
5312 }
5313
5314 /* Expand an atomic clear operation.
5315         void _atomic_clear (BOOL *obj, enum memmodel)
5316    EXP is the call expression.  */
5317
5318 static rtx
5319 expand_builtin_atomic_clear (tree exp) 
5320 {
5321   machine_mode mode;
5322   rtx mem, ret;
5323   enum memmodel model;
5324
5325   mode = mode_for_size (BOOL_TYPE_SIZE, MODE_INT, 0);
5326   mem = get_builtin_sync_mem (CALL_EXPR_ARG (exp, 0), mode);
5327   model = get_memmodel (CALL_EXPR_ARG (exp, 1));
5328
5329   if (is_mm_consume (model) || is_mm_acquire (model) || is_mm_acq_rel (model))
5330     {
5331       source_location loc
5332         = expansion_point_location_if_in_system_header (input_location);
5333       warning_at (loc, OPT_Winvalid_memory_model,
5334                   "invalid memory model for %<__atomic_store%>");
5335       model = MEMMODEL_SEQ_CST;
5336     }
5337
5338   /* Try issuing an __atomic_store, and allow fallback to __sync_lock_release.
5339      Failing that, a store is issued by __atomic_store.  The only way this can
5340      fail is if the bool type is larger than a word size.  Unlikely, but
5341      handle it anyway for completeness.  Assume a single threaded model since
5342      there is no atomic support in this case, and no barriers are required.  */
5343   ret = expand_atomic_store (mem, const0_rtx, model, true);
5344   if (!ret)
5345     emit_move_insn (mem, const0_rtx);
5346   return const0_rtx;
5347 }
5348
5349 /* Expand an atomic test_and_set operation.
5350         bool _atomic_test_and_set (BOOL *obj, enum memmodel)
5351    EXP is the call expression.  */
5352
5353 static rtx
5354 expand_builtin_atomic_test_and_set (tree exp, rtx target)
5355 {
5356   rtx mem;
5357   enum memmodel model;
5358   machine_mode mode;
5359
5360   mode = mode_for_size (BOOL_TYPE_SIZE, MODE_INT, 0);
5361   mem = get_builtin_sync_mem (CALL_EXPR_ARG (exp, 0), mode);
5362   model = get_memmodel (CALL_EXPR_ARG (exp, 1));
5363
5364   return expand_atomic_test_and_set (target, mem, model);
5365 }
5366
5367
5368 /* Return true if (optional) argument ARG1 of size ARG0 is always lock free on
5369    this architecture.  If ARG1 is NULL, use typical alignment for size ARG0.  */
5370
5371 static tree
5372 fold_builtin_atomic_always_lock_free (tree arg0, tree arg1)
5373 {
5374   int size;
5375   machine_mode mode;
5376   unsigned int mode_align, type_align;
5377
5378   if (TREE_CODE (arg0) != INTEGER_CST)
5379     return NULL_TREE;
5380
5381   size = INTVAL (expand_normal (arg0)) * BITS_PER_UNIT;
5382   mode = mode_for_size (size, MODE_INT, 0);
5383   mode_align = GET_MODE_ALIGNMENT (mode);
5384
5385   if (TREE_CODE (arg1) == INTEGER_CST)
5386     {
5387       unsigned HOST_WIDE_INT val = UINTVAL (expand_normal (arg1));
5388
5389       /* Either this argument is null, or it's a fake pointer encoding
5390          the alignment of the object.  */
5391       val = val & -val;
5392       val *= BITS_PER_UNIT;
5393
5394       if (val == 0 || mode_align < val)
5395         type_align = mode_align;
5396       else
5397         type_align = val;
5398     }
5399   else
5400     {
5401       tree ttype = TREE_TYPE (arg1);
5402
5403       /* This function is usually invoked and folded immediately by the front
5404          end before anything else has a chance to look at it.  The pointer
5405          parameter at this point is usually cast to a void *, so check for that
5406          and look past the cast.  */
5407       if (CONVERT_EXPR_P (arg1)
5408           && POINTER_TYPE_P (ttype)
5409           && VOID_TYPE_P (TREE_TYPE (ttype))
5410           && POINTER_TYPE_P (TREE_TYPE (TREE_OPERAND (arg1, 0))))
5411         arg1 = TREE_OPERAND (arg1, 0);
5412
5413       ttype = TREE_TYPE (arg1);
5414       gcc_assert (POINTER_TYPE_P (ttype));
5415
5416       /* Get the underlying type of the object.  */
5417       ttype = TREE_TYPE (ttype);
5418       type_align = TYPE_ALIGN (ttype);
5419     }
5420
5421   /* If the object has smaller alignment, the lock free routines cannot
5422      be used.  */
5423   if (type_align < mode_align)
5424     return boolean_false_node;
5425
5426   /* Check if a compare_and_swap pattern exists for the mode which represents
5427      the required size.  The pattern is not allowed to fail, so the existence
5428      of the pattern indicates support is present.  */
5429   if (can_compare_and_swap_p (mode, true))
5430     return boolean_true_node;
5431   else
5432     return boolean_false_node;
5433 }
5434
5435 /* Return true if the parameters to call EXP represent an object which will
5436    always generate lock free instructions.  The first argument represents the
5437    size of the object, and the second parameter is a pointer to the object 
5438    itself.  If NULL is passed for the object, then the result is based on 
5439    typical alignment for an object of the specified size.  Otherwise return 
5440    false.  */
5441
5442 static rtx
5443 expand_builtin_atomic_always_lock_free (tree exp)
5444 {
5445   tree size;
5446   tree arg0 = CALL_EXPR_ARG (exp, 0);
5447   tree arg1 = CALL_EXPR_ARG (exp, 1);
5448
5449   if (TREE_CODE (arg0) != INTEGER_CST)
5450     {
5451       error ("non-constant argument 1 to __atomic_always_lock_free");
5452       return const0_rtx;
5453     }
5454
5455   size = fold_builtin_atomic_always_lock_free (arg0, arg1);
5456   if (size == boolean_true_node)
5457     return const1_rtx;
5458   return const0_rtx;
5459 }
5460
5461 /* Return a one or zero if it can be determined that object ARG1 of size ARG 
5462    is lock free on this architecture.  */
5463
5464 static tree
5465 fold_builtin_atomic_is_lock_free (tree arg0, tree arg1)
5466 {
5467   if (!flag_inline_atomics)
5468     return NULL_TREE;
5469   
5470   /* If it isn't always lock free, don't generate a result.  */
5471   if (fold_builtin_atomic_always_lock_free (arg0, arg1) == boolean_true_node)
5472     return boolean_true_node;
5473
5474   return NULL_TREE;
5475 }
5476
5477 /* Return true if the parameters to call EXP represent an object which will
5478    always generate lock free instructions.  The first argument represents the
5479    size of the object, and the second parameter is a pointer to the object 
5480    itself.  If NULL is passed for the object, then the result is based on 
5481    typical alignment for an object of the specified size.  Otherwise return 
5482    NULL*/
5483
5484 static rtx
5485 expand_builtin_atomic_is_lock_free (tree exp)
5486 {
5487   tree size;
5488   tree arg0 = CALL_EXPR_ARG (exp, 0);
5489   tree arg1 = CALL_EXPR_ARG (exp, 1);
5490
5491   if (!INTEGRAL_TYPE_P (TREE_TYPE (arg0)))
5492     {
5493       error ("non-integer argument 1 to __atomic_is_lock_free");
5494       return NULL_RTX;
5495     }
5496
5497   if (!flag_inline_atomics)
5498     return NULL_RTX; 
5499
5500   /* If the value is known at compile time, return the RTX for it.  */
5501   size = fold_builtin_atomic_is_lock_free (arg0, arg1);
5502   if (size == boolean_true_node)
5503     return const1_rtx;
5504
5505   return NULL_RTX;
5506 }
5507
5508 /* Expand the __atomic_thread_fence intrinsic:
5509         void __atomic_thread_fence (enum memmodel)
5510    EXP is the CALL_EXPR.  */
5511
5512 static void
5513 expand_builtin_atomic_thread_fence (tree exp)
5514 {
5515   enum memmodel model = get_memmodel (CALL_EXPR_ARG (exp, 0));
5516   expand_mem_thread_fence (model);
5517 }
5518
5519 /* Expand the __atomic_signal_fence intrinsic:
5520         void __atomic_signal_fence (enum memmodel)
5521    EXP is the CALL_EXPR.  */
5522
5523 static void
5524 expand_builtin_atomic_signal_fence (tree exp)
5525 {
5526   enum memmodel model = get_memmodel (CALL_EXPR_ARG (exp, 0));
5527   expand_mem_signal_fence (model);
5528 }
5529
5530 /* Expand the __sync_synchronize intrinsic.  */
5531
5532 static void
5533 expand_builtin_sync_synchronize (void)
5534 {
5535   expand_mem_thread_fence (MEMMODEL_SYNC_SEQ_CST);
5536 }
5537
5538 static rtx
5539 expand_builtin_thread_pointer (tree exp, rtx target)
5540 {
5541   enum insn_code icode;
5542   if (!validate_arglist (exp, VOID_TYPE))
5543     return const0_rtx;
5544   icode = direct_optab_handler (get_thread_pointer_optab, Pmode);
5545   if (icode != CODE_FOR_nothing)
5546     {
5547       struct expand_operand op;
5548       /* If the target is not sutitable then create a new target. */
5549       if (target == NULL_RTX
5550           || !REG_P (target)
5551           || GET_MODE (target) != Pmode)
5552         target = gen_reg_rtx (Pmode);
5553       create_output_operand (&op, target, Pmode);
5554       expand_insn (icode, 1, &op);
5555       return target;
5556     }
5557   error ("__builtin_thread_pointer is not supported on this target");
5558   return const0_rtx;
5559 }
5560
5561 static void
5562 expand_builtin_set_thread_pointer (tree exp)
5563 {
5564   enum insn_code icode;
5565   if (!validate_arglist (exp, POINTER_TYPE, VOID_TYPE))
5566     return;
5567   icode = direct_optab_handler (set_thread_pointer_optab, Pmode);
5568   if (icode != CODE_FOR_nothing)
5569     {
5570       struct expand_operand op;
5571       rtx val = expand_expr (CALL_EXPR_ARG (exp, 0), NULL_RTX,
5572                              Pmode, EXPAND_NORMAL);      
5573       create_input_operand (&op, val, Pmode);
5574       expand_insn (icode, 1, &op);
5575       return;
5576     }
5577   error ("__builtin_set_thread_pointer is not supported on this target");
5578 }
5579
5580 \f
5581 /* Emit code to restore the current value of stack.  */
5582
5583 static void
5584 expand_stack_restore (tree var)
5585 {
5586   rtx_insn *prev;
5587   rtx sa = expand_normal (var);
5588
5589   sa = convert_memory_address (Pmode, sa);
5590
5591   prev = get_last_insn ();
5592   emit_stack_restore (SAVE_BLOCK, sa);
5593
5594   record_new_stack_level ();
5595
5596   fixup_args_size_notes (prev, get_last_insn (), 0);
5597 }
5598
5599 /* Emit code to save the current value of stack.  */
5600
5601 static rtx
5602 expand_stack_save (void)
5603 {
5604   rtx ret = NULL_RTX;
5605
5606   emit_stack_save (SAVE_BLOCK, &ret);
5607   return ret;
5608 }
5609
5610
5611 /* Expand a call to __builtin_speculation_safe_value_<N>.  MODE
5612    represents the size of the first argument to that call, or VOIDmode
5613    if the argument is a pointer.  IGNORE will be true if the result
5614    isn't used.  */
5615 static rtx
5616 expand_speculation_safe_value (machine_mode mode, tree exp, rtx target,
5617                                bool ignore)
5618 {
5619   rtx val, failsafe;
5620   unsigned nargs = call_expr_nargs (exp);
5621
5622   tree arg0 = CALL_EXPR_ARG (exp, 0);
5623
5624   if (mode == VOIDmode)
5625     {
5626       mode = TYPE_MODE (TREE_TYPE (arg0));
5627       gcc_assert (GET_MODE_CLASS (mode) == MODE_INT);
5628     }
5629
5630   val = expand_expr (arg0, NULL_RTX, mode, EXPAND_NORMAL);
5631
5632   /* An optional second argument can be used as a failsafe value on
5633      some machines.  If it isn't present, then the failsafe value is
5634      assumed to be 0.  */
5635   if (nargs > 1)
5636     {
5637       tree arg1 = CALL_EXPR_ARG (exp, 1);
5638       failsafe = expand_expr (arg1, NULL_RTX, mode, EXPAND_NORMAL);
5639     }
5640   else
5641     failsafe = const0_rtx;
5642
5643   /* If the result isn't used, the behavior is undefined.  It would be
5644      nice to emit a warning here, but path splitting means this might
5645      happen with legitimate code.  So simply drop the builtin
5646      expansion in that case; we've handled any side-effects above.  */
5647   if (ignore)
5648     return const0_rtx;
5649
5650   /* If we don't have a suitable target, create one to hold the result.  */
5651   if (target == NULL || GET_MODE (target) != mode)
5652     target = gen_reg_rtx (mode);
5653
5654   if (GET_MODE (val) != mode && GET_MODE (val) != VOIDmode)
5655     val = convert_modes (mode, VOIDmode, val, false);
5656
5657   return targetm.speculation_safe_value (mode, target, val, failsafe);
5658 }
5659
5660 /* Expand an expression EXP that calls a built-in function,
5661    with result going to TARGET if that's convenient
5662    (and in mode MODE if that's convenient).
5663    SUBTARGET may be used as the target for computing one of EXP's operands.
5664    IGNORE is nonzero if the value is to be ignored.  */
5665
5666 rtx
5667 expand_builtin (tree exp, rtx target, rtx subtarget, machine_mode mode,
5668                 int ignore)
5669 {
5670   tree fndecl = get_callee_fndecl (exp);
5671   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
5672   machine_mode target_mode = TYPE_MODE (TREE_TYPE (exp));
5673   int flags;
5674
5675   if (DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_MD)
5676     return targetm.expand_builtin (exp, target, subtarget, mode, ignore);
5677
5678   /* When ASan is enabled, we don't want to expand some memory/string
5679      builtins and rely on libsanitizer's hooks.  This allows us to avoid
5680      redundant checks and be sure, that possible overflow will be detected
5681      by ASan.  */
5682
5683   if ((flag_sanitize & SANITIZE_ADDRESS) && asan_intercepted_p (fcode))
5684     return expand_call (exp, target, ignore);
5685
5686   /* When not optimizing, generate calls to library functions for a certain
5687      set of builtins.  */
5688   if (!optimize
5689       && !called_as_built_in (fndecl)
5690       && fcode != BUILT_IN_FORK
5691       && fcode != BUILT_IN_EXECL
5692       && fcode != BUILT_IN_EXECV
5693       && fcode != BUILT_IN_EXECLP
5694       && fcode != BUILT_IN_EXECLE
5695       && fcode != BUILT_IN_EXECVP
5696       && fcode != BUILT_IN_EXECVE
5697       && fcode != BUILT_IN_ALLOCA
5698       && fcode != BUILT_IN_ALLOCA_WITH_ALIGN
5699       && fcode != BUILT_IN_FREE
5700       && fcode != BUILT_IN_CHKP_SET_PTR_BOUNDS
5701       && fcode != BUILT_IN_CHKP_INIT_PTR_BOUNDS
5702       && fcode != BUILT_IN_CHKP_NULL_PTR_BOUNDS
5703       && fcode != BUILT_IN_CHKP_COPY_PTR_BOUNDS
5704       && fcode != BUILT_IN_CHKP_NARROW_PTR_BOUNDS
5705       && fcode != BUILT_IN_CHKP_STORE_PTR_BOUNDS
5706       && fcode != BUILT_IN_CHKP_CHECK_PTR_LBOUNDS
5707       && fcode != BUILT_IN_CHKP_CHECK_PTR_UBOUNDS
5708       && fcode != BUILT_IN_CHKP_CHECK_PTR_BOUNDS
5709       && fcode != BUILT_IN_CHKP_GET_PTR_LBOUND
5710       && fcode != BUILT_IN_CHKP_GET_PTR_UBOUND
5711       && fcode != BUILT_IN_CHKP_BNDRET)
5712     return expand_call (exp, target, ignore);
5713
5714   /* The built-in function expanders test for target == const0_rtx
5715      to determine whether the function's result will be ignored.  */
5716   if (ignore)
5717     target = const0_rtx;
5718
5719   /* If the result of a pure or const built-in function is ignored, and
5720      none of its arguments are volatile, we can avoid expanding the
5721      built-in call and just evaluate the arguments for side-effects.  */
5722   if (target == const0_rtx
5723       && ((flags = flags_from_decl_or_type (fndecl)) & (ECF_CONST | ECF_PURE))
5724       && !(flags & ECF_LOOPING_CONST_OR_PURE))
5725     {
5726       bool volatilep = false;
5727       tree arg;
5728       call_expr_arg_iterator iter;
5729
5730       FOR_EACH_CALL_EXPR_ARG (arg, iter, exp)
5731         if (TREE_THIS_VOLATILE (arg))
5732           {
5733             volatilep = true;
5734             break;
5735           }
5736
5737       if (! volatilep)
5738         {
5739           FOR_EACH_CALL_EXPR_ARG (arg, iter, exp)
5740             expand_expr (arg, const0_rtx, VOIDmode, EXPAND_NORMAL);
5741           return const0_rtx;
5742         }
5743     }
5744
5745   /* expand_builtin_with_bounds is supposed to be used for
5746      instrumented builtin calls.  */
5747   gcc_assert (!CALL_WITH_BOUNDS_P (exp));
5748
5749   switch (fcode)
5750     {
5751     CASE_FLT_FN (BUILT_IN_FABS):
5752     case BUILT_IN_FABSD32:
5753     case BUILT_IN_FABSD64:
5754     case BUILT_IN_FABSD128:
5755       target = expand_builtin_fabs (exp, target, subtarget);
5756       if (target)
5757         return target;
5758       break;
5759
5760     CASE_FLT_FN (BUILT_IN_COPYSIGN):
5761       target = expand_builtin_copysign (exp, target, subtarget);
5762       if (target)
5763         return target;
5764       break;
5765
5766       /* Just do a normal library call if we were unable to fold
5767          the values.  */
5768     CASE_FLT_FN (BUILT_IN_CABS):
5769       break;
5770
5771     CASE_FLT_FN (BUILT_IN_FMA):
5772       target = expand_builtin_mathfn_ternary (exp, target, subtarget);
5773       if (target)
5774         return target;
5775       break;
5776
5777     CASE_FLT_FN (BUILT_IN_ILOGB):
5778       if (! flag_unsafe_math_optimizations)
5779         break;
5780       gcc_fallthrough ();
5781     CASE_FLT_FN (BUILT_IN_ISINF):
5782     CASE_FLT_FN (BUILT_IN_FINITE):
5783     case BUILT_IN_ISFINITE:
5784     case BUILT_IN_ISNORMAL:
5785       target = expand_builtin_interclass_mathfn (exp, target);
5786       if (target)
5787         return target;
5788       break;
5789
5790     CASE_FLT_FN (BUILT_IN_ICEIL):
5791     CASE_FLT_FN (BUILT_IN_LCEIL):
5792     CASE_FLT_FN (BUILT_IN_LLCEIL):
5793     CASE_FLT_FN (BUILT_IN_LFLOOR):
5794     CASE_FLT_FN (BUILT_IN_IFLOOR):
5795     CASE_FLT_FN (BUILT_IN_LLFLOOR):
5796       target = expand_builtin_int_roundingfn (exp, target);
5797       if (target)
5798         return target;
5799       break;
5800
5801     CASE_FLT_FN (BUILT_IN_IRINT):
5802     CASE_FLT_FN (BUILT_IN_LRINT):
5803     CASE_FLT_FN (BUILT_IN_LLRINT):
5804     CASE_FLT_FN (BUILT_IN_IROUND):
5805     CASE_FLT_FN (BUILT_IN_LROUND):
5806     CASE_FLT_FN (BUILT_IN_LLROUND):
5807       target = expand_builtin_int_roundingfn_2 (exp, target);
5808       if (target)
5809         return target;
5810       break;
5811
5812     CASE_FLT_FN (BUILT_IN_POWI):
5813       target = expand_builtin_powi (exp, target);
5814       if (target)
5815         return target;
5816       break;
5817
5818     CASE_FLT_FN (BUILT_IN_CEXPI):
5819       target = expand_builtin_cexpi (exp, target);
5820       gcc_assert (target);
5821       return target;
5822
5823     CASE_FLT_FN (BUILT_IN_SIN):
5824     CASE_FLT_FN (BUILT_IN_COS):
5825       if (! flag_unsafe_math_optimizations)
5826         break;
5827       target = expand_builtin_mathfn_3 (exp, target, subtarget);
5828       if (target)
5829         return target;
5830       break;
5831
5832     CASE_FLT_FN (BUILT_IN_SINCOS):
5833       if (! flag_unsafe_math_optimizations)
5834         break;
5835       target = expand_builtin_sincos (exp);
5836       if (target)
5837         return target;
5838       break;
5839
5840     case BUILT_IN_APPLY_ARGS:
5841       return expand_builtin_apply_args ();
5842
5843       /* __builtin_apply (FUNCTION, ARGUMENTS, ARGSIZE) invokes
5844          FUNCTION with a copy of the parameters described by
5845          ARGUMENTS, and ARGSIZE.  It returns a block of memory
5846          allocated on the stack into which is stored all the registers
5847          that might possibly be used for returning the result of a
5848          function.  ARGUMENTS is the value returned by
5849          __builtin_apply_args.  ARGSIZE is the number of bytes of
5850          arguments that must be copied.  ??? How should this value be
5851          computed?  We'll also need a safe worst case value for varargs
5852          functions.  */
5853     case BUILT_IN_APPLY:
5854       if (!validate_arglist (exp, POINTER_TYPE,
5855                              POINTER_TYPE, INTEGER_TYPE, VOID_TYPE)
5856           && !validate_arglist (exp, REFERENCE_TYPE,
5857                                 POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
5858         return const0_rtx;
5859       else
5860         {
5861           rtx ops[3];
5862
5863           ops[0] = expand_normal (CALL_EXPR_ARG (exp, 0));
5864           ops[1] = expand_normal (CALL_EXPR_ARG (exp, 1));
5865           ops[2] = expand_normal (CALL_EXPR_ARG (exp, 2));
5866
5867           return expand_builtin_apply (ops[0], ops[1], ops[2]);
5868         }
5869
5870       /* __builtin_return (RESULT) causes the function to return the
5871          value described by RESULT.  RESULT is address of the block of
5872          memory returned by __builtin_apply.  */
5873     case BUILT_IN_RETURN:
5874       if (validate_arglist (exp, POINTER_TYPE, VOID_TYPE))
5875         expand_builtin_return (expand_normal (CALL_EXPR_ARG (exp, 0)));
5876       return const0_rtx;
5877
5878     case BUILT_IN_SAVEREGS:
5879       return expand_builtin_saveregs ();
5880
5881     case BUILT_IN_VA_ARG_PACK:
5882       /* All valid uses of __builtin_va_arg_pack () are removed during
5883          inlining.  */
5884       error ("%Kinvalid use of %<__builtin_va_arg_pack ()%>", exp);
5885       return const0_rtx;
5886
5887     case BUILT_IN_VA_ARG_PACK_LEN:
5888       /* All valid uses of __builtin_va_arg_pack_len () are removed during
5889          inlining.  */
5890       error ("%Kinvalid use of %<__builtin_va_arg_pack_len ()%>", exp);
5891       return const0_rtx;
5892
5893       /* Return the address of the first anonymous stack arg.  */
5894     case BUILT_IN_NEXT_ARG:
5895       if (fold_builtin_next_arg (exp, false))
5896         return const0_rtx;
5897       return expand_builtin_next_arg ();
5898
5899     case BUILT_IN_CLEAR_CACHE:
5900       target = expand_builtin___clear_cache (exp);
5901       if (target)
5902         return target;
5903       break;
5904
5905     case BUILT_IN_CLASSIFY_TYPE:
5906       return expand_builtin_classify_type (exp);
5907
5908     case BUILT_IN_CONSTANT_P:
5909       return const0_rtx;
5910
5911     case BUILT_IN_FRAME_ADDRESS:
5912     case BUILT_IN_RETURN_ADDRESS:
5913       return expand_builtin_frame_address (fndecl, exp);
5914
5915     /* Returns the address of the area where the structure is returned.
5916        0 otherwise.  */
5917     case BUILT_IN_AGGREGATE_INCOMING_ADDRESS:
5918       if (call_expr_nargs (exp) != 0
5919           || ! AGGREGATE_TYPE_P (TREE_TYPE (TREE_TYPE (current_function_decl)))
5920           || !MEM_P (DECL_RTL (DECL_RESULT (current_function_decl))))
5921         return const0_rtx;
5922       else
5923         return XEXP (DECL_RTL (DECL_RESULT (current_function_decl)), 0);
5924
5925     case BUILT_IN_ALLOCA:
5926     case BUILT_IN_ALLOCA_WITH_ALIGN:
5927       /* If the allocation stems from the declaration of a variable-sized
5928          object, it cannot accumulate.  */
5929       target = expand_builtin_alloca (exp, CALL_ALLOCA_FOR_VAR_P (exp));
5930       if (target)
5931         return target;
5932       break;
5933
5934     case BUILT_IN_STACK_SAVE:
5935       return expand_stack_save ();
5936
5937     case BUILT_IN_STACK_RESTORE:
5938       expand_stack_restore (CALL_EXPR_ARG (exp, 0));
5939       return const0_rtx;
5940
5941     case BUILT_IN_BSWAP16:
5942     case BUILT_IN_BSWAP32:
5943     case BUILT_IN_BSWAP64:
5944       target = expand_builtin_bswap (target_mode, exp, target, subtarget);
5945       if (target)
5946         return target;
5947       break;
5948
5949     CASE_INT_FN (BUILT_IN_FFS):
5950       target = expand_builtin_unop (target_mode, exp, target,
5951                                     subtarget, ffs_optab);
5952       if (target)
5953         return target;
5954       break;
5955
5956     CASE_INT_FN (BUILT_IN_CLZ):
5957       target = expand_builtin_unop (target_mode, exp, target,
5958                                     subtarget, clz_optab);
5959       if (target)
5960         return target;
5961       break;
5962
5963     CASE_INT_FN (BUILT_IN_CTZ):
5964       target = expand_builtin_unop (target_mode, exp, target,
5965                                     subtarget, ctz_optab);
5966       if (target)
5967         return target;
5968       break;
5969
5970     CASE_INT_FN (BUILT_IN_CLRSB):
5971       target = expand_builtin_unop (target_mode, exp, target,
5972                                     subtarget, clrsb_optab);
5973       if (target)
5974         return target;
5975       break;
5976
5977     CASE_INT_FN (BUILT_IN_POPCOUNT):
5978       target = expand_builtin_unop (target_mode, exp, target,
5979                                     subtarget, popcount_optab);
5980       if (target)
5981         return target;
5982       break;
5983
5984     CASE_INT_FN (BUILT_IN_PARITY):
5985       target = expand_builtin_unop (target_mode, exp, target,
5986                                     subtarget, parity_optab);
5987       if (target)
5988         return target;
5989       break;
5990
5991     case BUILT_IN_STRLEN:
5992       target = expand_builtin_strlen (exp, target, target_mode);
5993       if (target)
5994         return target;
5995       break;
5996
5997     case BUILT_IN_STRCPY:
5998       target = expand_builtin_strcpy (exp, target);
5999       if (target)
6000         return target;
6001       break;
6002
6003     case BUILT_IN_STRNCPY:
6004       target = expand_builtin_strncpy (exp, target);
6005       if (target)
6006         return target;
6007       break;
6008
6009     case BUILT_IN_STPCPY:
6010       target = expand_builtin_stpcpy (exp, target, mode);
6011       if (target)
6012         return target;
6013       break;
6014
6015     case BUILT_IN_MEMCPY:
6016       target = expand_builtin_memcpy (exp, target);
6017       if (target)
6018         return target;
6019       break;
6020
6021     case BUILT_IN_MEMPCPY:
6022       target = expand_builtin_mempcpy (exp, target, mode);
6023       if (target)
6024         return target;
6025       break;
6026
6027     case BUILT_IN_MEMSET:
6028       target = expand_builtin_memset (exp, target, mode);
6029       if (target)
6030         return target;
6031       break;
6032
6033     case BUILT_IN_BZERO:
6034       target = expand_builtin_bzero (exp);
6035       if (target)
6036         return target;
6037       break;
6038
6039     case BUILT_IN_STRCMP:
6040       target = expand_builtin_strcmp (exp, target);
6041       if (target)
6042         return target;
6043       break;
6044
6045     case BUILT_IN_STRNCMP:
6046       target = expand_builtin_strncmp (exp, target, mode);
6047       if (target)
6048         return target;
6049       break;
6050
6051     case BUILT_IN_BCMP:
6052     case BUILT_IN_MEMCMP:
6053       target = expand_builtin_memcmp (exp, target);
6054       if (target)
6055         return target;
6056       break;
6057
6058     case BUILT_IN_SETJMP:
6059       /* This should have been lowered to the builtins below.  */
6060       gcc_unreachable ();
6061
6062     case BUILT_IN_SETJMP_SETUP:
6063       /* __builtin_setjmp_setup is passed a pointer to an array of five words
6064           and the receiver label.  */
6065       if (validate_arglist (exp, POINTER_TYPE, POINTER_TYPE, VOID_TYPE))
6066         {
6067           rtx buf_addr = expand_expr (CALL_EXPR_ARG (exp, 0), subtarget,
6068                                       VOIDmode, EXPAND_NORMAL);
6069           tree label = TREE_OPERAND (CALL_EXPR_ARG (exp, 1), 0);
6070           rtx_insn *label_r = label_rtx (label);
6071
6072           /* This is copied from the handling of non-local gotos.  */
6073           expand_builtin_setjmp_setup (buf_addr, label_r);
6074           nonlocal_goto_handler_labels
6075             = gen_rtx_INSN_LIST (VOIDmode, label_r,
6076                                  nonlocal_goto_handler_labels);
6077           /* ??? Do not let expand_label treat us as such since we would
6078              not want to be both on the list of non-local labels and on
6079              the list of forced labels.  */
6080           FORCED_LABEL (label) = 0;
6081           return const0_rtx;
6082         }
6083       break;
6084
6085     case BUILT_IN_SETJMP_RECEIVER:
6086        /* __builtin_setjmp_receiver is passed the receiver label.  */
6087       if (validate_arglist (exp, POINTER_TYPE, VOID_TYPE))
6088         {
6089           tree label = TREE_OPERAND (CALL_EXPR_ARG (exp, 0), 0);
6090           rtx_insn *label_r = label_rtx (label);
6091
6092           expand_builtin_setjmp_receiver (label_r);
6093           return const0_rtx;
6094         }
6095       break;
6096
6097       /* __builtin_longjmp is passed a pointer to an array of five words.
6098          It's similar to the C library longjmp function but works with
6099          __builtin_setjmp above.  */
6100     case BUILT_IN_LONGJMP:
6101       if (validate_arglist (exp, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
6102         {
6103           rtx buf_addr = expand_expr (CALL_EXPR_ARG (exp, 0), subtarget,
6104                                       VOIDmode, EXPAND_NORMAL);
6105           rtx value = expand_normal (CALL_EXPR_ARG (exp, 1));
6106
6107           if (value != const1_rtx)
6108             {
6109               error ("%<__builtin_longjmp%> second argument must be 1");
6110               return const0_rtx;
6111             }
6112
6113           expand_builtin_longjmp (buf_addr, value);
6114           return const0_rtx;
6115         }
6116       break;
6117
6118     case BUILT_IN_NONLOCAL_GOTO:
6119       target = expand_builtin_nonlocal_goto (exp);
6120       if (target)
6121         return target;
6122       break;
6123
6124       /* This updates the setjmp buffer that is its argument with the value
6125          of the current stack pointer.  */
6126     case BUILT_IN_UPDATE_SETJMP_BUF:
6127       if (validate_arglist (exp, POINTER_TYPE, VOID_TYPE))
6128         {
6129           rtx buf_addr
6130             = expand_normal (CALL_EXPR_ARG (exp, 0));
6131
6132           expand_builtin_update_setjmp_buf (buf_addr);
6133           return const0_rtx;
6134         }
6135       break;
6136
6137     case BUILT_IN_TRAP:
6138       expand_builtin_trap ();
6139       return const0_rtx;
6140
6141     case BUILT_IN_UNREACHABLE:
6142       expand_builtin_unreachable ();
6143       return const0_rtx;
6144
6145     CASE_FLT_FN (BUILT_IN_SIGNBIT):
6146     case BUILT_IN_SIGNBITD32:
6147     case BUILT_IN_SIGNBITD64:
6148     case BUILT_IN_SIGNBITD128:
6149       target = expand_builtin_signbit (exp, target);
6150       if (target)
6151         return target;
6152       break;
6153
6154       /* Various hooks for the DWARF 2 __throw routine.  */
6155     case BUILT_IN_UNWIND_INIT:
6156       expand_builtin_unwind_init ();
6157       return const0_rtx;
6158     case BUILT_IN_DWARF_CFA:
6159       return virtual_cfa_rtx;
6160 #ifdef DWARF2_UNWIND_INFO
6161     case BUILT_IN_DWARF_SP_COLUMN:
6162       return expand_builtin_dwarf_sp_column ();
6163     case BUILT_IN_INIT_DWARF_REG_SIZES:
6164       expand_builtin_init_dwarf_reg_sizes (CALL_EXPR_ARG (exp, 0));
6165       return const0_rtx;
6166 #endif
6167     case BUILT_IN_FROB_RETURN_ADDR:
6168       return expand_builtin_frob_return_addr (CALL_EXPR_ARG (exp, 0));
6169     case BUILT_IN_EXTRACT_RETURN_ADDR:
6170       return expand_builtin_extract_return_addr (CALL_EXPR_ARG (exp, 0));
6171     case BUILT_IN_EH_RETURN:
6172       expand_builtin_eh_return (CALL_EXPR_ARG (exp, 0),
6173                                 CALL_EXPR_ARG (exp, 1));
6174       return const0_rtx;
6175     case BUILT_IN_EH_RETURN_DATA_REGNO:
6176       return expand_builtin_eh_return_data_regno (exp);
6177     case BUILT_IN_EXTEND_POINTER:
6178       return expand_builtin_extend_pointer (CALL_EXPR_ARG (exp, 0));
6179     case BUILT_IN_EH_POINTER:
6180       return expand_builtin_eh_pointer (exp);
6181     case BUILT_IN_EH_FILTER:
6182       return expand_builtin_eh_filter (exp);
6183     case BUILT_IN_EH_COPY_VALUES:
6184       return expand_builtin_eh_copy_values (exp);
6185
6186     case BUILT_IN_VA_START:
6187       return expand_builtin_va_start (exp);
6188     case BUILT_IN_VA_END:
6189       return expand_builtin_va_end (exp);
6190     case BUILT_IN_VA_COPY:
6191       return expand_builtin_va_copy (exp);
6192     case BUILT_IN_EXPECT:
6193       return expand_builtin_expect (exp, target);
6194     case BUILT_IN_ASSUME_ALIGNED:
6195       return expand_builtin_assume_aligned (exp, target);
6196     case BUILT_IN_PREFETCH:
6197       expand_builtin_prefetch (exp);
6198       return const0_rtx;
6199
6200     case BUILT_IN_INIT_TRAMPOLINE:
6201       return expand_builtin_init_trampoline (exp, true);
6202     case BUILT_IN_INIT_HEAP_TRAMPOLINE:
6203       return expand_builtin_init_trampoline (exp, false);
6204     case BUILT_IN_ADJUST_TRAMPOLINE:
6205       return expand_builtin_adjust_trampoline (exp);
6206
6207     case BUILT_IN_FORK:
6208     case BUILT_IN_EXECL:
6209     case BUILT_IN_EXECV:
6210     case BUILT_IN_EXECLP:
6211     case BUILT_IN_EXECLE:
6212     case BUILT_IN_EXECVP:
6213     case BUILT_IN_EXECVE:
6214       target = expand_builtin_fork_or_exec (fndecl, exp, target, ignore);
6215       if (target)
6216         return target;
6217       break;
6218
6219     case BUILT_IN_SYNC_FETCH_AND_ADD_1:
6220     case BUILT_IN_SYNC_FETCH_AND_ADD_2:
6221     case BUILT_IN_SYNC_FETCH_AND_ADD_4:
6222     case BUILT_IN_SYNC_FETCH_AND_ADD_8:
6223     case BUILT_IN_SYNC_FETCH_AND_ADD_16:
6224       mode = get_builtin_sync_mode (fcode - BUILT_IN_SYNC_FETCH_AND_ADD_1);
6225       target = expand_builtin_sync_operation (mode, exp, PLUS, false, target);
6226       if (target)
6227         return target;
6228       break;
6229
6230     case BUILT_IN_SYNC_FETCH_AND_SUB_1:
6231     case BUILT_IN_SYNC_FETCH_AND_SUB_2:
6232     case BUILT_IN_SYNC_FETCH_AND_SUB_4:
6233     case BUILT_IN_SYNC_FETCH_AND_SUB_8:
6234     case BUILT_IN_SYNC_FETCH_AND_SUB_16:
6235       mode = get_builtin_sync_mode (fcode - BUILT_IN_SYNC_FETCH_AND_SUB_1);
6236       target = expand_builtin_sync_operation (mode, exp, MINUS, false, target);
6237       if (target)
6238         return target;
6239       break;
6240
6241     case BUILT_IN_SYNC_FETCH_AND_OR_1:
6242     case BUILT_IN_SYNC_FETCH_AND_OR_2:
6243     case BUILT_IN_SYNC_FETCH_AND_OR_4:
6244     case BUILT_IN_SYNC_FETCH_AND_OR_8:
6245     case BUILT_IN_SYNC_FETCH_AND_OR_16:
6246       mode = get_builtin_sync_mode (fcode - BUILT_IN_SYNC_FETCH_AND_OR_1);
6247       target = expand_builtin_sync_operation (mode, exp, IOR, false, target);
6248       if (target)
6249         return target;
6250       break;
6251
6252     case BUILT_IN_SYNC_FETCH_AND_AND_1:
6253     case BUILT_IN_SYNC_FETCH_AND_AND_2:
6254     case BUILT_IN_SYNC_FETCH_AND_AND_4:
6255     case BUILT_IN_SYNC_FETCH_AND_AND_8:
6256     case BUILT_IN_SYNC_FETCH_AND_AND_16:
6257       mode = get_builtin_sync_mode (fcode - BUILT_IN_SYNC_FETCH_AND_AND_1);
6258       target = expand_builtin_sync_operation (mode, exp, AND, false, target);
6259       if (target)
6260         return target;
6261       break;
6262
6263     case BUILT_IN_SYNC_FETCH_AND_XOR_1:
6264     case BUILT_IN_SYNC_FETCH_AND_XOR_2:
6265     case BUILT_IN_SYNC_FETCH_AND_XOR_4:
6266     case BUILT_IN_SYNC_FETCH_AND_XOR_8:
6267     case BUILT_IN_SYNC_FETCH_AND_XOR_16:
6268       mode = get_builtin_sync_mode (fcode - BUILT_IN_SYNC_FETCH_AND_XOR_1);
6269       target = expand_builtin_sync_operation (mode, exp, XOR, false, target);
6270       if (target)
6271         return target;
6272       break;
6273
6274     case BUILT_IN_SYNC_FETCH_AND_NAND_1:
6275     case BUILT_IN_SYNC_FETCH_AND_NAND_2:
6276     case BUILT_IN_SYNC_FETCH_AND_NAND_4:
6277     case BUILT_IN_SYNC_FETCH_AND_NAND_8:
6278     case BUILT_IN_SYNC_FETCH_AND_NAND_16:
6279       mode = get_builtin_sync_mode (fcode - BUILT_IN_SYNC_FETCH_AND_NAND_1);
6280       target = expand_builtin_sync_operation (mode, exp, NOT, false, target);
6281       if (target)
6282         return target;
6283       break;
6284
6285     case BUILT_IN_SYNC_ADD_AND_FETCH_1:
6286     case BUILT_IN_SYNC_ADD_AND_FETCH_2:
6287     case BUILT_IN_SYNC_ADD_AND_FETCH_4:
6288     case BUILT_IN_SYNC_ADD_AND_FETCH_8:
6289     case BUILT_IN_SYNC_ADD_AND_FETCH_16:
6290       mode = get_builtin_sync_mode (fcode - BUILT_IN_SYNC_ADD_AND_FETCH_1);
6291       target = expand_builtin_sync_operation (mode, exp, PLUS, true, target);
6292       if (target)
6293         return target;
6294       break;
6295
6296     case BUILT_IN_SYNC_SUB_AND_FETCH_1:
6297     case BUILT_IN_SYNC_SUB_AND_FETCH_2:
6298     case BUILT_IN_SYNC_SUB_AND_FETCH_4:
6299     case BUILT_IN_SYNC_SUB_AND_FETCH_8:
6300     case BUILT_IN_SYNC_SUB_AND_FETCH_16:
6301       mode = get_builtin_sync_mode (fcode - BUILT_IN_SYNC_SUB_AND_FETCH_1);
6302       target = expand_builtin_sync_operation (mode, exp, MINUS, true, target);
6303       if (target)
6304         return target;
6305       break;
6306
6307     case BUILT_IN_SYNC_OR_AND_FETCH_1:
6308     case BUILT_IN_SYNC_OR_AND_FETCH_2:
6309     case BUILT_IN_SYNC_OR_AND_FETCH_4:
6310     case BUILT_IN_SYNC_OR_AND_FETCH_8:
6311     case BUILT_IN_SYNC_OR_AND_FETCH_16:
6312       mode = get_builtin_sync_mode (fcode - BUILT_IN_SYNC_OR_AND_FETCH_1);
6313       target = expand_builtin_sync_operation (mode, exp, IOR, true, target);
6314       if (target)
6315         return target;
6316       break;
6317
6318     case BUILT_IN_SYNC_AND_AND_FETCH_1:
6319     case BUILT_IN_SYNC_AND_AND_FETCH_2:
6320     case BUILT_IN_SYNC_AND_AND_FETCH_4:
6321     case BUILT_IN_SYNC_AND_AND_FETCH_8:
6322     case BUILT_IN_SYNC_AND_AND_FETCH_16:
6323       mode = get_builtin_sync_mode (fcode - BUILT_IN_SYNC_AND_AND_FETCH_1);
6324       target = expand_builtin_sync_operation (mode, exp, AND, true, target);
6325       if (target)
6326         return target;
6327       break;
6328
6329     case BUILT_IN_SYNC_XOR_AND_FETCH_1:
6330     case BUILT_IN_SYNC_XOR_AND_FETCH_2:
6331     case BUILT_IN_SYNC_XOR_AND_FETCH_4:
6332     case BUILT_IN_SYNC_XOR_AND_FETCH_8:
6333     case BUILT_IN_SYNC_XOR_AND_FETCH_16:
6334       mode = get_builtin_sync_mode (fcode - BUILT_IN_SYNC_XOR_AND_FETCH_1);
6335       target = expand_builtin_sync_operation (mode, exp, XOR, true, target);
6336       if (target)
6337         return target;
6338       break;
6339
6340     case BUILT_IN_SYNC_NAND_AND_FETCH_1:
6341     case BUILT_IN_SYNC_NAND_AND_FETCH_2:
6342     case BUILT_IN_SYNC_NAND_AND_FETCH_4:
6343     case BUILT_IN_SYNC_NAND_AND_FETCH_8:
6344     case BUILT_IN_SYNC_NAND_AND_FETCH_16:
6345       mode = get_builtin_sync_mode (fcode - BUILT_IN_SYNC_NAND_AND_FETCH_1);
6346       target = expand_builtin_sync_operation (mode, exp, NOT, true, target);
6347       if (target)
6348         return target;
6349       break;
6350
6351     case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_1:
6352     case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_2:
6353     case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_4:
6354     case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_8:
6355     case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_16:
6356       if (mode == VOIDmode)
6357         mode = TYPE_MODE (boolean_type_node);
6358       if (!target || !register_operand (target, mode))
6359         target = gen_reg_rtx (mode);
6360
6361       mode = get_builtin_sync_mode 
6362                                 (fcode - BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_1);
6363       target = expand_builtin_compare_and_swap (mode, exp, true, target);
6364       if (target)
6365         return target;
6366       break;
6367
6368     case BUILT_IN_SYNC_VAL_COMPARE_AND_SWAP_1:
6369     case BUILT_IN_SYNC_VAL_COMPARE_AND_SWAP_2:
6370     case BUILT_IN_SYNC_VAL_COMPARE_AND_SWAP_4:
6371     case BUILT_IN_SYNC_VAL_COMPARE_AND_SWAP_8:
6372     case BUILT_IN_SYNC_VAL_COMPARE_AND_SWAP_16:
6373       mode = get_builtin_sync_mode 
6374                                 (fcode - BUILT_IN_SYNC_VAL_COMPARE_AND_SWAP_1);
6375       target = expand_builtin_compare_and_swap (mode, exp, false, target);
6376       if (target)
6377         return target;
6378       break;
6379
6380     case BUILT_IN_SYNC_LOCK_TEST_AND_SET_1:
6381     case BUILT_IN_SYNC_LOCK_TEST_AND_SET_2:
6382     case BUILT_IN_SYNC_LOCK_TEST_AND_SET_4:
6383     case BUILT_IN_SYNC_LOCK_TEST_AND_SET_8:
6384     case BUILT_IN_SYNC_LOCK_TEST_AND_SET_16:
6385       mode = get_builtin_sync_mode (fcode - BUILT_IN_SYNC_LOCK_TEST_AND_SET_1);
6386       target = expand_builtin_sync_lock_test_and_set (mode, exp, target);
6387       if (target)
6388         return target;
6389       break;
6390
6391     case BUILT_IN_SYNC_LOCK_RELEASE_1:
6392     case BUILT_IN_SYNC_LOCK_RELEASE_2:
6393     case BUILT_IN_SYNC_LOCK_RELEASE_4:
6394     case BUILT_IN_SYNC_LOCK_RELEASE_8:
6395     case BUILT_IN_SYNC_LOCK_RELEASE_16:
6396       mode = get_builtin_sync_mode (fcode - BUILT_IN_SYNC_LOCK_RELEASE_1);
6397       expand_builtin_sync_lock_release (mode, exp);
6398       return const0_rtx;
6399
6400     case BUILT_IN_SYNC_SYNCHRONIZE:
6401       expand_builtin_sync_synchronize ();
6402       return const0_rtx;
6403
6404     case BUILT_IN_ATOMIC_EXCHANGE_1:
6405     case BUILT_IN_ATOMIC_EXCHANGE_2:
6406     case BUILT_IN_ATOMIC_EXCHANGE_4:
6407     case BUILT_IN_ATOMIC_EXCHANGE_8:
6408     case BUILT_IN_ATOMIC_EXCHANGE_16:
6409       mode = get_builtin_sync_mode (fcode - BUILT_IN_ATOMIC_EXCHANGE_1);
6410       target = expand_builtin_atomic_exchange (mode, exp, target);
6411       if (target)
6412         return target;
6413       break;
6414
6415     case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_1:
6416     case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_2:
6417     case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_4:
6418     case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_8:
6419     case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_16:
6420       {
6421         unsigned int nargs, z;
6422         vec<tree, va_gc> *vec;
6423
6424         mode = 
6425             get_builtin_sync_mode (fcode - BUILT_IN_ATOMIC_COMPARE_EXCHANGE_1);
6426         target = expand_builtin_atomic_compare_exchange (mode, exp, target);
6427         if (target)
6428           return target;
6429
6430         /* If this is turned into an external library call, the weak parameter
6431            must be dropped to match the expected parameter list.  */
6432         nargs = call_expr_nargs (exp);
6433         vec_alloc (vec, nargs - 1);
6434         for (z = 0; z < 3; z++)
6435           vec->quick_push (CALL_EXPR_ARG (exp, z));
6436         /* Skip the boolean weak parameter.  */
6437         for (z = 4; z < 6; z++)
6438           vec->quick_push (CALL_EXPR_ARG (exp, z));
6439         exp = build_call_vec (TREE_TYPE (exp), CALL_EXPR_FN (exp), vec);
6440         break;
6441       }
6442
6443     case BUILT_IN_ATOMIC_LOAD_1:
6444     case BUILT_IN_ATOMIC_LOAD_2:
6445     case BUILT_IN_ATOMIC_LOAD_4:
6446     case BUILT_IN_ATOMIC_LOAD_8:
6447     case BUILT_IN_ATOMIC_LOAD_16:
6448       mode = get_builtin_sync_mode (fcode - BUILT_IN_ATOMIC_LOAD_1);
6449       target = expand_builtin_atomic_load (mode, exp, target);
6450       if (target)
6451         return target;
6452       break;
6453
6454     case BUILT_IN_ATOMIC_STORE_1:
6455     case BUILT_IN_ATOMIC_STORE_2:
6456     case BUILT_IN_ATOMIC_STORE_4:
6457     case BUILT_IN_ATOMIC_STORE_8:
6458     case BUILT_IN_ATOMIC_STORE_16:
6459       mode = get_builtin_sync_mode (fcode - BUILT_IN_ATOMIC_STORE_1);
6460       target = expand_builtin_atomic_store (mode, exp);
6461       if (target)
6462         return const0_rtx;
6463       break;
6464
6465     case BUILT_IN_ATOMIC_ADD_FETCH_1:
6466     case BUILT_IN_ATOMIC_ADD_FETCH_2:
6467     case BUILT_IN_ATOMIC_ADD_FETCH_4:
6468     case BUILT_IN_ATOMIC_ADD_FETCH_8:
6469     case BUILT_IN_ATOMIC_ADD_FETCH_16:
6470       {
6471         enum built_in_function lib;
6472         mode = get_builtin_sync_mode (fcode - BUILT_IN_ATOMIC_ADD_FETCH_1);
6473         lib = (enum built_in_function)((int)BUILT_IN_ATOMIC_FETCH_ADD_1 + 
6474                                        (fcode - BUILT_IN_ATOMIC_ADD_FETCH_1));
6475         target = expand_builtin_atomic_fetch_op (mode, exp, target, PLUS, true,
6476                                                  ignore, lib);
6477         if (target)
6478           return target;
6479         break;
6480       }
6481     case BUILT_IN_ATOMIC_SUB_FETCH_1:
6482     case BUILT_IN_ATOMIC_SUB_FETCH_2:
6483     case BUILT_IN_ATOMIC_SUB_FETCH_4:
6484     case BUILT_IN_ATOMIC_SUB_FETCH_8:
6485     case BUILT_IN_ATOMIC_SUB_FETCH_16:
6486       {
6487         enum built_in_function lib;
6488         mode = get_builtin_sync_mode (fcode - BUILT_IN_ATOMIC_SUB_FETCH_1);
6489         lib = (enum built_in_function)((int)BUILT_IN_ATOMIC_FETCH_SUB_1 + 
6490                                        (fcode - BUILT_IN_ATOMIC_SUB_FETCH_1));
6491         target = expand_builtin_atomic_fetch_op (mode, exp, target, MINUS, true,
6492                                                  ignore, lib);
6493         if (target)
6494           return target;
6495         break;
6496       }
6497     case BUILT_IN_ATOMIC_AND_FETCH_1:
6498     case BUILT_IN_ATOMIC_AND_FETCH_2:
6499     case BUILT_IN_ATOMIC_AND_FETCH_4:
6500     case BUILT_IN_ATOMIC_AND_FETCH_8:
6501     case BUILT_IN_ATOMIC_AND_FETCH_16:
6502       {
6503         enum built_in_function lib;
6504         mode = get_builtin_sync_mode (fcode - BUILT_IN_ATOMIC_AND_FETCH_1);
6505         lib = (enum built_in_function)((int)BUILT_IN_ATOMIC_FETCH_AND_1 + 
6506                                        (fcode - BUILT_IN_ATOMIC_AND_FETCH_1));
6507         target = expand_builtin_atomic_fetch_op (mode, exp, target, AND, true,
6508                                                  ignore, lib);
6509         if (target)
6510           return target;
6511         break;
6512       }
6513     case BUILT_IN_ATOMIC_NAND_FETCH_1:
6514     case BUILT_IN_ATOMIC_NAND_FETCH_2:
6515     case BUILT_IN_ATOMIC_NAND_FETCH_4:
6516     case BUILT_IN_ATOMIC_NAND_FETCH_8:
6517     case BUILT_IN_ATOMIC_NAND_FETCH_16:
6518       {
6519         enum built_in_function lib;
6520         mode = get_builtin_sync_mode (fcode - BUILT_IN_ATOMIC_NAND_FETCH_1);
6521         lib = (enum built_in_function)((int)BUILT_IN_ATOMIC_FETCH_NAND_1 + 
6522                                        (fcode - BUILT_IN_ATOMIC_NAND_FETCH_1));
6523         target = expand_builtin_atomic_fetch_op (mode, exp, target, NOT, true,
6524                                                  ignore, lib);
6525         if (target)
6526           return target;
6527         break;
6528       }
6529     case BUILT_IN_ATOMIC_XOR_FETCH_1:
6530     case BUILT_IN_ATOMIC_XOR_FETCH_2:
6531     case BUILT_IN_ATOMIC_XOR_FETCH_4:
6532     case BUILT_IN_ATOMIC_XOR_FETCH_8:
6533     case BUILT_IN_ATOMIC_XOR_FETCH_16:
6534       {
6535         enum built_in_function lib;
6536         mode = get_builtin_sync_mode (fcode - BUILT_IN_ATOMIC_XOR_FETCH_1);
6537         lib = (enum built_in_function)((int)BUILT_IN_ATOMIC_FETCH_XOR_1 + 
6538                                        (fcode - BUILT_IN_ATOMIC_XOR_FETCH_1));
6539         target = expand_builtin_atomic_fetch_op (mode, exp, target, XOR, true,
6540                                                  ignore, lib);
6541         if (target)
6542           return target;
6543         break;
6544       }
6545     case BUILT_IN_ATOMIC_OR_FETCH_1:
6546     case BUILT_IN_ATOMIC_OR_FETCH_2:
6547     case BUILT_IN_ATOMIC_OR_FETCH_4:
6548     case BUILT_IN_ATOMIC_OR_FETCH_8:
6549     case BUILT_IN_ATOMIC_OR_FETCH_16:
6550       {
6551         enum built_in_function lib;
6552         mode = get_builtin_sync_mode (fcode - BUILT_IN_ATOMIC_OR_FETCH_1);
6553         lib = (enum built_in_function)((int)BUILT_IN_ATOMIC_FETCH_OR_1 + 
6554                                        (fcode - BUILT_IN_ATOMIC_OR_FETCH_1));
6555         target = expand_builtin_atomic_fetch_op (mode, exp, target, IOR, true,
6556                                                  ignore, lib);
6557         if (target)
6558           return target;
6559         break;
6560       }
6561     case BUILT_IN_ATOMIC_FETCH_ADD_1:
6562     case BUILT_IN_ATOMIC_FETCH_ADD_2:
6563     case BUILT_IN_ATOMIC_FETCH_ADD_4:
6564     case BUILT_IN_ATOMIC_FETCH_ADD_8:
6565     case BUILT_IN_ATOMIC_FETCH_ADD_16:
6566       mode = get_builtin_sync_mode (fcode - BUILT_IN_ATOMIC_FETCH_ADD_1);
6567       target = expand_builtin_atomic_fetch_op (mode, exp, target, PLUS, false,
6568                                                ignore, BUILT_IN_NONE);
6569       if (target)
6570         return target;
6571       break;
6572  
6573     case BUILT_IN_ATOMIC_FETCH_SUB_1:
6574     case BUILT_IN_ATOMIC_FETCH_SUB_2:
6575     case BUILT_IN_ATOMIC_FETCH_SUB_4:
6576     case BUILT_IN_ATOMIC_FETCH_SUB_8:
6577     case BUILT_IN_ATOMIC_FETCH_SUB_16:
6578       mode = get_builtin_sync_mode (fcode - BUILT_IN_ATOMIC_FETCH_SUB_1);
6579       target = expand_builtin_atomic_fetch_op (mode, exp, target, MINUS, false,
6580                                                ignore, BUILT_IN_NONE);
6581       if (target)
6582         return target;
6583       break;
6584
6585     case BUILT_IN_ATOMIC_FETCH_AND_1:
6586     case BUILT_IN_ATOMIC_FETCH_AND_2:
6587     case BUILT_IN_ATOMIC_FETCH_AND_4:
6588     case BUILT_IN_ATOMIC_FETCH_AND_8:
6589     case BUILT_IN_ATOMIC_FETCH_AND_16:
6590       mode = get_builtin_sync_mode (fcode - BUILT_IN_ATOMIC_FETCH_AND_1);
6591       target = expand_builtin_atomic_fetch_op (mode, exp, target, AND, false,
6592                                                ignore, BUILT_IN_NONE);
6593       if (target)
6594         return target;
6595       break;
6596   
6597     case BUILT_IN_ATOMIC_FETCH_NAND_1:
6598     case BUILT_IN_ATOMIC_FETCH_NAND_2:
6599     case BUILT_IN_ATOMIC_FETCH_NAND_4:
6600     case BUILT_IN_ATOMIC_FETCH_NAND_8:
6601     case BUILT_IN_ATOMIC_FETCH_NAND_16:
6602       mode = get_builtin_sync_mode (fcode - BUILT_IN_ATOMIC_FETCH_NAND_1);
6603       target = expand_builtin_atomic_fetch_op (mode, exp, target, NOT, false,
6604                                                ignore, BUILT_IN_NONE);
6605       if (target)
6606         return target;
6607       break;
6608  
6609     case BUILT_IN_ATOMIC_FETCH_XOR_1:
6610     case BUILT_IN_ATOMIC_FETCH_XOR_2:
6611     case BUILT_IN_ATOMIC_FETCH_XOR_4:
6612     case BUILT_IN_ATOMIC_FETCH_XOR_8:
6613     case BUILT_IN_ATOMIC_FETCH_XOR_16:
6614       mode = get_builtin_sync_mode (fcode - BUILT_IN_ATOMIC_FETCH_XOR_1);
6615       target = expand_builtin_atomic_fetch_op (mode, exp, target, XOR, false,
6616                                                ignore, BUILT_IN_NONE);
6617       if (target)
6618         return target;
6619       break;
6620  
6621     case BUILT_IN_ATOMIC_FETCH_OR_1:
6622     case BUILT_IN_ATOMIC_FETCH_OR_2:
6623     case BUILT_IN_ATOMIC_FETCH_OR_4:
6624     case BUILT_IN_ATOMIC_FETCH_OR_8:
6625     case BUILT_IN_ATOMIC_FETCH_OR_16:
6626       mode = get_builtin_sync_mode (fcode - BUILT_IN_ATOMIC_FETCH_OR_1);
6627       target = expand_builtin_atomic_fetch_op (mode, exp, target, IOR, false,
6628                                                ignore, BUILT_IN_NONE);
6629       if (target)
6630         return target;
6631       break;
6632
6633     case BUILT_IN_ATOMIC_TEST_AND_SET:
6634       return expand_builtin_atomic_test_and_set (exp, target);
6635
6636     case BUILT_IN_ATOMIC_CLEAR:
6637       return expand_builtin_atomic_clear (exp);
6638  
6639     case BUILT_IN_ATOMIC_ALWAYS_LOCK_FREE:
6640       return expand_builtin_atomic_always_lock_free (exp);
6641
6642     case BUILT_IN_ATOMIC_IS_LOCK_FREE:
6643       target = expand_builtin_atomic_is_lock_free (exp);
6644       if (target)
6645         return target;
6646       break;
6647
6648     case BUILT_IN_ATOMIC_THREAD_FENCE:
6649       expand_builtin_atomic_thread_fence (exp);
6650       return const0_rtx;
6651
6652     case BUILT_IN_ATOMIC_SIGNAL_FENCE:
6653       expand_builtin_atomic_signal_fence (exp);
6654       return const0_rtx;
6655
6656     case BUILT_IN_OBJECT_SIZE:
6657       return expand_builtin_object_size (exp);
6658
6659     case BUILT_IN_MEMCPY_CHK:
6660     case BUILT_IN_MEMPCPY_CHK:
6661     case BUILT_IN_MEMMOVE_CHK:
6662     case BUILT_IN_MEMSET_CHK:
6663       target = expand_builtin_memory_chk (exp, target, mode, fcode);
6664       if (target)
6665         return target;
6666       break;
6667
6668     case BUILT_IN_STRCPY_CHK:
6669     case BUILT_IN_STPCPY_CHK:
6670     case BUILT_IN_STRNCPY_CHK:
6671     case BUILT_IN_STPNCPY_CHK:
6672     case BUILT_IN_STRCAT_CHK:
6673     case BUILT_IN_STRNCAT_CHK:
6674     case BUILT_IN_SNPRINTF_CHK:
6675     case BUILT_IN_VSNPRINTF_CHK:
6676       maybe_emit_chk_warning (exp, fcode);
6677       break;
6678
6679     case BUILT_IN_SPRINTF_CHK:
6680     case BUILT_IN_VSPRINTF_CHK:
6681       maybe_emit_sprintf_chk_warning (exp, fcode);
6682       break;
6683
6684     case BUILT_IN_FREE:
6685       if (warn_free_nonheap_object)
6686         maybe_emit_free_warning (exp);
6687       break;
6688
6689     case BUILT_IN_THREAD_POINTER:
6690       return expand_builtin_thread_pointer (exp, target);
6691
6692     case BUILT_IN_SET_THREAD_POINTER:
6693       expand_builtin_set_thread_pointer (exp);
6694       return const0_rtx;
6695
6696     case BUILT_IN_CILK_DETACH:
6697       expand_builtin_cilk_detach (exp);
6698       return const0_rtx;
6699       
6700     case BUILT_IN_CILK_POP_FRAME:
6701       expand_builtin_cilk_pop_frame (exp);
6702       return const0_rtx;
6703
6704     case BUILT_IN_CHKP_INIT_PTR_BOUNDS:
6705     case BUILT_IN_CHKP_NULL_PTR_BOUNDS:
6706     case BUILT_IN_CHKP_COPY_PTR_BOUNDS:
6707     case BUILT_IN_CHKP_CHECK_PTR_LBOUNDS:
6708     case BUILT_IN_CHKP_CHECK_PTR_UBOUNDS:
6709     case BUILT_IN_CHKP_CHECK_PTR_BOUNDS:
6710     case BUILT_IN_CHKP_SET_PTR_BOUNDS:
6711     case BUILT_IN_CHKP_NARROW_PTR_BOUNDS:
6712     case BUILT_IN_CHKP_STORE_PTR_BOUNDS:
6713     case BUILT_IN_CHKP_GET_PTR_LBOUND:
6714     case BUILT_IN_CHKP_GET_PTR_UBOUND:
6715       /* We allow user CHKP builtins if Pointer Bounds
6716          Checker is off.  */
6717       if (!chkp_function_instrumented_p (current_function_decl))
6718         {
6719           if (fcode == BUILT_IN_CHKP_SET_PTR_BOUNDS
6720               || fcode == BUILT_IN_CHKP_NARROW_PTR_BOUNDS
6721               || fcode == BUILT_IN_CHKP_INIT_PTR_BOUNDS
6722               || fcode == BUILT_IN_CHKP_NULL_PTR_BOUNDS
6723               || fcode == BUILT_IN_CHKP_COPY_PTR_BOUNDS)
6724             return expand_normal (CALL_EXPR_ARG (exp, 0));
6725           else if (fcode == BUILT_IN_CHKP_GET_PTR_LBOUND)
6726             return expand_normal (size_zero_node);
6727           else if (fcode == BUILT_IN_CHKP_GET_PTR_UBOUND)
6728             return expand_normal (size_int (-1));
6729           else
6730             return const0_rtx;
6731         }
6732       /* FALLTHROUGH */
6733
6734     case BUILT_IN_CHKP_BNDMK:
6735     case BUILT_IN_CHKP_BNDSTX:
6736     case BUILT_IN_CHKP_BNDCL:
6737     case BUILT_IN_CHKP_BNDCU:
6738     case BUILT_IN_CHKP_BNDLDX:
6739     case BUILT_IN_CHKP_BNDRET:
6740     case BUILT_IN_CHKP_INTERSECT:
6741     case BUILT_IN_CHKP_NARROW:
6742     case BUILT_IN_CHKP_EXTRACT_LOWER:
6743     case BUILT_IN_CHKP_EXTRACT_UPPER:
6744       /* Software implementation of Pointer Bounds Checker is NYI.
6745          Target support is required.  */
6746       error ("Your target platform does not support -fcheck-pointer-bounds");
6747       break;
6748
6749     case BUILT_IN_ACC_ON_DEVICE:
6750       /* Do library call, if we failed to expand the builtin when
6751          folding.  */
6752       break;
6753
6754     case BUILT_IN_SPECULATION_SAFE_VALUE_PTR:
6755       return expand_speculation_safe_value (VOIDmode, exp, target, ignore);
6756
6757     case BUILT_IN_SPECULATION_SAFE_VALUE_1:
6758     case BUILT_IN_SPECULATION_SAFE_VALUE_2:
6759     case BUILT_IN_SPECULATION_SAFE_VALUE_4:
6760     case BUILT_IN_SPECULATION_SAFE_VALUE_8:
6761     case BUILT_IN_SPECULATION_SAFE_VALUE_16:
6762       mode = get_builtin_sync_mode (fcode - BUILT_IN_SPECULATION_SAFE_VALUE_1);
6763       return expand_speculation_safe_value (mode, exp, target, ignore);
6764
6765     default:    /* just do library call, if unknown builtin */
6766       break;
6767     }
6768
6769   /* The switch statement above can drop through to cause the function
6770      to be called normally.  */
6771   return expand_call (exp, target, ignore);
6772 }
6773
6774 /* Similar to expand_builtin but is used for instrumented calls.  */
6775
6776 rtx
6777 expand_builtin_with_bounds (tree exp, rtx target,
6778                             rtx subtarget ATTRIBUTE_UNUSED,
6779                             machine_mode mode, int ignore)
6780 {
6781   tree fndecl = get_callee_fndecl (exp);
6782   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
6783
6784   gcc_assert (CALL_WITH_BOUNDS_P (exp));
6785
6786   if (DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_MD)
6787     return targetm.expand_builtin (exp, target, subtarget, mode, ignore);
6788
6789   gcc_assert (fcode > BEGIN_CHKP_BUILTINS
6790               && fcode < END_CHKP_BUILTINS);
6791
6792   switch (fcode)
6793     {
6794     case BUILT_IN_CHKP_MEMCPY_NOBND_NOCHK_CHKP:
6795       target = expand_builtin_memcpy_with_bounds (exp, target);
6796       if (target)
6797         return target;
6798       break;
6799
6800     case BUILT_IN_CHKP_MEMPCPY_NOBND_NOCHK_CHKP:
6801       target = expand_builtin_mempcpy_with_bounds (exp, target, mode);
6802       if (target)
6803         return target;
6804       break;
6805
6806     case BUILT_IN_CHKP_MEMSET_NOBND_NOCHK_CHKP:
6807       target = expand_builtin_memset_with_bounds (exp, target, mode);
6808       if (target)
6809         return target;
6810       break;
6811
6812     default:
6813       break;
6814     }
6815
6816   /* The switch statement above can drop through to cause the function
6817      to be called normally.  */
6818   return expand_call (exp, target, ignore);
6819  }
6820
6821 /* Determine whether a tree node represents a call to a built-in
6822    function.  If the tree T is a call to a built-in function with
6823    the right number of arguments of the appropriate types, return
6824    the DECL_FUNCTION_CODE of the call, e.g. BUILT_IN_SQRT.
6825    Otherwise the return value is END_BUILTINS.  */
6826
6827 enum built_in_function
6828 builtin_mathfn_code (const_tree t)
6829 {
6830   const_tree fndecl, arg, parmlist;
6831   const_tree argtype, parmtype;
6832   const_call_expr_arg_iterator iter;
6833
6834   if (TREE_CODE (t) != CALL_EXPR
6835       || !CALL_EXPR_FN (t)
6836       || TREE_CODE (CALL_EXPR_FN (t)) != ADDR_EXPR)
6837     return END_BUILTINS;
6838
6839   fndecl = get_callee_fndecl (t);
6840   if (fndecl == NULL_TREE
6841       || TREE_CODE (fndecl) != FUNCTION_DECL
6842       || ! DECL_BUILT_IN (fndecl)
6843       || DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_MD)
6844     return END_BUILTINS;
6845
6846   parmlist = TYPE_ARG_TYPES (TREE_TYPE (fndecl));
6847   init_const_call_expr_arg_iterator (t, &iter);
6848   for (; parmlist; parmlist = TREE_CHAIN (parmlist))
6849     {
6850       /* If a function doesn't take a variable number of arguments,
6851          the last element in the list will have type `void'.  */
6852       parmtype = TREE_VALUE (parmlist);
6853       if (VOID_TYPE_P (parmtype))
6854         {
6855           if (more_const_call_expr_args_p (&iter))
6856             return END_BUILTINS;
6857           return DECL_FUNCTION_CODE (fndecl);
6858         }
6859
6860       if (! more_const_call_expr_args_p (&iter))
6861         return END_BUILTINS;
6862
6863       arg = next_const_call_expr_arg (&iter);
6864       argtype = TREE_TYPE (arg);
6865
6866       if (SCALAR_FLOAT_TYPE_P (parmtype))
6867         {
6868           if (! SCALAR_FLOAT_TYPE_P (argtype))
6869             return END_BUILTINS;
6870         }
6871       else if (COMPLEX_FLOAT_TYPE_P (parmtype))
6872         {
6873           if (! COMPLEX_FLOAT_TYPE_P (argtype))
6874             return END_BUILTINS;
6875         }
6876       else if (POINTER_TYPE_P (parmtype))
6877         {
6878           if (! POINTER_TYPE_P (argtype))
6879             return END_BUILTINS;
6880         }
6881       else if (INTEGRAL_TYPE_P (parmtype))
6882         {
6883           if (! INTEGRAL_TYPE_P (argtype))
6884             return END_BUILTINS;
6885         }
6886       else
6887         return END_BUILTINS;
6888     }
6889
6890   /* Variable-length argument list.  */
6891   return DECL_FUNCTION_CODE (fndecl);
6892 }
6893
6894 /* Fold a call to __builtin_constant_p, if we know its argument ARG will
6895    evaluate to a constant.  */
6896
6897 static tree
6898 fold_builtin_constant_p (tree arg)
6899 {
6900   /* We return 1 for a numeric type that's known to be a constant
6901      value at compile-time or for an aggregate type that's a
6902      literal constant.  */
6903   STRIP_NOPS (arg);
6904
6905   /* If we know this is a constant, emit the constant of one.  */
6906   if (CONSTANT_CLASS_P (arg)
6907       || (TREE_CODE (arg) == CONSTRUCTOR
6908           && TREE_CONSTANT (arg)))
6909     return integer_one_node;
6910   if (TREE_CODE (arg) == ADDR_EXPR)
6911     {
6912        tree op = TREE_OPERAND (arg, 0);
6913        if (TREE_CODE (op) == STRING_CST
6914            || (TREE_CODE (op) == ARRAY_REF
6915                && integer_zerop (TREE_OPERAND (op, 1))
6916                && TREE_CODE (TREE_OPERAND (op, 0)) == STRING_CST))
6917          return integer_one_node;
6918     }
6919
6920   /* If this expression has side effects, show we don't know it to be a
6921      constant.  Likewise if it's a pointer or aggregate type since in
6922      those case we only want literals, since those are only optimized
6923      when generating RTL, not later.
6924      And finally, if we are compiling an initializer, not code, we
6925      need to return a definite result now; there's not going to be any
6926      more optimization done.  */
6927   if (TREE_SIDE_EFFECTS (arg)
6928       || AGGREGATE_TYPE_P (TREE_TYPE (arg))
6929       || POINTER_TYPE_P (TREE_TYPE (arg))
6930       || cfun == 0
6931       || folding_initializer
6932       || force_folding_builtin_constant_p)
6933     return integer_zero_node;
6934
6935   return NULL_TREE;
6936 }
6937
6938 /* Create builtin_expect with PRED and EXPECTED as its arguments and
6939    return it as a truthvalue.  */
6940
6941 static tree
6942 build_builtin_expect_predicate (location_t loc, tree pred, tree expected,
6943                                 tree predictor)
6944 {
6945   tree fn, arg_types, pred_type, expected_type, call_expr, ret_type;
6946
6947   fn = builtin_decl_explicit (BUILT_IN_EXPECT);
6948   arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
6949   ret_type = TREE_TYPE (TREE_TYPE (fn));
6950   pred_type = TREE_VALUE (arg_types);
6951   expected_type = TREE_VALUE (TREE_CHAIN (arg_types));
6952
6953   pred = fold_convert_loc (loc, pred_type, pred);
6954   expected = fold_convert_loc (loc, expected_type, expected);
6955   call_expr = build_call_expr_loc (loc, fn, predictor ? 3 : 2, pred, expected,
6956                                    predictor);
6957
6958   return build2 (NE_EXPR, TREE_TYPE (pred), call_expr,
6959                  build_int_cst (ret_type, 0));
6960 }
6961
6962 /* Fold a call to builtin_expect with arguments ARG0 and ARG1.  Return
6963    NULL_TREE if no simplification is possible.  */
6964
6965 tree
6966 fold_builtin_expect (location_t loc, tree arg0, tree arg1, tree arg2)
6967 {
6968   tree inner, fndecl, inner_arg0;
6969   enum tree_code code;
6970
6971   /* Distribute the expected value over short-circuiting operators.
6972      See through the cast from truthvalue_type_node to long.  */
6973   inner_arg0 = arg0;
6974   while (CONVERT_EXPR_P (inner_arg0)
6975          && INTEGRAL_TYPE_P (TREE_TYPE (inner_arg0))
6976          && INTEGRAL_TYPE_P (TREE_TYPE (TREE_OPERAND (inner_arg0, 0))))
6977     inner_arg0 = TREE_OPERAND (inner_arg0, 0);
6978
6979   /* If this is a builtin_expect within a builtin_expect keep the
6980      inner one.  See through a comparison against a constant.  It
6981      might have been added to create a thruthvalue.  */
6982   inner = inner_arg0;
6983
6984   if (COMPARISON_CLASS_P (inner)
6985       && TREE_CODE (TREE_OPERAND (inner, 1)) == INTEGER_CST)
6986     inner = TREE_OPERAND (inner, 0);
6987
6988   if (TREE_CODE (inner) == CALL_EXPR
6989       && (fndecl = get_callee_fndecl (inner))
6990       && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL
6991       && DECL_FUNCTION_CODE (fndecl) == BUILT_IN_EXPECT)
6992     return arg0;
6993
6994   inner = inner_arg0;
6995   code = TREE_CODE (inner);
6996   if (code == TRUTH_ANDIF_EXPR || code == TRUTH_ORIF_EXPR)
6997     {
6998       tree op0 = TREE_OPERAND (inner, 0);
6999       tree op1 = TREE_OPERAND (inner, 1);
7000
7001       op0 = build_builtin_expect_predicate (loc, op0, arg1, arg2);
7002       op1 = build_builtin_expect_predicate (loc, op1, arg1, arg2);
7003       inner = build2 (code, TREE_TYPE (inner), op0, op1);
7004
7005       return fold_convert_loc (loc, TREE_TYPE (arg0), inner);
7006     }
7007
7008   /* If the argument isn't invariant then there's nothing else we can do.  */
7009   if (!TREE_CONSTANT (inner_arg0))
7010     return NULL_TREE;
7011
7012   /* If we expect that a comparison against the argument will fold to
7013      a constant return the constant.  In practice, this means a true
7014      constant or the address of a non-weak symbol.  */
7015   inner = inner_arg0;
7016   STRIP_NOPS (inner);
7017   if (TREE_CODE (inner) == ADDR_EXPR)
7018     {
7019       do
7020         {
7021           inner = TREE_OPERAND (inner, 0);
7022         }
7023       while (TREE_CODE (inner) == COMPONENT_REF
7024              || TREE_CODE (inner) == ARRAY_REF);
7025       if ((TREE_CODE (inner) == VAR_DECL
7026            || TREE_CODE (inner) == FUNCTION_DECL)
7027           && DECL_WEAK (inner))
7028         return NULL_TREE;
7029     }
7030
7031   /* Otherwise, ARG0 already has the proper type for the return value.  */
7032   return arg0;
7033 }
7034
7035 /* Fold a call to __builtin_classify_type with argument ARG.  */
7036
7037 static tree
7038 fold_builtin_classify_type (tree arg)
7039 {
7040   if (arg == 0)
7041     return build_int_cst (integer_type_node, no_type_class);
7042
7043   return build_int_cst (integer_type_node, type_to_class (TREE_TYPE (arg)));
7044 }
7045
7046 /* Fold a call to __builtin_strlen with argument ARG.  */
7047
7048 static tree
7049 fold_builtin_strlen (location_t loc, tree type, tree arg)
7050 {
7051   if (!validate_arg (arg, POINTER_TYPE))
7052     return NULL_TREE;
7053   else
7054     {
7055       tree len = c_strlen (arg, 0);
7056
7057       if (len)
7058         return fold_convert_loc (loc, type, len);
7059
7060       return NULL_TREE;
7061     }
7062 }
7063
7064 /* Fold a call to __builtin_inf or __builtin_huge_val.  */
7065
7066 static tree
7067 fold_builtin_inf (location_t loc, tree type, int warn)
7068 {
7069   REAL_VALUE_TYPE real;
7070
7071   /* __builtin_inff is intended to be usable to define INFINITY on all
7072      targets.  If an infinity is not available, INFINITY expands "to a
7073      positive constant of type float that overflows at translation
7074      time", footnote "In this case, using INFINITY will violate the
7075      constraint in 6.4.4 and thus require a diagnostic." (C99 7.12#4).
7076      Thus we pedwarn to ensure this constraint violation is
7077      diagnosed.  */
7078   if (!MODE_HAS_INFINITIES (TYPE_MODE (type)) && warn)
7079     pedwarn (loc, 0, "target format does not support infinity");
7080
7081   real_inf (&real);
7082   return build_real (type, real);
7083 }
7084
7085 /* Fold function call to builtin sincos, sincosf, or sincosl.  Return
7086    NULL_TREE if no simplification can be made.  */
7087
7088 static tree
7089 fold_builtin_sincos (location_t loc,
7090                      tree arg0, tree arg1, tree arg2)
7091 {
7092   tree type;
7093   tree fndecl, call = NULL_TREE;
7094
7095   if (!validate_arg (arg0, REAL_TYPE)
7096       || !validate_arg (arg1, POINTER_TYPE)
7097       || !validate_arg (arg2, POINTER_TYPE))
7098     return NULL_TREE;
7099
7100   type = TREE_TYPE (arg0);
7101
7102   /* Calculate the result when the argument is a constant.  */
7103   built_in_function fn = mathfn_built_in_2 (type, CFN_BUILT_IN_CEXPI);
7104   if (fn == END_BUILTINS)
7105     return NULL_TREE;
7106
7107   /* Canonicalize sincos to cexpi.  */
7108   if (TREE_CODE (arg0) == REAL_CST)
7109     {
7110       tree complex_type = build_complex_type (type);
7111       call = fold_const_call (as_combined_fn (fn), complex_type, arg0);
7112     }
7113   if (!call)
7114     {
7115       if (!targetm.libc_has_function (function_c99_math_complex)
7116           || !builtin_decl_implicit_p (fn))
7117         return NULL_TREE;
7118       fndecl = builtin_decl_explicit (fn);
7119       call = build_call_expr_loc (loc, fndecl, 1, arg0);
7120       call = builtin_save_expr (call);
7121     }
7122
7123   return build2 (COMPOUND_EXPR, void_type_node,
7124                  build2 (MODIFY_EXPR, void_type_node,
7125                          build_fold_indirect_ref_loc (loc, arg1),
7126                          fold_build1_loc (loc, IMAGPART_EXPR, type, call)),
7127                  build2 (MODIFY_EXPR, void_type_node,
7128                          build_fold_indirect_ref_loc (loc, arg2),
7129                          fold_build1_loc (loc, REALPART_EXPR, type, call)));
7130 }
7131
7132 /* Fold function call to builtin memchr.  ARG1, ARG2 and LEN are the
7133    arguments to the call, and TYPE is its return type.
7134    Return NULL_TREE if no simplification can be made.  */
7135
7136 static tree
7137 fold_builtin_memchr (location_t loc, tree arg1, tree arg2, tree len, tree type)
7138 {
7139   if (!validate_arg (arg1, POINTER_TYPE)
7140       || !validate_arg (arg2, INTEGER_TYPE)
7141       || !validate_arg (len, INTEGER_TYPE))
7142     return NULL_TREE;
7143   else
7144     {
7145       const char *p1;
7146
7147       if (TREE_CODE (arg2) != INTEGER_CST
7148           || !tree_fits_uhwi_p (len))
7149         return NULL_TREE;
7150
7151       p1 = c_getstr (arg1);
7152       if (p1 && compare_tree_int (len, strlen (p1) + 1) <= 0)
7153         {
7154           char c;
7155           const char *r;
7156           tree tem;
7157
7158           if (target_char_cast (arg2, &c))
7159             return NULL_TREE;
7160
7161           r = (const char *) memchr (p1, c, tree_to_uhwi (len));
7162
7163           if (r == NULL)
7164             return build_int_cst (TREE_TYPE (arg1), 0);
7165
7166           tem = fold_build_pointer_plus_hwi_loc (loc, arg1, r - p1);
7167           return fold_convert_loc (loc, type, tem);
7168         }
7169       return NULL_TREE;
7170     }
7171 }
7172
7173 /* Fold function call to builtin memcmp with arguments ARG1 and ARG2.
7174    Return NULL_TREE if no simplification can be made.  */
7175
7176 static tree
7177 fold_builtin_memcmp (location_t loc, tree arg1, tree arg2, tree len)
7178 {
7179   if (!validate_arg (arg1, POINTER_TYPE)
7180       || !validate_arg (arg2, POINTER_TYPE)
7181       || !validate_arg (len, INTEGER_TYPE))
7182     return NULL_TREE;
7183
7184   /* If the LEN parameter is zero, return zero.  */
7185   if (integer_zerop (len))
7186     return omit_two_operands_loc (loc, integer_type_node, integer_zero_node,
7187                               arg1, arg2);
7188
7189   /* If ARG1 and ARG2 are the same (and not volatile), return zero.  */
7190   if (operand_equal_p (arg1, arg2, 0))
7191     return omit_one_operand_loc (loc, integer_type_node, integer_zero_node, len);
7192
7193   /* If len parameter is one, return an expression corresponding to
7194      (*(const unsigned char*)arg1 - (const unsigned char*)arg2).  */
7195   if (tree_fits_uhwi_p (len) && tree_to_uhwi (len) == 1)
7196     {
7197       tree cst_uchar_node = build_type_variant (unsigned_char_type_node, 1, 0);
7198       tree cst_uchar_ptr_node
7199         = build_pointer_type_for_mode (cst_uchar_node, ptr_mode, true);
7200
7201       tree ind1
7202         = fold_convert_loc (loc, integer_type_node,
7203                             build1 (INDIRECT_REF, cst_uchar_node,
7204                                     fold_convert_loc (loc,
7205                                                       cst_uchar_ptr_node,
7206                                                       arg1)));
7207       tree ind2
7208         = fold_convert_loc (loc, integer_type_node,
7209                             build1 (INDIRECT_REF, cst_uchar_node,
7210                                     fold_convert_loc (loc,
7211                                                       cst_uchar_ptr_node,
7212                                                       arg2)));
7213       return fold_build2_loc (loc, MINUS_EXPR, integer_type_node, ind1, ind2);
7214     }
7215
7216   return NULL_TREE;
7217 }
7218
7219 /* Fold function call to builtin strcmp with arguments ARG1 and ARG2.
7220    Return NULL_TREE if no simplification can be made.  */
7221
7222 static tree
7223 fold_builtin_strcmp (location_t loc, tree arg1, tree arg2)
7224 {
7225   if (!validate_arg (arg1, POINTER_TYPE)
7226       || !validate_arg (arg2, POINTER_TYPE))
7227     return NULL_TREE;
7228
7229   /* If ARG1 and ARG2 are the same (and not volatile), return zero.  */
7230   if (operand_equal_p (arg1, arg2, 0))
7231     return integer_zero_node;
7232
7233   /* If the second arg is "", return *(const unsigned char*)arg1.  */
7234   const char *p2 = c_getstr (arg2);
7235   if (p2 && *p2 == '\0')
7236     {
7237       tree cst_uchar_node = build_type_variant (unsigned_char_type_node, 1, 0);
7238       tree cst_uchar_ptr_node
7239         = build_pointer_type_for_mode (cst_uchar_node, ptr_mode, true);
7240
7241       return fold_convert_loc (loc, integer_type_node,
7242                                build1 (INDIRECT_REF, cst_uchar_node,
7243                                        fold_convert_loc (loc,
7244                                                          cst_uchar_ptr_node,
7245                                                          arg1)));
7246     }
7247
7248   /* If the first arg is "", return -*(const unsigned char*)arg2.  */
7249   const char *p1 = c_getstr (arg1);
7250   if (p1 && *p1 == '\0')
7251     {
7252       tree cst_uchar_node = build_type_variant (unsigned_char_type_node, 1, 0);
7253       tree cst_uchar_ptr_node
7254         = build_pointer_type_for_mode (cst_uchar_node, ptr_mode, true);
7255
7256       tree temp
7257         = fold_convert_loc (loc, integer_type_node,
7258                             build1 (INDIRECT_REF, cst_uchar_node,
7259                                     fold_convert_loc (loc,
7260                                                       cst_uchar_ptr_node,
7261                                                       arg2)));
7262       return fold_build1_loc (loc, NEGATE_EXPR, integer_type_node, temp);
7263     }
7264
7265   return NULL_TREE;
7266 }
7267
7268 /* Fold function call to builtin strncmp with arguments ARG1, ARG2, and LEN.
7269    Return NULL_TREE if no simplification can be made.  */
7270
7271 static tree
7272 fold_builtin_strncmp (location_t loc, tree arg1, tree arg2, tree len)
7273 {
7274   if (!validate_arg (arg1, POINTER_TYPE)
7275       || !validate_arg (arg2, POINTER_TYPE)
7276       || !validate_arg (len, INTEGER_TYPE))
7277     return NULL_TREE;
7278
7279   /* If the LEN parameter is zero, return zero.  */
7280   if (integer_zerop (len))
7281     return omit_two_operands_loc (loc, integer_type_node, integer_zero_node,
7282                               arg1, arg2);
7283
7284   /* If ARG1 and ARG2 are the same (and not volatile), return zero.  */
7285   if (operand_equal_p (arg1, arg2, 0))
7286     return omit_one_operand_loc (loc, integer_type_node, integer_zero_node, len);
7287
7288   /* If the second arg is "", and the length is greater than zero,
7289      return *(const unsigned char*)arg1.  */
7290   const char *p2 = c_getstr (arg2);
7291   if (p2 && *p2 == '\0'
7292       && TREE_CODE (len) == INTEGER_CST
7293       && tree_int_cst_sgn (len) == 1)
7294     {
7295       tree cst_uchar_node = build_type_variant (unsigned_char_type_node, 1, 0);
7296       tree cst_uchar_ptr_node
7297         = build_pointer_type_for_mode (cst_uchar_node, ptr_mode, true);
7298
7299       return fold_convert_loc (loc, integer_type_node,
7300                                build1 (INDIRECT_REF, cst_uchar_node,
7301                                        fold_convert_loc (loc,
7302                                                          cst_uchar_ptr_node,
7303                                                          arg1)));
7304     }
7305
7306   /* If the first arg is "", and the length is greater than zero,
7307      return -*(const unsigned char*)arg2.  */
7308   const char *p1 = c_getstr (arg1);
7309   if (p1 && *p1 == '\0'
7310       && TREE_CODE (len) == INTEGER_CST
7311       && tree_int_cst_sgn (len) == 1)
7312     {
7313       tree cst_uchar_node = build_type_variant (unsigned_char_type_node, 1, 0);
7314       tree cst_uchar_ptr_node
7315         = build_pointer_type_for_mode (cst_uchar_node, ptr_mode, true);
7316
7317       tree temp = fold_convert_loc (loc, integer_type_node,
7318                                     build1 (INDIRECT_REF, cst_uchar_node,
7319                                             fold_convert_loc (loc,
7320                                                               cst_uchar_ptr_node,
7321                                                               arg2)));
7322       return fold_build1_loc (loc, NEGATE_EXPR, integer_type_node, temp);
7323     }
7324
7325   /* If len parameter is one, return an expression corresponding to
7326      (*(const unsigned char*)arg1 - (const unsigned char*)arg2).  */
7327   if (tree_fits_uhwi_p (len) && tree_to_uhwi (len) == 1)
7328     {
7329       tree cst_uchar_node = build_type_variant (unsigned_char_type_node, 1, 0);
7330       tree cst_uchar_ptr_node
7331         = build_pointer_type_for_mode (cst_uchar_node, ptr_mode, true);
7332
7333       tree ind1 = fold_convert_loc (loc, integer_type_node,
7334                                     build1 (INDIRECT_REF, cst_uchar_node,
7335                                             fold_convert_loc (loc,
7336                                                               cst_uchar_ptr_node,
7337                                                               arg1)));
7338       tree ind2 = fold_convert_loc (loc, integer_type_node,
7339                                     build1 (INDIRECT_REF, cst_uchar_node,
7340                                             fold_convert_loc (loc,
7341                                                               cst_uchar_ptr_node,
7342                                                               arg2)));
7343       return fold_build2_loc (loc, MINUS_EXPR, integer_type_node, ind1, ind2);
7344     }
7345
7346   return NULL_TREE;
7347 }
7348
7349 /* Fold a call to builtin isascii with argument ARG.  */
7350
7351 static tree
7352 fold_builtin_isascii (location_t loc, tree arg)
7353 {
7354   if (!validate_arg (arg, INTEGER_TYPE))
7355     return NULL_TREE;
7356   else
7357     {
7358       /* Transform isascii(c) -> ((c & ~0x7f) == 0).  */
7359       arg = fold_build2 (BIT_AND_EXPR, integer_type_node, arg,
7360                          build_int_cst (integer_type_node,
7361                                         ~ (unsigned HOST_WIDE_INT) 0x7f));
7362       return fold_build2_loc (loc, EQ_EXPR, integer_type_node,
7363                               arg, integer_zero_node);
7364     }
7365 }
7366
7367 /* Fold a call to builtin toascii with argument ARG.  */
7368
7369 static tree
7370 fold_builtin_toascii (location_t loc, tree arg)
7371 {
7372   if (!validate_arg (arg, INTEGER_TYPE))
7373     return NULL_TREE;
7374
7375   /* Transform toascii(c) -> (c & 0x7f).  */
7376   return fold_build2_loc (loc, BIT_AND_EXPR, integer_type_node, arg,
7377                           build_int_cst (integer_type_node, 0x7f));
7378 }
7379
7380 /* Fold a call to builtin isdigit with argument ARG.  */
7381
7382 static tree
7383 fold_builtin_isdigit (location_t loc, tree arg)
7384 {
7385   if (!validate_arg (arg, INTEGER_TYPE))
7386     return NULL_TREE;
7387   else
7388     {
7389       /* Transform isdigit(c) -> (unsigned)(c) - '0' <= 9.  */
7390       /* According to the C standard, isdigit is unaffected by locale.
7391          However, it definitely is affected by the target character set.  */
7392       unsigned HOST_WIDE_INT target_digit0
7393         = lang_hooks.to_target_charset ('0');
7394
7395       if (target_digit0 == 0)
7396         return NULL_TREE;
7397
7398       arg = fold_convert_loc (loc, unsigned_type_node, arg);
7399       arg = fold_build2 (MINUS_EXPR, unsigned_type_node, arg,
7400                          build_int_cst (unsigned_type_node, target_digit0));
7401       return fold_build2_loc (loc, LE_EXPR, integer_type_node, arg,
7402                           build_int_cst (unsigned_type_node, 9));
7403     }
7404 }
7405
7406 /* Fold a call to fabs, fabsf or fabsl with argument ARG.  */
7407
7408 static tree
7409 fold_builtin_fabs (location_t loc, tree arg, tree type)
7410 {
7411   if (!validate_arg (arg, REAL_TYPE))
7412     return NULL_TREE;
7413
7414   arg = fold_convert_loc (loc, type, arg);
7415   return fold_build1_loc (loc, ABS_EXPR, type, arg);
7416 }
7417
7418 /* Fold a call to abs, labs, llabs or imaxabs with argument ARG.  */
7419
7420 static tree
7421 fold_builtin_abs (location_t loc, tree arg, tree type)
7422 {
7423   if (!validate_arg (arg, INTEGER_TYPE))
7424     return NULL_TREE;
7425
7426   arg = fold_convert_loc (loc, type, arg);
7427   return fold_build1_loc (loc, ABS_EXPR, type, arg);
7428 }
7429
7430 /* Fold a call to fma, fmaf, or fmal with arguments ARG[012].  */
7431
7432 static tree
7433 fold_builtin_fma (location_t loc, tree arg0, tree arg1, tree arg2, tree type)
7434 {
7435   /* ??? Only expand to FMA_EXPR if it's directly supported.  */
7436   if (validate_arg (arg0, REAL_TYPE)
7437       && validate_arg (arg1, REAL_TYPE)
7438       && validate_arg (arg2, REAL_TYPE)
7439       && optab_handler (fma_optab, TYPE_MODE (type)) != CODE_FOR_nothing)
7440     return fold_build3_loc (loc, FMA_EXPR, type, arg0, arg1, arg2);
7441
7442   return NULL_TREE;
7443 }
7444
7445 /* Fold a call to builtin carg(a+bi) -> atan2(b,a).  */
7446
7447 static tree
7448 fold_builtin_carg (location_t loc, tree arg, tree type)
7449 {
7450   if (validate_arg (arg, COMPLEX_TYPE)
7451       && TREE_CODE (TREE_TYPE (TREE_TYPE (arg))) == REAL_TYPE)
7452     {
7453       tree atan2_fn = mathfn_built_in (type, BUILT_IN_ATAN2);
7454
7455       if (atan2_fn)
7456         {
7457           tree new_arg = builtin_save_expr (arg);
7458           tree r_arg = fold_build1_loc (loc, REALPART_EXPR, type, new_arg);
7459           tree i_arg = fold_build1_loc (loc, IMAGPART_EXPR, type, new_arg);
7460           return build_call_expr_loc (loc, atan2_fn, 2, i_arg, r_arg);
7461         }
7462     }
7463
7464   return NULL_TREE;
7465 }
7466
7467 /* Fold a call to builtin frexp, we can assume the base is 2.  */
7468
7469 static tree
7470 fold_builtin_frexp (location_t loc, tree arg0, tree arg1, tree rettype)
7471 {
7472   if (! validate_arg (arg0, REAL_TYPE) || ! validate_arg (arg1, POINTER_TYPE))
7473     return NULL_TREE;
7474
7475   STRIP_NOPS (arg0);
7476
7477   if (!(TREE_CODE (arg0) == REAL_CST && ! TREE_OVERFLOW (arg0)))
7478     return NULL_TREE;
7479
7480   arg1 = build_fold_indirect_ref_loc (loc, arg1);
7481
7482   /* Proceed if a valid pointer type was passed in.  */
7483   if (TYPE_MAIN_VARIANT (TREE_TYPE (arg1)) == integer_type_node)
7484     {
7485       const REAL_VALUE_TYPE *const value = TREE_REAL_CST_PTR (arg0);
7486       tree frac, exp;
7487
7488       switch (value->cl)
7489       {
7490       case rvc_zero:
7491         /* For +-0, return (*exp = 0, +-0).  */
7492         exp = integer_zero_node;
7493         frac = arg0;
7494         break;
7495       case rvc_nan:
7496       case rvc_inf:
7497         /* For +-NaN or +-Inf, *exp is unspecified, return arg0.  */
7498         return omit_one_operand_loc (loc, rettype, arg0, arg1);
7499       case rvc_normal:
7500         {
7501           /* Since the frexp function always expects base 2, and in
7502              GCC normalized significands are already in the range
7503              [0.5, 1.0), we have exactly what frexp wants.  */
7504           REAL_VALUE_TYPE frac_rvt = *value;
7505           SET_REAL_EXP (&frac_rvt, 0);
7506           frac = build_real (rettype, frac_rvt);
7507           exp = build_int_cst (integer_type_node, REAL_EXP (value));
7508         }
7509         break;
7510       default:
7511         gcc_unreachable ();
7512       }
7513
7514       /* Create the COMPOUND_EXPR (*arg1 = trunc, frac). */
7515       arg1 = fold_build2_loc (loc, MODIFY_EXPR, rettype, arg1, exp);
7516       TREE_SIDE_EFFECTS (arg1) = 1;
7517       return fold_build2_loc (loc, COMPOUND_EXPR, rettype, arg1, frac);
7518     }
7519
7520   return NULL_TREE;
7521 }
7522
7523 /* Fold a call to builtin modf.  */
7524
7525 static tree
7526 fold_builtin_modf (location_t loc, tree arg0, tree arg1, tree rettype)
7527 {
7528   if (! validate_arg (arg0, REAL_TYPE) || ! validate_arg (arg1, POINTER_TYPE))
7529     return NULL_TREE;
7530
7531   STRIP_NOPS (arg0);
7532
7533   if (!(TREE_CODE (arg0) == REAL_CST && ! TREE_OVERFLOW (arg0)))
7534     return NULL_TREE;
7535
7536   arg1 = build_fold_indirect_ref_loc (loc, arg1);
7537
7538   /* Proceed if a valid pointer type was passed in.  */
7539   if (TYPE_MAIN_VARIANT (TREE_TYPE (arg1)) == TYPE_MAIN_VARIANT (rettype))
7540     {
7541       const REAL_VALUE_TYPE *const value = TREE_REAL_CST_PTR (arg0);
7542       REAL_VALUE_TYPE trunc, frac;
7543
7544       switch (value->cl)
7545       {
7546       case rvc_nan:
7547       case rvc_zero:
7548         /* For +-NaN or +-0, return (*arg1 = arg0, arg0).  */
7549         trunc = frac = *value;
7550         break;
7551       case rvc_inf:
7552         /* For +-Inf, return (*arg1 = arg0, +-0).  */
7553         frac = dconst0;
7554         frac.sign = value->sign;
7555         trunc = *value;
7556         break;
7557       case rvc_normal:
7558         /* Return (*arg1 = trunc(arg0), arg0-trunc(arg0)).  */
7559         real_trunc (&trunc, VOIDmode, value);
7560         real_arithmetic (&frac, MINUS_EXPR, value, &trunc);
7561         /* If the original number was negative and already
7562            integral, then the fractional part is -0.0.  */
7563         if (value->sign && frac.cl == rvc_zero)
7564           frac.sign = value->sign;
7565         break;
7566       }
7567
7568       /* Create the COMPOUND_EXPR (*arg1 = trunc, frac). */
7569       arg1 = fold_build2_loc (loc, MODIFY_EXPR, rettype, arg1,
7570                           build_real (rettype, trunc));
7571       TREE_SIDE_EFFECTS (arg1) = 1;
7572       return fold_build2_loc (loc, COMPOUND_EXPR, rettype, arg1,
7573                           build_real (rettype, frac));
7574     }
7575
7576   return NULL_TREE;
7577 }
7578
7579 /* Given a location LOC, an interclass builtin function decl FNDECL
7580    and its single argument ARG, return an folded expression computing
7581    the same, or NULL_TREE if we either couldn't or didn't want to fold
7582    (the latter happen if there's an RTL instruction available).  */
7583
7584 static tree
7585 fold_builtin_interclass_mathfn (location_t loc, tree fndecl, tree arg)
7586 {
7587   machine_mode mode;
7588
7589   if (!validate_arg (arg, REAL_TYPE))
7590     return NULL_TREE;
7591
7592   if (interclass_mathfn_icode (arg, fndecl) != CODE_FOR_nothing)
7593     return NULL_TREE;
7594
7595   mode = TYPE_MODE (TREE_TYPE (arg));
7596
7597   bool is_ibm_extended = MODE_COMPOSITE_P (mode);
7598
7599   /* If there is no optab, try generic code.  */
7600   switch (DECL_FUNCTION_CODE (fndecl))
7601     {
7602       tree result;
7603
7604     CASE_FLT_FN (BUILT_IN_ISINF):
7605       {
7606         /* isinf(x) -> isgreater(fabs(x),DBL_MAX).  */
7607         tree const isgr_fn = builtin_decl_explicit (BUILT_IN_ISGREATER);
7608         tree type = TREE_TYPE (arg);
7609         REAL_VALUE_TYPE r;
7610         char buf[128];
7611
7612         if (is_ibm_extended)
7613           {
7614             /* NaN and Inf are encoded in the high-order double value
7615                only.  The low-order value is not significant.  */
7616             type = double_type_node;
7617             mode = DFmode;
7618             arg = fold_build1_loc (loc, NOP_EXPR, type, arg);
7619           }
7620         get_max_float (REAL_MODE_FORMAT (mode), buf, sizeof (buf));
7621         real_from_string (&r, buf);
7622         result = build_call_expr (isgr_fn, 2,
7623                                   fold_build1_loc (loc, ABS_EXPR, type, arg),
7624                                   build_real (type, r));
7625         return result;
7626       }
7627     CASE_FLT_FN (BUILT_IN_FINITE):
7628     case BUILT_IN_ISFINITE:
7629       {
7630         /* isfinite(x) -> islessequal(fabs(x),DBL_MAX).  */
7631         tree const isle_fn = builtin_decl_explicit (BUILT_IN_ISLESSEQUAL);
7632         tree type = TREE_TYPE (arg);
7633         REAL_VALUE_TYPE r;
7634         char buf[128];
7635
7636         if (is_ibm_extended)
7637           {
7638             /* NaN and Inf are encoded in the high-order double value
7639                only.  The low-order value is not significant.  */
7640             type = double_type_node;
7641             mode = DFmode;
7642             arg = fold_build1_loc (loc, NOP_EXPR, type, arg);
7643           }
7644         get_max_float (REAL_MODE_FORMAT (mode), buf, sizeof (buf));
7645         real_from_string (&r, buf);
7646         result = build_call_expr (isle_fn, 2,
7647                                   fold_build1_loc (loc, ABS_EXPR, type, arg),
7648                                   build_real (type, r));
7649         /*result = fold_build2_loc (loc, UNGT_EXPR,
7650                                   TREE_TYPE (TREE_TYPE (fndecl)),
7651                                   fold_build1_loc (loc, ABS_EXPR, type, arg),
7652                                   build_real (type, r));
7653         result = fold_build1_loc (loc, TRUTH_NOT_EXPR,
7654                                   TREE_TYPE (TREE_TYPE (fndecl)),
7655                                   result);*/
7656         return result;
7657       }
7658     case BUILT_IN_ISNORMAL:
7659       {
7660         /* isnormal(x) -> isgreaterequal(fabs(x),DBL_MIN) &
7661            islessequal(fabs(x),DBL_MAX).  */
7662         tree const isle_fn = builtin_decl_explicit (BUILT_IN_ISLESSEQUAL);
7663         tree type = TREE_TYPE (arg);
7664         tree orig_arg, max_exp, min_exp;
7665         machine_mode orig_mode = mode;
7666         REAL_VALUE_TYPE rmax, rmin;
7667         char buf[128];
7668
7669         orig_arg = arg = builtin_save_expr (arg);
7670         if (is_ibm_extended)
7671           {
7672             /* Use double to test the normal range of IBM extended
7673                precision.  Emin for IBM extended precision is
7674                different to emin for IEEE double, being 53 higher
7675                since the low double exponent is at least 53 lower
7676                than the high double exponent.  */
7677             type = double_type_node;
7678             mode = DFmode;
7679             arg = fold_build1_loc (loc, NOP_EXPR, type, arg);
7680           }
7681         arg = fold_build1_loc (loc, ABS_EXPR, type, arg);
7682
7683         get_max_float (REAL_MODE_FORMAT (mode), buf, sizeof (buf));
7684         real_from_string (&rmax, buf);
7685         sprintf (buf, "0x1p%d", REAL_MODE_FORMAT (orig_mode)->emin - 1);
7686         real_from_string (&rmin, buf);
7687         max_exp = build_real (type, rmax);
7688         min_exp = build_real (type, rmin);
7689
7690         max_exp = build_call_expr (isle_fn, 2, arg, max_exp);
7691         if (is_ibm_extended)
7692           {
7693             /* Testing the high end of the range is done just using
7694                the high double, using the same test as isfinite().
7695                For the subnormal end of the range we first test the
7696                high double, then if its magnitude is equal to the
7697                limit of 0x1p-969, we test whether the low double is
7698                non-zero and opposite sign to the high double.  */
7699             tree const islt_fn = builtin_decl_explicit (BUILT_IN_ISLESS);
7700             tree const isgt_fn = builtin_decl_explicit (BUILT_IN_ISGREATER);
7701             tree gt_min = build_call_expr (isgt_fn, 2, arg, min_exp);
7702             tree eq_min = fold_build2 (EQ_EXPR, integer_type_node,
7703                                        arg, min_exp);
7704             tree as_complex = build1 (VIEW_CONVERT_EXPR,
7705                                       complex_double_type_node, orig_arg);
7706             tree hi_dbl = build1 (REALPART_EXPR, type, as_complex);
7707             tree lo_dbl = build1 (IMAGPART_EXPR, type, as_complex);
7708             tree zero = build_real (type, dconst0);
7709             tree hilt = build_call_expr (islt_fn, 2, hi_dbl, zero);
7710             tree lolt = build_call_expr (islt_fn, 2, lo_dbl, zero);
7711             tree logt = build_call_expr (isgt_fn, 2, lo_dbl, zero);
7712             tree ok_lo = fold_build1 (TRUTH_NOT_EXPR, integer_type_node,
7713                                       fold_build3 (COND_EXPR,
7714                                                    integer_type_node,
7715                                                    hilt, logt, lolt));
7716             eq_min = fold_build2 (TRUTH_ANDIF_EXPR, integer_type_node,
7717                                   eq_min, ok_lo);
7718             min_exp = fold_build2 (TRUTH_ORIF_EXPR, integer_type_node,
7719                                    gt_min, eq_min);
7720           }
7721         else
7722           {
7723             tree const isge_fn
7724               = builtin_decl_explicit (BUILT_IN_ISGREATEREQUAL);
7725             min_exp = build_call_expr (isge_fn, 2, arg, min_exp);
7726           }
7727         result = fold_build2 (BIT_AND_EXPR, integer_type_node,
7728                               max_exp, min_exp);
7729         return result;
7730       }
7731     default:
7732       break;
7733     }
7734
7735   return NULL_TREE;
7736 }
7737
7738 /* Fold a call to __builtin_isnan(), __builtin_isinf, __builtin_finite.
7739    ARG is the argument for the call.  */
7740
7741 static tree
7742 fold_builtin_classify (location_t loc, tree fndecl, tree arg, int builtin_index)
7743 {
7744   tree type = TREE_TYPE (TREE_TYPE (fndecl));
7745
7746   if (!validate_arg (arg, REAL_TYPE))
7747     return NULL_TREE;
7748
7749   switch (builtin_index)
7750     {
7751     case BUILT_IN_ISINF:
7752       if (!HONOR_INFINITIES (arg))
7753         return omit_one_operand_loc (loc, type, integer_zero_node, arg);
7754
7755       return NULL_TREE;
7756
7757     case BUILT_IN_ISINF_SIGN:
7758       {
7759         /* isinf_sign(x) -> isinf(x) ? (signbit(x) ? -1 : 1) : 0 */
7760         /* In a boolean context, GCC will fold the inner COND_EXPR to
7761            1.  So e.g. "if (isinf_sign(x))" would be folded to just
7762            "if (isinf(x) ? 1 : 0)" which becomes "if (isinf(x))". */
7763         tree signbit_fn = mathfn_built_in_1
7764           (TREE_TYPE (arg), CFN_BUILT_IN_SIGNBIT, 0);
7765         tree isinf_fn = builtin_decl_explicit (BUILT_IN_ISINF);
7766         tree tmp = NULL_TREE;
7767
7768         arg = builtin_save_expr (arg);
7769
7770         if (signbit_fn && isinf_fn)
7771           {
7772             tree signbit_call = build_call_expr_loc (loc, signbit_fn, 1, arg);
7773             tree isinf_call = build_call_expr_loc (loc, isinf_fn, 1, arg);
7774
7775             signbit_call = fold_build2_loc (loc, NE_EXPR, integer_type_node,
7776                                         signbit_call, integer_zero_node);
7777             isinf_call = fold_build2_loc (loc, NE_EXPR, integer_type_node,
7778                                       isinf_call, integer_zero_node);
7779
7780             tmp = fold_build3_loc (loc, COND_EXPR, integer_type_node, signbit_call,
7781                                integer_minus_one_node, integer_one_node);
7782             tmp = fold_build3_loc (loc, COND_EXPR, integer_type_node,
7783                                isinf_call, tmp,
7784                                integer_zero_node);
7785           }
7786
7787         return tmp;
7788       }
7789
7790     case BUILT_IN_ISFINITE:
7791       if (!HONOR_NANS (arg)
7792           && !HONOR_INFINITIES (arg))
7793         return omit_one_operand_loc (loc, type, integer_one_node, arg);
7794
7795       return NULL_TREE;
7796
7797     case BUILT_IN_ISNAN:
7798       if (!HONOR_NANS (arg))
7799         return omit_one_operand_loc (loc, type, integer_zero_node, arg);
7800
7801       {
7802         bool is_ibm_extended = MODE_COMPOSITE_P (TYPE_MODE (TREE_TYPE (arg)));
7803         if (is_ibm_extended)
7804           {
7805             /* NaN and Inf are encoded in the high-order double value
7806                only.  The low-order value is not significant.  */
7807             arg = fold_build1_loc (loc, NOP_EXPR, double_type_node, arg);
7808           }
7809       }
7810       arg = builtin_save_expr (arg);
7811       return fold_build2_loc (loc, UNORDERED_EXPR, type, arg, arg);
7812
7813     default:
7814       gcc_unreachable ();
7815     }
7816 }
7817
7818 /* Fold a call to __builtin_fpclassify(int, int, int, int, int, ...).
7819    This builtin will generate code to return the appropriate floating
7820    point classification depending on the value of the floating point
7821    number passed in.  The possible return values must be supplied as
7822    int arguments to the call in the following order: FP_NAN, FP_INFINITE,
7823    FP_NORMAL, FP_SUBNORMAL and FP_ZERO.  The ellipses is for exactly
7824    one floating point argument which is "type generic".  */
7825
7826 static tree
7827 fold_builtin_fpclassify (location_t loc, tree *args, int nargs)
7828 {
7829   tree fp_nan, fp_infinite, fp_normal, fp_subnormal, fp_zero,
7830     arg, type, res, tmp;
7831   machine_mode mode;
7832   REAL_VALUE_TYPE r;
7833   char buf[128];
7834
7835   /* Verify the required arguments in the original call.  */
7836   if (nargs != 6
7837       || !validate_arg (args[0], INTEGER_TYPE)
7838       || !validate_arg (args[1], INTEGER_TYPE)
7839       || !validate_arg (args[2], INTEGER_TYPE)
7840       || !validate_arg (args[3], INTEGER_TYPE)
7841       || !validate_arg (args[4], INTEGER_TYPE)
7842       || !validate_arg (args[5], REAL_TYPE))
7843     return NULL_TREE;
7844
7845   fp_nan = args[0];
7846   fp_infinite = args[1];
7847   fp_normal = args[2];
7848   fp_subnormal = args[3];
7849   fp_zero = args[4];
7850   arg = args[5];
7851   type = TREE_TYPE (arg);
7852   mode = TYPE_MODE (type);
7853   arg = builtin_save_expr (fold_build1_loc (loc, ABS_EXPR, type, arg));
7854
7855   /* fpclassify(x) ->
7856        isnan(x) ? FP_NAN :
7857          (fabs(x) == Inf ? FP_INFINITE :
7858            (fabs(x) >= DBL_MIN ? FP_NORMAL :
7859              (x == 0 ? FP_ZERO : FP_SUBNORMAL))).  */
7860
7861   tmp = fold_build2_loc (loc, EQ_EXPR, integer_type_node, arg,
7862                      build_real (type, dconst0));
7863   res = fold_build3_loc (loc, COND_EXPR, integer_type_node,
7864                      tmp, fp_zero, fp_subnormal);
7865
7866   sprintf (buf, "0x1p%d", REAL_MODE_FORMAT (mode)->emin - 1);
7867   real_from_string (&r, buf);
7868   tmp = fold_build2_loc (loc, GE_EXPR, integer_type_node,
7869                      arg, build_real (type, r));
7870   res = fold_build3_loc (loc, COND_EXPR, integer_type_node, tmp, fp_normal, res);
7871
7872   if (HONOR_INFINITIES (mode))
7873     {
7874       real_inf (&r);
7875       tmp = fold_build2_loc (loc, EQ_EXPR, integer_type_node, arg,
7876                          build_real (type, r));
7877       res = fold_build3_loc (loc, COND_EXPR, integer_type_node, tmp,
7878                          fp_infinite, res);
7879     }
7880
7881   if (HONOR_NANS (mode))
7882     {
7883       tmp = fold_build2_loc (loc, ORDERED_EXPR, integer_type_node, arg, arg);
7884       res = fold_build3_loc (loc, COND_EXPR, integer_type_node, tmp, res, fp_nan);
7885     }
7886
7887   return res;
7888 }
7889
7890 /* Fold a call to an unordered comparison function such as
7891    __builtin_isgreater().  FNDECL is the FUNCTION_DECL for the function
7892    being called and ARG0 and ARG1 are the arguments for the call.
7893    UNORDERED_CODE and ORDERED_CODE are comparison codes that give
7894    the opposite of the desired result.  UNORDERED_CODE is used
7895    for modes that can hold NaNs and ORDERED_CODE is used for
7896    the rest.  */
7897
7898 static tree
7899 fold_builtin_unordered_cmp (location_t loc, tree fndecl, tree arg0, tree arg1,
7900                             enum tree_code unordered_code,
7901                             enum tree_code ordered_code)
7902 {
7903   tree type = TREE_TYPE (TREE_TYPE (fndecl));
7904   enum tree_code code;
7905   tree type0, type1;
7906   enum tree_code code0, code1;
7907   tree cmp_type = NULL_TREE;
7908
7909   type0 = TREE_TYPE (arg0);
7910   type1 = TREE_TYPE (arg1);
7911
7912   code0 = TREE_CODE (type0);
7913   code1 = TREE_CODE (type1);
7914
7915   if (code0 == REAL_TYPE && code1 == REAL_TYPE)
7916     /* Choose the wider of two real types.  */
7917     cmp_type = TYPE_PRECISION (type0) >= TYPE_PRECISION (type1)
7918       ? type0 : type1;
7919   else if (code0 == REAL_TYPE && code1 == INTEGER_TYPE)
7920     cmp_type = type0;
7921   else if (code0 == INTEGER_TYPE && code1 == REAL_TYPE)
7922     cmp_type = type1;
7923
7924   arg0 = fold_convert_loc (loc, cmp_type, arg0);
7925   arg1 = fold_convert_loc (loc, cmp_type, arg1);
7926
7927   if (unordered_code == UNORDERED_EXPR)
7928     {
7929       if (!HONOR_NANS (arg0))
7930         return omit_two_operands_loc (loc, type, integer_zero_node, arg0, arg1);
7931       return fold_build2_loc (loc, UNORDERED_EXPR, type, arg0, arg1);
7932     }
7933
7934   code = HONOR_NANS (arg0) ? unordered_code : ordered_code;
7935   return fold_build1_loc (loc, TRUTH_NOT_EXPR, type,
7936                       fold_build2_loc (loc, code, type, arg0, arg1));
7937 }
7938
7939 /* Fold __builtin_{,s,u}{add,sub,mul}{,l,ll}_overflow, either into normal
7940    arithmetics if it can never overflow, or into internal functions that
7941    return both result of arithmetics and overflowed boolean flag in
7942    a complex integer result, or some other check for overflow.  */
7943
7944 static tree
7945 fold_builtin_arith_overflow (location_t loc, enum built_in_function fcode,
7946                              tree arg0, tree arg1, tree arg2)
7947 {
7948   enum internal_fn ifn = IFN_LAST;
7949   tree type = TREE_TYPE (TREE_TYPE (arg2));
7950   tree mem_arg2 = build_fold_indirect_ref_loc (loc, arg2);
7951   switch (fcode)
7952     {
7953     case BUILT_IN_ADD_OVERFLOW:
7954     case BUILT_IN_SADD_OVERFLOW:
7955     case BUILT_IN_SADDL_OVERFLOW:
7956     case BUILT_IN_SADDLL_OVERFLOW:
7957     case BUILT_IN_UADD_OVERFLOW:
7958     case BUILT_IN_UADDL_OVERFLOW:
7959     case BUILT_IN_UADDLL_OVERFLOW:
7960       ifn = IFN_ADD_OVERFLOW;
7961       break;
7962     case BUILT_IN_SUB_OVERFLOW:
7963     case BUILT_IN_SSUB_OVERFLOW:
7964     case BUILT_IN_SSUBL_OVERFLOW:
7965     case BUILT_IN_SSUBLL_OVERFLOW:
7966     case BUILT_IN_USUB_OVERFLOW:
7967     case BUILT_IN_USUBL_OVERFLOW:
7968     case BUILT_IN_USUBLL_OVERFLOW:
7969       ifn = IFN_SUB_OVERFLOW;
7970       break;
7971     case BUILT_IN_MUL_OVERFLOW:
7972     case BUILT_IN_SMUL_OVERFLOW:
7973     case BUILT_IN_SMULL_OVERFLOW:
7974     case BUILT_IN_SMULLL_OVERFLOW:
7975     case BUILT_IN_UMUL_OVERFLOW:
7976     case BUILT_IN_UMULL_OVERFLOW:
7977     case BUILT_IN_UMULLL_OVERFLOW:
7978       ifn = IFN_MUL_OVERFLOW;
7979       break;
7980     default:
7981       gcc_unreachable ();
7982     }
7983   tree ctype = build_complex_type (type);
7984   tree call = build_call_expr_internal_loc (loc, ifn, ctype,
7985                                             2, arg0, arg1);
7986   tree tgt = save_expr (call);
7987   tree intres = build1_loc (loc, REALPART_EXPR, type, tgt);
7988   tree ovfres = build1_loc (loc, IMAGPART_EXPR, type, tgt);
7989   ovfres = fold_convert_loc (loc, boolean_type_node, ovfres);
7990   tree store
7991     = fold_build2_loc (loc, MODIFY_EXPR, void_type_node, mem_arg2, intres);
7992   return build2_loc (loc, COMPOUND_EXPR, boolean_type_node, store, ovfres);
7993 }
7994
7995 /* Fold a call to built-in function FNDECL with 0 arguments.
7996    This function returns NULL_TREE if no simplification was possible.  */
7997
7998 static tree
7999 fold_builtin_0 (location_t loc, tree fndecl)
8000 {
8001   tree type = TREE_TYPE (TREE_TYPE (fndecl));
8002   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
8003   switch (fcode)
8004     {
8005     CASE_FLT_FN (BUILT_IN_INF):
8006     case BUILT_IN_INFD32:
8007     case BUILT_IN_INFD64:
8008     case BUILT_IN_INFD128:
8009       return fold_builtin_inf (loc, type, true);
8010
8011     CASE_FLT_FN (BUILT_IN_HUGE_VAL):
8012       return fold_builtin_inf (loc, type, false);
8013
8014     case BUILT_IN_CLASSIFY_TYPE:
8015       return fold_builtin_classify_type (NULL_TREE);
8016
8017     default:
8018       break;
8019     }
8020   return NULL_TREE;
8021 }
8022
8023 /* Fold a call to built-in function FNDECL with 1 argument, ARG0.
8024    This function returns NULL_TREE if no simplification was possible.  */
8025
8026 static tree
8027 fold_builtin_1 (location_t loc, tree fndecl, tree arg0)
8028 {
8029   tree type = TREE_TYPE (TREE_TYPE (fndecl));
8030   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
8031
8032   if (TREE_CODE (arg0) == ERROR_MARK)
8033     return NULL_TREE;
8034
8035   if (tree ret = fold_const_call (as_combined_fn (fcode), type, arg0))
8036     return ret;
8037
8038   switch (fcode)
8039     {
8040     case BUILT_IN_CONSTANT_P:
8041       {
8042         tree val = fold_builtin_constant_p (arg0);
8043
8044         /* Gimplification will pull the CALL_EXPR for the builtin out of
8045            an if condition.  When not optimizing, we'll not CSE it back.
8046            To avoid link error types of regressions, return false now.  */
8047         if (!val && !optimize)
8048           val = integer_zero_node;
8049
8050         return val;
8051       }
8052
8053     case BUILT_IN_CLASSIFY_TYPE:
8054       return fold_builtin_classify_type (arg0);
8055
8056     case BUILT_IN_STRLEN:
8057       return fold_builtin_strlen (loc, type, arg0);
8058
8059     CASE_FLT_FN (BUILT_IN_FABS):
8060     case BUILT_IN_FABSD32:
8061     case BUILT_IN_FABSD64:
8062     case BUILT_IN_FABSD128:
8063       return fold_builtin_fabs (loc, arg0, type);
8064
8065     case BUILT_IN_ABS:
8066     case BUILT_IN_LABS:
8067     case BUILT_IN_LLABS:
8068     case BUILT_IN_IMAXABS:
8069       return fold_builtin_abs (loc, arg0, type);
8070
8071     CASE_FLT_FN (BUILT_IN_CONJ):
8072       if (validate_arg (arg0, COMPLEX_TYPE)
8073         && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
8074         return fold_build1_loc (loc, CONJ_EXPR, type, arg0);
8075     break;
8076
8077     CASE_FLT_FN (BUILT_IN_CREAL):
8078       if (validate_arg (arg0, COMPLEX_TYPE)
8079         && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
8080         return non_lvalue_loc (loc, fold_build1_loc (loc, REALPART_EXPR, type, arg0));
8081     break;
8082
8083     CASE_FLT_FN (BUILT_IN_CIMAG):
8084       if (validate_arg (arg0, COMPLEX_TYPE)
8085           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
8086         return non_lvalue_loc (loc, fold_build1_loc (loc, IMAGPART_EXPR, type, arg0));
8087     break;
8088
8089     CASE_FLT_FN (BUILT_IN_CARG):
8090       return fold_builtin_carg (loc, arg0, type);
8091
8092     case BUILT_IN_ISASCII:
8093       return fold_builtin_isascii (loc, arg0);
8094
8095     case BUILT_IN_TOASCII:
8096       return fold_builtin_toascii (loc, arg0);
8097
8098     case BUILT_IN_ISDIGIT:
8099       return fold_builtin_isdigit (loc, arg0);
8100
8101     CASE_FLT_FN (BUILT_IN_FINITE):
8102     case BUILT_IN_FINITED32:
8103     case BUILT_IN_FINITED64:
8104     case BUILT_IN_FINITED128:
8105     case BUILT_IN_ISFINITE:
8106       {
8107         tree ret = fold_builtin_classify (loc, fndecl, arg0, BUILT_IN_ISFINITE);
8108         if (ret)
8109           return ret;
8110         return fold_builtin_interclass_mathfn (loc, fndecl, arg0);
8111       }
8112
8113     CASE_FLT_FN (BUILT_IN_ISINF):
8114     case BUILT_IN_ISINFD32:
8115     case BUILT_IN_ISINFD64:
8116     case BUILT_IN_ISINFD128:
8117       {
8118         tree ret = fold_builtin_classify (loc, fndecl, arg0, BUILT_IN_ISINF);
8119         if (ret)
8120           return ret;
8121         return fold_builtin_interclass_mathfn (loc, fndecl, arg0);
8122       }
8123
8124     case BUILT_IN_ISNORMAL:
8125       return fold_builtin_interclass_mathfn (loc, fndecl, arg0);
8126
8127     case BUILT_IN_ISINF_SIGN:
8128       return fold_builtin_classify (loc, fndecl, arg0, BUILT_IN_ISINF_SIGN);
8129
8130     CASE_FLT_FN (BUILT_IN_ISNAN):
8131     case BUILT_IN_ISNAND32:
8132     case BUILT_IN_ISNAND64:
8133     case BUILT_IN_ISNAND128:
8134       return fold_builtin_classify (loc, fndecl, arg0, BUILT_IN_ISNAN);
8135
8136     case BUILT_IN_FREE:
8137       if (integer_zerop (arg0))
8138         return build_empty_stmt (loc);
8139       break;
8140
8141     default:
8142       break;
8143     }
8144
8145   return NULL_TREE;
8146
8147 }
8148
8149 /* Fold a call to built-in function FNDECL with 2 arguments, ARG0 and ARG1.
8150    This function returns NULL_TREE if no simplification was possible.  */
8151
8152 static tree
8153 fold_builtin_2 (location_t loc, tree fndecl, tree arg0, tree arg1)
8154 {
8155   tree type = TREE_TYPE (TREE_TYPE (fndecl));
8156   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
8157
8158   if (TREE_CODE (arg0) == ERROR_MARK
8159       || TREE_CODE (arg1) == ERROR_MARK)
8160     return NULL_TREE;
8161
8162   if (tree ret = fold_const_call (as_combined_fn (fcode), type, arg0, arg1))
8163     return ret;
8164
8165   switch (fcode)
8166     {
8167     CASE_FLT_FN_REENT (BUILT_IN_GAMMA): /* GAMMA_R */
8168     CASE_FLT_FN_REENT (BUILT_IN_LGAMMA): /* LGAMMA_R */
8169       if (validate_arg (arg0, REAL_TYPE)
8170           && validate_arg (arg1, POINTER_TYPE))
8171         return do_mpfr_lgamma_r (arg0, arg1, type);
8172     break;
8173
8174     CASE_FLT_FN (BUILT_IN_FREXP):
8175       return fold_builtin_frexp (loc, arg0, arg1, type);
8176
8177     CASE_FLT_FN (BUILT_IN_MODF):
8178       return fold_builtin_modf (loc, arg0, arg1, type);
8179
8180     case BUILT_IN_STRSTR:
8181       return fold_builtin_strstr (loc, arg0, arg1, type);
8182
8183     case BUILT_IN_STRSPN:
8184       return fold_builtin_strspn (loc, arg0, arg1);
8185
8186     case BUILT_IN_STRCSPN:
8187       return fold_builtin_strcspn (loc, arg0, arg1);
8188
8189     case BUILT_IN_STRCHR:
8190     case BUILT_IN_INDEX:
8191       return fold_builtin_strchr (loc, arg0, arg1, type);
8192
8193     case BUILT_IN_STRRCHR:
8194     case BUILT_IN_RINDEX:
8195       return fold_builtin_strrchr (loc, arg0, arg1, type);
8196
8197     case BUILT_IN_STRCMP:
8198       return fold_builtin_strcmp (loc, arg0, arg1);
8199
8200     case BUILT_IN_STRPBRK:
8201       return fold_builtin_strpbrk (loc, arg0, arg1, type);
8202
8203     case BUILT_IN_EXPECT:
8204       return fold_builtin_expect (loc, arg0, arg1, NULL_TREE);
8205
8206     case BUILT_IN_ISGREATER:
8207       return fold_builtin_unordered_cmp (loc, fndecl,
8208                                          arg0, arg1, UNLE_EXPR, LE_EXPR);
8209     case BUILT_IN_ISGREATEREQUAL:
8210       return fold_builtin_unordered_cmp (loc, fndecl,
8211                                          arg0, arg1, UNLT_EXPR, LT_EXPR);
8212     case BUILT_IN_ISLESS:
8213       return fold_builtin_unordered_cmp (loc, fndecl,
8214                                          arg0, arg1, UNGE_EXPR, GE_EXPR);
8215     case BUILT_IN_ISLESSEQUAL:
8216       return fold_builtin_unordered_cmp (loc, fndecl,
8217                                          arg0, arg1, UNGT_EXPR, GT_EXPR);
8218     case BUILT_IN_ISLESSGREATER:
8219       return fold_builtin_unordered_cmp (loc, fndecl,
8220                                          arg0, arg1, UNEQ_EXPR, EQ_EXPR);
8221     case BUILT_IN_ISUNORDERED:
8222       return fold_builtin_unordered_cmp (loc, fndecl,
8223                                          arg0, arg1, UNORDERED_EXPR,
8224                                          NOP_EXPR);
8225
8226       /* We do the folding for va_start in the expander.  */
8227     case BUILT_IN_VA_START:
8228       break;
8229
8230     case BUILT_IN_OBJECT_SIZE:
8231       return fold_builtin_object_size (arg0, arg1);
8232
8233     case BUILT_IN_ATOMIC_ALWAYS_LOCK_FREE:
8234       return fold_builtin_atomic_always_lock_free (arg0, arg1);
8235
8236     case BUILT_IN_ATOMIC_IS_LOCK_FREE:
8237       return fold_builtin_atomic_is_lock_free (arg0, arg1);
8238
8239     default:
8240       break;
8241     }
8242   return NULL_TREE;
8243 }
8244
8245 /* Fold a call to built-in function FNDECL with 3 arguments, ARG0, ARG1,
8246    and ARG2.
8247    This function returns NULL_TREE if no simplification was possible.  */
8248
8249 static tree
8250 fold_builtin_3 (location_t loc, tree fndecl,
8251                 tree arg0, tree arg1, tree arg2)
8252 {
8253   tree type = TREE_TYPE (TREE_TYPE (fndecl));
8254   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
8255
8256   if (TREE_CODE (arg0) == ERROR_MARK
8257       || TREE_CODE (arg1) == ERROR_MARK
8258       || TREE_CODE (arg2) == ERROR_MARK)
8259     return NULL_TREE;
8260
8261   if (tree ret = fold_const_call (as_combined_fn (fcode), type,
8262                                   arg0, arg1, arg2))
8263     return ret;
8264
8265   switch (fcode)
8266     {
8267
8268     CASE_FLT_FN (BUILT_IN_SINCOS):
8269       return fold_builtin_sincos (loc, arg0, arg1, arg2);
8270
8271     CASE_FLT_FN (BUILT_IN_FMA):
8272       return fold_builtin_fma (loc, arg0, arg1, arg2, type);
8273
8274     CASE_FLT_FN (BUILT_IN_REMQUO):
8275       if (validate_arg (arg0, REAL_TYPE)
8276           && validate_arg (arg1, REAL_TYPE)
8277           && validate_arg (arg2, POINTER_TYPE))
8278         return do_mpfr_remquo (arg0, arg1, arg2);
8279     break;
8280
8281     case BUILT_IN_STRNCMP:
8282       return fold_builtin_strncmp (loc, arg0, arg1, arg2);
8283
8284     case BUILT_IN_MEMCHR:
8285       return fold_builtin_memchr (loc, arg0, arg1, arg2, type);
8286
8287     case BUILT_IN_BCMP:
8288     case BUILT_IN_MEMCMP:
8289       return fold_builtin_memcmp (loc, arg0, arg1, arg2);;
8290
8291     case BUILT_IN_EXPECT:
8292       return fold_builtin_expect (loc, arg0, arg1, arg2);
8293
8294     case BUILT_IN_ADD_OVERFLOW:
8295     case BUILT_IN_SUB_OVERFLOW:
8296     case BUILT_IN_MUL_OVERFLOW:
8297     case BUILT_IN_SADD_OVERFLOW:
8298     case BUILT_IN_SADDL_OVERFLOW:
8299     case BUILT_IN_SADDLL_OVERFLOW:
8300     case BUILT_IN_SSUB_OVERFLOW:
8301     case BUILT_IN_SSUBL_OVERFLOW:
8302     case BUILT_IN_SSUBLL_OVERFLOW:
8303     case BUILT_IN_SMUL_OVERFLOW:
8304     case BUILT_IN_SMULL_OVERFLOW:
8305     case BUILT_IN_SMULLL_OVERFLOW:
8306     case BUILT_IN_UADD_OVERFLOW:
8307     case BUILT_IN_UADDL_OVERFLOW:
8308     case BUILT_IN_UADDLL_OVERFLOW:
8309     case BUILT_IN_USUB_OVERFLOW:
8310     case BUILT_IN_USUBL_OVERFLOW:
8311     case BUILT_IN_USUBLL_OVERFLOW:
8312     case BUILT_IN_UMUL_OVERFLOW:
8313     case BUILT_IN_UMULL_OVERFLOW:
8314     case BUILT_IN_UMULLL_OVERFLOW:
8315       return fold_builtin_arith_overflow (loc, fcode, arg0, arg1, arg2);
8316
8317     default:
8318       break;
8319     }
8320   return NULL_TREE;
8321 }
8322
8323 /* Fold a call to built-in function FNDECL.  ARGS is an array of NARGS
8324    arguments.  IGNORE is true if the result of the
8325    function call is ignored.  This function returns NULL_TREE if no
8326    simplification was possible.  */
8327
8328 tree
8329 fold_builtin_n (location_t loc, tree fndecl, tree *args, int nargs, bool)
8330 {
8331   tree ret = NULL_TREE;
8332
8333   switch (nargs)
8334     {
8335     case 0:
8336       ret = fold_builtin_0 (loc, fndecl);
8337       break;
8338     case 1:
8339       ret = fold_builtin_1 (loc, fndecl, args[0]);
8340       break;
8341     case 2:
8342       ret = fold_builtin_2 (loc, fndecl, args[0], args[1]);
8343       break;
8344     case 3:
8345       ret = fold_builtin_3 (loc, fndecl, args[0], args[1], args[2]);
8346       break;
8347     default:
8348       ret = fold_builtin_varargs (loc, fndecl, args, nargs);
8349       break;
8350     }
8351   if (ret)
8352     {
8353       ret = build1 (NOP_EXPR, TREE_TYPE (ret), ret);
8354       SET_EXPR_LOCATION (ret, loc);
8355       TREE_NO_WARNING (ret) = 1;
8356       return ret;
8357     }
8358   return NULL_TREE;
8359 }
8360
8361 /* Construct a new CALL_EXPR to FNDECL using the tail of the argument
8362    list ARGS along with N new arguments in NEWARGS.  SKIP is the number
8363    of arguments in ARGS to be omitted.  OLDNARGS is the number of
8364    elements in ARGS.  */
8365
8366 static tree
8367 rewrite_call_expr_valist (location_t loc, int oldnargs, tree *args,
8368                           int skip, tree fndecl, int n, va_list newargs)
8369 {
8370   int nargs = oldnargs - skip + n;
8371   tree *buffer;
8372
8373   if (n > 0)
8374     {
8375       int i, j;
8376
8377       buffer = XALLOCAVEC (tree, nargs);
8378       for (i = 0; i < n; i++)
8379         buffer[i] = va_arg (newargs, tree);
8380       for (j = skip; j < oldnargs; j++, i++)
8381         buffer[i] = args[j];
8382     }
8383   else
8384     buffer = args + skip;
8385
8386   return build_call_expr_loc_array (loc, fndecl, nargs, buffer);
8387 }
8388
8389 /* Return true if FNDECL shouldn't be folded right now.
8390    If a built-in function has an inline attribute always_inline
8391    wrapper, defer folding it after always_inline functions have
8392    been inlined, otherwise e.g. -D_FORTIFY_SOURCE checking
8393    might not be performed.  */
8394
8395 bool
8396 avoid_folding_inline_builtin (tree fndecl)
8397 {
8398   return (DECL_DECLARED_INLINE_P (fndecl)
8399           && DECL_DISREGARD_INLINE_LIMITS (fndecl)
8400           && cfun
8401           && !cfun->always_inline_functions_inlined
8402           && lookup_attribute ("always_inline", DECL_ATTRIBUTES (fndecl)));
8403 }
8404
8405 /* A wrapper function for builtin folding that prevents warnings for
8406    "statement without effect" and the like, caused by removing the
8407    call node earlier than the warning is generated.  */
8408
8409 tree
8410 fold_call_expr (location_t loc, tree exp, bool ignore)
8411 {
8412   tree ret = NULL_TREE;
8413   tree fndecl = get_callee_fndecl (exp);
8414   if (fndecl
8415       && TREE_CODE (fndecl) == FUNCTION_DECL
8416       && DECL_BUILT_IN (fndecl)
8417       /* If CALL_EXPR_VA_ARG_PACK is set, the arguments aren't finalized
8418          yet.  Defer folding until we see all the arguments
8419          (after inlining).  */
8420       && !CALL_EXPR_VA_ARG_PACK (exp))
8421     {
8422       int nargs = call_expr_nargs (exp);
8423
8424       /* Before gimplification CALL_EXPR_VA_ARG_PACK is not set, but
8425          instead last argument is __builtin_va_arg_pack ().  Defer folding
8426          even in that case, until arguments are finalized.  */
8427       if (nargs && TREE_CODE (CALL_EXPR_ARG (exp, nargs - 1)) == CALL_EXPR)
8428         {
8429           tree fndecl2 = get_callee_fndecl (CALL_EXPR_ARG (exp, nargs - 1));
8430           if (fndecl2
8431               && TREE_CODE (fndecl2) == FUNCTION_DECL
8432               && DECL_BUILT_IN_CLASS (fndecl2) == BUILT_IN_NORMAL
8433               && DECL_FUNCTION_CODE (fndecl2) == BUILT_IN_VA_ARG_PACK)
8434             return NULL_TREE;
8435         }
8436
8437       if (avoid_folding_inline_builtin (fndecl))
8438         return NULL_TREE;
8439
8440       if (DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_MD)
8441         return targetm.fold_builtin (fndecl, call_expr_nargs (exp),
8442                                      CALL_EXPR_ARGP (exp), ignore);
8443       else
8444         {
8445           tree *args = CALL_EXPR_ARGP (exp);
8446           ret = fold_builtin_n (loc, fndecl, args, nargs, ignore);
8447           if (ret)
8448             return ret;
8449         }
8450     }
8451   return NULL_TREE;
8452 }
8453
8454 /* Fold a CALL_EXPR with type TYPE with FN as the function expression.
8455    N arguments are passed in the array ARGARRAY.  Return a folded
8456    expression or NULL_TREE if no simplification was possible.  */
8457
8458 tree
8459 fold_builtin_call_array (location_t loc, tree,
8460                          tree fn,
8461                          int n,
8462                          tree *argarray)
8463 {
8464   if (TREE_CODE (fn) != ADDR_EXPR)
8465     return NULL_TREE;
8466
8467   tree fndecl = TREE_OPERAND (fn, 0);
8468   if (TREE_CODE (fndecl) == FUNCTION_DECL
8469       && DECL_BUILT_IN (fndecl))
8470     {
8471       /* If last argument is __builtin_va_arg_pack (), arguments to this
8472          function are not finalized yet.  Defer folding until they are.  */
8473       if (n && TREE_CODE (argarray[n - 1]) == CALL_EXPR)
8474         {
8475           tree fndecl2 = get_callee_fndecl (argarray[n - 1]);
8476           if (fndecl2
8477               && TREE_CODE (fndecl2) == FUNCTION_DECL
8478               && DECL_BUILT_IN_CLASS (fndecl2) == BUILT_IN_NORMAL
8479               && DECL_FUNCTION_CODE (fndecl2) == BUILT_IN_VA_ARG_PACK)
8480             return NULL_TREE;
8481         }
8482       if (avoid_folding_inline_builtin (fndecl))
8483         return NULL_TREE;
8484       if (DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_MD)
8485         return targetm.fold_builtin (fndecl, n, argarray, false);
8486       else
8487         return fold_builtin_n (loc, fndecl, argarray, n, false);
8488     }
8489
8490   return NULL_TREE;
8491 }
8492
8493 /* Construct a new CALL_EXPR using the tail of the argument list of EXP
8494    along with N new arguments specified as the "..." parameters.  SKIP
8495    is the number of arguments in EXP to be omitted.  This function is used
8496    to do varargs-to-varargs transformations.  */
8497
8498 static tree
8499 rewrite_call_expr (location_t loc, tree exp, int skip, tree fndecl, int n, ...)
8500 {
8501   va_list ap;
8502   tree t;
8503
8504   va_start (ap, n);
8505   t = rewrite_call_expr_valist (loc, call_expr_nargs (exp),
8506                                 CALL_EXPR_ARGP (exp), skip, fndecl, n, ap);
8507   va_end (ap);
8508
8509   return t;
8510 }
8511
8512 /* Validate a single argument ARG against a tree code CODE representing
8513    a type.  */
8514
8515 static bool
8516 validate_arg (const_tree arg, enum tree_code code)
8517 {
8518   if (!arg)
8519     return false;
8520   else if (code == POINTER_TYPE)
8521     return POINTER_TYPE_P (TREE_TYPE (arg));
8522   else if (code == INTEGER_TYPE)
8523     return INTEGRAL_TYPE_P (TREE_TYPE (arg));
8524   return code == TREE_CODE (TREE_TYPE (arg));
8525 }
8526
8527 /* This function validates the types of a function call argument list
8528    against a specified list of tree_codes.  If the last specifier is a 0,
8529    that represents an ellipses, otherwise the last specifier must be a
8530    VOID_TYPE.
8531
8532    This is the GIMPLE version of validate_arglist.  Eventually we want to
8533    completely convert builtins.c to work from GIMPLEs and the tree based
8534    validate_arglist will then be removed.  */
8535
8536 bool
8537 validate_gimple_arglist (const gcall *call, ...)
8538 {
8539   enum tree_code code;
8540   bool res = 0;
8541   va_list ap;
8542   const_tree arg;
8543   size_t i;
8544
8545   va_start (ap, call);
8546   i = 0;
8547
8548   do
8549     {
8550       code = (enum tree_code) va_arg (ap, int);
8551       switch (code)
8552         {
8553         case 0:
8554           /* This signifies an ellipses, any further arguments are all ok.  */
8555           res = true;
8556           goto end;
8557         case VOID_TYPE:
8558           /* This signifies an endlink, if no arguments remain, return
8559              true, otherwise return false.  */
8560           res = (i == gimple_call_num_args (call));
8561           goto end;
8562         default:
8563           /* If no parameters remain or the parameter's code does not
8564              match the specified code, return false.  Otherwise continue
8565              checking any remaining arguments.  */
8566           arg = gimple_call_arg (call, i++);
8567           if (!validate_arg (arg, code))
8568             goto end;
8569           break;
8570         }
8571     }
8572   while (1);
8573
8574   /* We need gotos here since we can only have one VA_CLOSE in a
8575      function.  */
8576  end: ;
8577   va_end (ap);
8578
8579   return res;
8580 }
8581
8582 /* Default target-specific builtin expander that does nothing.  */
8583
8584 rtx
8585 default_expand_builtin (tree exp ATTRIBUTE_UNUSED,
8586                         rtx target ATTRIBUTE_UNUSED,
8587                         rtx subtarget ATTRIBUTE_UNUSED,
8588                         machine_mode mode ATTRIBUTE_UNUSED,
8589                         int ignore ATTRIBUTE_UNUSED)
8590 {
8591   return NULL_RTX;
8592 }
8593
8594 /* Returns true is EXP represents data that would potentially reside
8595    in a readonly section.  */
8596
8597 bool
8598 readonly_data_expr (tree exp)
8599 {
8600   STRIP_NOPS (exp);
8601
8602   if (TREE_CODE (exp) != ADDR_EXPR)
8603     return false;
8604
8605   exp = get_base_address (TREE_OPERAND (exp, 0));
8606   if (!exp)
8607     return false;
8608
8609   /* Make sure we call decl_readonly_section only for trees it
8610      can handle (since it returns true for everything it doesn't
8611      understand).  */
8612   if (TREE_CODE (exp) == STRING_CST
8613       || TREE_CODE (exp) == CONSTRUCTOR
8614       || (TREE_CODE (exp) == VAR_DECL && TREE_STATIC (exp)))
8615     return decl_readonly_section (exp, 0);
8616   else
8617     return false;
8618 }
8619
8620 /* Simplify a call to the strstr builtin.  S1 and S2 are the arguments
8621    to the call, and TYPE is its return type.
8622
8623    Return NULL_TREE if no simplification was possible, otherwise return the
8624    simplified form of the call as a tree.
8625
8626    The simplified form may be a constant or other expression which
8627    computes the same value, but in a more efficient manner (including
8628    calls to other builtin functions).
8629
8630    The call may contain arguments which need to be evaluated, but
8631    which are not useful to determine the result of the call.  In
8632    this case we return a chain of COMPOUND_EXPRs.  The LHS of each
8633    COMPOUND_EXPR will be an argument which must be evaluated.
8634    COMPOUND_EXPRs are chained through their RHS.  The RHS of the last
8635    COMPOUND_EXPR in the chain will contain the tree for the simplified
8636    form of the builtin function call.  */
8637
8638 static tree
8639 fold_builtin_strstr (location_t loc, tree s1, tree s2, tree type)
8640 {
8641   if (!validate_arg (s1, POINTER_TYPE)
8642       || !validate_arg (s2, POINTER_TYPE))
8643     return NULL_TREE;
8644   else
8645     {
8646       tree fn;
8647       const char *p1, *p2;
8648
8649       p2 = c_getstr (s2);
8650       if (p2 == NULL)
8651         return NULL_TREE;
8652
8653       p1 = c_getstr (s1);
8654       if (p1 != NULL)
8655         {
8656           const char *r = strstr (p1, p2);
8657           tree tem;
8658
8659           if (r == NULL)
8660             return build_int_cst (TREE_TYPE (s1), 0);
8661
8662           /* Return an offset into the constant string argument.  */
8663           tem = fold_build_pointer_plus_hwi_loc (loc, s1, r - p1);
8664           return fold_convert_loc (loc, type, tem);
8665         }
8666
8667       /* The argument is const char *, and the result is char *, so we need
8668          a type conversion here to avoid a warning.  */
8669       if (p2[0] == '\0')
8670         return fold_convert_loc (loc, type, s1);
8671
8672       if (p2[1] != '\0')
8673         return NULL_TREE;
8674
8675       fn = builtin_decl_implicit (BUILT_IN_STRCHR);
8676       if (!fn)
8677         return NULL_TREE;
8678
8679       /* New argument list transforming strstr(s1, s2) to
8680          strchr(s1, s2[0]).  */
8681       return build_call_expr_loc (loc, fn, 2, s1,
8682                                   build_int_cst (integer_type_node, p2[0]));
8683     }
8684 }
8685
8686 /* Simplify a call to the strchr builtin.  S1 and S2 are the arguments to
8687    the call, and TYPE is its return type.
8688
8689    Return NULL_TREE if no simplification was possible, otherwise return the
8690    simplified form of the call as a tree.
8691
8692    The simplified form may be a constant or other expression which
8693    computes the same value, but in a more efficient manner (including
8694    calls to other builtin functions).
8695
8696    The call may contain arguments which need to be evaluated, but
8697    which are not useful to determine the result of the call.  In
8698    this case we return a chain of COMPOUND_EXPRs.  The LHS of each
8699    COMPOUND_EXPR will be an argument which must be evaluated.
8700    COMPOUND_EXPRs are chained through their RHS.  The RHS of the last
8701    COMPOUND_EXPR in the chain will contain the tree for the simplified
8702    form of the builtin function call.  */
8703
8704 static tree
8705 fold_builtin_strchr (location_t loc, tree s1, tree s2, tree type)
8706 {
8707   if (!validate_arg (s1, POINTER_TYPE)
8708       || !validate_arg (s2, INTEGER_TYPE))
8709     return NULL_TREE;
8710   else
8711     {
8712       const char *p1;
8713
8714       if (TREE_CODE (s2) != INTEGER_CST)
8715         return NULL_TREE;
8716
8717       p1 = c_getstr (s1);
8718       if (p1 != NULL)
8719         {
8720           char c;
8721           const char *r;
8722           tree tem;
8723
8724           if (target_char_cast (s2, &c))
8725             return NULL_TREE;
8726
8727           r = strchr (p1, c);
8728
8729           if (r == NULL)
8730             return build_int_cst (TREE_TYPE (s1), 0);
8731
8732           /* Return an offset into the constant string argument.  */
8733           tem = fold_build_pointer_plus_hwi_loc (loc, s1, r - p1);
8734           return fold_convert_loc (loc, type, tem);
8735         }
8736       return NULL_TREE;
8737     }
8738 }
8739
8740 /* Simplify a call to the strrchr builtin.  S1 and S2 are the arguments to
8741    the call, and TYPE is its return type.
8742
8743    Return NULL_TREE if no simplification was possible, otherwise return the
8744    simplified form of the call as a tree.
8745
8746    The simplified form may be a constant or other expression which
8747    computes the same value, but in a more efficient manner (including
8748    calls to other builtin functions).
8749
8750    The call may contain arguments which need to be evaluated, but
8751    which are not useful to determine the result of the call.  In
8752    this case we return a chain of COMPOUND_EXPRs.  The LHS of each
8753    COMPOUND_EXPR will be an argument which must be evaluated.
8754    COMPOUND_EXPRs are chained through their RHS.  The RHS of the last
8755    COMPOUND_EXPR in the chain will contain the tree for the simplified
8756    form of the builtin function call.  */
8757
8758 static tree
8759 fold_builtin_strrchr (location_t loc, tree s1, tree s2, tree type)
8760 {
8761   if (!validate_arg (s1, POINTER_TYPE)
8762       || !validate_arg (s2, INTEGER_TYPE))
8763     return NULL_TREE;
8764   else
8765     {
8766       tree fn;
8767       const char *p1;
8768
8769       if (TREE_CODE (s2) != INTEGER_CST)
8770         return NULL_TREE;
8771
8772       p1 = c_getstr (s1);
8773       if (p1 != NULL)
8774         {
8775           char c;
8776           const char *r;
8777           tree tem;
8778
8779           if (target_char_cast (s2, &c))
8780             return NULL_TREE;
8781
8782           r = strrchr (p1, c);
8783
8784           if (r == NULL)
8785             return build_int_cst (TREE_TYPE (s1), 0);
8786
8787           /* Return an offset into the constant string argument.  */
8788           tem = fold_build_pointer_plus_hwi_loc (loc, s1, r - p1);
8789           return fold_convert_loc (loc, type, tem);
8790         }
8791
8792       if (! integer_zerop (s2))
8793         return NULL_TREE;
8794
8795       fn = builtin_decl_implicit (BUILT_IN_STRCHR);
8796       if (!fn)
8797         return NULL_TREE;
8798
8799       /* Transform strrchr(s1, '\0') to strchr(s1, '\0').  */
8800       return build_call_expr_loc (loc, fn, 2, s1, s2);
8801     }
8802 }
8803
8804 /* Simplify a call to the strpbrk builtin.  S1 and S2 are the arguments
8805    to the call, and TYPE is its return type.
8806
8807    Return NULL_TREE if no simplification was possible, otherwise return the
8808    simplified form of the call as a tree.
8809
8810    The simplified form may be a constant or other expression which
8811    computes the same value, but in a more efficient manner (including
8812    calls to other builtin functions).
8813
8814    The call may contain arguments which need to be evaluated, but
8815    which are not useful to determine the result of the call.  In
8816    this case we return a chain of COMPOUND_EXPRs.  The LHS of each
8817    COMPOUND_EXPR will be an argument which must be evaluated.
8818    COMPOUND_EXPRs are chained through their RHS.  The RHS of the last
8819    COMPOUND_EXPR in the chain will contain the tree for the simplified
8820    form of the builtin function call.  */
8821
8822 static tree
8823 fold_builtin_strpbrk (location_t loc, tree s1, tree s2, tree type)
8824 {
8825   if (!validate_arg (s1, POINTER_TYPE)
8826       || !validate_arg (s2, POINTER_TYPE))
8827     return NULL_TREE;
8828   else
8829     {
8830       tree fn;
8831       const char *p1, *p2;
8832
8833       p2 = c_getstr (s2);
8834       if (p2 == NULL)
8835         return NULL_TREE;
8836
8837       p1 = c_getstr (s1);
8838       if (p1 != NULL)
8839         {
8840           const char *r = strpbrk (p1, p2);
8841           tree tem;
8842
8843           if (r == NULL)
8844             return build_int_cst (TREE_TYPE (s1), 0);
8845
8846           /* Return an offset into the constant string argument.  */
8847           tem = fold_build_pointer_plus_hwi_loc (loc, s1, r - p1);
8848           return fold_convert_loc (loc, type, tem);
8849         }
8850
8851       if (p2[0] == '\0')
8852         /* strpbrk(x, "") == NULL.
8853            Evaluate and ignore s1 in case it had side-effects.  */
8854         return omit_one_operand_loc (loc, TREE_TYPE (s1), integer_zero_node, s1);
8855
8856       if (p2[1] != '\0')
8857         return NULL_TREE;  /* Really call strpbrk.  */
8858
8859       fn = builtin_decl_implicit (BUILT_IN_STRCHR);
8860       if (!fn)
8861         return NULL_TREE;
8862
8863       /* New argument list transforming strpbrk(s1, s2) to
8864          strchr(s1, s2[0]).  */
8865       return build_call_expr_loc (loc, fn, 2, s1,
8866                                   build_int_cst (integer_type_node, p2[0]));
8867     }
8868 }
8869
8870 /* Simplify a call to the strspn builtin.  S1 and S2 are the arguments
8871    to the call.
8872
8873    Return NULL_TREE if no simplification was possible, otherwise return the
8874    simplified form of the call as a tree.
8875
8876    The simplified form may be a constant or other expression which
8877    computes the same value, but in a more efficient manner (including
8878    calls to other builtin functions).
8879
8880    The call may contain arguments which need to be evaluated, but
8881    which are not useful to determine the result of the call.  In
8882    this case we return a chain of COMPOUND_EXPRs.  The LHS of each
8883    COMPOUND_EXPR will be an argument which must be evaluated.
8884    COMPOUND_EXPRs are chained through their RHS.  The RHS of the last
8885    COMPOUND_EXPR in the chain will contain the tree for the simplified
8886    form of the builtin function call.  */
8887
8888 static tree
8889 fold_builtin_strspn (location_t loc, tree s1, tree s2)
8890 {
8891   if (!validate_arg (s1, POINTER_TYPE)
8892       || !validate_arg (s2, POINTER_TYPE))
8893     return NULL_TREE;
8894   else
8895     {
8896       const char *p1 = c_getstr (s1), *p2 = c_getstr (s2);
8897
8898       /* If either argument is "", return NULL_TREE.  */
8899       if ((p1 && *p1 == '\0') || (p2 && *p2 == '\0'))
8900         /* Evaluate and ignore both arguments in case either one has
8901            side-effects.  */
8902         return omit_two_operands_loc (loc, size_type_node, size_zero_node,
8903                                   s1, s2);
8904       return NULL_TREE;
8905     }
8906 }
8907
8908 /* Simplify a call to the strcspn builtin.  S1 and S2 are the arguments
8909    to the call.
8910
8911    Return NULL_TREE if no simplification was possible, otherwise return the
8912    simplified form of the call as a tree.
8913
8914    The simplified form may be a constant or other expression which
8915    computes the same value, but in a more efficient manner (including
8916    calls to other builtin functions).
8917
8918    The call may contain arguments which need to be evaluated, but
8919    which are not useful to determine the result of the call.  In
8920    this case we return a chain of COMPOUND_EXPRs.  The LHS of each
8921    COMPOUND_EXPR will be an argument which must be evaluated.
8922    COMPOUND_EXPRs are chained through their RHS.  The RHS of the last
8923    COMPOUND_EXPR in the chain will contain the tree for the simplified
8924    form of the builtin function call.  */
8925
8926 static tree
8927 fold_builtin_strcspn (location_t loc, tree s1, tree s2)
8928 {
8929   if (!validate_arg (s1, POINTER_TYPE)
8930       || !validate_arg (s2, POINTER_TYPE))
8931     return NULL_TREE;
8932   else
8933     {
8934       /* If the first argument is "", return NULL_TREE.  */
8935       const char *p1 = c_getstr (s1);
8936       if (p1 && *p1 == '\0')
8937         {
8938           /* Evaluate and ignore argument s2 in case it has
8939              side-effects.  */
8940           return omit_one_operand_loc (loc, size_type_node,
8941                                    size_zero_node, s2);
8942         }
8943
8944       /* If the second argument is "", return __builtin_strlen(s1).  */
8945       const char *p2 = c_getstr (s2);
8946       if (p2 && *p2 == '\0')
8947         {
8948           tree fn = builtin_decl_implicit (BUILT_IN_STRLEN);
8949
8950           /* If the replacement _DECL isn't initialized, don't do the
8951              transformation.  */
8952           if (!fn)
8953             return NULL_TREE;
8954
8955           return build_call_expr_loc (loc, fn, 1, s1);
8956         }
8957       return NULL_TREE;
8958     }
8959 }
8960
8961 /* Fold the next_arg or va_start call EXP. Returns true if there was an error
8962    produced.  False otherwise.  This is done so that we don't output the error
8963    or warning twice or three times.  */
8964
8965 bool
8966 fold_builtin_next_arg (tree exp, bool va_start_p)
8967 {
8968   tree fntype = TREE_TYPE (current_function_decl);
8969   int nargs = call_expr_nargs (exp);
8970   tree arg;
8971   /* There is good chance the current input_location points inside the
8972      definition of the va_start macro (perhaps on the token for
8973      builtin) in a system header, so warnings will not be emitted.
8974      Use the location in real source code.  */
8975   source_location current_location =
8976     linemap_unwind_to_first_non_reserved_loc (line_table, input_location,
8977                                               NULL);
8978
8979   if (!stdarg_p (fntype))
8980     {
8981       error ("%<va_start%> used in function with fixed args");
8982       return true;
8983     }
8984
8985   if (va_start_p)
8986     {
8987       if (va_start_p && (nargs != 2))
8988         {
8989           error ("wrong number of arguments to function %<va_start%>");
8990           return true;
8991         }
8992       arg = CALL_EXPR_ARG (exp, 1);
8993     }
8994   /* We use __builtin_va_start (ap, 0, 0) or __builtin_next_arg (0, 0)
8995      when we checked the arguments and if needed issued a warning.  */
8996   else
8997     {
8998       if (nargs == 0)
8999         {
9000           /* Evidently an out of date version of <stdarg.h>; can't validate
9001              va_start's second argument, but can still work as intended.  */
9002           warning_at (current_location,
9003                       OPT_Wvarargs,
9004                    "%<__builtin_next_arg%> called without an argument");
9005           return true;
9006         }
9007       else if (nargs > 1)
9008         {
9009           error ("wrong number of arguments to function %<__builtin_next_arg%>");
9010           return true;
9011         }
9012       arg = CALL_EXPR_ARG (exp, 0);
9013     }
9014
9015   if (TREE_CODE (arg) == SSA_NAME)
9016     arg = SSA_NAME_VAR (arg);
9017
9018   /* We destructively modify the call to be __builtin_va_start (ap, 0)
9019      or __builtin_next_arg (0) the first time we see it, after checking
9020      the arguments and if needed issuing a warning.  */
9021   if (!integer_zerop (arg))
9022     {
9023       tree last_parm = tree_last (DECL_ARGUMENTS (current_function_decl));
9024
9025       /* Strip off all nops for the sake of the comparison.  This
9026          is not quite the same as STRIP_NOPS.  It does more.
9027          We must also strip off INDIRECT_EXPR for C++ reference
9028          parameters.  */
9029       while (CONVERT_EXPR_P (arg)
9030              || TREE_CODE (arg) == INDIRECT_REF)
9031         arg = TREE_OPERAND (arg, 0);
9032       if (arg != last_parm)
9033         {
9034           /* FIXME: Sometimes with the tree optimizers we can get the
9035              not the last argument even though the user used the last
9036              argument.  We just warn and set the arg to be the last
9037              argument so that we will get wrong-code because of
9038              it.  */
9039           warning_at (current_location,
9040                       OPT_Wvarargs,
9041                       "second parameter of %<va_start%> not last named argument");
9042         }
9043
9044       /* Undefined by C99 7.15.1.4p4 (va_start):
9045          "If the parameter parmN is declared with the register storage
9046          class, with a function or array type, or with a type that is
9047          not compatible with the type that results after application of
9048          the default argument promotions, the behavior is undefined."
9049       */
9050       else if (DECL_REGISTER (arg))
9051         {
9052           warning_at (current_location,
9053                       OPT_Wvarargs,
9054                       "undefined behavior when second parameter of "
9055                       "%<va_start%> is declared with %<register%> storage");
9056         }
9057
9058       /* We want to verify the second parameter just once before the tree
9059          optimizers are run and then avoid keeping it in the tree,
9060          as otherwise we could warn even for correct code like:
9061          void foo (int i, ...)
9062          { va_list ap; i++; va_start (ap, i); va_end (ap); }  */
9063       if (va_start_p)
9064         CALL_EXPR_ARG (exp, 1) = integer_zero_node;
9065       else
9066         CALL_EXPR_ARG (exp, 0) = integer_zero_node;
9067     }
9068   return false;
9069 }
9070
9071
9072 /* Expand a call EXP to __builtin_object_size.  */
9073
9074 static rtx
9075 expand_builtin_object_size (tree exp)
9076 {
9077   tree ost;
9078   int object_size_type;
9079   tree fndecl = get_callee_fndecl (exp);
9080
9081   if (!validate_arglist (exp, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
9082     {
9083       error ("%Kfirst argument of %D must be a pointer, second integer constant",
9084              exp, fndecl);
9085       expand_builtin_trap ();
9086       return const0_rtx;
9087     }
9088
9089   ost = CALL_EXPR_ARG (exp, 1);
9090   STRIP_NOPS (ost);
9091
9092   if (TREE_CODE (ost) != INTEGER_CST
9093       || tree_int_cst_sgn (ost) < 0
9094       || compare_tree_int (ost, 3) > 0)
9095     {
9096       error ("%Klast argument of %D is not integer constant between 0 and 3",
9097              exp, fndecl);
9098       expand_builtin_trap ();
9099       return const0_rtx;
9100     }
9101
9102   object_size_type = tree_to_shwi (ost);
9103
9104   return object_size_type < 2 ? constm1_rtx : const0_rtx;
9105 }
9106
9107 /* Expand EXP, a call to the __mem{cpy,pcpy,move,set}_chk builtin.
9108    FCODE is the BUILT_IN_* to use.
9109    Return NULL_RTX if we failed; the caller should emit a normal call,
9110    otherwise try to get the result in TARGET, if convenient (and in
9111    mode MODE if that's convenient).  */
9112
9113 static rtx
9114 expand_builtin_memory_chk (tree exp, rtx target, machine_mode mode,
9115                            enum built_in_function fcode)
9116 {
9117   tree dest, src, len, size;
9118
9119   if (!validate_arglist (exp,
9120                          POINTER_TYPE,
9121                          fcode == BUILT_IN_MEMSET_CHK
9122                          ? INTEGER_TYPE : POINTER_TYPE,
9123                          INTEGER_TYPE, INTEGER_TYPE, VOID_TYPE))
9124     return NULL_RTX;
9125
9126   dest = CALL_EXPR_ARG (exp, 0);
9127   src = CALL_EXPR_ARG (exp, 1);
9128   len = CALL_EXPR_ARG (exp, 2);
9129   size = CALL_EXPR_ARG (exp, 3);
9130
9131   if (! tree_fits_uhwi_p (size))
9132     return NULL_RTX;
9133
9134   if (tree_fits_uhwi_p (len) || integer_all_onesp (size))
9135     {
9136       tree fn;
9137
9138       if (! integer_all_onesp (size) && tree_int_cst_lt (size, len))
9139         {
9140           warning_at (tree_nonartificial_location (exp),
9141                       0, "%Kcall to %D will always overflow destination buffer",
9142                       exp, get_callee_fndecl (exp));
9143           return NULL_RTX;
9144         }
9145
9146       fn = NULL_TREE;
9147       /* If __builtin_mem{cpy,pcpy,move,set}_chk is used, assume
9148          mem{cpy,pcpy,move,set} is available.  */
9149       switch (fcode)
9150         {
9151         case BUILT_IN_MEMCPY_CHK:
9152           fn = builtin_decl_explicit (BUILT_IN_MEMCPY);
9153           break;
9154         case BUILT_IN_MEMPCPY_CHK:
9155           fn = builtin_decl_explicit (BUILT_IN_MEMPCPY);
9156           break;
9157         case BUILT_IN_MEMMOVE_CHK:
9158           fn = builtin_decl_explicit (BUILT_IN_MEMMOVE);
9159           break;
9160         case BUILT_IN_MEMSET_CHK:
9161           fn = builtin_decl_explicit (BUILT_IN_MEMSET);
9162           break;
9163         default:
9164           break;
9165         }
9166
9167       if (! fn)
9168         return NULL_RTX;
9169
9170       fn = build_call_nofold_loc (EXPR_LOCATION (exp), fn, 3, dest, src, len);
9171       gcc_assert (TREE_CODE (fn) == CALL_EXPR);
9172       CALL_EXPR_TAILCALL (fn) = CALL_EXPR_TAILCALL (exp);
9173       return expand_expr (fn, target, mode, EXPAND_NORMAL);
9174     }
9175   else if (fcode == BUILT_IN_MEMSET_CHK)
9176     return NULL_RTX;
9177   else
9178     {
9179       unsigned int dest_align = get_pointer_alignment (dest);
9180
9181       /* If DEST is not a pointer type, call the normal function.  */
9182       if (dest_align == 0)
9183         return NULL_RTX;
9184
9185       /* If SRC and DEST are the same (and not volatile), do nothing.  */
9186       if (operand_equal_p (src, dest, 0))
9187         {
9188           tree expr;
9189
9190           if (fcode != BUILT_IN_MEMPCPY_CHK)
9191             {
9192               /* Evaluate and ignore LEN in case it has side-effects.  */
9193               expand_expr (len, const0_rtx, VOIDmode, EXPAND_NORMAL);
9194               return expand_expr (dest, target, mode, EXPAND_NORMAL);
9195             }
9196
9197           expr = fold_build_pointer_plus (dest, len);
9198           return expand_expr (expr, target, mode, EXPAND_NORMAL);
9199         }
9200
9201       /* __memmove_chk special case.  */
9202       if (fcode == BUILT_IN_MEMMOVE_CHK)
9203         {
9204           unsigned int src_align = get_pointer_alignment (src);
9205
9206           if (src_align == 0)
9207             return NULL_RTX;
9208
9209           /* If src is categorized for a readonly section we can use
9210              normal __memcpy_chk.  */
9211           if (readonly_data_expr (src))
9212             {
9213               tree fn = builtin_decl_explicit (BUILT_IN_MEMCPY_CHK);
9214               if (!fn)
9215                 return NULL_RTX;
9216               fn = build_call_nofold_loc (EXPR_LOCATION (exp), fn, 4,
9217                                           dest, src, len, size);
9218               gcc_assert (TREE_CODE (fn) == CALL_EXPR);
9219               CALL_EXPR_TAILCALL (fn) = CALL_EXPR_TAILCALL (exp);
9220               return expand_expr (fn, target, mode, EXPAND_NORMAL);
9221             }
9222         }
9223       return NULL_RTX;
9224     }
9225 }
9226
9227 /* Emit warning if a buffer overflow is detected at compile time.  */
9228
9229 static void
9230 maybe_emit_chk_warning (tree exp, enum built_in_function fcode)
9231 {
9232   int is_strlen = 0;
9233   tree len, size;
9234   location_t loc = tree_nonartificial_location (exp);
9235
9236   switch (fcode)
9237     {
9238     case BUILT_IN_STRCPY_CHK:
9239     case BUILT_IN_STPCPY_CHK:
9240     /* For __strcat_chk the warning will be emitted only if overflowing
9241        by at least strlen (dest) + 1 bytes.  */
9242     case BUILT_IN_STRCAT_CHK:
9243       len = CALL_EXPR_ARG (exp, 1);
9244       size = CALL_EXPR_ARG (exp, 2);
9245       is_strlen = 1;
9246       break;
9247     case BUILT_IN_STRNCAT_CHK:
9248     case BUILT_IN_STRNCPY_CHK:
9249     case BUILT_IN_STPNCPY_CHK:
9250       len = CALL_EXPR_ARG (exp, 2);
9251       size = CALL_EXPR_ARG (exp, 3);
9252       break;
9253     case BUILT_IN_SNPRINTF_CHK:
9254     case BUILT_IN_VSNPRINTF_CHK:
9255       len = CALL_EXPR_ARG (exp, 1);
9256       size = CALL_EXPR_ARG (exp, 3);
9257       break;
9258     default:
9259       gcc_unreachable ();
9260     }
9261
9262   if (!len || !size)
9263     return;
9264
9265   if (! tree_fits_uhwi_p (size) || integer_all_onesp (size))
9266     return;
9267
9268   if (is_strlen)
9269     {
9270       len = c_strlen (len, 1);
9271       if (! len || ! tree_fits_uhwi_p (len) || tree_int_cst_lt (len, size))
9272         return;
9273     }
9274   else if (fcode == BUILT_IN_STRNCAT_CHK)
9275     {
9276       tree src = CALL_EXPR_ARG (exp, 1);
9277       if (! src || ! tree_fits_uhwi_p (len) || tree_int_cst_lt (len, size))
9278         return;
9279       src = c_strlen (src, 1);
9280       if (! src || ! tree_fits_uhwi_p (src))
9281         {
9282           warning_at (loc, 0, "%Kcall to %D might overflow destination buffer",
9283                       exp, get_callee_fndecl (exp));
9284           return;
9285         }
9286       else if (tree_int_cst_lt (src, size))
9287         return;
9288     }
9289   else if (! tree_fits_uhwi_p (len) || ! tree_int_cst_lt (size, len))
9290     return;
9291
9292   warning_at (loc, 0, "%Kcall to %D will always overflow destination buffer",
9293               exp, get_callee_fndecl (exp));
9294 }
9295
9296 /* Emit warning if a buffer overflow is detected at compile time
9297    in __sprintf_chk/__vsprintf_chk calls.  */
9298
9299 static void
9300 maybe_emit_sprintf_chk_warning (tree exp, enum built_in_function fcode)
9301 {
9302   tree size, len, fmt;
9303   const char *fmt_str;
9304   int nargs = call_expr_nargs (exp);
9305
9306   /* Verify the required arguments in the original call.  */
9307
9308   if (nargs < 4)
9309     return;
9310   size = CALL_EXPR_ARG (exp, 2);
9311   fmt = CALL_EXPR_ARG (exp, 3);
9312
9313   if (! tree_fits_uhwi_p (size) || integer_all_onesp (size))
9314     return;
9315
9316   /* Check whether the format is a literal string constant.  */
9317   fmt_str = c_getstr (fmt);
9318   if (fmt_str == NULL)
9319     return;
9320
9321   if (!init_target_chars ())
9322     return;
9323
9324   /* If the format doesn't contain % args or %%, we know its size.  */
9325   if (strchr (fmt_str, target_percent) == 0)
9326     len = build_int_cstu (size_type_node, strlen (fmt_str));
9327   /* If the format is "%s" and first ... argument is a string literal,
9328      we know it too.  */
9329   else if (fcode == BUILT_IN_SPRINTF_CHK
9330            && strcmp (fmt_str, target_percent_s) == 0)
9331     {
9332       tree arg;
9333
9334       if (nargs < 5)
9335         return;
9336       arg = CALL_EXPR_ARG (exp, 4);
9337       if (! POINTER_TYPE_P (TREE_TYPE (arg)))
9338         return;
9339
9340       len = c_strlen (arg, 1);
9341       if (!len || ! tree_fits_uhwi_p (len))
9342         return;
9343     }
9344   else
9345     return;
9346
9347   if (! tree_int_cst_lt (len, size))
9348     warning_at (tree_nonartificial_location (exp),
9349                 0, "%Kcall to %D will always overflow destination buffer",
9350                 exp, get_callee_fndecl (exp));
9351 }
9352
9353 /* Emit warning if a free is called with address of a variable.  */
9354
9355 static void
9356 maybe_emit_free_warning (tree exp)
9357 {
9358   tree arg = CALL_EXPR_ARG (exp, 0);
9359
9360   STRIP_NOPS (arg);
9361   if (TREE_CODE (arg) != ADDR_EXPR)
9362     return;
9363
9364   arg = get_base_address (TREE_OPERAND (arg, 0));
9365   if (arg == NULL || INDIRECT_REF_P (arg) || TREE_CODE (arg) == MEM_REF)
9366     return;
9367
9368   if (SSA_VAR_P (arg))
9369     warning_at (tree_nonartificial_location (exp), OPT_Wfree_nonheap_object,
9370                 "%Kattempt to free a non-heap object %qD", exp, arg);
9371   else
9372     warning_at (tree_nonartificial_location (exp), OPT_Wfree_nonheap_object,
9373                 "%Kattempt to free a non-heap object", exp);
9374 }
9375
9376 /* Fold a call to __builtin_object_size with arguments PTR and OST,
9377    if possible.  */
9378
9379 static tree
9380 fold_builtin_object_size (tree ptr, tree ost)
9381 {
9382   unsigned HOST_WIDE_INT bytes;
9383   int object_size_type;
9384
9385   if (!validate_arg (ptr, POINTER_TYPE)
9386       || !validate_arg (ost, INTEGER_TYPE))
9387     return NULL_TREE;
9388
9389   STRIP_NOPS (ost);
9390
9391   if (TREE_CODE (ost) != INTEGER_CST
9392       || tree_int_cst_sgn (ost) < 0
9393       || compare_tree_int (ost, 3) > 0)
9394     return NULL_TREE;
9395
9396   object_size_type = tree_to_shwi (ost);
9397
9398   /* __builtin_object_size doesn't evaluate side-effects in its arguments;
9399      if there are any side-effects, it returns (size_t) -1 for types 0 and 1
9400      and (size_t) 0 for types 2 and 3.  */
9401   if (TREE_SIDE_EFFECTS (ptr))
9402     return build_int_cst_type (size_type_node, object_size_type < 2 ? -1 : 0);
9403
9404   if (TREE_CODE (ptr) == ADDR_EXPR)
9405     {
9406       bytes = compute_builtin_object_size (ptr, object_size_type);
9407       if (wi::fits_to_tree_p (bytes, size_type_node))
9408         return build_int_cstu (size_type_node, bytes);
9409     }
9410   else if (TREE_CODE (ptr) == SSA_NAME)
9411     {
9412       /* If object size is not known yet, delay folding until
9413        later.  Maybe subsequent passes will help determining
9414        it.  */
9415       bytes = compute_builtin_object_size (ptr, object_size_type);
9416       if (bytes != (unsigned HOST_WIDE_INT) (object_size_type < 2 ? -1 : 0)
9417           && wi::fits_to_tree_p (bytes, size_type_node))
9418         return build_int_cstu (size_type_node, bytes);
9419     }
9420
9421   return NULL_TREE;
9422 }
9423
9424 /* Builtins with folding operations that operate on "..." arguments
9425    need special handling; we need to store the arguments in a convenient
9426    data structure before attempting any folding.  Fortunately there are
9427    only a few builtins that fall into this category.  FNDECL is the
9428    function, EXP is the CALL_EXPR for the call.  */
9429
9430 static tree
9431 fold_builtin_varargs (location_t loc, tree fndecl, tree *args, int nargs)
9432 {
9433   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
9434   tree ret = NULL_TREE;
9435
9436   switch (fcode)
9437     {
9438     case BUILT_IN_FPCLASSIFY:
9439       ret = fold_builtin_fpclassify (loc, args, nargs);
9440       break;
9441
9442     default:
9443       break;
9444     }
9445   if (ret)
9446     {
9447       ret = build1 (NOP_EXPR, TREE_TYPE (ret), ret);
9448       SET_EXPR_LOCATION (ret, loc);
9449       TREE_NO_WARNING (ret) = 1;
9450       return ret;
9451     }
9452   return NULL_TREE;
9453 }
9454
9455 /* Initialize format string characters in the target charset.  */
9456
9457 bool
9458 init_target_chars (void)
9459 {
9460   static bool init;
9461   if (!init)
9462     {
9463       target_newline = lang_hooks.to_target_charset ('\n');
9464       target_percent = lang_hooks.to_target_charset ('%');
9465       target_c = lang_hooks.to_target_charset ('c');
9466       target_s = lang_hooks.to_target_charset ('s');
9467       if (target_newline == 0 || target_percent == 0 || target_c == 0
9468           || target_s == 0)
9469         return false;
9470
9471       target_percent_c[0] = target_percent;
9472       target_percent_c[1] = target_c;
9473       target_percent_c[2] = '\0';
9474
9475       target_percent_s[0] = target_percent;
9476       target_percent_s[1] = target_s;
9477       target_percent_s[2] = '\0';
9478
9479       target_percent_s_newline[0] = target_percent;
9480       target_percent_s_newline[1] = target_s;
9481       target_percent_s_newline[2] = target_newline;
9482       target_percent_s_newline[3] = '\0';
9483
9484       init = true;
9485     }
9486   return true;
9487 }
9488
9489 /* Helper function for do_mpfr_arg*().  Ensure M is a normal number
9490    and no overflow/underflow occurred.  INEXACT is true if M was not
9491    exactly calculated.  TYPE is the tree type for the result.  This
9492    function assumes that you cleared the MPFR flags and then
9493    calculated M to see if anything subsequently set a flag prior to
9494    entering this function.  Return NULL_TREE if any checks fail.  */
9495
9496 static tree
9497 do_mpfr_ckconv (mpfr_srcptr m, tree type, int inexact)
9498 {
9499   /* Proceed iff we get a normal number, i.e. not NaN or Inf and no
9500      overflow/underflow occurred.  If -frounding-math, proceed iff the
9501      result of calling FUNC was exact.  */
9502   if (mpfr_number_p (m) && !mpfr_overflow_p () && !mpfr_underflow_p ()
9503       && (!flag_rounding_math || !inexact))
9504     {
9505       REAL_VALUE_TYPE rr;
9506
9507       real_from_mpfr (&rr, m, type, GMP_RNDN);
9508       /* Proceed iff GCC's REAL_VALUE_TYPE can hold the MPFR value,
9509          check for overflow/underflow.  If the REAL_VALUE_TYPE is zero
9510          but the mpft_t is not, then we underflowed in the
9511          conversion.  */
9512       if (real_isfinite (&rr)
9513           && (rr.cl == rvc_zero) == (mpfr_zero_p (m) != 0))
9514         {
9515           REAL_VALUE_TYPE rmode;
9516
9517           real_convert (&rmode, TYPE_MODE (type), &rr);
9518           /* Proceed iff the specified mode can hold the value.  */
9519           if (real_identical (&rmode, &rr))
9520             return build_real (type, rmode);
9521         }
9522     }
9523   return NULL_TREE;
9524 }
9525
9526 /* Helper function for do_mpc_arg*().  Ensure M is a normal complex
9527    number and no overflow/underflow occurred.  INEXACT is true if M
9528    was not exactly calculated.  TYPE is the tree type for the result.
9529    This function assumes that you cleared the MPFR flags and then
9530    calculated M to see if anything subsequently set a flag prior to
9531    entering this function.  Return NULL_TREE if any checks fail, if
9532    FORCE_CONVERT is true, then bypass the checks.  */
9533
9534 static tree
9535 do_mpc_ckconv (mpc_srcptr m, tree type, int inexact, int force_convert)
9536 {
9537   /* Proceed iff we get a normal number, i.e. not NaN or Inf and no
9538      overflow/underflow occurred.  If -frounding-math, proceed iff the
9539      result of calling FUNC was exact.  */
9540   if (force_convert
9541       || (mpfr_number_p (mpc_realref (m)) && mpfr_number_p (mpc_imagref (m))
9542           && !mpfr_overflow_p () && !mpfr_underflow_p ()
9543           && (!flag_rounding_math || !inexact)))
9544     {
9545       REAL_VALUE_TYPE re, im;
9546
9547       real_from_mpfr (&re, mpc_realref (m), TREE_TYPE (type), GMP_RNDN);
9548       real_from_mpfr (&im, mpc_imagref (m), TREE_TYPE (type), GMP_RNDN);
9549       /* Proceed iff GCC's REAL_VALUE_TYPE can hold the MPFR values,
9550          check for overflow/underflow.  If the REAL_VALUE_TYPE is zero
9551          but the mpft_t is not, then we underflowed in the
9552          conversion.  */
9553       if (force_convert
9554           || (real_isfinite (&re) && real_isfinite (&im)
9555               && (re.cl == rvc_zero) == (mpfr_zero_p (mpc_realref (m)) != 0)
9556               && (im.cl == rvc_zero) == (mpfr_zero_p (mpc_imagref (m)) != 0)))
9557         {
9558           REAL_VALUE_TYPE re_mode, im_mode;
9559
9560           real_convert (&re_mode, TYPE_MODE (TREE_TYPE (type)), &re);
9561           real_convert (&im_mode, TYPE_MODE (TREE_TYPE (type)), &im);
9562           /* Proceed iff the specified mode can hold the value.  */
9563           if (force_convert
9564               || (real_identical (&re_mode, &re)
9565                   && real_identical (&im_mode, &im)))
9566             return build_complex (type, build_real (TREE_TYPE (type), re_mode),
9567                                   build_real (TREE_TYPE (type), im_mode));
9568         }
9569     }
9570   return NULL_TREE;
9571 }
9572
9573 /* If arguments ARG0 and ARG1 are REAL_CSTs, call mpfr_remquo() to set
9574    the pointer *(ARG_QUO) and return the result.  The type is taken
9575    from the type of ARG0 and is used for setting the precision of the
9576    calculation and results.  */
9577
9578 static tree
9579 do_mpfr_remquo (tree arg0, tree arg1, tree arg_quo)
9580 {
9581   tree const type = TREE_TYPE (arg0);
9582   tree result = NULL_TREE;
9583
9584   STRIP_NOPS (arg0);
9585   STRIP_NOPS (arg1);
9586
9587   /* To proceed, MPFR must exactly represent the target floating point
9588      format, which only happens when the target base equals two.  */
9589   if (REAL_MODE_FORMAT (TYPE_MODE (type))->b == 2
9590       && TREE_CODE (arg0) == REAL_CST && !TREE_OVERFLOW (arg0)
9591       && TREE_CODE (arg1) == REAL_CST && !TREE_OVERFLOW (arg1))
9592     {
9593       const REAL_VALUE_TYPE *const ra0 = TREE_REAL_CST_PTR (arg0);
9594       const REAL_VALUE_TYPE *const ra1 = TREE_REAL_CST_PTR (arg1);
9595
9596       if (real_isfinite (ra0) && real_isfinite (ra1))
9597         {
9598           const struct real_format *fmt = REAL_MODE_FORMAT (TYPE_MODE (type));
9599           const int prec = fmt->p;
9600           const mp_rnd_t rnd = fmt->round_towards_zero? GMP_RNDZ : GMP_RNDN;
9601           tree result_rem;
9602           long integer_quo;
9603           mpfr_t m0, m1;
9604
9605           mpfr_inits2 (prec, m0, m1, NULL);
9606           mpfr_from_real (m0, ra0, GMP_RNDN);
9607           mpfr_from_real (m1, ra1, GMP_RNDN);
9608           mpfr_clear_flags ();
9609           mpfr_remquo (m0, &integer_quo, m0, m1, rnd);
9610           /* Remquo is independent of the rounding mode, so pass
9611              inexact=0 to do_mpfr_ckconv().  */
9612           result_rem = do_mpfr_ckconv (m0, type, /*inexact=*/ 0);
9613           mpfr_clears (m0, m1, NULL);
9614           if (result_rem)
9615             {
9616               /* MPFR calculates quo in the host's long so it may
9617                  return more bits in quo than the target int can hold
9618                  if sizeof(host long) > sizeof(target int).  This can
9619                  happen even for native compilers in LP64 mode.  In
9620                  these cases, modulo the quo value with the largest
9621                  number that the target int can hold while leaving one
9622                  bit for the sign.  */
9623               if (sizeof (integer_quo) * CHAR_BIT > INT_TYPE_SIZE)
9624                 integer_quo %= (long)(1UL << (INT_TYPE_SIZE - 1));
9625
9626               /* Dereference the quo pointer argument.  */
9627               arg_quo = build_fold_indirect_ref (arg_quo);
9628               /* Proceed iff a valid pointer type was passed in.  */
9629               if (TYPE_MAIN_VARIANT (TREE_TYPE (arg_quo)) == integer_type_node)
9630                 {
9631                   /* Set the value. */
9632                   tree result_quo
9633                     = fold_build2 (MODIFY_EXPR, TREE_TYPE (arg_quo), arg_quo,
9634                                    build_int_cst (TREE_TYPE (arg_quo),
9635                                                   integer_quo));
9636                   TREE_SIDE_EFFECTS (result_quo) = 1;
9637                   /* Combine the quo assignment with the rem.  */
9638                   result = non_lvalue (fold_build2 (COMPOUND_EXPR, type,
9639                                                     result_quo, result_rem));
9640                 }
9641             }
9642         }
9643     }
9644   return result;
9645 }
9646
9647 /* If ARG is a REAL_CST, call mpfr_lgamma() on it and return the
9648    resulting value as a tree with type TYPE.  The mpfr precision is
9649    set to the precision of TYPE.  We assume that this mpfr function
9650    returns zero if the result could be calculated exactly within the
9651    requested precision.  In addition, the integer pointer represented
9652    by ARG_SG will be dereferenced and set to the appropriate signgam
9653    (-1,1) value.  */
9654
9655 static tree
9656 do_mpfr_lgamma_r (tree arg, tree arg_sg, tree type)
9657 {
9658   tree result = NULL_TREE;
9659
9660   STRIP_NOPS (arg);
9661
9662   /* To proceed, MPFR must exactly represent the target floating point
9663      format, which only happens when the target base equals two.  Also
9664      verify ARG is a constant and that ARG_SG is an int pointer.  */
9665   if (REAL_MODE_FORMAT (TYPE_MODE (type))->b == 2
9666       && TREE_CODE (arg) == REAL_CST && !TREE_OVERFLOW (arg)
9667       && TREE_CODE (TREE_TYPE (arg_sg)) == POINTER_TYPE
9668       && TYPE_MAIN_VARIANT (TREE_TYPE (TREE_TYPE (arg_sg))) == integer_type_node)
9669     {
9670       const REAL_VALUE_TYPE *const ra = TREE_REAL_CST_PTR (arg);
9671
9672       /* In addition to NaN and Inf, the argument cannot be zero or a
9673          negative integer.  */
9674       if (real_isfinite (ra)
9675           && ra->cl != rvc_zero
9676           && !(real_isneg (ra) && real_isinteger (ra, TYPE_MODE (type))))
9677         {
9678           const struct real_format *fmt = REAL_MODE_FORMAT (TYPE_MODE (type));
9679           const int prec = fmt->p;
9680           const mp_rnd_t rnd = fmt->round_towards_zero? GMP_RNDZ : GMP_RNDN;
9681           int inexact, sg;
9682           mpfr_t m;
9683           tree result_lg;
9684
9685           mpfr_init2 (m, prec);
9686           mpfr_from_real (m, ra, GMP_RNDN);
9687           mpfr_clear_flags ();
9688           inexact = mpfr_lgamma (m, &sg, m, rnd);
9689           result_lg = do_mpfr_ckconv (m, type, inexact);
9690           mpfr_clear (m);
9691           if (result_lg)
9692             {
9693               tree result_sg;
9694
9695               /* Dereference the arg_sg pointer argument.  */
9696               arg_sg = build_fold_indirect_ref (arg_sg);
9697               /* Assign the signgam value into *arg_sg. */
9698               result_sg = fold_build2 (MODIFY_EXPR,
9699                                        TREE_TYPE (arg_sg), arg_sg,
9700                                        build_int_cst (TREE_TYPE (arg_sg), sg));
9701               TREE_SIDE_EFFECTS (result_sg) = 1;
9702               /* Combine the signgam assignment with the lgamma result.  */
9703               result = non_lvalue (fold_build2 (COMPOUND_EXPR, type,
9704                                                 result_sg, result_lg));
9705             }
9706         }
9707     }
9708
9709   return result;
9710 }
9711
9712 /* If arguments ARG0 and ARG1 are a COMPLEX_CST, call the two-argument
9713    mpc function FUNC on it and return the resulting value as a tree
9714    with type TYPE.  The mpfr precision is set to the precision of
9715    TYPE.  We assume that function FUNC returns zero if the result
9716    could be calculated exactly within the requested precision.  If
9717    DO_NONFINITE is true, then fold expressions containing Inf or NaN
9718    in the arguments and/or results.  */
9719
9720 tree
9721 do_mpc_arg2 (tree arg0, tree arg1, tree type, int do_nonfinite,
9722              int (*func)(mpc_ptr, mpc_srcptr, mpc_srcptr, mpc_rnd_t))
9723 {
9724   tree result = NULL_TREE;
9725
9726   STRIP_NOPS (arg0);
9727   STRIP_NOPS (arg1);
9728
9729   /* To proceed, MPFR must exactly represent the target floating point
9730      format, which only happens when the target base equals two.  */
9731   if (TREE_CODE (arg0) == COMPLEX_CST && !TREE_OVERFLOW (arg0)
9732       && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE
9733       && TREE_CODE (arg1) == COMPLEX_CST && !TREE_OVERFLOW (arg1)
9734       && TREE_CODE (TREE_TYPE (TREE_TYPE (arg1))) == REAL_TYPE
9735       && REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (TREE_TYPE (arg0))))->b == 2)
9736     {
9737       const REAL_VALUE_TYPE *const re0 = TREE_REAL_CST_PTR (TREE_REALPART (arg0));
9738       const REAL_VALUE_TYPE *const im0 = TREE_REAL_CST_PTR (TREE_IMAGPART (arg0));
9739       const REAL_VALUE_TYPE *const re1 = TREE_REAL_CST_PTR (TREE_REALPART (arg1));
9740       const REAL_VALUE_TYPE *const im1 = TREE_REAL_CST_PTR (TREE_IMAGPART (arg1));
9741
9742       if (do_nonfinite
9743           || (real_isfinite (re0) && real_isfinite (im0)
9744               && real_isfinite (re1) && real_isfinite (im1)))
9745         {
9746           const struct real_format *const fmt =
9747             REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (type)));
9748           const int prec = fmt->p;
9749           const mp_rnd_t rnd = fmt->round_towards_zero ? GMP_RNDZ : GMP_RNDN;
9750           const mpc_rnd_t crnd = fmt->round_towards_zero ? MPC_RNDZZ : MPC_RNDNN;
9751           int inexact;
9752           mpc_t m0, m1;
9753
9754           mpc_init2 (m0, prec);
9755           mpc_init2 (m1, prec);
9756           mpfr_from_real (mpc_realref (m0), re0, rnd);
9757           mpfr_from_real (mpc_imagref (m0), im0, rnd);
9758           mpfr_from_real (mpc_realref (m1), re1, rnd);
9759           mpfr_from_real (mpc_imagref (m1), im1, rnd);
9760           mpfr_clear_flags ();
9761           inexact = func (m0, m0, m1, crnd);
9762           result = do_mpc_ckconv (m0, type, inexact, do_nonfinite);
9763           mpc_clear (m0);
9764           mpc_clear (m1);
9765         }
9766     }
9767
9768   return result;
9769 }
9770
9771 /* A wrapper function for builtin folding that prevents warnings for
9772    "statement without effect" and the like, caused by removing the
9773    call node earlier than the warning is generated.  */
9774
9775 tree
9776 fold_call_stmt (gcall *stmt, bool ignore)
9777 {
9778   tree ret = NULL_TREE;
9779   tree fndecl = gimple_call_fndecl (stmt);
9780   location_t loc = gimple_location (stmt);
9781   if (fndecl
9782       && TREE_CODE (fndecl) == FUNCTION_DECL
9783       && DECL_BUILT_IN (fndecl)
9784       && !gimple_call_va_arg_pack_p (stmt))
9785     {
9786       int nargs = gimple_call_num_args (stmt);
9787       tree *args = (nargs > 0
9788                     ? gimple_call_arg_ptr (stmt, 0)
9789                     : &error_mark_node);
9790
9791       if (avoid_folding_inline_builtin (fndecl))
9792         return NULL_TREE;
9793       if (DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_MD)
9794         {
9795           return targetm.fold_builtin (fndecl, nargs, args, ignore);
9796         }
9797       else
9798         {
9799           ret = fold_builtin_n (loc, fndecl, args, nargs, ignore);
9800           if (ret)
9801             {
9802               /* Propagate location information from original call to
9803                  expansion of builtin.  Otherwise things like
9804                  maybe_emit_chk_warning, that operate on the expansion
9805                  of a builtin, will use the wrong location information.  */
9806               if (gimple_has_location (stmt))
9807                 {
9808                   tree realret = ret;
9809                   if (TREE_CODE (ret) == NOP_EXPR)
9810                     realret = TREE_OPERAND (ret, 0);
9811                   if (CAN_HAVE_LOCATION_P (realret)
9812                       && !EXPR_HAS_LOCATION (realret))
9813                     SET_EXPR_LOCATION (realret, loc);
9814                   return realret;
9815                 }
9816               return ret;
9817             }
9818         }
9819     }
9820   return NULL_TREE;
9821 }
9822
9823 /* Look up the function in builtin_decl that corresponds to DECL
9824    and set ASMSPEC as its user assembler name.  DECL must be a
9825    function decl that declares a builtin.  */
9826
9827 void
9828 set_builtin_user_assembler_name (tree decl, const char *asmspec)
9829 {
9830   tree builtin;
9831   gcc_assert (TREE_CODE (decl) == FUNCTION_DECL
9832               && DECL_BUILT_IN_CLASS (decl) == BUILT_IN_NORMAL
9833               && asmspec != 0);
9834
9835   builtin = builtin_decl_explicit (DECL_FUNCTION_CODE (decl));
9836   set_user_assembler_name (builtin, asmspec);
9837   switch (DECL_FUNCTION_CODE (decl))
9838     {
9839     case BUILT_IN_MEMCPY:
9840       init_block_move_fn (asmspec);
9841       memcpy_libfunc = set_user_assembler_libfunc ("memcpy", asmspec);
9842       break;
9843     case BUILT_IN_MEMSET:
9844       init_block_clear_fn (asmspec);
9845       memset_libfunc = set_user_assembler_libfunc ("memset", asmspec);
9846       break;
9847     case BUILT_IN_MEMMOVE:
9848       memmove_libfunc = set_user_assembler_libfunc ("memmove", asmspec);
9849       break;
9850     case BUILT_IN_MEMCMP:
9851       memcmp_libfunc = set_user_assembler_libfunc ("memcmp", asmspec);
9852       break;
9853     case BUILT_IN_ABORT:
9854       abort_libfunc = set_user_assembler_libfunc ("abort", asmspec);
9855       break;
9856     case BUILT_IN_FFS:
9857       if (INT_TYPE_SIZE < BITS_PER_WORD)
9858         {
9859           set_user_assembler_libfunc ("ffs", asmspec);
9860           set_optab_libfunc (ffs_optab, mode_for_size (INT_TYPE_SIZE,
9861                                                        MODE_INT, 0), "ffs");
9862         }
9863       break;
9864     default:
9865       break;
9866     }
9867 }
9868
9869 /* Return true if DECL is a builtin that expands to a constant or similarly
9870    simple code.  */
9871 bool
9872 is_simple_builtin (tree decl)
9873 {
9874   if (decl && DECL_BUILT_IN_CLASS (decl) == BUILT_IN_NORMAL)
9875     switch (DECL_FUNCTION_CODE (decl))
9876       {
9877         /* Builtins that expand to constants.  */
9878       case BUILT_IN_CONSTANT_P:
9879       case BUILT_IN_EXPECT:
9880       case BUILT_IN_OBJECT_SIZE:
9881       case BUILT_IN_UNREACHABLE:
9882         /* Simple register moves or loads from stack.  */
9883       case BUILT_IN_ASSUME_ALIGNED:
9884       case BUILT_IN_RETURN_ADDRESS:
9885       case BUILT_IN_EXTRACT_RETURN_ADDR:
9886       case BUILT_IN_FROB_RETURN_ADDR:
9887       case BUILT_IN_RETURN:
9888       case BUILT_IN_AGGREGATE_INCOMING_ADDRESS:
9889       case BUILT_IN_FRAME_ADDRESS:
9890       case BUILT_IN_VA_END:
9891       case BUILT_IN_STACK_SAVE:
9892       case BUILT_IN_STACK_RESTORE:
9893         /* Exception state returns or moves registers around.  */
9894       case BUILT_IN_EH_FILTER:
9895       case BUILT_IN_EH_POINTER:
9896       case BUILT_IN_EH_COPY_VALUES:
9897         return true;
9898
9899       default:
9900         return false;
9901       }
9902
9903   return false;
9904 }
9905
9906 /* Return true if DECL is a builtin that is not expensive, i.e., they are
9907    most probably expanded inline into reasonably simple code.  This is a
9908    superset of is_simple_builtin.  */
9909 bool
9910 is_inexpensive_builtin (tree decl)
9911 {
9912   if (!decl)
9913     return false;
9914   else if (DECL_BUILT_IN_CLASS (decl) == BUILT_IN_MD)
9915     return true;
9916   else if (DECL_BUILT_IN_CLASS (decl) == BUILT_IN_NORMAL)
9917     switch (DECL_FUNCTION_CODE (decl))
9918       {
9919       case BUILT_IN_ABS:
9920       case BUILT_IN_ALLOCA:
9921       case BUILT_IN_ALLOCA_WITH_ALIGN:
9922       case BUILT_IN_BSWAP16:
9923       case BUILT_IN_BSWAP32:
9924       case BUILT_IN_BSWAP64:
9925       case BUILT_IN_CLZ:
9926       case BUILT_IN_CLZIMAX:
9927       case BUILT_IN_CLZL:
9928       case BUILT_IN_CLZLL:
9929       case BUILT_IN_CTZ:
9930       case BUILT_IN_CTZIMAX:
9931       case BUILT_IN_CTZL:
9932       case BUILT_IN_CTZLL:
9933       case BUILT_IN_FFS:
9934       case BUILT_IN_FFSIMAX:
9935       case BUILT_IN_FFSL:
9936       case BUILT_IN_FFSLL:
9937       case BUILT_IN_IMAXABS:
9938       case BUILT_IN_FINITE:
9939       case BUILT_IN_FINITEF:
9940       case BUILT_IN_FINITEL:
9941       case BUILT_IN_FINITED32:
9942       case BUILT_IN_FINITED64:
9943       case BUILT_IN_FINITED128:
9944       case BUILT_IN_FPCLASSIFY:
9945       case BUILT_IN_ISFINITE:
9946       case BUILT_IN_ISINF_SIGN:
9947       case BUILT_IN_ISINF:
9948       case BUILT_IN_ISINFF:
9949       case BUILT_IN_ISINFL:
9950       case BUILT_IN_ISINFD32:
9951       case BUILT_IN_ISINFD64:
9952       case BUILT_IN_ISINFD128:
9953       case BUILT_IN_ISNAN:
9954       case BUILT_IN_ISNANF:
9955       case BUILT_IN_ISNANL:
9956       case BUILT_IN_ISNAND32:
9957       case BUILT_IN_ISNAND64:
9958       case BUILT_IN_ISNAND128:
9959       case BUILT_IN_ISNORMAL:
9960       case BUILT_IN_ISGREATER:
9961       case BUILT_IN_ISGREATEREQUAL:
9962       case BUILT_IN_ISLESS:
9963       case BUILT_IN_ISLESSEQUAL:
9964       case BUILT_IN_ISLESSGREATER:
9965       case BUILT_IN_ISUNORDERED:
9966       case BUILT_IN_VA_ARG_PACK:
9967       case BUILT_IN_VA_ARG_PACK_LEN:
9968       case BUILT_IN_VA_COPY:
9969       case BUILT_IN_TRAP:
9970       case BUILT_IN_SAVEREGS:
9971       case BUILT_IN_POPCOUNTL:
9972       case BUILT_IN_POPCOUNTLL:
9973       case BUILT_IN_POPCOUNTIMAX:
9974       case BUILT_IN_POPCOUNT:
9975       case BUILT_IN_PARITYL:
9976       case BUILT_IN_PARITYLL:
9977       case BUILT_IN_PARITYIMAX:
9978       case BUILT_IN_PARITY:
9979       case BUILT_IN_LABS:
9980       case BUILT_IN_LLABS:
9981       case BUILT_IN_PREFETCH:
9982       case BUILT_IN_ACC_ON_DEVICE:
9983         return true;
9984
9985       default:
9986         return is_simple_builtin (decl);
9987       }
9988
9989   return false;
9990 }