Update change log
[platform/upstream/gcc48.git] / gcc / builtins.c
1 /* Expand builtin functions.
2    Copyright (C) 1988-2013 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 #include "config.h"
21 #include "system.h"
22 #include "coretypes.h"
23 #include "tm.h"
24 #include "machmode.h"
25 #include "rtl.h"
26 #include "tree.h"
27 #include "realmpfr.h"
28 #include "gimple.h"
29 #include "flags.h"
30 #include "regs.h"
31 #include "hard-reg-set.h"
32 #include "except.h"
33 #include "function.h"
34 #include "insn-config.h"
35 #include "expr.h"
36 #include "optabs.h"
37 #include "libfuncs.h"
38 #include "recog.h"
39 #include "output.h"
40 #include "typeclass.h"
41 #include "predict.h"
42 #include "tm_p.h"
43 #include "target.h"
44 #include "langhooks.h"
45 #include "basic-block.h"
46 #include "tree-mudflap.h"
47 #include "tree-flow.h"
48 #include "value-prof.h"
49 #include "diagnostic-core.h"
50 #include "builtins.h"
51
52
53 #ifndef PAD_VARARGS_DOWN
54 #define PAD_VARARGS_DOWN BYTES_BIG_ENDIAN
55 #endif
56 static tree do_mpc_arg1 (tree, tree, int (*)(mpc_ptr, mpc_srcptr, mpc_rnd_t));
57
58 struct target_builtins default_target_builtins;
59 #if SWITCHABLE_TARGET
60 struct target_builtins *this_target_builtins = &default_target_builtins;
61 #endif
62
63 /* Define the names of the builtin function types and codes.  */
64 const char *const built_in_class_names[4]
65   = {"NOT_BUILT_IN", "BUILT_IN_FRONTEND", "BUILT_IN_MD", "BUILT_IN_NORMAL"};
66
67 #define DEF_BUILTIN(X, N, C, T, LT, B, F, NA, AT, IM, COND) #X,
68 const char * built_in_names[(int) END_BUILTINS] =
69 {
70 #include "builtins.def"
71 };
72 #undef DEF_BUILTIN
73
74 /* Setup an array of _DECL trees, make sure each element is
75    initialized to NULL_TREE.  */
76 builtin_info_type builtin_info;
77
78 static const char *c_getstr (tree);
79 static rtx c_readstr (const char *, enum machine_mode);
80 static int target_char_cast (tree, char *);
81 static rtx get_memory_rtx (tree, tree);
82 static int apply_args_size (void);
83 static int apply_result_size (void);
84 #if defined (HAVE_untyped_call) || defined (HAVE_untyped_return)
85 static rtx result_vector (int, rtx);
86 #endif
87 static void expand_builtin_update_setjmp_buf (rtx);
88 static void expand_builtin_prefetch (tree);
89 static rtx expand_builtin_apply_args (void);
90 static rtx expand_builtin_apply_args_1 (void);
91 static rtx expand_builtin_apply (rtx, rtx, rtx);
92 static void expand_builtin_return (rtx);
93 static enum type_class type_to_class (tree);
94 static rtx expand_builtin_classify_type (tree);
95 static void expand_errno_check (tree, rtx);
96 static rtx expand_builtin_mathfn (tree, rtx, rtx);
97 static rtx expand_builtin_mathfn_2 (tree, rtx, rtx);
98 static rtx expand_builtin_mathfn_3 (tree, rtx, rtx);
99 static rtx expand_builtin_mathfn_ternary (tree, rtx, rtx);
100 static rtx expand_builtin_interclass_mathfn (tree, rtx);
101 static rtx expand_builtin_sincos (tree);
102 static rtx expand_builtin_cexpi (tree, rtx);
103 static rtx expand_builtin_int_roundingfn (tree, rtx);
104 static rtx expand_builtin_int_roundingfn_2 (tree, rtx);
105 static rtx expand_builtin_next_arg (void);
106 static rtx expand_builtin_va_start (tree);
107 static rtx expand_builtin_va_end (tree);
108 static rtx expand_builtin_va_copy (tree);
109 static rtx expand_builtin_memcmp (tree, rtx, enum machine_mode);
110 static rtx expand_builtin_strcmp (tree, rtx);
111 static rtx expand_builtin_strncmp (tree, rtx, enum machine_mode);
112 static rtx builtin_memcpy_read_str (void *, HOST_WIDE_INT, enum machine_mode);
113 static rtx expand_builtin_memcpy (tree, rtx);
114 static rtx expand_builtin_mempcpy (tree, rtx, enum machine_mode);
115 static rtx expand_builtin_mempcpy_args (tree, tree, tree, rtx,
116                                         enum machine_mode, int);
117 static rtx expand_builtin_strcpy (tree, rtx);
118 static rtx expand_builtin_strcpy_args (tree, tree, rtx);
119 static rtx expand_builtin_stpcpy (tree, rtx, enum machine_mode);
120 static rtx expand_builtin_strncpy (tree, rtx);
121 static rtx builtin_memset_gen_str (void *, HOST_WIDE_INT, enum machine_mode);
122 static rtx expand_builtin_memset (tree, rtx, enum machine_mode);
123 static rtx expand_builtin_memset_args (tree, tree, tree, rtx, enum machine_mode, tree);
124 static rtx expand_builtin_bzero (tree);
125 static rtx expand_builtin_strlen (tree, rtx, enum machine_mode);
126 static rtx expand_builtin_alloca (tree, bool);
127 static rtx expand_builtin_unop (enum machine_mode, tree, rtx, rtx, optab);
128 static rtx expand_builtin_frame_address (tree, tree);
129 static tree stabilize_va_list_loc (location_t, tree, int);
130 static rtx expand_builtin_expect (tree, rtx);
131 static tree fold_builtin_constant_p (tree);
132 static tree fold_builtin_expect (location_t, tree, tree);
133 static tree fold_builtin_classify_type (tree);
134 static tree fold_builtin_strlen (location_t, tree, tree);
135 static tree fold_builtin_inf (location_t, tree, int);
136 static tree fold_builtin_nan (tree, tree, int);
137 static tree rewrite_call_expr (location_t, tree, int, tree, int, ...);
138 static bool validate_arg (const_tree, enum tree_code code);
139 static bool integer_valued_real_p (tree);
140 static tree fold_trunc_transparent_mathfn (location_t, tree, tree);
141 static bool readonly_data_expr (tree);
142 static rtx expand_builtin_fabs (tree, rtx, rtx);
143 static rtx expand_builtin_signbit (tree, rtx);
144 static tree fold_builtin_sqrt (location_t, tree, tree);
145 static tree fold_builtin_cbrt (location_t, tree, tree);
146 static tree fold_builtin_pow (location_t, tree, tree, tree, tree);
147 static tree fold_builtin_powi (location_t, tree, tree, tree, tree);
148 static tree fold_builtin_cos (location_t, tree, tree, tree);
149 static tree fold_builtin_cosh (location_t, tree, tree, tree);
150 static tree fold_builtin_tan (tree, tree);
151 static tree fold_builtin_trunc (location_t, tree, tree);
152 static tree fold_builtin_floor (location_t, tree, tree);
153 static tree fold_builtin_ceil (location_t, tree, tree);
154 static tree fold_builtin_round (location_t, tree, tree);
155 static tree fold_builtin_int_roundingfn (location_t, tree, tree);
156 static tree fold_builtin_bitop (tree, tree);
157 static tree fold_builtin_memory_op (location_t, tree, tree, tree, tree, bool, int);
158 static tree fold_builtin_strchr (location_t, tree, tree, tree);
159 static tree fold_builtin_memchr (location_t, tree, tree, tree, tree);
160 static tree fold_builtin_memcmp (location_t, tree, tree, tree);
161 static tree fold_builtin_strcmp (location_t, tree, tree);
162 static tree fold_builtin_strncmp (location_t, tree, tree, tree);
163 static tree fold_builtin_signbit (location_t, tree, tree);
164 static tree fold_builtin_copysign (location_t, tree, tree, tree, tree);
165 static tree fold_builtin_isascii (location_t, tree);
166 static tree fold_builtin_toascii (location_t, tree);
167 static tree fold_builtin_isdigit (location_t, tree);
168 static tree fold_builtin_fabs (location_t, tree, tree);
169 static tree fold_builtin_abs (location_t, tree, tree);
170 static tree fold_builtin_unordered_cmp (location_t, tree, tree, tree, enum tree_code,
171                                         enum tree_code);
172 static tree fold_builtin_n (location_t, tree, tree *, int, bool);
173 static tree fold_builtin_0 (location_t, tree, bool);
174 static tree fold_builtin_1 (location_t, tree, tree, bool);
175 static tree fold_builtin_2 (location_t, tree, tree, tree, bool);
176 static tree fold_builtin_3 (location_t, tree, tree, tree, tree, bool);
177 static tree fold_builtin_4 (location_t, tree, tree, tree, tree, tree, bool);
178 static tree fold_builtin_varargs (location_t, tree, tree, bool);
179
180 static tree fold_builtin_strpbrk (location_t, tree, tree, tree);
181 static tree fold_builtin_strstr (location_t, tree, tree, tree);
182 static tree fold_builtin_strrchr (location_t, tree, tree, tree);
183 static tree fold_builtin_strcat (location_t, tree, tree);
184 static tree fold_builtin_strncat (location_t, tree, tree, tree);
185 static tree fold_builtin_strspn (location_t, tree, tree);
186 static tree fold_builtin_strcspn (location_t, tree, tree);
187 static tree fold_builtin_sprintf (location_t, tree, tree, tree, int);
188 static tree fold_builtin_snprintf (location_t, tree, tree, tree, tree, int);
189
190 static rtx expand_builtin_object_size (tree);
191 static rtx expand_builtin_memory_chk (tree, rtx, enum machine_mode,
192                                       enum built_in_function);
193 static void maybe_emit_chk_warning (tree, enum built_in_function);
194 static void maybe_emit_sprintf_chk_warning (tree, enum built_in_function);
195 static void maybe_emit_free_warning (tree);
196 static tree fold_builtin_object_size (tree, tree);
197 static tree fold_builtin_strcat_chk (location_t, tree, tree, tree, tree);
198 static tree fold_builtin_strncat_chk (location_t, tree, tree, tree, tree, tree);
199 static tree fold_builtin_sprintf_chk (location_t, tree, enum built_in_function);
200 static tree fold_builtin_printf (location_t, tree, tree, tree, bool, enum built_in_function);
201 static tree fold_builtin_fprintf (location_t, tree, tree, tree, tree, bool,
202                                   enum built_in_function);
203 static bool init_target_chars (void);
204
205 static unsigned HOST_WIDE_INT target_newline;
206 static unsigned HOST_WIDE_INT target_percent;
207 static unsigned HOST_WIDE_INT target_c;
208 static unsigned HOST_WIDE_INT target_s;
209 static char target_percent_c[3];
210 static char target_percent_s[3];
211 static char target_percent_s_newline[4];
212 static tree do_mpfr_arg1 (tree, tree, int (*)(mpfr_ptr, mpfr_srcptr, mp_rnd_t),
213                           const REAL_VALUE_TYPE *, const REAL_VALUE_TYPE *, bool);
214 static tree do_mpfr_arg2 (tree, tree, tree,
215                           int (*)(mpfr_ptr, mpfr_srcptr, mpfr_srcptr, mp_rnd_t));
216 static tree do_mpfr_arg3 (tree, tree, tree, tree,
217                           int (*)(mpfr_ptr, mpfr_srcptr, mpfr_srcptr, mpfr_srcptr, mp_rnd_t));
218 static tree do_mpfr_sincos (tree, tree, tree);
219 static tree do_mpfr_bessel_n (tree, tree, tree,
220                               int (*)(mpfr_ptr, long, mpfr_srcptr, mp_rnd_t),
221                               const REAL_VALUE_TYPE *, bool);
222 static tree do_mpfr_remquo (tree, tree, tree);
223 static tree do_mpfr_lgamma_r (tree, tree, tree);
224 static void expand_builtin_sync_synchronize (void);
225
226 /* Return true if NAME starts with __builtin_ or __sync_.  */
227
228 static bool
229 is_builtin_name (const char *name)
230 {
231   if (strncmp (name, "__builtin_", 10) == 0)
232     return true;
233   if (strncmp (name, "__sync_", 7) == 0)
234     return true;
235   if (strncmp (name, "__atomic_", 9) == 0)
236     return true;
237   return false;
238 }
239
240
241 /* Return true if DECL is a function symbol representing a built-in.  */
242
243 bool
244 is_builtin_fn (tree decl)
245 {
246   return TREE_CODE (decl) == FUNCTION_DECL && DECL_BUILT_IN (decl);
247 }
248
249
250 /* Return true if NODE should be considered for inline expansion regardless
251    of the optimization level.  This means whenever a function is invoked with
252    its "internal" name, which normally contains the prefix "__builtin".  */
253
254 static bool
255 called_as_built_in (tree node)
256 {
257   /* Note that we must use DECL_NAME, not DECL_ASSEMBLER_NAME_SET_P since
258      we want the name used to call the function, not the name it
259      will have. */
260   const char *name = IDENTIFIER_POINTER (DECL_NAME (node));
261   return is_builtin_name (name);
262 }
263
264 /* Compute values M and N such that M divides (address of EXP - N) and such
265    that N < M.  If these numbers can be determined, store M in alignp and N in
266    *BITPOSP and return true.  Otherwise return false and store BITS_PER_UNIT to
267    *alignp and any bit-offset to *bitposp.
268
269    Note that the address (and thus the alignment) computed here is based
270    on the address to which a symbol resolves, whereas DECL_ALIGN is based
271    on the address at which an object is actually located.  These two
272    addresses are not always the same.  For example, on ARM targets,
273    the address &foo of a Thumb function foo() has the lowest bit set,
274    whereas foo() itself starts on an even address.
275
276    If ADDR_P is true we are taking the address of the memory reference EXP
277    and thus cannot rely on the access taking place.  */
278
279 static bool
280 get_object_alignment_2 (tree exp, unsigned int *alignp,
281                         unsigned HOST_WIDE_INT *bitposp, bool addr_p)
282 {
283   HOST_WIDE_INT bitsize, bitpos;
284   tree offset;
285   enum machine_mode mode;
286   int unsignedp, volatilep;
287   unsigned int inner, align = BITS_PER_UNIT;
288   bool known_alignment = false;
289
290   /* Get the innermost object and the constant (bitpos) and possibly
291      variable (offset) offset of the access.  */
292   exp = get_inner_reference (exp, &bitsize, &bitpos, &offset,
293                              &mode, &unsignedp, &volatilep, true);
294
295   /* Extract alignment information from the innermost object and
296      possibly adjust bitpos and offset.  */
297   if (TREE_CODE (exp) == FUNCTION_DECL)
298     {
299       /* Function addresses can encode extra information besides their
300          alignment.  However, if TARGET_PTRMEMFUNC_VBIT_LOCATION
301          allows the low bit to be used as a virtual bit, we know
302          that the address itself must be at least 2-byte aligned.  */
303       if (TARGET_PTRMEMFUNC_VBIT_LOCATION == ptrmemfunc_vbit_in_pfn)
304         align = 2 * BITS_PER_UNIT;
305     }
306   else if (TREE_CODE (exp) == LABEL_DECL)
307     ;
308   else if (TREE_CODE (exp) == CONST_DECL)
309     {
310       /* The alignment of a CONST_DECL is determined by its initializer.  */
311       exp = DECL_INITIAL (exp);
312       align = TYPE_ALIGN (TREE_TYPE (exp));
313 #ifdef CONSTANT_ALIGNMENT
314       if (CONSTANT_CLASS_P (exp))
315         align = (unsigned) CONSTANT_ALIGNMENT (exp, align);
316 #endif
317       known_alignment = true;
318     }
319   else if (DECL_P (exp))
320     {
321       align = DECL_ALIGN (exp);
322       known_alignment = true;
323     }
324   else if (TREE_CODE (exp) == VIEW_CONVERT_EXPR)
325     {
326       align = TYPE_ALIGN (TREE_TYPE (exp));
327     }
328   else if (TREE_CODE (exp) == INDIRECT_REF
329            || TREE_CODE (exp) == MEM_REF
330            || TREE_CODE (exp) == TARGET_MEM_REF)
331     {
332       tree addr = TREE_OPERAND (exp, 0);
333       unsigned ptr_align;
334       unsigned HOST_WIDE_INT ptr_bitpos;
335
336       if (TREE_CODE (addr) == BIT_AND_EXPR
337           && TREE_CODE (TREE_OPERAND (addr, 1)) == INTEGER_CST)
338         {
339           align = (TREE_INT_CST_LOW (TREE_OPERAND (addr, 1))
340                     & -TREE_INT_CST_LOW (TREE_OPERAND (addr, 1)));
341           align *= BITS_PER_UNIT;
342           addr = TREE_OPERAND (addr, 0);
343         }
344
345       known_alignment
346         = get_pointer_alignment_1 (addr, &ptr_align, &ptr_bitpos);
347       align = MAX (ptr_align, align);
348
349       /* The alignment of the pointer operand in a TARGET_MEM_REF
350          has to take the variable offset parts into account.  */
351       if (TREE_CODE (exp) == TARGET_MEM_REF)
352         {
353           if (TMR_INDEX (exp))
354             {
355               unsigned HOST_WIDE_INT step = 1;
356               if (TMR_STEP (exp))
357                 step = TREE_INT_CST_LOW (TMR_STEP (exp));
358               align = MIN (align, (step & -step) * BITS_PER_UNIT);
359             }
360           if (TMR_INDEX2 (exp))
361             align = BITS_PER_UNIT;
362           known_alignment = false;
363         }
364
365       /* When EXP is an actual memory reference then we can use
366          TYPE_ALIGN of a pointer indirection to derive alignment.
367          Do so only if get_pointer_alignment_1 did not reveal absolute
368          alignment knowledge and if using that alignment would
369          improve the situation.  */
370       if (!addr_p && !known_alignment
371           && TYPE_ALIGN (TREE_TYPE (exp)) > align)
372         align = TYPE_ALIGN (TREE_TYPE (exp));
373       else
374         {
375           /* Else adjust bitpos accordingly.  */
376           bitpos += ptr_bitpos;
377           if (TREE_CODE (exp) == MEM_REF
378               || TREE_CODE (exp) == TARGET_MEM_REF)
379             bitpos += mem_ref_offset (exp).low * BITS_PER_UNIT;
380         }
381     }
382   else if (TREE_CODE (exp) == STRING_CST)
383     {
384       /* STRING_CST are the only constant objects we allow to be not
385          wrapped inside a CONST_DECL.  */
386       align = TYPE_ALIGN (TREE_TYPE (exp));
387 #ifdef CONSTANT_ALIGNMENT
388       if (CONSTANT_CLASS_P (exp))
389         align = (unsigned) CONSTANT_ALIGNMENT (exp, align);
390 #endif
391       known_alignment = true;
392     }
393
394   /* If there is a non-constant offset part extract the maximum
395      alignment that can prevail.  */
396   inner = ~0U;
397   while (offset)
398     {
399       tree next_offset;
400
401       if (TREE_CODE (offset) == PLUS_EXPR)
402         {
403           next_offset = TREE_OPERAND (offset, 0);
404           offset = TREE_OPERAND (offset, 1);
405         }
406       else
407         next_offset = NULL;
408       if (host_integerp (offset, 1))
409         {
410           /* Any overflow in calculating offset_bits won't change
411              the alignment.  */
412           unsigned offset_bits
413             = ((unsigned) tree_low_cst (offset, 1) * BITS_PER_UNIT);
414
415           if (offset_bits)
416             inner = MIN (inner, (offset_bits & -offset_bits));
417         }
418       else if (TREE_CODE (offset) == MULT_EXPR
419                && host_integerp (TREE_OPERAND (offset, 1), 1))
420         {
421           /* Any overflow in calculating offset_factor won't change
422              the alignment.  */
423           unsigned offset_factor
424             = ((unsigned) tree_low_cst (TREE_OPERAND (offset, 1), 1)
425                * BITS_PER_UNIT);
426
427           if (offset_factor)
428             inner = MIN (inner, (offset_factor & -offset_factor));
429         }
430       else
431         {
432           inner = MIN (inner, BITS_PER_UNIT);
433           break;
434         }
435       offset = next_offset;
436     }
437   /* Alignment is innermost object alignment adjusted by the constant
438      and non-constant offset parts.  */
439   align = MIN (align, inner);
440
441   *alignp = align;
442   *bitposp = bitpos & (*alignp - 1);
443   return known_alignment;
444 }
445
446 /* For a memory reference expression EXP compute values M and N such that M
447    divides (&EXP - N) and such that N < M.  If these numbers can be determined,
448    store M in alignp and N in *BITPOSP and return true.  Otherwise return false
449    and store BITS_PER_UNIT to *alignp and any bit-offset to *bitposp.  */
450
451 bool
452 get_object_alignment_1 (tree exp, unsigned int *alignp,
453                         unsigned HOST_WIDE_INT *bitposp)
454 {
455   return get_object_alignment_2 (exp, alignp, bitposp, false);
456 }
457
458 /* Return the alignment in bits of EXP, an object.  */
459
460 unsigned int
461 get_object_alignment (tree exp)
462 {
463   unsigned HOST_WIDE_INT bitpos = 0;
464   unsigned int align;
465
466   get_object_alignment_1 (exp, &align, &bitpos);
467
468   /* align and bitpos now specify known low bits of the pointer.
469      ptr & (align - 1) == bitpos.  */
470
471   if (bitpos != 0)
472     align = (bitpos & -bitpos);
473   return align;
474 }
475
476 /* For a pointer valued expression EXP compute values M and N such that M
477    divides (EXP - N) and such that N < M.  If these numbers can be determined,
478    store M in alignp and N in *BITPOSP and return true.  Return false if
479    the results are just a conservative approximation.
480
481    If EXP is not a pointer, false is returned too.  */
482
483 bool
484 get_pointer_alignment_1 (tree exp, unsigned int *alignp,
485                          unsigned HOST_WIDE_INT *bitposp)
486 {
487   STRIP_NOPS (exp);
488
489   if (TREE_CODE (exp) == ADDR_EXPR)
490     return get_object_alignment_2 (TREE_OPERAND (exp, 0),
491                                    alignp, bitposp, true);
492   else if (TREE_CODE (exp) == SSA_NAME
493            && POINTER_TYPE_P (TREE_TYPE (exp)))
494     {
495       unsigned int ptr_align, ptr_misalign;
496       struct ptr_info_def *pi = SSA_NAME_PTR_INFO (exp);
497
498       if (pi && get_ptr_info_alignment (pi, &ptr_align, &ptr_misalign))
499         {
500           *bitposp = ptr_misalign * BITS_PER_UNIT;
501           *alignp = ptr_align * BITS_PER_UNIT;
502           /* We cannot really tell whether this result is an approximation.  */
503           return true;
504         }
505       else
506         {
507           *bitposp = 0;
508           *alignp = BITS_PER_UNIT;
509           return false;
510         }
511     }
512   else if (TREE_CODE (exp) == INTEGER_CST)
513     {
514       *alignp = BIGGEST_ALIGNMENT;
515       *bitposp = ((TREE_INT_CST_LOW (exp) * BITS_PER_UNIT)
516                   & (BIGGEST_ALIGNMENT - 1));
517       return true;
518     }
519
520   *bitposp = 0;
521   *alignp = BITS_PER_UNIT;
522   return false;
523 }
524
525 /* Return the alignment in bits of EXP, a pointer valued expression.
526    The alignment returned is, by default, the alignment of the thing that
527    EXP points to.  If it is not a POINTER_TYPE, 0 is returned.
528
529    Otherwise, look at the expression to see if we can do better, i.e., if the
530    expression is actually pointing at an object whose alignment is tighter.  */
531
532 unsigned int
533 get_pointer_alignment (tree exp)
534 {
535   unsigned HOST_WIDE_INT bitpos = 0;
536   unsigned int align;
537
538   get_pointer_alignment_1 (exp, &align, &bitpos);
539
540   /* align and bitpos now specify known low bits of the pointer.
541      ptr & (align - 1) == bitpos.  */
542
543   if (bitpos != 0)
544     align = (bitpos & -bitpos);
545
546   return align;
547 }
548
549 /* Compute the length of a C string.  TREE_STRING_LENGTH is not the right
550    way, because it could contain a zero byte in the middle.
551    TREE_STRING_LENGTH is the size of the character array, not the string.
552
553    ONLY_VALUE should be nonzero if the result is not going to be emitted
554    into the instruction stream and zero if it is going to be expanded.
555    E.g. with i++ ? "foo" : "bar", if ONLY_VALUE is nonzero, constant 3
556    is returned, otherwise NULL, since
557    len = c_strlen (src, 1); if (len) expand_expr (len, ...); would not
558    evaluate the side-effects.
559
560    The value returned is of type `ssizetype'.
561
562    Unfortunately, string_constant can't access the values of const char
563    arrays with initializers, so neither can we do so here.  */
564
565 tree
566 c_strlen (tree src, int only_value)
567 {
568   tree offset_node;
569   HOST_WIDE_INT offset;
570   int max;
571   const char *ptr;
572   location_t loc;
573
574   STRIP_NOPS (src);
575   if (TREE_CODE (src) == COND_EXPR
576       && (only_value || !TREE_SIDE_EFFECTS (TREE_OPERAND (src, 0))))
577     {
578       tree len1, len2;
579
580       len1 = c_strlen (TREE_OPERAND (src, 1), only_value);
581       len2 = c_strlen (TREE_OPERAND (src, 2), only_value);
582       if (tree_int_cst_equal (len1, len2))
583         return len1;
584     }
585
586   if (TREE_CODE (src) == COMPOUND_EXPR
587       && (only_value || !TREE_SIDE_EFFECTS (TREE_OPERAND (src, 0))))
588     return c_strlen (TREE_OPERAND (src, 1), only_value);
589
590   loc = EXPR_LOC_OR_HERE (src);
591
592   src = string_constant (src, &offset_node);
593   if (src == 0)
594     return NULL_TREE;
595
596   max = TREE_STRING_LENGTH (src) - 1;
597   ptr = TREE_STRING_POINTER (src);
598
599   if (offset_node && TREE_CODE (offset_node) != INTEGER_CST)
600     {
601       /* If the string has an internal zero byte (e.g., "foo\0bar"), we can't
602          compute the offset to the following null if we don't know where to
603          start searching for it.  */
604       int i;
605
606       for (i = 0; i < max; i++)
607         if (ptr[i] == 0)
608           return NULL_TREE;
609
610       /* We don't know the starting offset, but we do know that the string
611          has no internal zero bytes.  We can assume that the offset falls
612          within the bounds of the string; otherwise, the programmer deserves
613          what he gets.  Subtract the offset from the length of the string,
614          and return that.  This would perhaps not be valid if we were dealing
615          with named arrays in addition to literal string constants.  */
616
617       return size_diffop_loc (loc, size_int (max), offset_node);
618     }
619
620   /* We have a known offset into the string.  Start searching there for
621      a null character if we can represent it as a single HOST_WIDE_INT.  */
622   if (offset_node == 0)
623     offset = 0;
624   else if (! host_integerp (offset_node, 0))
625     offset = -1;
626   else
627     offset = tree_low_cst (offset_node, 0);
628
629   /* If the offset is known to be out of bounds, warn, and call strlen at
630      runtime.  */
631   if (offset < 0 || offset > max)
632     {
633      /* Suppress multiple warnings for propagated constant strings.  */
634       if (! TREE_NO_WARNING (src))
635         {
636           warning_at (loc, 0, "offset outside bounds of constant string");
637           TREE_NO_WARNING (src) = 1;
638         }
639       return NULL_TREE;
640     }
641
642   /* Use strlen to search for the first zero byte.  Since any strings
643      constructed with build_string will have nulls appended, we win even
644      if we get handed something like (char[4])"abcd".
645
646      Since OFFSET is our starting index into the string, no further
647      calculation is needed.  */
648   return ssize_int (strlen (ptr + offset));
649 }
650
651 /* Return a char pointer for a C string if it is a string constant
652    or sum of string constant and integer constant.  */
653
654 static const char *
655 c_getstr (tree src)
656 {
657   tree offset_node;
658
659   src = string_constant (src, &offset_node);
660   if (src == 0)
661     return 0;
662
663   if (offset_node == 0)
664     return TREE_STRING_POINTER (src);
665   else if (!host_integerp (offset_node, 1)
666            || compare_tree_int (offset_node, TREE_STRING_LENGTH (src) - 1) > 0)
667     return 0;
668
669   return TREE_STRING_POINTER (src) + tree_low_cst (offset_node, 1);
670 }
671
672 /* Return a CONST_INT or CONST_DOUBLE corresponding to target reading
673    GET_MODE_BITSIZE (MODE) bits from string constant STR.  */
674
675 static rtx
676 c_readstr (const char *str, enum machine_mode mode)
677 {
678   HOST_WIDE_INT c[2];
679   HOST_WIDE_INT ch;
680   unsigned int i, j;
681
682   gcc_assert (GET_MODE_CLASS (mode) == MODE_INT);
683
684   c[0] = 0;
685   c[1] = 0;
686   ch = 1;
687   for (i = 0; i < GET_MODE_SIZE (mode); i++)
688     {
689       j = i;
690       if (WORDS_BIG_ENDIAN)
691         j = GET_MODE_SIZE (mode) - i - 1;
692       if (BYTES_BIG_ENDIAN != WORDS_BIG_ENDIAN
693           && GET_MODE_SIZE (mode) >= UNITS_PER_WORD)
694         j = j + UNITS_PER_WORD - 2 * (j % UNITS_PER_WORD) - 1;
695       j *= BITS_PER_UNIT;
696       gcc_assert (j < HOST_BITS_PER_DOUBLE_INT);
697
698       if (ch)
699         ch = (unsigned char) str[i];
700       c[j / HOST_BITS_PER_WIDE_INT] |= ch << (j % HOST_BITS_PER_WIDE_INT);
701     }
702   return immed_double_const (c[0], c[1], mode);
703 }
704
705 /* Cast a target constant CST to target CHAR and if that value fits into
706    host char type, return zero and put that value into variable pointed to by
707    P.  */
708
709 static int
710 target_char_cast (tree cst, char *p)
711 {
712   unsigned HOST_WIDE_INT val, hostval;
713
714   if (TREE_CODE (cst) != INTEGER_CST
715       || CHAR_TYPE_SIZE > HOST_BITS_PER_WIDE_INT)
716     return 1;
717
718   val = TREE_INT_CST_LOW (cst);
719   if (CHAR_TYPE_SIZE < HOST_BITS_PER_WIDE_INT)
720     val &= (((unsigned HOST_WIDE_INT) 1) << CHAR_TYPE_SIZE) - 1;
721
722   hostval = val;
723   if (HOST_BITS_PER_CHAR < HOST_BITS_PER_WIDE_INT)
724     hostval &= (((unsigned HOST_WIDE_INT) 1) << HOST_BITS_PER_CHAR) - 1;
725
726   if (val != hostval)
727     return 1;
728
729   *p = hostval;
730   return 0;
731 }
732
733 /* Similar to save_expr, but assumes that arbitrary code is not executed
734    in between the multiple evaluations.  In particular, we assume that a
735    non-addressable local variable will not be modified.  */
736
737 static tree
738 builtin_save_expr (tree exp)
739 {
740   if (TREE_CODE (exp) == SSA_NAME
741       || (TREE_ADDRESSABLE (exp) == 0
742           && (TREE_CODE (exp) == PARM_DECL
743               || (TREE_CODE (exp) == VAR_DECL && !TREE_STATIC (exp)))))
744     return exp;
745
746   return save_expr (exp);
747 }
748
749 /* Given TEM, a pointer to a stack frame, follow the dynamic chain COUNT
750    times to get the address of either a higher stack frame, or a return
751    address located within it (depending on FNDECL_CODE).  */
752
753 static rtx
754 expand_builtin_return_addr (enum built_in_function fndecl_code, int count)
755 {
756   int i;
757
758 #ifdef INITIAL_FRAME_ADDRESS_RTX
759   rtx tem = INITIAL_FRAME_ADDRESS_RTX;
760 #else
761   rtx tem;
762
763   /* For a zero count with __builtin_return_address, we don't care what
764      frame address we return, because target-specific definitions will
765      override us.  Therefore frame pointer elimination is OK, and using
766      the soft frame pointer is OK.
767
768      For a nonzero count, or a zero count with __builtin_frame_address,
769      we require a stable offset from the current frame pointer to the
770      previous one, so we must use the hard frame pointer, and
771      we must disable frame pointer elimination.  */
772   if (count == 0 && fndecl_code == BUILT_IN_RETURN_ADDRESS)
773     tem = frame_pointer_rtx;
774   else
775     {
776       tem = hard_frame_pointer_rtx;
777
778       /* Tell reload not to eliminate the frame pointer.  */
779       crtl->accesses_prior_frames = 1;
780     }
781 #endif
782
783   /* Some machines need special handling before we can access
784      arbitrary frames.  For example, on the SPARC, we must first flush
785      all register windows to the stack.  */
786 #ifdef SETUP_FRAME_ADDRESSES
787   if (count > 0)
788     SETUP_FRAME_ADDRESSES ();
789 #endif
790
791   /* On the SPARC, the return address is not in the frame, it is in a
792      register.  There is no way to access it off of the current frame
793      pointer, but it can be accessed off the previous frame pointer by
794      reading the value from the register window save area.  */
795 #ifdef RETURN_ADDR_IN_PREVIOUS_FRAME
796   if (fndecl_code == BUILT_IN_RETURN_ADDRESS)
797     count--;
798 #endif
799
800   /* Scan back COUNT frames to the specified frame.  */
801   for (i = 0; i < count; i++)
802     {
803       /* Assume the dynamic chain pointer is in the word that the
804          frame address points to, unless otherwise specified.  */
805 #ifdef DYNAMIC_CHAIN_ADDRESS
806       tem = DYNAMIC_CHAIN_ADDRESS (tem);
807 #endif
808       tem = memory_address (Pmode, tem);
809       tem = gen_frame_mem (Pmode, tem);
810       tem = copy_to_reg (tem);
811     }
812
813   /* For __builtin_frame_address, return what we've got.  But, on
814      the SPARC for example, we may have to add a bias.  */
815   if (fndecl_code == BUILT_IN_FRAME_ADDRESS)
816 #ifdef FRAME_ADDR_RTX
817     return FRAME_ADDR_RTX (tem);
818 #else
819     return tem;
820 #endif
821
822   /* For __builtin_return_address, get the return address from that frame.  */
823 #ifdef RETURN_ADDR_RTX
824   tem = RETURN_ADDR_RTX (count, tem);
825 #else
826   tem = memory_address (Pmode,
827                         plus_constant (Pmode, tem, GET_MODE_SIZE (Pmode)));
828   tem = gen_frame_mem (Pmode, tem);
829 #endif
830   return tem;
831 }
832
833 /* Alias set used for setjmp buffer.  */
834 static alias_set_type setjmp_alias_set = -1;
835
836 /* Construct the leading half of a __builtin_setjmp call.  Control will
837    return to RECEIVER_LABEL.  This is also called directly by the SJLJ
838    exception handling code.  */
839
840 void
841 expand_builtin_setjmp_setup (rtx buf_addr, rtx receiver_label)
842 {
843   enum machine_mode sa_mode = STACK_SAVEAREA_MODE (SAVE_NONLOCAL);
844   rtx stack_save;
845   rtx mem;
846
847   if (setjmp_alias_set == -1)
848     setjmp_alias_set = new_alias_set ();
849
850   buf_addr = convert_memory_address (Pmode, buf_addr);
851
852   buf_addr = force_reg (Pmode, force_operand (buf_addr, NULL_RTX));
853
854   /* We store the frame pointer and the address of receiver_label in
855      the buffer and use the rest of it for the stack save area, which
856      is machine-dependent.  */
857
858   mem = gen_rtx_MEM (Pmode, buf_addr);
859   set_mem_alias_set (mem, setjmp_alias_set);
860   emit_move_insn (mem, targetm.builtin_setjmp_frame_value ());
861
862   mem = gen_rtx_MEM (Pmode, plus_constant (Pmode, buf_addr,
863                                            GET_MODE_SIZE (Pmode))),
864   set_mem_alias_set (mem, setjmp_alias_set);
865
866   emit_move_insn (validize_mem (mem),
867                   force_reg (Pmode, gen_rtx_LABEL_REF (Pmode, receiver_label)));
868
869   stack_save = gen_rtx_MEM (sa_mode,
870                             plus_constant (Pmode, buf_addr,
871                                            2 * GET_MODE_SIZE (Pmode)));
872   set_mem_alias_set (stack_save, setjmp_alias_set);
873   emit_stack_save (SAVE_NONLOCAL, &stack_save);
874
875   /* If there is further processing to do, do it.  */
876 #ifdef HAVE_builtin_setjmp_setup
877   if (HAVE_builtin_setjmp_setup)
878     emit_insn (gen_builtin_setjmp_setup (buf_addr));
879 #endif
880
881   /* We have a nonlocal label.   */
882   cfun->has_nonlocal_label = 1;
883 }
884
885 /* Construct the trailing part of a __builtin_setjmp call.  This is
886    also called directly by the SJLJ exception handling code.  */
887
888 void
889 expand_builtin_setjmp_receiver (rtx receiver_label ATTRIBUTE_UNUSED)
890 {
891   rtx chain;
892
893   /* Clobber the FP when we get here, so we have to make sure it's
894      marked as used by this function.  */
895   emit_use (hard_frame_pointer_rtx);
896
897   /* Mark the static chain as clobbered here so life information
898      doesn't get messed up for it.  */
899   chain = targetm.calls.static_chain (current_function_decl, true);
900   if (chain && REG_P (chain))
901     emit_clobber (chain);
902
903   /* Now put in the code to restore the frame pointer, and argument
904      pointer, if needed.  */
905 #ifdef HAVE_nonlocal_goto
906   if (! HAVE_nonlocal_goto)
907 #endif
908     {
909       emit_move_insn (virtual_stack_vars_rtx, hard_frame_pointer_rtx);
910       /* This might change the hard frame pointer in ways that aren't
911          apparent to early optimization passes, so force a clobber.  */
912       emit_clobber (hard_frame_pointer_rtx);
913     }
914
915 #if !HARD_FRAME_POINTER_IS_ARG_POINTER
916   if (fixed_regs[ARG_POINTER_REGNUM])
917     {
918 #ifdef ELIMINABLE_REGS
919       size_t i;
920       static const struct elims {const int from, to;} elim_regs[] = ELIMINABLE_REGS;
921
922       for (i = 0; i < ARRAY_SIZE (elim_regs); i++)
923         if (elim_regs[i].from == ARG_POINTER_REGNUM
924             && elim_regs[i].to == HARD_FRAME_POINTER_REGNUM)
925           break;
926
927       if (i == ARRAY_SIZE (elim_regs))
928 #endif
929         {
930           /* Now restore our arg pointer from the address at which it
931              was saved in our stack frame.  */
932           emit_move_insn (crtl->args.internal_arg_pointer,
933                           copy_to_reg (get_arg_pointer_save_area ()));
934         }
935     }
936 #endif
937
938 #ifdef HAVE_builtin_setjmp_receiver
939   if (HAVE_builtin_setjmp_receiver)
940     emit_insn (gen_builtin_setjmp_receiver (receiver_label));
941   else
942 #endif
943 #ifdef HAVE_nonlocal_goto_receiver
944     if (HAVE_nonlocal_goto_receiver)
945       emit_insn (gen_nonlocal_goto_receiver ());
946     else
947 #endif
948       { /* Nothing */ }
949
950   /* We must not allow the code we just generated to be reordered by
951      scheduling.  Specifically, the update of the frame pointer must
952      happen immediately, not later.  Similarly, we must block
953      (frame-related) register values to be used across this code.  */
954   emit_insn (gen_blockage ());
955 }
956
957 /* __builtin_longjmp is passed a pointer to an array of five words (not
958    all will be used on all machines).  It operates similarly to the C
959    library function of the same name, but is more efficient.  Much of
960    the code below is copied from the handling of non-local gotos.  */
961
962 static void
963 expand_builtin_longjmp (rtx buf_addr, rtx value)
964 {
965   rtx fp, lab, stack, insn, last;
966   enum machine_mode sa_mode = STACK_SAVEAREA_MODE (SAVE_NONLOCAL);
967
968   /* DRAP is needed for stack realign if longjmp is expanded to current
969      function  */
970   if (SUPPORTS_STACK_ALIGNMENT)
971     crtl->need_drap = true;
972
973   if (setjmp_alias_set == -1)
974     setjmp_alias_set = new_alias_set ();
975
976   buf_addr = convert_memory_address (Pmode, buf_addr);
977
978   buf_addr = force_reg (Pmode, buf_addr);
979
980   /* We require that the user must pass a second argument of 1, because
981      that is what builtin_setjmp will return.  */
982   gcc_assert (value == const1_rtx);
983
984   last = get_last_insn ();
985 #ifdef HAVE_builtin_longjmp
986   if (HAVE_builtin_longjmp)
987     emit_insn (gen_builtin_longjmp (buf_addr));
988   else
989 #endif
990     {
991       fp = gen_rtx_MEM (Pmode, buf_addr);
992       lab = gen_rtx_MEM (Pmode, plus_constant (Pmode, buf_addr,
993                                                GET_MODE_SIZE (Pmode)));
994
995       stack = gen_rtx_MEM (sa_mode, plus_constant (Pmode, buf_addr,
996                                                    2 * GET_MODE_SIZE (Pmode)));
997       set_mem_alias_set (fp, setjmp_alias_set);
998       set_mem_alias_set (lab, setjmp_alias_set);
999       set_mem_alias_set (stack, setjmp_alias_set);
1000
1001       /* Pick up FP, label, and SP from the block and jump.  This code is
1002          from expand_goto in stmt.c; see there for detailed comments.  */
1003 #ifdef HAVE_nonlocal_goto
1004       if (HAVE_nonlocal_goto)
1005         /* We have to pass a value to the nonlocal_goto pattern that will
1006            get copied into the static_chain pointer, but it does not matter
1007            what that value is, because builtin_setjmp does not use it.  */
1008         emit_insn (gen_nonlocal_goto (value, lab, stack, fp));
1009       else
1010 #endif
1011         {
1012           lab = copy_to_reg (lab);
1013
1014           emit_clobber (gen_rtx_MEM (BLKmode, gen_rtx_SCRATCH (VOIDmode)));
1015           emit_clobber (gen_rtx_MEM (BLKmode, hard_frame_pointer_rtx));
1016
1017           emit_move_insn (hard_frame_pointer_rtx, fp);
1018           emit_stack_restore (SAVE_NONLOCAL, stack);
1019
1020           emit_use (hard_frame_pointer_rtx);
1021           emit_use (stack_pointer_rtx);
1022           emit_indirect_jump (lab);
1023         }
1024     }
1025
1026   /* Search backwards and mark the jump insn as a non-local goto.
1027      Note that this precludes the use of __builtin_longjmp to a
1028      __builtin_setjmp target in the same function.  However, we've
1029      already cautioned the user that these functions are for
1030      internal exception handling use only.  */
1031   for (insn = get_last_insn (); insn; insn = PREV_INSN (insn))
1032     {
1033       gcc_assert (insn != last);
1034
1035       if (JUMP_P (insn))
1036         {
1037           add_reg_note (insn, REG_NON_LOCAL_GOTO, const0_rtx);
1038           break;
1039         }
1040       else if (CALL_P (insn))
1041         break;
1042     }
1043 }
1044
1045 /* Expand a call to __builtin_nonlocal_goto.  We're passed the target label
1046    and the address of the save area.  */
1047
1048 static rtx
1049 expand_builtin_nonlocal_goto (tree exp)
1050 {
1051   tree t_label, t_save_area;
1052   rtx r_label, r_save_area, r_fp, r_sp, insn;
1053
1054   if (!validate_arglist (exp, POINTER_TYPE, POINTER_TYPE, VOID_TYPE))
1055     return NULL_RTX;
1056
1057   t_label = CALL_EXPR_ARG (exp, 0);
1058   t_save_area = CALL_EXPR_ARG (exp, 1);
1059
1060   r_label = expand_normal (t_label);
1061   r_label = convert_memory_address (Pmode, r_label);
1062   r_save_area = expand_normal (t_save_area);
1063   r_save_area = convert_memory_address (Pmode, r_save_area);
1064   /* Copy the address of the save location to a register just in case it was
1065      based on the frame pointer.   */
1066   r_save_area = copy_to_reg (r_save_area);
1067   r_fp = gen_rtx_MEM (Pmode, r_save_area);
1068   r_sp = gen_rtx_MEM (STACK_SAVEAREA_MODE (SAVE_NONLOCAL),
1069                       plus_constant (Pmode, r_save_area,
1070                                      GET_MODE_SIZE (Pmode)));
1071
1072   crtl->has_nonlocal_goto = 1;
1073
1074 #ifdef HAVE_nonlocal_goto
1075   /* ??? We no longer need to pass the static chain value, afaik.  */
1076   if (HAVE_nonlocal_goto)
1077     emit_insn (gen_nonlocal_goto (const0_rtx, r_label, r_sp, r_fp));
1078   else
1079 #endif
1080     {
1081       r_label = copy_to_reg (r_label);
1082
1083       emit_clobber (gen_rtx_MEM (BLKmode, gen_rtx_SCRATCH (VOIDmode)));
1084       emit_clobber (gen_rtx_MEM (BLKmode, hard_frame_pointer_rtx));
1085
1086       /* Restore frame pointer for containing function.  */
1087       emit_move_insn (hard_frame_pointer_rtx, r_fp);
1088       emit_stack_restore (SAVE_NONLOCAL, r_sp);
1089
1090       /* USE of hard_frame_pointer_rtx added for consistency;
1091          not clear if really needed.  */
1092       emit_use (hard_frame_pointer_rtx);
1093       emit_use (stack_pointer_rtx);
1094
1095       /* If the architecture is using a GP register, we must
1096          conservatively assume that the target function makes use of it.
1097          The prologue of functions with nonlocal gotos must therefore
1098          initialize the GP register to the appropriate value, and we
1099          must then make sure that this value is live at the point
1100          of the jump.  (Note that this doesn't necessarily apply
1101          to targets with a nonlocal_goto pattern; they are free
1102          to implement it in their own way.  Note also that this is
1103          a no-op if the GP register is a global invariant.)  */
1104       if ((unsigned) PIC_OFFSET_TABLE_REGNUM != INVALID_REGNUM
1105           && fixed_regs[PIC_OFFSET_TABLE_REGNUM])
1106         emit_use (pic_offset_table_rtx);
1107
1108       emit_indirect_jump (r_label);
1109     }
1110
1111   /* Search backwards to the jump insn and mark it as a
1112      non-local goto.  */
1113   for (insn = get_last_insn (); insn; insn = PREV_INSN (insn))
1114     {
1115       if (JUMP_P (insn))
1116         {
1117           add_reg_note (insn, REG_NON_LOCAL_GOTO, const0_rtx);
1118           break;
1119         }
1120       else if (CALL_P (insn))
1121         break;
1122     }
1123
1124   return const0_rtx;
1125 }
1126
1127 /* __builtin_update_setjmp_buf is passed a pointer to an array of five words
1128    (not all will be used on all machines) that was passed to __builtin_setjmp.
1129    It updates the stack pointer in that block to correspond to the current
1130    stack pointer.  */
1131
1132 static void
1133 expand_builtin_update_setjmp_buf (rtx buf_addr)
1134 {
1135   enum machine_mode sa_mode = STACK_SAVEAREA_MODE (SAVE_NONLOCAL);
1136   rtx stack_save
1137     = gen_rtx_MEM (sa_mode,
1138                    memory_address
1139                    (sa_mode,
1140                     plus_constant (Pmode, buf_addr,
1141                                    2 * GET_MODE_SIZE (Pmode))));
1142
1143   emit_stack_save (SAVE_NONLOCAL, &stack_save);
1144 }
1145
1146 /* Expand a call to __builtin_prefetch.  For a target that does not support
1147    data prefetch, evaluate the memory address argument in case it has side
1148    effects.  */
1149
1150 static void
1151 expand_builtin_prefetch (tree exp)
1152 {
1153   tree arg0, arg1, arg2;
1154   int nargs;
1155   rtx op0, op1, op2;
1156
1157   if (!validate_arglist (exp, POINTER_TYPE, 0))
1158     return;
1159
1160   arg0 = CALL_EXPR_ARG (exp, 0);
1161
1162   /* Arguments 1 and 2 are optional; argument 1 (read/write) defaults to
1163      zero (read) and argument 2 (locality) defaults to 3 (high degree of
1164      locality).  */
1165   nargs = call_expr_nargs (exp);
1166   if (nargs > 1)
1167     arg1 = CALL_EXPR_ARG (exp, 1);
1168   else
1169     arg1 = integer_zero_node;
1170   if (nargs > 2)
1171     arg2 = CALL_EXPR_ARG (exp, 2);
1172   else
1173     arg2 = integer_three_node;
1174
1175   /* Argument 0 is an address.  */
1176   op0 = expand_expr (arg0, NULL_RTX, Pmode, EXPAND_NORMAL);
1177
1178   /* Argument 1 (read/write flag) must be a compile-time constant int.  */
1179   if (TREE_CODE (arg1) != INTEGER_CST)
1180     {
1181       error ("second argument to %<__builtin_prefetch%> must be a constant");
1182       arg1 = integer_zero_node;
1183     }
1184   op1 = expand_normal (arg1);
1185   /* Argument 1 must be either zero or one.  */
1186   if (INTVAL (op1) != 0 && INTVAL (op1) != 1)
1187     {
1188       warning (0, "invalid second argument to %<__builtin_prefetch%>;"
1189                " using zero");
1190       op1 = const0_rtx;
1191     }
1192
1193   /* Argument 2 (locality) must be a compile-time constant int.  */
1194   if (TREE_CODE (arg2) != INTEGER_CST)
1195     {
1196       error ("third argument to %<__builtin_prefetch%> must be a constant");
1197       arg2 = integer_zero_node;
1198     }
1199   op2 = expand_normal (arg2);
1200   /* Argument 2 must be 0, 1, 2, or 3.  */
1201   if (INTVAL (op2) < 0 || INTVAL (op2) > 3)
1202     {
1203       warning (0, "invalid third argument to %<__builtin_prefetch%>; using zero");
1204       op2 = const0_rtx;
1205     }
1206
1207 #ifdef HAVE_prefetch
1208   if (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 (CODE_FOR_prefetch, 3, ops))
1216         return;
1217     }
1218 #endif
1219
1220   /* Don't do anything with direct references to volatile memory, but
1221      generate code to handle other side effects.  */
1222   if (!MEM_P (op0) && side_effects_p (op0))
1223     emit_insn (op0);
1224 }
1225
1226 /* Get a MEM rtx for expression EXP which is the address of an operand
1227    to be used in a string instruction (cmpstrsi, movmemsi, ..).  LEN is
1228    the maximum length of the block of memory that might be accessed or
1229    NULL if unknown.  */
1230
1231 static rtx
1232 get_memory_rtx (tree exp, tree len)
1233 {
1234   tree orig_exp = exp;
1235   rtx addr, mem;
1236
1237   /* When EXP is not resolved SAVE_EXPR, MEM_ATTRS can be still derived
1238      from its expression, for expr->a.b only <variable>.a.b is recorded.  */
1239   if (TREE_CODE (exp) == SAVE_EXPR && !SAVE_EXPR_RESOLVED_P (exp))
1240     exp = TREE_OPERAND (exp, 0);
1241
1242   addr = expand_expr (orig_exp, NULL_RTX, ptr_mode, EXPAND_NORMAL);
1243   mem = gen_rtx_MEM (BLKmode, memory_address (BLKmode, addr));
1244
1245   /* Get an expression we can use to find the attributes to assign to MEM.
1246      First remove any nops.  */
1247   while (CONVERT_EXPR_P (exp)
1248          && POINTER_TYPE_P (TREE_TYPE (TREE_OPERAND (exp, 0))))
1249     exp = TREE_OPERAND (exp, 0);
1250
1251   /* Build a MEM_REF representing the whole accessed area as a byte blob,
1252      (as builtin stringops may alias with anything).  */
1253   exp = fold_build2 (MEM_REF,
1254                      build_array_type (char_type_node,
1255                                        build_range_type (sizetype,
1256                                                          size_one_node, len)),
1257                      exp, build_int_cst (ptr_type_node, 0));
1258
1259   /* If the MEM_REF has no acceptable address, try to get the base object
1260      from the original address we got, and build an all-aliasing
1261      unknown-sized access to that one.  */
1262   if (is_gimple_mem_ref_addr (TREE_OPERAND (exp, 0)))
1263     set_mem_attributes (mem, exp, 0);
1264   else if (TREE_CODE (TREE_OPERAND (exp, 0)) == ADDR_EXPR
1265            && (exp = get_base_address (TREE_OPERAND (TREE_OPERAND (exp, 0),
1266                                                      0))))
1267     {
1268       exp = build_fold_addr_expr (exp);
1269       exp = fold_build2 (MEM_REF,
1270                          build_array_type (char_type_node,
1271                                            build_range_type (sizetype,
1272                                                              size_zero_node,
1273                                                              NULL)),
1274                          exp, build_int_cst (ptr_type_node, 0));
1275       set_mem_attributes (mem, exp, 0);
1276     }
1277   set_mem_alias_set (mem, 0);
1278   return mem;
1279 }
1280 \f
1281 /* Built-in functions to perform an untyped call and return.  */
1282
1283 #define apply_args_mode \
1284   (this_target_builtins->x_apply_args_mode)
1285 #define apply_result_mode \
1286   (this_target_builtins->x_apply_result_mode)
1287
1288 /* Return the size required for the block returned by __builtin_apply_args,
1289    and initialize apply_args_mode.  */
1290
1291 static int
1292 apply_args_size (void)
1293 {
1294   static int size = -1;
1295   int align;
1296   unsigned int regno;
1297   enum machine_mode mode;
1298
1299   /* The values computed by this function never change.  */
1300   if (size < 0)
1301     {
1302       /* The first value is the incoming arg-pointer.  */
1303       size = GET_MODE_SIZE (Pmode);
1304
1305       /* The second value is the structure value address unless this is
1306          passed as an "invisible" first argument.  */
1307       if (targetm.calls.struct_value_rtx (cfun ? TREE_TYPE (cfun->decl) : 0, 0))
1308         size += GET_MODE_SIZE (Pmode);
1309
1310       for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
1311         if (FUNCTION_ARG_REGNO_P (regno))
1312           {
1313             mode = targetm.calls.get_raw_arg_mode (regno);
1314
1315             gcc_assert (mode != VOIDmode);
1316
1317             align = GET_MODE_ALIGNMENT (mode) / BITS_PER_UNIT;
1318             if (size % align != 0)
1319               size = CEIL (size, align) * align;
1320             size += GET_MODE_SIZE (mode);
1321             apply_args_mode[regno] = mode;
1322           }
1323         else
1324           {
1325             apply_args_mode[regno] = VOIDmode;
1326           }
1327     }
1328   return size;
1329 }
1330
1331 /* Return the size required for the block returned by __builtin_apply,
1332    and initialize apply_result_mode.  */
1333
1334 static int
1335 apply_result_size (void)
1336 {
1337   static int size = -1;
1338   int align, regno;
1339   enum machine_mode mode;
1340
1341   /* The values computed by this function never change.  */
1342   if (size < 0)
1343     {
1344       size = 0;
1345
1346       for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
1347         if (targetm.calls.function_value_regno_p (regno))
1348           {
1349             mode = targetm.calls.get_raw_result_mode (regno);
1350
1351             gcc_assert (mode != VOIDmode);
1352
1353             align = GET_MODE_ALIGNMENT (mode) / BITS_PER_UNIT;
1354             if (size % align != 0)
1355               size = CEIL (size, align) * align;
1356             size += GET_MODE_SIZE (mode);
1357             apply_result_mode[regno] = mode;
1358           }
1359         else
1360           apply_result_mode[regno] = VOIDmode;
1361
1362       /* Allow targets that use untyped_call and untyped_return to override
1363          the size so that machine-specific information can be stored here.  */
1364 #ifdef APPLY_RESULT_SIZE
1365       size = APPLY_RESULT_SIZE;
1366 #endif
1367     }
1368   return size;
1369 }
1370
1371 #if defined (HAVE_untyped_call) || defined (HAVE_untyped_return)
1372 /* Create a vector describing the result block RESULT.  If SAVEP is true,
1373    the result block is used to save the values; otherwise it is used to
1374    restore the values.  */
1375
1376 static rtx
1377 result_vector (int savep, rtx result)
1378 {
1379   int regno, size, align, nelts;
1380   enum machine_mode mode;
1381   rtx reg, mem;
1382   rtx *savevec = XALLOCAVEC (rtx, FIRST_PSEUDO_REGISTER);
1383
1384   size = nelts = 0;
1385   for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
1386     if ((mode = apply_result_mode[regno]) != VOIDmode)
1387       {
1388         align = GET_MODE_ALIGNMENT (mode) / BITS_PER_UNIT;
1389         if (size % align != 0)
1390           size = CEIL (size, align) * align;
1391         reg = gen_rtx_REG (mode, savep ? regno : INCOMING_REGNO (regno));
1392         mem = adjust_address (result, mode, size);
1393         savevec[nelts++] = (savep
1394                             ? gen_rtx_SET (VOIDmode, mem, reg)
1395                             : gen_rtx_SET (VOIDmode, reg, mem));
1396         size += GET_MODE_SIZE (mode);
1397       }
1398   return gen_rtx_PARALLEL (VOIDmode, gen_rtvec_v (nelts, savevec));
1399 }
1400 #endif /* HAVE_untyped_call or HAVE_untyped_return */
1401
1402 /* Save the state required to perform an untyped call with the same
1403    arguments as were passed to the current function.  */
1404
1405 static rtx
1406 expand_builtin_apply_args_1 (void)
1407 {
1408   rtx registers, tem;
1409   int size, align, regno;
1410   enum machine_mode mode;
1411   rtx struct_incoming_value = targetm.calls.struct_value_rtx (cfun ? TREE_TYPE (cfun->decl) : 0, 1);
1412
1413   /* Create a block where the arg-pointer, structure value address,
1414      and argument registers can be saved.  */
1415   registers = assign_stack_local (BLKmode, apply_args_size (), -1);
1416
1417   /* Walk past the arg-pointer and structure value address.  */
1418   size = GET_MODE_SIZE (Pmode);
1419   if (targetm.calls.struct_value_rtx (cfun ? TREE_TYPE (cfun->decl) : 0, 0))
1420     size += GET_MODE_SIZE (Pmode);
1421
1422   /* Save each register used in calling a function to the block.  */
1423   for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
1424     if ((mode = apply_args_mode[regno]) != VOIDmode)
1425       {
1426         align = GET_MODE_ALIGNMENT (mode) / BITS_PER_UNIT;
1427         if (size % align != 0)
1428           size = CEIL (size, align) * align;
1429
1430         tem = gen_rtx_REG (mode, INCOMING_REGNO (regno));
1431
1432         emit_move_insn (adjust_address (registers, mode, size), tem);
1433         size += GET_MODE_SIZE (mode);
1434       }
1435
1436   /* Save the arg pointer to the block.  */
1437   tem = copy_to_reg (crtl->args.internal_arg_pointer);
1438 #ifdef STACK_GROWS_DOWNWARD
1439   /* We need the pointer as the caller actually passed them to us, not
1440      as we might have pretended they were passed.  Make sure it's a valid
1441      operand, as emit_move_insn isn't expected to handle a PLUS.  */
1442   tem
1443     = force_operand (plus_constant (Pmode, tem, crtl->args.pretend_args_size),
1444                      NULL_RTX);
1445 #endif
1446   emit_move_insn (adjust_address (registers, Pmode, 0), tem);
1447
1448   size = GET_MODE_SIZE (Pmode);
1449
1450   /* Save the structure value address unless this is passed as an
1451      "invisible" first argument.  */
1452   if (struct_incoming_value)
1453     {
1454       emit_move_insn (adjust_address (registers, Pmode, size),
1455                       copy_to_reg (struct_incoming_value));
1456       size += GET_MODE_SIZE (Pmode);
1457     }
1458
1459   /* Return the address of the block.  */
1460   return copy_addr_to_reg (XEXP (registers, 0));
1461 }
1462
1463 /* __builtin_apply_args returns block of memory allocated on
1464    the stack into which is stored the arg pointer, structure
1465    value address, static chain, and all the registers that might
1466    possibly be used in performing a function call.  The code is
1467    moved to the start of the function so the incoming values are
1468    saved.  */
1469
1470 static rtx
1471 expand_builtin_apply_args (void)
1472 {
1473   /* Don't do __builtin_apply_args more than once in a function.
1474      Save the result of the first call and reuse it.  */
1475   if (apply_args_value != 0)
1476     return apply_args_value;
1477   {
1478     /* When this function is called, it means that registers must be
1479        saved on entry to this function.  So we migrate the
1480        call to the first insn of this function.  */
1481     rtx temp;
1482     rtx seq;
1483
1484     start_sequence ();
1485     temp = expand_builtin_apply_args_1 ();
1486     seq = get_insns ();
1487     end_sequence ();
1488
1489     apply_args_value = temp;
1490
1491     /* Put the insns after the NOTE that starts the function.
1492        If this is inside a start_sequence, make the outer-level insn
1493        chain current, so the code is placed at the start of the
1494        function.  If internal_arg_pointer is a non-virtual pseudo,
1495        it needs to be placed after the function that initializes
1496        that pseudo.  */
1497     push_topmost_sequence ();
1498     if (REG_P (crtl->args.internal_arg_pointer)
1499         && REGNO (crtl->args.internal_arg_pointer) > LAST_VIRTUAL_REGISTER)
1500       emit_insn_before (seq, parm_birth_insn);
1501     else
1502       emit_insn_before (seq, NEXT_INSN (entry_of_function ()));
1503     pop_topmost_sequence ();
1504     return temp;
1505   }
1506 }
1507
1508 /* Perform an untyped call and save the state required to perform an
1509    untyped return of whatever value was returned by the given function.  */
1510
1511 static rtx
1512 expand_builtin_apply (rtx function, rtx arguments, rtx argsize)
1513 {
1514   int size, align, regno;
1515   enum machine_mode mode;
1516   rtx incoming_args, result, reg, dest, src, call_insn;
1517   rtx old_stack_level = 0;
1518   rtx call_fusage = 0;
1519   rtx struct_value = targetm.calls.struct_value_rtx (cfun ? TREE_TYPE (cfun->decl) : 0, 0);
1520
1521   arguments = convert_memory_address (Pmode, arguments);
1522
1523   /* Create a block where the return registers can be saved.  */
1524   result = assign_stack_local (BLKmode, apply_result_size (), -1);
1525
1526   /* Fetch the arg pointer from the ARGUMENTS block.  */
1527   incoming_args = gen_reg_rtx (Pmode);
1528   emit_move_insn (incoming_args, gen_rtx_MEM (Pmode, arguments));
1529 #ifndef STACK_GROWS_DOWNWARD
1530   incoming_args = expand_simple_binop (Pmode, MINUS, incoming_args, argsize,
1531                                        incoming_args, 0, OPTAB_LIB_WIDEN);
1532 #endif
1533
1534   /* Push a new argument block and copy the arguments.  Do not allow
1535      the (potential) memcpy call below to interfere with our stack
1536      manipulations.  */
1537   do_pending_stack_adjust ();
1538   NO_DEFER_POP;
1539
1540   /* Save the stack with nonlocal if available.  */
1541 #ifdef HAVE_save_stack_nonlocal
1542   if (HAVE_save_stack_nonlocal)
1543     emit_stack_save (SAVE_NONLOCAL, &old_stack_level);
1544   else
1545 #endif
1546     emit_stack_save (SAVE_BLOCK, &old_stack_level);
1547
1548   /* Allocate a block of memory onto the stack and copy the memory
1549      arguments to the outgoing arguments address.  We can pass TRUE
1550      as the 4th argument because we just saved the stack pointer
1551      and will restore it right after the call.  */
1552   allocate_dynamic_stack_space (argsize, 0, BIGGEST_ALIGNMENT, true);
1553
1554   /* Set DRAP flag to true, even though allocate_dynamic_stack_space
1555      may have already set current_function_calls_alloca to true.
1556      current_function_calls_alloca won't be set if argsize is zero,
1557      so we have to guarantee need_drap is true here.  */
1558   if (SUPPORTS_STACK_ALIGNMENT)
1559     crtl->need_drap = true;
1560
1561   dest = virtual_outgoing_args_rtx;
1562 #ifndef STACK_GROWS_DOWNWARD
1563   if (CONST_INT_P (argsize))
1564     dest = plus_constant (Pmode, dest, -INTVAL (argsize));
1565   else
1566     dest = gen_rtx_PLUS (Pmode, dest, negate_rtx (Pmode, argsize));
1567 #endif
1568   dest = gen_rtx_MEM (BLKmode, dest);
1569   set_mem_align (dest, PARM_BOUNDARY);
1570   src = gen_rtx_MEM (BLKmode, incoming_args);
1571   set_mem_align (src, PARM_BOUNDARY);
1572   emit_block_move (dest, src, argsize, BLOCK_OP_NORMAL);
1573
1574   /* Refer to the argument block.  */
1575   apply_args_size ();
1576   arguments = gen_rtx_MEM (BLKmode, arguments);
1577   set_mem_align (arguments, PARM_BOUNDARY);
1578
1579   /* Walk past the arg-pointer and structure value address.  */
1580   size = GET_MODE_SIZE (Pmode);
1581   if (struct_value)
1582     size += GET_MODE_SIZE (Pmode);
1583
1584   /* Restore each of the registers previously saved.  Make USE insns
1585      for each of these registers for use in making the call.  */
1586   for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
1587     if ((mode = apply_args_mode[regno]) != VOIDmode)
1588       {
1589         align = GET_MODE_ALIGNMENT (mode) / BITS_PER_UNIT;
1590         if (size % align != 0)
1591           size = CEIL (size, align) * align;
1592         reg = gen_rtx_REG (mode, regno);
1593         emit_move_insn (reg, adjust_address (arguments, mode, size));
1594         use_reg (&call_fusage, reg);
1595         size += GET_MODE_SIZE (mode);
1596       }
1597
1598   /* Restore the structure value address unless this is passed as an
1599      "invisible" first argument.  */
1600   size = GET_MODE_SIZE (Pmode);
1601   if (struct_value)
1602     {
1603       rtx value = gen_reg_rtx (Pmode);
1604       emit_move_insn (value, adjust_address (arguments, Pmode, size));
1605       emit_move_insn (struct_value, value);
1606       if (REG_P (struct_value))
1607         use_reg (&call_fusage, struct_value);
1608       size += GET_MODE_SIZE (Pmode);
1609     }
1610
1611   /* All arguments and registers used for the call are set up by now!  */
1612   function = prepare_call_address (NULL, function, NULL, &call_fusage, 0, 0);
1613
1614   /* Ensure address is valid.  SYMBOL_REF is already valid, so no need,
1615      and we don't want to load it into a register as an optimization,
1616      because prepare_call_address already did it if it should be done.  */
1617   if (GET_CODE (function) != SYMBOL_REF)
1618     function = memory_address (FUNCTION_MODE, function);
1619
1620   /* Generate the actual call instruction and save the return value.  */
1621 #ifdef HAVE_untyped_call
1622   if (HAVE_untyped_call)
1623     emit_call_insn (gen_untyped_call (gen_rtx_MEM (FUNCTION_MODE, function),
1624                                       result, result_vector (1, result)));
1625   else
1626 #endif
1627 #ifdef HAVE_call_value
1628   if (HAVE_call_value)
1629     {
1630       rtx valreg = 0;
1631
1632       /* Locate the unique return register.  It is not possible to
1633          express a call that sets more than one return register using
1634          call_value; use untyped_call for that.  In fact, untyped_call
1635          only needs to save the return registers in the given block.  */
1636       for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
1637         if ((mode = apply_result_mode[regno]) != VOIDmode)
1638           {
1639             gcc_assert (!valreg); /* HAVE_untyped_call required.  */
1640
1641             valreg = gen_rtx_REG (mode, regno);
1642           }
1643
1644       emit_call_insn (GEN_CALL_VALUE (valreg,
1645                                       gen_rtx_MEM (FUNCTION_MODE, function),
1646                                       const0_rtx, NULL_RTX, const0_rtx));
1647
1648       emit_move_insn (adjust_address (result, GET_MODE (valreg), 0), valreg);
1649     }
1650   else
1651 #endif
1652     gcc_unreachable ();
1653
1654   /* Find the CALL insn we just emitted, and attach the register usage
1655      information.  */
1656   call_insn = last_call_insn ();
1657   add_function_usage_to (call_insn, call_fusage);
1658
1659   /* Restore the stack.  */
1660 #ifdef HAVE_save_stack_nonlocal
1661   if (HAVE_save_stack_nonlocal)
1662     emit_stack_restore (SAVE_NONLOCAL, old_stack_level);
1663   else
1664 #endif
1665     emit_stack_restore (SAVE_BLOCK, old_stack_level);
1666   fixup_args_size_notes (call_insn, get_last_insn(), 0);
1667
1668   OK_DEFER_POP;
1669
1670   /* Return the address of the result block.  */
1671   result = copy_addr_to_reg (XEXP (result, 0));
1672   return convert_memory_address (ptr_mode, result);
1673 }
1674
1675 /* Perform an untyped return.  */
1676
1677 static void
1678 expand_builtin_return (rtx result)
1679 {
1680   int size, align, regno;
1681   enum machine_mode mode;
1682   rtx reg;
1683   rtx call_fusage = 0;
1684
1685   result = convert_memory_address (Pmode, result);
1686
1687   apply_result_size ();
1688   result = gen_rtx_MEM (BLKmode, result);
1689
1690 #ifdef HAVE_untyped_return
1691   if (HAVE_untyped_return)
1692     {
1693       emit_jump_insn (gen_untyped_return (result, result_vector (0, result)));
1694       emit_barrier ();
1695       return;
1696     }
1697 #endif
1698
1699   /* Restore the return value and note that each value is used.  */
1700   size = 0;
1701   for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
1702     if ((mode = apply_result_mode[regno]) != VOIDmode)
1703       {
1704         align = GET_MODE_ALIGNMENT (mode) / BITS_PER_UNIT;
1705         if (size % align != 0)
1706           size = CEIL (size, align) * align;
1707         reg = gen_rtx_REG (mode, INCOMING_REGNO (regno));
1708         emit_move_insn (reg, adjust_address (result, mode, size));
1709
1710         push_to_sequence (call_fusage);
1711         emit_use (reg);
1712         call_fusage = get_insns ();
1713         end_sequence ();
1714         size += GET_MODE_SIZE (mode);
1715       }
1716
1717   /* Put the USE insns before the return.  */
1718   emit_insn (call_fusage);
1719
1720   /* Return whatever values was restored by jumping directly to the end
1721      of the function.  */
1722   expand_naked_return ();
1723 }
1724
1725 /* Used by expand_builtin_classify_type and fold_builtin_classify_type.  */
1726
1727 static enum type_class
1728 type_to_class (tree type)
1729 {
1730   switch (TREE_CODE (type))
1731     {
1732     case VOID_TYPE:        return void_type_class;
1733     case INTEGER_TYPE:     return integer_type_class;
1734     case ENUMERAL_TYPE:    return enumeral_type_class;
1735     case BOOLEAN_TYPE:     return boolean_type_class;
1736     case POINTER_TYPE:     return pointer_type_class;
1737     case REFERENCE_TYPE:   return reference_type_class;
1738     case OFFSET_TYPE:      return offset_type_class;
1739     case REAL_TYPE:        return real_type_class;
1740     case COMPLEX_TYPE:     return complex_type_class;
1741     case FUNCTION_TYPE:    return function_type_class;
1742     case METHOD_TYPE:      return method_type_class;
1743     case RECORD_TYPE:      return record_type_class;
1744     case UNION_TYPE:
1745     case QUAL_UNION_TYPE:  return union_type_class;
1746     case ARRAY_TYPE:       return (TYPE_STRING_FLAG (type)
1747                                    ? string_type_class : array_type_class);
1748     case LANG_TYPE:        return lang_type_class;
1749     default:               return no_type_class;
1750     }
1751 }
1752
1753 /* Expand a call EXP to __builtin_classify_type.  */
1754
1755 static rtx
1756 expand_builtin_classify_type (tree exp)
1757 {
1758   if (call_expr_nargs (exp))
1759     return GEN_INT (type_to_class (TREE_TYPE (CALL_EXPR_ARG (exp, 0))));
1760   return GEN_INT (no_type_class);
1761 }
1762
1763 /* This helper macro, meant to be used in mathfn_built_in below,
1764    determines which among a set of three builtin math functions is
1765    appropriate for a given type mode.  The `F' and `L' cases are
1766    automatically generated from the `double' case.  */
1767 #define CASE_MATHFN(BUILT_IN_MATHFN) \
1768   case BUILT_IN_MATHFN: case BUILT_IN_MATHFN##F: case BUILT_IN_MATHFN##L: \
1769   fcode = BUILT_IN_MATHFN; fcodef = BUILT_IN_MATHFN##F ; \
1770   fcodel = BUILT_IN_MATHFN##L ; break;
1771 /* Similar to above, but appends _R after any F/L suffix.  */
1772 #define CASE_MATHFN_REENT(BUILT_IN_MATHFN) \
1773   case BUILT_IN_MATHFN##_R: case BUILT_IN_MATHFN##F_R: case BUILT_IN_MATHFN##L_R: \
1774   fcode = BUILT_IN_MATHFN##_R; fcodef = BUILT_IN_MATHFN##F_R ; \
1775   fcodel = BUILT_IN_MATHFN##L_R ; break;
1776
1777 /* Return mathematic function equivalent to FN but operating directly on TYPE,
1778    if available.  If IMPLICIT is true use the implicit builtin declaration,
1779    otherwise use the explicit declaration.  If we can't do the conversion,
1780    return zero.  */
1781
1782 static tree
1783 mathfn_built_in_1 (tree type, enum built_in_function fn, bool implicit_p)
1784 {
1785   enum built_in_function fcode, fcodef, fcodel, fcode2;
1786
1787   switch (fn)
1788     {
1789       CASE_MATHFN (BUILT_IN_ACOS)
1790       CASE_MATHFN (BUILT_IN_ACOSH)
1791       CASE_MATHFN (BUILT_IN_ASIN)
1792       CASE_MATHFN (BUILT_IN_ASINH)
1793       CASE_MATHFN (BUILT_IN_ATAN)
1794       CASE_MATHFN (BUILT_IN_ATAN2)
1795       CASE_MATHFN (BUILT_IN_ATANH)
1796       CASE_MATHFN (BUILT_IN_CBRT)
1797       CASE_MATHFN (BUILT_IN_CEIL)
1798       CASE_MATHFN (BUILT_IN_CEXPI)
1799       CASE_MATHFN (BUILT_IN_COPYSIGN)
1800       CASE_MATHFN (BUILT_IN_COS)
1801       CASE_MATHFN (BUILT_IN_COSH)
1802       CASE_MATHFN (BUILT_IN_DREM)
1803       CASE_MATHFN (BUILT_IN_ERF)
1804       CASE_MATHFN (BUILT_IN_ERFC)
1805       CASE_MATHFN (BUILT_IN_EXP)
1806       CASE_MATHFN (BUILT_IN_EXP10)
1807       CASE_MATHFN (BUILT_IN_EXP2)
1808       CASE_MATHFN (BUILT_IN_EXPM1)
1809       CASE_MATHFN (BUILT_IN_FABS)
1810       CASE_MATHFN (BUILT_IN_FDIM)
1811       CASE_MATHFN (BUILT_IN_FLOOR)
1812       CASE_MATHFN (BUILT_IN_FMA)
1813       CASE_MATHFN (BUILT_IN_FMAX)
1814       CASE_MATHFN (BUILT_IN_FMIN)
1815       CASE_MATHFN (BUILT_IN_FMOD)
1816       CASE_MATHFN (BUILT_IN_FREXP)
1817       CASE_MATHFN (BUILT_IN_GAMMA)
1818       CASE_MATHFN_REENT (BUILT_IN_GAMMA) /* GAMMA_R */
1819       CASE_MATHFN (BUILT_IN_HUGE_VAL)
1820       CASE_MATHFN (BUILT_IN_HYPOT)
1821       CASE_MATHFN (BUILT_IN_ILOGB)
1822       CASE_MATHFN (BUILT_IN_ICEIL)
1823       CASE_MATHFN (BUILT_IN_IFLOOR)
1824       CASE_MATHFN (BUILT_IN_INF)
1825       CASE_MATHFN (BUILT_IN_IRINT)
1826       CASE_MATHFN (BUILT_IN_IROUND)
1827       CASE_MATHFN (BUILT_IN_ISINF)
1828       CASE_MATHFN (BUILT_IN_J0)
1829       CASE_MATHFN (BUILT_IN_J1)
1830       CASE_MATHFN (BUILT_IN_JN)
1831       CASE_MATHFN (BUILT_IN_LCEIL)
1832       CASE_MATHFN (BUILT_IN_LDEXP)
1833       CASE_MATHFN (BUILT_IN_LFLOOR)
1834       CASE_MATHFN (BUILT_IN_LGAMMA)
1835       CASE_MATHFN_REENT (BUILT_IN_LGAMMA) /* LGAMMA_R */
1836       CASE_MATHFN (BUILT_IN_LLCEIL)
1837       CASE_MATHFN (BUILT_IN_LLFLOOR)
1838       CASE_MATHFN (BUILT_IN_LLRINT)
1839       CASE_MATHFN (BUILT_IN_LLROUND)
1840       CASE_MATHFN (BUILT_IN_LOG)
1841       CASE_MATHFN (BUILT_IN_LOG10)
1842       CASE_MATHFN (BUILT_IN_LOG1P)
1843       CASE_MATHFN (BUILT_IN_LOG2)
1844       CASE_MATHFN (BUILT_IN_LOGB)
1845       CASE_MATHFN (BUILT_IN_LRINT)
1846       CASE_MATHFN (BUILT_IN_LROUND)
1847       CASE_MATHFN (BUILT_IN_MODF)
1848       CASE_MATHFN (BUILT_IN_NAN)
1849       CASE_MATHFN (BUILT_IN_NANS)
1850       CASE_MATHFN (BUILT_IN_NEARBYINT)
1851       CASE_MATHFN (BUILT_IN_NEXTAFTER)
1852       CASE_MATHFN (BUILT_IN_NEXTTOWARD)
1853       CASE_MATHFN (BUILT_IN_POW)
1854       CASE_MATHFN (BUILT_IN_POWI)
1855       CASE_MATHFN (BUILT_IN_POW10)
1856       CASE_MATHFN (BUILT_IN_REMAINDER)
1857       CASE_MATHFN (BUILT_IN_REMQUO)
1858       CASE_MATHFN (BUILT_IN_RINT)
1859       CASE_MATHFN (BUILT_IN_ROUND)
1860       CASE_MATHFN (BUILT_IN_SCALB)
1861       CASE_MATHFN (BUILT_IN_SCALBLN)
1862       CASE_MATHFN (BUILT_IN_SCALBN)
1863       CASE_MATHFN (BUILT_IN_SIGNBIT)
1864       CASE_MATHFN (BUILT_IN_SIGNIFICAND)
1865       CASE_MATHFN (BUILT_IN_SIN)
1866       CASE_MATHFN (BUILT_IN_SINCOS)
1867       CASE_MATHFN (BUILT_IN_SINH)
1868       CASE_MATHFN (BUILT_IN_SQRT)
1869       CASE_MATHFN (BUILT_IN_TAN)
1870       CASE_MATHFN (BUILT_IN_TANH)
1871       CASE_MATHFN (BUILT_IN_TGAMMA)
1872       CASE_MATHFN (BUILT_IN_TRUNC)
1873       CASE_MATHFN (BUILT_IN_Y0)
1874       CASE_MATHFN (BUILT_IN_Y1)
1875       CASE_MATHFN (BUILT_IN_YN)
1876
1877       default:
1878         return NULL_TREE;
1879       }
1880
1881   if (TYPE_MAIN_VARIANT (type) == double_type_node)
1882     fcode2 = fcode;
1883   else if (TYPE_MAIN_VARIANT (type) == float_type_node)
1884     fcode2 = fcodef;
1885   else if (TYPE_MAIN_VARIANT (type) == long_double_type_node)
1886     fcode2 = fcodel;
1887   else
1888     return NULL_TREE;
1889
1890   if (implicit_p && !builtin_decl_implicit_p (fcode2))
1891     return NULL_TREE;
1892
1893   return builtin_decl_explicit (fcode2);
1894 }
1895
1896 /* Like mathfn_built_in_1(), but always use the implicit array.  */
1897
1898 tree
1899 mathfn_built_in (tree type, enum built_in_function fn)
1900 {
1901   return mathfn_built_in_1 (type, fn, /*implicit=*/ 1);
1902 }
1903
1904 /* If errno must be maintained, expand the RTL to check if the result,
1905    TARGET, of a built-in function call, EXP, is NaN, and if so set
1906    errno to EDOM.  */
1907
1908 static void
1909 expand_errno_check (tree exp, rtx target)
1910 {
1911   rtx lab = gen_label_rtx ();
1912
1913   /* Test the result; if it is NaN, set errno=EDOM because
1914      the argument was not in the domain.  */
1915   do_compare_rtx_and_jump (target, target, EQ, 0, GET_MODE (target),
1916                            NULL_RTX, NULL_RTX, lab,
1917                            /* The jump is very likely.  */
1918                            REG_BR_PROB_BASE - (REG_BR_PROB_BASE / 2000 - 1));
1919
1920 #ifdef TARGET_EDOM
1921   /* If this built-in doesn't throw an exception, set errno directly.  */
1922   if (TREE_NOTHROW (TREE_OPERAND (CALL_EXPR_FN (exp), 0)))
1923     {
1924 #ifdef GEN_ERRNO_RTX
1925       rtx errno_rtx = GEN_ERRNO_RTX;
1926 #else
1927       rtx errno_rtx
1928           = gen_rtx_MEM (word_mode, gen_rtx_SYMBOL_REF (Pmode, "errno"));
1929 #endif
1930       emit_move_insn (errno_rtx, GEN_INT (TARGET_EDOM));
1931       emit_label (lab);
1932       return;
1933     }
1934 #endif
1935
1936   /* Make sure the library call isn't expanded as a tail call.  */
1937   CALL_EXPR_TAILCALL (exp) = 0;
1938
1939   /* We can't set errno=EDOM directly; let the library call do it.
1940      Pop the arguments right away in case the call gets deleted.  */
1941   NO_DEFER_POP;
1942   expand_call (exp, target, 0);
1943   OK_DEFER_POP;
1944   emit_label (lab);
1945 }
1946
1947 /* Expand a call to one of the builtin math functions (sqrt, exp, or log).
1948    Return NULL_RTX if a normal call should be emitted rather than expanding
1949    the function in-line.  EXP is the expression that is a call to the builtin
1950    function; if convenient, the result should be placed in TARGET.
1951    SUBTARGET may be used as the target for computing one of EXP's operands.  */
1952
1953 static rtx
1954 expand_builtin_mathfn (tree exp, rtx target, rtx subtarget)
1955 {
1956   optab builtin_optab;
1957   rtx op0, insns;
1958   tree fndecl = get_callee_fndecl (exp);
1959   enum machine_mode mode;
1960   bool errno_set = false;
1961   tree arg;
1962
1963   if (!validate_arglist (exp, REAL_TYPE, VOID_TYPE))
1964     return NULL_RTX;
1965
1966   arg = CALL_EXPR_ARG (exp, 0);
1967
1968   switch (DECL_FUNCTION_CODE (fndecl))
1969     {
1970     CASE_FLT_FN (BUILT_IN_SQRT):
1971       errno_set = ! tree_expr_nonnegative_p (arg);
1972       builtin_optab = sqrt_optab;
1973       break;
1974     CASE_FLT_FN (BUILT_IN_EXP):
1975       errno_set = true; builtin_optab = exp_optab; break;
1976     CASE_FLT_FN (BUILT_IN_EXP10):
1977     CASE_FLT_FN (BUILT_IN_POW10):
1978       errno_set = true; builtin_optab = exp10_optab; break;
1979     CASE_FLT_FN (BUILT_IN_EXP2):
1980       errno_set = true; builtin_optab = exp2_optab; break;
1981     CASE_FLT_FN (BUILT_IN_EXPM1):
1982       errno_set = true; builtin_optab = expm1_optab; break;
1983     CASE_FLT_FN (BUILT_IN_LOGB):
1984       errno_set = true; builtin_optab = logb_optab; break;
1985     CASE_FLT_FN (BUILT_IN_LOG):
1986       errno_set = true; builtin_optab = log_optab; break;
1987     CASE_FLT_FN (BUILT_IN_LOG10):
1988       errno_set = true; builtin_optab = log10_optab; break;
1989     CASE_FLT_FN (BUILT_IN_LOG2):
1990       errno_set = true; builtin_optab = log2_optab; break;
1991     CASE_FLT_FN (BUILT_IN_LOG1P):
1992       errno_set = true; builtin_optab = log1p_optab; break;
1993     CASE_FLT_FN (BUILT_IN_ASIN):
1994       builtin_optab = asin_optab; break;
1995     CASE_FLT_FN (BUILT_IN_ACOS):
1996       builtin_optab = acos_optab; break;
1997     CASE_FLT_FN (BUILT_IN_TAN):
1998       builtin_optab = tan_optab; break;
1999     CASE_FLT_FN (BUILT_IN_ATAN):
2000       builtin_optab = atan_optab; break;
2001     CASE_FLT_FN (BUILT_IN_FLOOR):
2002       builtin_optab = floor_optab; break;
2003     CASE_FLT_FN (BUILT_IN_CEIL):
2004       builtin_optab = ceil_optab; break;
2005     CASE_FLT_FN (BUILT_IN_TRUNC):
2006       builtin_optab = btrunc_optab; break;
2007     CASE_FLT_FN (BUILT_IN_ROUND):
2008       builtin_optab = round_optab; break;
2009     CASE_FLT_FN (BUILT_IN_NEARBYINT):
2010       builtin_optab = nearbyint_optab;
2011       if (flag_trapping_math)
2012         break;
2013       /* Else fallthrough and expand as rint.  */
2014     CASE_FLT_FN (BUILT_IN_RINT):
2015       builtin_optab = rint_optab; break;
2016     CASE_FLT_FN (BUILT_IN_SIGNIFICAND):
2017       builtin_optab = significand_optab; break;
2018     default:
2019       gcc_unreachable ();
2020     }
2021
2022   /* Make a suitable register to place result in.  */
2023   mode = TYPE_MODE (TREE_TYPE (exp));
2024
2025   if (! flag_errno_math || ! HONOR_NANS (mode))
2026     errno_set = false;
2027
2028   /* Before working hard, check whether the instruction is available.  */
2029   if (optab_handler (builtin_optab, mode) != CODE_FOR_nothing
2030       && (!errno_set || !optimize_insn_for_size_p ()))
2031     {
2032       rtx result = gen_reg_rtx (mode);
2033
2034       /* Wrap the computation of the argument in a SAVE_EXPR, as we may
2035          need to expand the argument again.  This way, we will not perform
2036          side-effects more the once.  */
2037       CALL_EXPR_ARG (exp, 0) = arg = builtin_save_expr (arg);
2038
2039       op0 = expand_expr (arg, subtarget, VOIDmode, EXPAND_NORMAL);
2040
2041       start_sequence ();
2042
2043       /* Compute into RESULT.
2044          Set RESULT to wherever the result comes back.  */
2045       result = expand_unop (mode, builtin_optab, op0, result, 0);
2046
2047       if (result != 0)
2048         {
2049           if (errno_set)
2050             expand_errno_check (exp, result);
2051
2052           /* Output the entire sequence.  */
2053           insns = get_insns ();
2054           end_sequence ();
2055           emit_insn (insns);
2056           return result;
2057         }
2058
2059       /* If we were unable to expand via the builtin, stop the sequence
2060          (without outputting the insns) and call to the library function
2061          with the stabilized argument list.  */
2062       end_sequence ();
2063     }
2064
2065   return expand_call (exp, target, target == const0_rtx);
2066 }
2067
2068 /* Expand a call to the builtin binary math functions (pow and atan2).
2069    Return NULL_RTX if a normal call should be emitted rather than expanding the
2070    function in-line.  EXP is the expression that is a call to the builtin
2071    function; if convenient, the result should be placed in TARGET.
2072    SUBTARGET may be used as the target for computing one of EXP's
2073    operands.  */
2074
2075 static rtx
2076 expand_builtin_mathfn_2 (tree exp, rtx target, rtx subtarget)
2077 {
2078   optab builtin_optab;
2079   rtx op0, op1, insns, result;
2080   int op1_type = REAL_TYPE;
2081   tree fndecl = get_callee_fndecl (exp);
2082   tree arg0, arg1;
2083   enum machine_mode mode;
2084   bool errno_set = true;
2085
2086   switch (DECL_FUNCTION_CODE (fndecl))
2087     {
2088     CASE_FLT_FN (BUILT_IN_SCALBN):
2089     CASE_FLT_FN (BUILT_IN_SCALBLN):
2090     CASE_FLT_FN (BUILT_IN_LDEXP):
2091       op1_type = INTEGER_TYPE;
2092     default:
2093       break;
2094     }
2095
2096   if (!validate_arglist (exp, REAL_TYPE, op1_type, VOID_TYPE))
2097     return NULL_RTX;
2098
2099   arg0 = CALL_EXPR_ARG (exp, 0);
2100   arg1 = CALL_EXPR_ARG (exp, 1);
2101
2102   switch (DECL_FUNCTION_CODE (fndecl))
2103     {
2104     CASE_FLT_FN (BUILT_IN_POW):
2105       builtin_optab = pow_optab; break;
2106     CASE_FLT_FN (BUILT_IN_ATAN2):
2107       builtin_optab = atan2_optab; break;
2108     CASE_FLT_FN (BUILT_IN_SCALB):
2109       if (REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (exp)))->b != 2)
2110         return 0;
2111       builtin_optab = scalb_optab; break;
2112     CASE_FLT_FN (BUILT_IN_SCALBN):
2113     CASE_FLT_FN (BUILT_IN_SCALBLN):
2114       if (REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (exp)))->b != 2)
2115         return 0;
2116     /* Fall through... */
2117     CASE_FLT_FN (BUILT_IN_LDEXP):
2118       builtin_optab = ldexp_optab; break;
2119     CASE_FLT_FN (BUILT_IN_FMOD):
2120       builtin_optab = fmod_optab; break;
2121     CASE_FLT_FN (BUILT_IN_REMAINDER):
2122     CASE_FLT_FN (BUILT_IN_DREM):
2123       builtin_optab = remainder_optab; break;
2124     default:
2125       gcc_unreachable ();
2126     }
2127
2128   /* Make a suitable register to place result in.  */
2129   mode = TYPE_MODE (TREE_TYPE (exp));
2130
2131   /* Before working hard, check whether the instruction is available.  */
2132   if (optab_handler (builtin_optab, mode) == CODE_FOR_nothing)
2133     return NULL_RTX;
2134
2135   result = gen_reg_rtx (mode);
2136
2137   if (! flag_errno_math || ! HONOR_NANS (mode))
2138     errno_set = false;
2139
2140   if (errno_set && optimize_insn_for_size_p ())
2141     return 0;
2142
2143   /* Always stabilize the argument list.  */
2144   CALL_EXPR_ARG (exp, 0) = arg0 = builtin_save_expr (arg0);
2145   CALL_EXPR_ARG (exp, 1) = arg1 = builtin_save_expr (arg1);
2146
2147   op0 = expand_expr (arg0, subtarget, VOIDmode, EXPAND_NORMAL);
2148   op1 = expand_normal (arg1);
2149
2150   start_sequence ();
2151
2152   /* Compute into RESULT.
2153      Set RESULT to wherever the result comes back.  */
2154   result = expand_binop (mode, builtin_optab, op0, op1,
2155                          result, 0, OPTAB_DIRECT);
2156
2157   /* If we were unable to expand via the builtin, stop the sequence
2158      (without outputting the insns) and call to the library function
2159      with the stabilized argument list.  */
2160   if (result == 0)
2161     {
2162       end_sequence ();
2163       return expand_call (exp, target, target == const0_rtx);
2164     }
2165
2166   if (errno_set)
2167     expand_errno_check (exp, result);
2168
2169   /* Output the entire sequence.  */
2170   insns = get_insns ();
2171   end_sequence ();
2172   emit_insn (insns);
2173
2174   return result;
2175 }
2176
2177 /* Expand a call to the builtin trinary math functions (fma).
2178    Return NULL_RTX if a normal call should be emitted rather than expanding the
2179    function in-line.  EXP is the expression that is a call to the builtin
2180    function; if convenient, the result should be placed in TARGET.
2181    SUBTARGET may be used as the target for computing one of EXP's
2182    operands.  */
2183
2184 static rtx
2185 expand_builtin_mathfn_ternary (tree exp, rtx target, rtx subtarget)
2186 {
2187   optab builtin_optab;
2188   rtx op0, op1, op2, insns, result;
2189   tree fndecl = get_callee_fndecl (exp);
2190   tree arg0, arg1, arg2;
2191   enum machine_mode mode;
2192
2193   if (!validate_arglist (exp, REAL_TYPE, REAL_TYPE, REAL_TYPE, VOID_TYPE))
2194     return NULL_RTX;
2195
2196   arg0 = CALL_EXPR_ARG (exp, 0);
2197   arg1 = CALL_EXPR_ARG (exp, 1);
2198   arg2 = CALL_EXPR_ARG (exp, 2);
2199
2200   switch (DECL_FUNCTION_CODE (fndecl))
2201     {
2202     CASE_FLT_FN (BUILT_IN_FMA):
2203       builtin_optab = fma_optab; break;
2204     default:
2205       gcc_unreachable ();
2206     }
2207
2208   /* Make a suitable register to place result in.  */
2209   mode = TYPE_MODE (TREE_TYPE (exp));
2210
2211   /* Before working hard, check whether the instruction is available.  */
2212   if (optab_handler (builtin_optab, mode) == CODE_FOR_nothing)
2213     return NULL_RTX;
2214
2215   result = gen_reg_rtx (mode);
2216
2217   /* Always stabilize the argument list.  */
2218   CALL_EXPR_ARG (exp, 0) = arg0 = builtin_save_expr (arg0);
2219   CALL_EXPR_ARG (exp, 1) = arg1 = builtin_save_expr (arg1);
2220   CALL_EXPR_ARG (exp, 2) = arg2 = builtin_save_expr (arg2);
2221
2222   op0 = expand_expr (arg0, subtarget, VOIDmode, EXPAND_NORMAL);
2223   op1 = expand_normal (arg1);
2224   op2 = expand_normal (arg2);
2225
2226   start_sequence ();
2227
2228   /* Compute into RESULT.
2229      Set RESULT to wherever the result comes back.  */
2230   result = expand_ternary_op (mode, builtin_optab, op0, op1, op2,
2231                               result, 0);
2232
2233   /* If we were unable to expand via the builtin, stop the sequence
2234      (without outputting the insns) and call to the library function
2235      with the stabilized argument list.  */
2236   if (result == 0)
2237     {
2238       end_sequence ();
2239       return expand_call (exp, target, target == const0_rtx);
2240     }
2241
2242   /* Output the entire sequence.  */
2243   insns = get_insns ();
2244   end_sequence ();
2245   emit_insn (insns);
2246
2247   return result;
2248 }
2249
2250 /* Expand a call to the builtin sin and cos math functions.
2251    Return NULL_RTX if a normal call should be emitted rather than expanding the
2252    function in-line.  EXP is the expression that is a call to the builtin
2253    function; if convenient, the result should be placed in TARGET.
2254    SUBTARGET may be used as the target for computing one of EXP's
2255    operands.  */
2256
2257 static rtx
2258 expand_builtin_mathfn_3 (tree exp, rtx target, rtx subtarget)
2259 {
2260   optab builtin_optab;
2261   rtx op0, insns;
2262   tree fndecl = get_callee_fndecl (exp);
2263   enum machine_mode mode;
2264   tree arg;
2265
2266   if (!validate_arglist (exp, REAL_TYPE, VOID_TYPE))
2267     return NULL_RTX;
2268
2269   arg = CALL_EXPR_ARG (exp, 0);
2270
2271   switch (DECL_FUNCTION_CODE (fndecl))
2272     {
2273     CASE_FLT_FN (BUILT_IN_SIN):
2274     CASE_FLT_FN (BUILT_IN_COS):
2275       builtin_optab = sincos_optab; break;
2276     default:
2277       gcc_unreachable ();
2278     }
2279
2280   /* Make a suitable register to place result in.  */
2281   mode = TYPE_MODE (TREE_TYPE (exp));
2282
2283   /* Check if sincos insn is available, otherwise fallback
2284      to sin or cos insn.  */
2285   if (optab_handler (builtin_optab, mode) == CODE_FOR_nothing)
2286     switch (DECL_FUNCTION_CODE (fndecl))
2287       {
2288       CASE_FLT_FN (BUILT_IN_SIN):
2289         builtin_optab = sin_optab; break;
2290       CASE_FLT_FN (BUILT_IN_COS):
2291         builtin_optab = cos_optab; break;
2292       default:
2293         gcc_unreachable ();
2294       }
2295
2296   /* Before working hard, check whether the instruction is available.  */
2297   if (optab_handler (builtin_optab, mode) != CODE_FOR_nothing)
2298     {
2299       rtx result = gen_reg_rtx (mode);
2300
2301       /* Wrap the computation of the argument in a SAVE_EXPR, as we may
2302          need to expand the argument again.  This way, we will not perform
2303          side-effects more the once.  */
2304       CALL_EXPR_ARG (exp, 0) = arg = builtin_save_expr (arg);
2305
2306       op0 = expand_expr (arg, subtarget, VOIDmode, EXPAND_NORMAL);
2307
2308       start_sequence ();
2309
2310       /* Compute into RESULT.
2311          Set RESULT to wherever the result comes back.  */
2312       if (builtin_optab == sincos_optab)
2313         {
2314           int ok;
2315
2316           switch (DECL_FUNCTION_CODE (fndecl))
2317             {
2318             CASE_FLT_FN (BUILT_IN_SIN):
2319               ok = expand_twoval_unop (builtin_optab, op0, 0, result, 0);
2320               break;
2321             CASE_FLT_FN (BUILT_IN_COS):
2322               ok = expand_twoval_unop (builtin_optab, op0, result, 0, 0);
2323               break;
2324             default:
2325               gcc_unreachable ();
2326             }
2327           gcc_assert (ok);
2328         }
2329       else
2330         result = expand_unop (mode, builtin_optab, op0, result, 0);
2331
2332       if (result != 0)
2333         {
2334           /* Output the entire sequence.  */
2335           insns = get_insns ();
2336           end_sequence ();
2337           emit_insn (insns);
2338           return result;
2339         }
2340
2341       /* If we were unable to expand via the builtin, stop the sequence
2342          (without outputting the insns) and call to the library function
2343          with the stabilized argument list.  */
2344       end_sequence ();
2345     }
2346
2347   return expand_call (exp, target, target == const0_rtx);
2348 }
2349
2350 /* Given an interclass math builtin decl FNDECL and it's argument ARG
2351    return an RTL instruction code that implements the functionality.
2352    If that isn't possible or available return CODE_FOR_nothing.  */
2353
2354 static enum insn_code
2355 interclass_mathfn_icode (tree arg, tree fndecl)
2356 {
2357   bool errno_set = false;
2358   optab builtin_optab = unknown_optab;
2359   enum machine_mode mode;
2360
2361   switch (DECL_FUNCTION_CODE (fndecl))
2362     {
2363     CASE_FLT_FN (BUILT_IN_ILOGB):
2364       errno_set = true; builtin_optab = ilogb_optab; break;
2365     CASE_FLT_FN (BUILT_IN_ISINF):
2366       builtin_optab = isinf_optab; break;
2367     case BUILT_IN_ISNORMAL:
2368     case BUILT_IN_ISFINITE:
2369     CASE_FLT_FN (BUILT_IN_FINITE):
2370     case BUILT_IN_FINITED32:
2371     case BUILT_IN_FINITED64:
2372     case BUILT_IN_FINITED128:
2373     case BUILT_IN_ISINFD32:
2374     case BUILT_IN_ISINFD64:
2375     case BUILT_IN_ISINFD128:
2376       /* These builtins have no optabs (yet).  */
2377       break;
2378     default:
2379       gcc_unreachable ();
2380     }
2381
2382   /* There's no easy way to detect the case we need to set EDOM.  */
2383   if (flag_errno_math && errno_set)
2384     return CODE_FOR_nothing;
2385
2386   /* Optab mode depends on the mode of the input argument.  */
2387   mode = TYPE_MODE (TREE_TYPE (arg));
2388
2389   if (builtin_optab)
2390     return optab_handler (builtin_optab, mode);
2391   return CODE_FOR_nothing;
2392 }
2393
2394 /* Expand a call to one of the builtin math functions that operate on
2395    floating point argument and output an integer result (ilogb, isinf,
2396    isnan, etc).
2397    Return 0 if a normal call should be emitted rather than expanding the
2398    function in-line.  EXP is the expression that is a call to the builtin
2399    function; if convenient, the result should be placed in TARGET.  */
2400
2401 static rtx
2402 expand_builtin_interclass_mathfn (tree exp, rtx target)
2403 {
2404   enum insn_code icode = CODE_FOR_nothing;
2405   rtx op0;
2406   tree fndecl = get_callee_fndecl (exp);
2407   enum machine_mode mode;
2408   tree arg;
2409
2410   if (!validate_arglist (exp, REAL_TYPE, VOID_TYPE))
2411     return NULL_RTX;
2412
2413   arg = CALL_EXPR_ARG (exp, 0);
2414   icode = interclass_mathfn_icode (arg, fndecl);
2415   mode = TYPE_MODE (TREE_TYPE (arg));
2416
2417   if (icode != CODE_FOR_nothing)
2418     {
2419       struct expand_operand ops[1];
2420       rtx last = get_last_insn ();
2421       tree orig_arg = arg;
2422
2423       /* Wrap the computation of the argument in a SAVE_EXPR, as we may
2424          need to expand the argument again.  This way, we will not perform
2425          side-effects more the once.  */
2426       CALL_EXPR_ARG (exp, 0) = arg = builtin_save_expr (arg);
2427
2428       op0 = expand_expr (arg, NULL_RTX, VOIDmode, EXPAND_NORMAL);
2429
2430       if (mode != GET_MODE (op0))
2431         op0 = convert_to_mode (mode, op0, 0);
2432
2433       create_output_operand (&ops[0], target, TYPE_MODE (TREE_TYPE (exp)));
2434       if (maybe_legitimize_operands (icode, 0, 1, ops)
2435           && maybe_emit_unop_insn (icode, ops[0].value, op0, UNKNOWN))
2436         return ops[0].value;
2437
2438       delete_insns_since (last);
2439       CALL_EXPR_ARG (exp, 0) = orig_arg;
2440     }
2441
2442   return NULL_RTX;
2443 }
2444
2445 /* Expand a call to the builtin sincos math function.
2446    Return NULL_RTX if a normal call should be emitted rather than expanding the
2447    function in-line.  EXP is the expression that is a call to the builtin
2448    function.  */
2449
2450 static rtx
2451 expand_builtin_sincos (tree exp)
2452 {
2453   rtx op0, op1, op2, target1, target2;
2454   enum machine_mode mode;
2455   tree arg, sinp, cosp;
2456   int result;
2457   location_t loc = EXPR_LOCATION (exp);
2458   tree alias_type, alias_off;
2459
2460   if (!validate_arglist (exp, REAL_TYPE,
2461                          POINTER_TYPE, POINTER_TYPE, VOID_TYPE))
2462     return NULL_RTX;
2463
2464   arg = CALL_EXPR_ARG (exp, 0);
2465   sinp = CALL_EXPR_ARG (exp, 1);
2466   cosp = CALL_EXPR_ARG (exp, 2);
2467
2468   /* Make a suitable register to place result in.  */
2469   mode = TYPE_MODE (TREE_TYPE (arg));
2470
2471   /* Check if sincos insn is available, otherwise emit the call.  */
2472   if (optab_handler (sincos_optab, mode) == CODE_FOR_nothing)
2473     return NULL_RTX;
2474
2475   target1 = gen_reg_rtx (mode);
2476   target2 = gen_reg_rtx (mode);
2477
2478   op0 = expand_normal (arg);
2479   alias_type = build_pointer_type_for_mode (TREE_TYPE (arg), ptr_mode, true);
2480   alias_off = build_int_cst (alias_type, 0);
2481   op1 = expand_normal (fold_build2_loc (loc, MEM_REF, TREE_TYPE (arg),
2482                                         sinp, alias_off));
2483   op2 = expand_normal (fold_build2_loc (loc, MEM_REF, TREE_TYPE (arg),
2484                                         cosp, alias_off));
2485
2486   /* Compute into target1 and target2.
2487      Set TARGET to wherever the result comes back.  */
2488   result = expand_twoval_unop (sincos_optab, op0, target2, target1, 0);
2489   gcc_assert (result);
2490
2491   /* Move target1 and target2 to the memory locations indicated
2492      by op1 and op2.  */
2493   emit_move_insn (op1, target1);
2494   emit_move_insn (op2, target2);
2495
2496   return const0_rtx;
2497 }
2498
2499 /* Expand a call to the internal cexpi builtin to the sincos math function.
2500    EXP is the expression that is a call to the builtin function; if convenient,
2501    the result should be placed in TARGET.  */
2502
2503 static rtx
2504 expand_builtin_cexpi (tree exp, rtx target)
2505 {
2506   tree fndecl = get_callee_fndecl (exp);
2507   tree arg, type;
2508   enum machine_mode mode;
2509   rtx op0, op1, op2;
2510   location_t loc = EXPR_LOCATION (exp);
2511
2512   if (!validate_arglist (exp, REAL_TYPE, VOID_TYPE))
2513     return NULL_RTX;
2514
2515   arg = CALL_EXPR_ARG (exp, 0);
2516   type = TREE_TYPE (arg);
2517   mode = TYPE_MODE (TREE_TYPE (arg));
2518
2519   /* Try expanding via a sincos optab, fall back to emitting a libcall
2520      to sincos or cexp.  We are sure we have sincos or cexp because cexpi
2521      is only generated from sincos, cexp or if we have either of them.  */
2522   if (optab_handler (sincos_optab, mode) != CODE_FOR_nothing)
2523     {
2524       op1 = gen_reg_rtx (mode);
2525       op2 = gen_reg_rtx (mode);
2526
2527       op0 = expand_expr (arg, NULL_RTX, VOIDmode, EXPAND_NORMAL);
2528
2529       /* Compute into op1 and op2.  */
2530       expand_twoval_unop (sincos_optab, op0, op2, op1, 0);
2531     }
2532   else if (TARGET_HAS_SINCOS)
2533     {
2534       tree call, fn = NULL_TREE;
2535       tree top1, top2;
2536       rtx op1a, op2a;
2537
2538       if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPIF)
2539         fn = builtin_decl_explicit (BUILT_IN_SINCOSF);
2540       else if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPI)
2541         fn = builtin_decl_explicit (BUILT_IN_SINCOS);
2542       else if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPIL)
2543         fn = builtin_decl_explicit (BUILT_IN_SINCOSL);
2544       else
2545         gcc_unreachable ();
2546
2547       op1 = assign_temp (TREE_TYPE (arg), 1, 1);
2548       op2 = assign_temp (TREE_TYPE (arg), 1, 1);
2549       op1a = copy_addr_to_reg (XEXP (op1, 0));
2550       op2a = copy_addr_to_reg (XEXP (op2, 0));
2551       top1 = make_tree (build_pointer_type (TREE_TYPE (arg)), op1a);
2552       top2 = make_tree (build_pointer_type (TREE_TYPE (arg)), op2a);
2553
2554       /* Make sure not to fold the sincos call again.  */
2555       call = build1 (ADDR_EXPR, build_pointer_type (TREE_TYPE (fn)), fn);
2556       expand_normal (build_call_nary (TREE_TYPE (TREE_TYPE (fn)),
2557                                       call, 3, arg, top1, top2));
2558     }
2559   else
2560     {
2561       tree call, fn = NULL_TREE, narg;
2562       tree ctype = build_complex_type (type);
2563
2564       if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPIF)
2565         fn = builtin_decl_explicit (BUILT_IN_CEXPF);
2566       else if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPI)
2567         fn = builtin_decl_explicit (BUILT_IN_CEXP);
2568       else if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPIL)
2569         fn = builtin_decl_explicit (BUILT_IN_CEXPL);
2570       else
2571         gcc_unreachable ();
2572
2573       /* If we don't have a decl for cexp create one.  This is the
2574          friendliest fallback if the user calls __builtin_cexpi
2575          without full target C99 function support.  */
2576       if (fn == NULL_TREE)
2577         {
2578           tree fntype;
2579           const char *name = NULL;
2580
2581           if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPIF)
2582             name = "cexpf";
2583           else if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPI)
2584             name = "cexp";
2585           else if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPIL)
2586             name = "cexpl";
2587
2588           fntype = build_function_type_list (ctype, ctype, NULL_TREE);
2589           fn = build_fn_decl (name, fntype);
2590         }
2591
2592       narg = fold_build2_loc (loc, COMPLEX_EXPR, ctype,
2593                           build_real (type, dconst0), arg);
2594
2595       /* Make sure not to fold the cexp call again.  */
2596       call = build1 (ADDR_EXPR, build_pointer_type (TREE_TYPE (fn)), fn);
2597       return expand_expr (build_call_nary (ctype, call, 1, narg),
2598                           target, VOIDmode, EXPAND_NORMAL);
2599     }
2600
2601   /* Now build the proper return type.  */
2602   return expand_expr (build2 (COMPLEX_EXPR, build_complex_type (type),
2603                               make_tree (TREE_TYPE (arg), op2),
2604                               make_tree (TREE_TYPE (arg), op1)),
2605                       target, VOIDmode, EXPAND_NORMAL);
2606 }
2607
2608 /* Conveniently construct a function call expression.  FNDECL names the
2609    function to be called, N is the number of arguments, and the "..."
2610    parameters are the argument expressions.  Unlike build_call_exr
2611    this doesn't fold the call, hence it will always return a CALL_EXPR.  */
2612
2613 static tree
2614 build_call_nofold_loc (location_t loc, tree fndecl, int n, ...)
2615 {
2616   va_list ap;
2617   tree fntype = TREE_TYPE (fndecl);
2618   tree fn = build1 (ADDR_EXPR, build_pointer_type (fntype), fndecl);
2619
2620   va_start (ap, n);
2621   fn = build_call_valist (TREE_TYPE (fntype), fn, n, ap);
2622   va_end (ap);
2623   SET_EXPR_LOCATION (fn, loc);
2624   return fn;
2625 }
2626
2627 /* Expand a call to one of the builtin rounding functions gcc defines
2628    as an extension (lfloor and lceil).  As these are gcc extensions we
2629    do not need to worry about setting errno to EDOM.
2630    If expanding via optab fails, lower expression to (int)(floor(x)).
2631    EXP is the expression that is a call to the builtin function;
2632    if convenient, the result should be placed in TARGET.  */
2633
2634 static rtx
2635 expand_builtin_int_roundingfn (tree exp, rtx target)
2636 {
2637   convert_optab builtin_optab;
2638   rtx op0, insns, tmp;
2639   tree fndecl = get_callee_fndecl (exp);
2640   enum built_in_function fallback_fn;
2641   tree fallback_fndecl;
2642   enum machine_mode mode;
2643   tree arg;
2644
2645   if (!validate_arglist (exp, REAL_TYPE, VOID_TYPE))
2646     gcc_unreachable ();
2647
2648   arg = CALL_EXPR_ARG (exp, 0);
2649
2650   switch (DECL_FUNCTION_CODE (fndecl))
2651     {
2652     CASE_FLT_FN (BUILT_IN_ICEIL):
2653     CASE_FLT_FN (BUILT_IN_LCEIL):
2654     CASE_FLT_FN (BUILT_IN_LLCEIL):
2655       builtin_optab = lceil_optab;
2656       fallback_fn = BUILT_IN_CEIL;
2657       break;
2658
2659     CASE_FLT_FN (BUILT_IN_IFLOOR):
2660     CASE_FLT_FN (BUILT_IN_LFLOOR):
2661     CASE_FLT_FN (BUILT_IN_LLFLOOR):
2662       builtin_optab = lfloor_optab;
2663       fallback_fn = BUILT_IN_FLOOR;
2664       break;
2665
2666     default:
2667       gcc_unreachable ();
2668     }
2669
2670   /* Make a suitable register to place result in.  */
2671   mode = TYPE_MODE (TREE_TYPE (exp));
2672
2673   target = gen_reg_rtx (mode);
2674
2675   /* Wrap the computation of the argument in a SAVE_EXPR, as we may
2676      need to expand the argument again.  This way, we will not perform
2677      side-effects more the once.  */
2678   CALL_EXPR_ARG (exp, 0) = arg = builtin_save_expr (arg);
2679
2680   op0 = expand_expr (arg, NULL, VOIDmode, EXPAND_NORMAL);
2681
2682   start_sequence ();
2683
2684   /* Compute into TARGET.  */
2685   if (expand_sfix_optab (target, op0, builtin_optab))
2686     {
2687       /* Output the entire sequence.  */
2688       insns = get_insns ();
2689       end_sequence ();
2690       emit_insn (insns);
2691       return target;
2692     }
2693
2694   /* If we were unable to expand via the builtin, stop the sequence
2695      (without outputting the insns).  */
2696   end_sequence ();
2697
2698   /* Fall back to floating point rounding optab.  */
2699   fallback_fndecl = mathfn_built_in (TREE_TYPE (arg), fallback_fn);
2700
2701   /* For non-C99 targets we may end up without a fallback fndecl here
2702      if the user called __builtin_lfloor directly.  In this case emit
2703      a call to the floor/ceil variants nevertheless.  This should result
2704      in the best user experience for not full C99 targets.  */
2705   if (fallback_fndecl == NULL_TREE)
2706     {
2707       tree fntype;
2708       const char *name = NULL;
2709
2710       switch (DECL_FUNCTION_CODE (fndecl))
2711         {
2712         case BUILT_IN_ICEIL:
2713         case BUILT_IN_LCEIL:
2714         case BUILT_IN_LLCEIL:
2715           name = "ceil";
2716           break;
2717         case BUILT_IN_ICEILF:
2718         case BUILT_IN_LCEILF:
2719         case BUILT_IN_LLCEILF:
2720           name = "ceilf";
2721           break;
2722         case BUILT_IN_ICEILL:
2723         case BUILT_IN_LCEILL:
2724         case BUILT_IN_LLCEILL:
2725           name = "ceill";
2726           break;
2727         case BUILT_IN_IFLOOR:
2728         case BUILT_IN_LFLOOR:
2729         case BUILT_IN_LLFLOOR:
2730           name = "floor";
2731           break;
2732         case BUILT_IN_IFLOORF:
2733         case BUILT_IN_LFLOORF:
2734         case BUILT_IN_LLFLOORF:
2735           name = "floorf";
2736           break;
2737         case BUILT_IN_IFLOORL:
2738         case BUILT_IN_LFLOORL:
2739         case BUILT_IN_LLFLOORL:
2740           name = "floorl";
2741           break;
2742         default:
2743           gcc_unreachable ();
2744         }
2745
2746       fntype = build_function_type_list (TREE_TYPE (arg),
2747                                          TREE_TYPE (arg), NULL_TREE);
2748       fallback_fndecl = build_fn_decl (name, fntype);
2749     }
2750
2751   exp = build_call_nofold_loc (EXPR_LOCATION (exp), fallback_fndecl, 1, arg);
2752
2753   tmp = expand_normal (exp);
2754   tmp = maybe_emit_group_store (tmp, TREE_TYPE (exp));
2755
2756   /* Truncate the result of floating point optab to integer
2757      via expand_fix ().  */
2758   target = gen_reg_rtx (mode);
2759   expand_fix (target, tmp, 0);
2760
2761   return target;
2762 }
2763
2764 /* Expand a call to one of the builtin math functions doing integer
2765    conversion (lrint).
2766    Return 0 if a normal call should be emitted rather than expanding the
2767    function in-line.  EXP is the expression that is a call to the builtin
2768    function; if convenient, the result should be placed in TARGET.  */
2769
2770 static rtx
2771 expand_builtin_int_roundingfn_2 (tree exp, rtx target)
2772 {
2773   convert_optab builtin_optab;
2774   rtx op0, insns;
2775   tree fndecl = get_callee_fndecl (exp);
2776   tree arg;
2777   enum machine_mode mode;
2778   enum built_in_function fallback_fn = BUILT_IN_NONE;
2779
2780   if (!validate_arglist (exp, REAL_TYPE, VOID_TYPE))
2781      gcc_unreachable ();
2782
2783   arg = CALL_EXPR_ARG (exp, 0);
2784
2785   switch (DECL_FUNCTION_CODE (fndecl))
2786     {
2787     CASE_FLT_FN (BUILT_IN_IRINT):
2788       fallback_fn = BUILT_IN_LRINT;
2789       /* FALLTHRU */
2790     CASE_FLT_FN (BUILT_IN_LRINT):
2791     CASE_FLT_FN (BUILT_IN_LLRINT):
2792       builtin_optab = lrint_optab;
2793       break;
2794
2795     CASE_FLT_FN (BUILT_IN_IROUND):
2796       fallback_fn = BUILT_IN_LROUND;
2797       /* FALLTHRU */
2798     CASE_FLT_FN (BUILT_IN_LROUND):
2799     CASE_FLT_FN (BUILT_IN_LLROUND):
2800       builtin_optab = lround_optab;
2801       break;
2802
2803     default:
2804       gcc_unreachable ();
2805     }
2806
2807   /* There's no easy way to detect the case we need to set EDOM.  */
2808   if (flag_errno_math && fallback_fn == BUILT_IN_NONE)
2809     return NULL_RTX;
2810
2811   /* Make a suitable register to place result in.  */
2812   mode = TYPE_MODE (TREE_TYPE (exp));
2813
2814   /* There's no easy way to detect the case we need to set EDOM.  */
2815   if (!flag_errno_math)
2816     {
2817       rtx result = gen_reg_rtx (mode);
2818
2819       /* Wrap the computation of the argument in a SAVE_EXPR, as we may
2820          need to expand the argument again.  This way, we will not perform
2821          side-effects more the once.  */
2822       CALL_EXPR_ARG (exp, 0) = arg = builtin_save_expr (arg);
2823
2824       op0 = expand_expr (arg, NULL, VOIDmode, EXPAND_NORMAL);
2825
2826       start_sequence ();
2827
2828       if (expand_sfix_optab (result, op0, builtin_optab))
2829         {
2830           /* Output the entire sequence.  */
2831           insns = get_insns ();
2832           end_sequence ();
2833           emit_insn (insns);
2834           return result;
2835         }
2836
2837       /* If we were unable to expand via the builtin, stop the sequence
2838          (without outputting the insns) and call to the library function
2839          with the stabilized argument list.  */
2840       end_sequence ();
2841     }
2842
2843   if (fallback_fn != BUILT_IN_NONE)
2844     {
2845       /* Fall back to rounding to long int.  Use implicit_p 0 - for non-C99
2846          targets, (int) round (x) should never be transformed into
2847          BUILT_IN_IROUND and if __builtin_iround is called directly, emit
2848          a call to lround in the hope that the target provides at least some
2849          C99 functions.  This should result in the best user experience for
2850          not full C99 targets.  */
2851       tree fallback_fndecl = mathfn_built_in_1 (TREE_TYPE (arg),
2852                                                 fallback_fn, 0);
2853
2854       exp = build_call_nofold_loc (EXPR_LOCATION (exp),
2855                                    fallback_fndecl, 1, arg);
2856
2857       target = expand_call (exp, NULL_RTX, target == const0_rtx);
2858       target = maybe_emit_group_store (target, TREE_TYPE (exp));
2859       return convert_to_mode (mode, target, 0);
2860     }
2861
2862   return expand_call (exp, target, target == const0_rtx);
2863 }
2864
2865 /* Expand a call to the powi built-in mathematical function.  Return NULL_RTX if
2866    a normal call should be emitted rather than expanding the function
2867    in-line.  EXP is the expression that is a call to the builtin
2868    function; if convenient, the result should be placed in TARGET.  */
2869
2870 static rtx
2871 expand_builtin_powi (tree exp, rtx target)
2872 {
2873   tree arg0, arg1;
2874   rtx op0, op1;
2875   enum machine_mode mode;
2876   enum machine_mode mode2;
2877
2878   if (! validate_arglist (exp, REAL_TYPE, INTEGER_TYPE, VOID_TYPE))
2879     return NULL_RTX;
2880
2881   arg0 = CALL_EXPR_ARG (exp, 0);
2882   arg1 = CALL_EXPR_ARG (exp, 1);
2883   mode = TYPE_MODE (TREE_TYPE (exp));
2884
2885   /* Emit a libcall to libgcc.  */
2886
2887   /* Mode of the 2nd argument must match that of an int.  */
2888   mode2 = mode_for_size (INT_TYPE_SIZE, MODE_INT, 0);
2889
2890   if (target == NULL_RTX)
2891     target = gen_reg_rtx (mode);
2892
2893   op0 = expand_expr (arg0, NULL_RTX, mode, EXPAND_NORMAL);
2894   if (GET_MODE (op0) != mode)
2895     op0 = convert_to_mode (mode, op0, 0);
2896   op1 = expand_expr (arg1, NULL_RTX, mode2, EXPAND_NORMAL);
2897   if (GET_MODE (op1) != mode2)
2898     op1 = convert_to_mode (mode2, op1, 0);
2899
2900   target = emit_library_call_value (optab_libfunc (powi_optab, mode),
2901                                     target, LCT_CONST, mode, 2,
2902                                     op0, mode, op1, mode2);
2903
2904   return target;
2905 }
2906
2907 /* Expand expression EXP which is a call to the strlen builtin.  Return
2908    NULL_RTX if we failed the caller should emit a normal call, otherwise
2909    try to get the result in TARGET, if convenient.  */
2910
2911 static rtx
2912 expand_builtin_strlen (tree exp, rtx target,
2913                        enum machine_mode target_mode)
2914 {
2915   if (!validate_arglist (exp, POINTER_TYPE, VOID_TYPE))
2916     return NULL_RTX;
2917   else
2918     {
2919       struct expand_operand ops[4];
2920       rtx pat;
2921       tree len;
2922       tree src = CALL_EXPR_ARG (exp, 0);
2923       rtx src_reg, before_strlen;
2924       enum machine_mode insn_mode = target_mode;
2925       enum insn_code icode = CODE_FOR_nothing;
2926       unsigned int align;
2927
2928       /* If the length can be computed at compile-time, return it.  */
2929       len = c_strlen (src, 0);
2930       if (len)
2931         return expand_expr (len, target, target_mode, EXPAND_NORMAL);
2932
2933       /* If the length can be computed at compile-time and is constant
2934          integer, but there are side-effects in src, evaluate
2935          src for side-effects, then return len.
2936          E.g. x = strlen (i++ ? "xfoo" + 1 : "bar");
2937          can be optimized into: i++; x = 3;  */
2938       len = c_strlen (src, 1);
2939       if (len && TREE_CODE (len) == INTEGER_CST)
2940         {
2941           expand_expr (src, const0_rtx, VOIDmode, EXPAND_NORMAL);
2942           return expand_expr (len, target, target_mode, EXPAND_NORMAL);
2943         }
2944
2945       align = get_pointer_alignment (src) / BITS_PER_UNIT;
2946
2947       /* If SRC is not a pointer type, don't do this operation inline.  */
2948       if (align == 0)
2949         return NULL_RTX;
2950
2951       /* Bail out if we can't compute strlen in the right mode.  */
2952       while (insn_mode != VOIDmode)
2953         {
2954           icode = optab_handler (strlen_optab, insn_mode);
2955           if (icode != CODE_FOR_nothing)
2956             break;
2957
2958           insn_mode = GET_MODE_WIDER_MODE (insn_mode);
2959         }
2960       if (insn_mode == VOIDmode)
2961         return NULL_RTX;
2962
2963       /* Make a place to hold the source address.  We will not expand
2964          the actual source until we are sure that the expansion will
2965          not fail -- there are trees that cannot be expanded twice.  */
2966       src_reg = gen_reg_rtx (Pmode);
2967
2968       /* Mark the beginning of the strlen sequence so we can emit the
2969          source operand later.  */
2970       before_strlen = get_last_insn ();
2971
2972       create_output_operand (&ops[0], target, insn_mode);
2973       create_fixed_operand (&ops[1], gen_rtx_MEM (BLKmode, src_reg));
2974       create_integer_operand (&ops[2], 0);
2975       create_integer_operand (&ops[3], align);
2976       if (!maybe_expand_insn (icode, 4, ops))
2977         return NULL_RTX;
2978
2979       /* Now that we are assured of success, expand the source.  */
2980       start_sequence ();
2981       pat = expand_expr (src, src_reg, Pmode, EXPAND_NORMAL);
2982       if (pat != src_reg)
2983         {
2984 #ifdef POINTERS_EXTEND_UNSIGNED
2985           if (GET_MODE (pat) != Pmode)
2986             pat = convert_to_mode (Pmode, pat,
2987                                    POINTERS_EXTEND_UNSIGNED);
2988 #endif
2989           emit_move_insn (src_reg, pat);
2990         }
2991       pat = get_insns ();
2992       end_sequence ();
2993
2994       if (before_strlen)
2995         emit_insn_after (pat, before_strlen);
2996       else
2997         emit_insn_before (pat, get_insns ());
2998
2999       /* Return the value in the proper mode for this function.  */
3000       if (GET_MODE (ops[0].value) == target_mode)
3001         target = ops[0].value;
3002       else if (target != 0)
3003         convert_move (target, ops[0].value, 0);
3004       else
3005         target = convert_to_mode (target_mode, ops[0].value, 0);
3006
3007       return target;
3008     }
3009 }
3010
3011 /* Callback routine for store_by_pieces.  Read GET_MODE_BITSIZE (MODE)
3012    bytes from constant string DATA + OFFSET and return it as target
3013    constant.  */
3014
3015 static rtx
3016 builtin_memcpy_read_str (void *data, HOST_WIDE_INT offset,
3017                          enum machine_mode mode)
3018 {
3019   const char *str = (const char *) data;
3020
3021   gcc_assert (offset >= 0
3022               && ((unsigned HOST_WIDE_INT) offset + GET_MODE_SIZE (mode)
3023                   <= strlen (str) + 1));
3024
3025   return c_readstr (str + offset, mode);
3026 }
3027
3028 /* Expand a call EXP to the memcpy builtin.
3029    Return NULL_RTX if we failed, the caller should emit a normal call,
3030    otherwise try to get the result in TARGET, if convenient (and in
3031    mode MODE if that's convenient).  */
3032
3033 static rtx
3034 expand_builtin_memcpy (tree exp, rtx target)
3035 {
3036   if (!validate_arglist (exp,
3037                          POINTER_TYPE, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
3038     return NULL_RTX;
3039   else
3040     {
3041       tree dest = CALL_EXPR_ARG (exp, 0);
3042       tree src = CALL_EXPR_ARG (exp, 1);
3043       tree len = CALL_EXPR_ARG (exp, 2);
3044       const char *src_str;
3045       unsigned int src_align = get_pointer_alignment (src);
3046       unsigned int dest_align = get_pointer_alignment (dest);
3047       rtx dest_mem, src_mem, dest_addr, len_rtx;
3048       HOST_WIDE_INT expected_size = -1;
3049       unsigned int expected_align = 0;
3050
3051       /* If DEST is not a pointer type, call the normal function.  */
3052       if (dest_align == 0)
3053         return NULL_RTX;
3054
3055       /* If either SRC is not a pointer type, don't do this
3056          operation in-line.  */
3057       if (src_align == 0)
3058         return NULL_RTX;
3059
3060       if (currently_expanding_gimple_stmt)
3061         stringop_block_profile (currently_expanding_gimple_stmt,
3062                                 &expected_align, &expected_size);
3063
3064       if (expected_align < dest_align)
3065         expected_align = dest_align;
3066       dest_mem = get_memory_rtx (dest, len);
3067       set_mem_align (dest_mem, dest_align);
3068       len_rtx = expand_normal (len);
3069       src_str = c_getstr (src);
3070
3071       /* If SRC is a string constant and block move would be done
3072          by pieces, we can avoid loading the string from memory
3073          and only stored the computed constants.  */
3074       if (src_str
3075           && CONST_INT_P (len_rtx)
3076           && (unsigned HOST_WIDE_INT) INTVAL (len_rtx) <= strlen (src_str) + 1
3077           && can_store_by_pieces (INTVAL (len_rtx), builtin_memcpy_read_str,
3078                                   CONST_CAST (char *, src_str),
3079                                   dest_align, false))
3080         {
3081           dest_mem = store_by_pieces (dest_mem, INTVAL (len_rtx),
3082                                       builtin_memcpy_read_str,
3083                                       CONST_CAST (char *, src_str),
3084                                       dest_align, false, 0);
3085           dest_mem = force_operand (XEXP (dest_mem, 0), target);
3086           dest_mem = convert_memory_address (ptr_mode, dest_mem);
3087           return dest_mem;
3088         }
3089
3090       src_mem = get_memory_rtx (src, len);
3091       set_mem_align (src_mem, src_align);
3092
3093       /* Copy word part most expediently.  */
3094       dest_addr = emit_block_move_hints (dest_mem, src_mem, len_rtx,
3095                                          CALL_EXPR_TAILCALL (exp)
3096                                          ? BLOCK_OP_TAILCALL : BLOCK_OP_NORMAL,
3097                                          expected_align, expected_size);
3098
3099       if (dest_addr == 0)
3100         {
3101           dest_addr = force_operand (XEXP (dest_mem, 0), target);
3102           dest_addr = convert_memory_address (ptr_mode, dest_addr);
3103         }
3104       return dest_addr;
3105     }
3106 }
3107
3108 /* Expand a call EXP to the mempcpy builtin.
3109    Return NULL_RTX if we failed; the caller should emit a normal call,
3110    otherwise try to get the result in TARGET, if convenient (and in
3111    mode MODE if that's convenient).  If ENDP is 0 return the
3112    destination pointer, if ENDP is 1 return the end pointer ala
3113    mempcpy, and if ENDP is 2 return the end pointer minus one ala
3114    stpcpy.  */
3115
3116 static rtx
3117 expand_builtin_mempcpy (tree exp, rtx target, enum machine_mode mode)
3118 {
3119   if (!validate_arglist (exp,
3120                          POINTER_TYPE, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
3121     return NULL_RTX;
3122   else
3123     {
3124       tree dest = CALL_EXPR_ARG (exp, 0);
3125       tree src = CALL_EXPR_ARG (exp, 1);
3126       tree len = CALL_EXPR_ARG (exp, 2);
3127       return expand_builtin_mempcpy_args (dest, src, len,
3128                                           target, mode, /*endp=*/ 1);
3129     }
3130 }
3131
3132 /* Helper function to do the actual work for expand_builtin_mempcpy.  The
3133    arguments to the builtin_mempcpy call DEST, SRC, and LEN are broken out
3134    so that this can also be called without constructing an actual CALL_EXPR.
3135    The other arguments and return value are the same as for
3136    expand_builtin_mempcpy.  */
3137
3138 static rtx
3139 expand_builtin_mempcpy_args (tree dest, tree src, tree len,
3140                              rtx target, enum machine_mode mode, int endp)
3141 {
3142     /* If return value is ignored, transform mempcpy into memcpy.  */
3143   if (target == const0_rtx && builtin_decl_implicit_p (BUILT_IN_MEMCPY))
3144     {
3145       tree fn = builtin_decl_implicit (BUILT_IN_MEMCPY);
3146       tree result = build_call_nofold_loc (UNKNOWN_LOCATION, fn, 3,
3147                                            dest, src, len);
3148       return expand_expr (result, target, mode, EXPAND_NORMAL);
3149     }
3150   else
3151     {
3152       const char *src_str;
3153       unsigned int src_align = get_pointer_alignment (src);
3154       unsigned int dest_align = get_pointer_alignment (dest);
3155       rtx dest_mem, src_mem, len_rtx;
3156
3157       /* If either SRC or DEST is not a pointer type, don't do this
3158          operation in-line.  */
3159       if (dest_align == 0 || src_align == 0)
3160         return NULL_RTX;
3161
3162       /* If LEN is not constant, call the normal function.  */
3163       if (! host_integerp (len, 1))
3164         return NULL_RTX;
3165
3166       len_rtx = expand_normal (len);
3167       src_str = c_getstr (src);
3168
3169       /* If SRC is a string constant and block move would be done
3170          by pieces, we can avoid loading the string from memory
3171          and only stored the computed constants.  */
3172       if (src_str
3173           && CONST_INT_P (len_rtx)
3174           && (unsigned HOST_WIDE_INT) INTVAL (len_rtx) <= strlen (src_str) + 1
3175           && can_store_by_pieces (INTVAL (len_rtx), builtin_memcpy_read_str,
3176                                   CONST_CAST (char *, src_str),
3177                                   dest_align, false))
3178         {
3179           dest_mem = get_memory_rtx (dest, len);
3180           set_mem_align (dest_mem, dest_align);
3181           dest_mem = store_by_pieces (dest_mem, INTVAL (len_rtx),
3182                                       builtin_memcpy_read_str,
3183                                       CONST_CAST (char *, src_str),
3184                                       dest_align, false, endp);
3185           dest_mem = force_operand (XEXP (dest_mem, 0), NULL_RTX);
3186           dest_mem = convert_memory_address (ptr_mode, dest_mem);
3187           return dest_mem;
3188         }
3189
3190       if (CONST_INT_P (len_rtx)
3191           && can_move_by_pieces (INTVAL (len_rtx),
3192                                  MIN (dest_align, src_align)))
3193         {
3194           dest_mem = get_memory_rtx (dest, len);
3195           set_mem_align (dest_mem, dest_align);
3196           src_mem = get_memory_rtx (src, len);
3197           set_mem_align (src_mem, src_align);
3198           dest_mem = move_by_pieces (dest_mem, src_mem, INTVAL (len_rtx),
3199                                      MIN (dest_align, src_align), endp);
3200           dest_mem = force_operand (XEXP (dest_mem, 0), NULL_RTX);
3201           dest_mem = convert_memory_address (ptr_mode, dest_mem);
3202           return dest_mem;
3203         }
3204
3205       return NULL_RTX;
3206     }
3207 }
3208
3209 #ifndef HAVE_movstr
3210 # define HAVE_movstr 0
3211 # define CODE_FOR_movstr CODE_FOR_nothing
3212 #endif
3213
3214 /* Expand into a movstr instruction, if one is available.  Return NULL_RTX if
3215    we failed, the caller should emit a normal call, otherwise try to
3216    get the result in TARGET, if convenient.  If ENDP is 0 return the
3217    destination pointer, if ENDP is 1 return the end pointer ala
3218    mempcpy, and if ENDP is 2 return the end pointer minus one ala
3219    stpcpy.  */
3220
3221 static rtx
3222 expand_movstr (tree dest, tree src, rtx target, int endp)
3223 {
3224   struct expand_operand ops[3];
3225   rtx dest_mem;
3226   rtx src_mem;
3227
3228   if (!HAVE_movstr)
3229     return NULL_RTX;
3230
3231   dest_mem = get_memory_rtx (dest, NULL);
3232   src_mem = get_memory_rtx (src, NULL);
3233   if (!endp)
3234     {
3235       target = force_reg (Pmode, XEXP (dest_mem, 0));
3236       dest_mem = replace_equiv_address (dest_mem, target);
3237     }
3238
3239   create_output_operand (&ops[0], endp ? target : NULL_RTX, Pmode);
3240   create_fixed_operand (&ops[1], dest_mem);
3241   create_fixed_operand (&ops[2], src_mem);
3242   expand_insn (CODE_FOR_movstr, 3, ops);
3243
3244   if (endp && target != const0_rtx)
3245     {
3246       target = ops[0].value;
3247       /* movstr is supposed to set end to the address of the NUL
3248          terminator.  If the caller requested a mempcpy-like return value,
3249          adjust it.  */
3250       if (endp == 1)
3251         {
3252           rtx tem = plus_constant (GET_MODE (target),
3253                                    gen_lowpart (GET_MODE (target), target), 1);
3254           emit_move_insn (target, force_operand (tem, NULL_RTX));
3255         }
3256     }
3257   return target;
3258 }
3259
3260 /* Expand expression EXP, which is a call to the strcpy builtin.  Return
3261    NULL_RTX if we failed the caller should emit a normal call, otherwise
3262    try to get the result in TARGET, if convenient (and in mode MODE if that's
3263    convenient).  */
3264
3265 static rtx
3266 expand_builtin_strcpy (tree exp, rtx target)
3267 {
3268   if (validate_arglist (exp, POINTER_TYPE, POINTER_TYPE, VOID_TYPE))
3269    {
3270      tree dest = CALL_EXPR_ARG (exp, 0);
3271      tree src = CALL_EXPR_ARG (exp, 1);
3272      return expand_builtin_strcpy_args (dest, src, target);
3273    }
3274    return NULL_RTX;
3275 }
3276
3277 /* Helper function to do the actual work for expand_builtin_strcpy.  The
3278    arguments to the builtin_strcpy call DEST and SRC are broken out
3279    so that this can also be called without constructing an actual CALL_EXPR.
3280    The other arguments and return value are the same as for
3281    expand_builtin_strcpy.  */
3282
3283 static rtx
3284 expand_builtin_strcpy_args (tree dest, tree src, rtx target)
3285 {
3286   return expand_movstr (dest, src, target, /*endp=*/0);
3287 }
3288
3289 /* Expand a call EXP to the stpcpy builtin.
3290    Return NULL_RTX if we failed the caller should emit a normal call,
3291    otherwise try to get the result in TARGET, if convenient (and in
3292    mode MODE if that's convenient).  */
3293
3294 static rtx
3295 expand_builtin_stpcpy (tree exp, rtx target, enum machine_mode mode)
3296 {
3297   tree dst, src;
3298   location_t loc = EXPR_LOCATION (exp);
3299
3300   if (!validate_arglist (exp, POINTER_TYPE, POINTER_TYPE, VOID_TYPE))
3301     return NULL_RTX;
3302
3303   dst = CALL_EXPR_ARG (exp, 0);
3304   src = CALL_EXPR_ARG (exp, 1);
3305
3306   /* If return value is ignored, transform stpcpy into strcpy.  */
3307   if (target == const0_rtx && builtin_decl_implicit (BUILT_IN_STRCPY))
3308     {
3309       tree fn = builtin_decl_implicit (BUILT_IN_STRCPY);
3310       tree result = build_call_nofold_loc (loc, fn, 2, dst, src);
3311       return expand_expr (result, target, mode, EXPAND_NORMAL);
3312     }
3313   else
3314     {
3315       tree len, lenp1;
3316       rtx ret;
3317
3318       /* Ensure we get an actual string whose length can be evaluated at
3319          compile-time, not an expression containing a string.  This is
3320          because the latter will potentially produce pessimized code
3321          when used to produce the return value.  */
3322       if (! c_getstr (src) || ! (len = c_strlen (src, 0)))
3323         return expand_movstr (dst, src, target, /*endp=*/2);
3324
3325       lenp1 = size_binop_loc (loc, PLUS_EXPR, len, ssize_int (1));
3326       ret = expand_builtin_mempcpy_args (dst, src, lenp1,
3327                                          target, mode, /*endp=*/2);
3328
3329       if (ret)
3330         return ret;
3331
3332       if (TREE_CODE (len) == INTEGER_CST)
3333         {
3334           rtx len_rtx = expand_normal (len);
3335
3336           if (CONST_INT_P (len_rtx))
3337             {
3338               ret = expand_builtin_strcpy_args (dst, src, target);
3339
3340               if (ret)
3341                 {
3342                   if (! target)
3343                     {
3344                       if (mode != VOIDmode)
3345                         target = gen_reg_rtx (mode);
3346                       else
3347                         target = gen_reg_rtx (GET_MODE (ret));
3348                     }
3349                   if (GET_MODE (target) != GET_MODE (ret))
3350                     ret = gen_lowpart (GET_MODE (target), ret);
3351
3352                   ret = plus_constant (GET_MODE (ret), ret, INTVAL (len_rtx));
3353                   ret = emit_move_insn (target, force_operand (ret, NULL_RTX));
3354                   gcc_assert (ret);
3355
3356                   return target;
3357                 }
3358             }
3359         }
3360
3361       return expand_movstr (dst, src, target, /*endp=*/2);
3362     }
3363 }
3364
3365 /* Callback routine for store_by_pieces.  Read GET_MODE_BITSIZE (MODE)
3366    bytes from constant string DATA + OFFSET and return it as target
3367    constant.  */
3368
3369 rtx
3370 builtin_strncpy_read_str (void *data, HOST_WIDE_INT offset,
3371                           enum machine_mode mode)
3372 {
3373   const char *str = (const char *) data;
3374
3375   if ((unsigned HOST_WIDE_INT) offset > strlen (str))
3376     return const0_rtx;
3377
3378   return c_readstr (str + offset, mode);
3379 }
3380
3381 /* Expand expression EXP, which is a call to the strncpy builtin.  Return
3382    NULL_RTX if we failed the caller should emit a normal call.  */
3383
3384 static rtx
3385 expand_builtin_strncpy (tree exp, rtx target)
3386 {
3387   location_t loc = EXPR_LOCATION (exp);
3388
3389   if (validate_arglist (exp,
3390                         POINTER_TYPE, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
3391     {
3392       tree dest = CALL_EXPR_ARG (exp, 0);
3393       tree src = CALL_EXPR_ARG (exp, 1);
3394       tree len = CALL_EXPR_ARG (exp, 2);
3395       tree slen = c_strlen (src, 1);
3396
3397       /* We must be passed a constant len and src parameter.  */
3398       if (!host_integerp (len, 1) || !slen || !host_integerp (slen, 1))
3399         return NULL_RTX;
3400
3401       slen = size_binop_loc (loc, PLUS_EXPR, slen, ssize_int (1));
3402
3403       /* We're required to pad with trailing zeros if the requested
3404          len is greater than strlen(s2)+1.  In that case try to
3405          use store_by_pieces, if it fails, punt.  */
3406       if (tree_int_cst_lt (slen, len))
3407         {
3408           unsigned int dest_align = get_pointer_alignment (dest);
3409           const char *p = c_getstr (src);
3410           rtx dest_mem;
3411
3412           if (!p || dest_align == 0 || !host_integerp (len, 1)
3413               || !can_store_by_pieces (tree_low_cst (len, 1),
3414                                        builtin_strncpy_read_str,
3415                                        CONST_CAST (char *, p),
3416                                        dest_align, false))
3417             return NULL_RTX;
3418
3419           dest_mem = get_memory_rtx (dest, len);
3420           store_by_pieces (dest_mem, tree_low_cst (len, 1),
3421                            builtin_strncpy_read_str,
3422                            CONST_CAST (char *, p), dest_align, false, 0);
3423           dest_mem = force_operand (XEXP (dest_mem, 0), target);
3424           dest_mem = convert_memory_address (ptr_mode, dest_mem);
3425           return dest_mem;
3426         }
3427     }
3428   return NULL_RTX;
3429 }
3430
3431 /* Callback routine for store_by_pieces.  Read GET_MODE_BITSIZE (MODE)
3432    bytes from constant string DATA + OFFSET and return it as target
3433    constant.  */
3434
3435 rtx
3436 builtin_memset_read_str (void *data, HOST_WIDE_INT offset ATTRIBUTE_UNUSED,
3437                          enum machine_mode mode)
3438 {
3439   const char *c = (const char *) data;
3440   char *p = XALLOCAVEC (char, GET_MODE_SIZE (mode));
3441
3442   memset (p, *c, GET_MODE_SIZE (mode));
3443
3444   return c_readstr (p, mode);
3445 }
3446
3447 /* Callback routine for store_by_pieces.  Return the RTL of a register
3448    containing GET_MODE_SIZE (MODE) consecutive copies of the unsigned
3449    char value given in the RTL register data.  For example, if mode is
3450    4 bytes wide, return the RTL for 0x01010101*data.  */
3451
3452 static rtx
3453 builtin_memset_gen_str (void *data, HOST_WIDE_INT offset ATTRIBUTE_UNUSED,
3454                         enum machine_mode mode)
3455 {
3456   rtx target, coeff;
3457   size_t size;
3458   char *p;
3459
3460   size = GET_MODE_SIZE (mode);
3461   if (size == 1)
3462     return (rtx) data;
3463
3464   p = XALLOCAVEC (char, size);
3465   memset (p, 1, size);
3466   coeff = c_readstr (p, mode);
3467
3468   target = convert_to_mode (mode, (rtx) data, 1);
3469   target = expand_mult (mode, target, coeff, NULL_RTX, 1);
3470   return force_reg (mode, target);
3471 }
3472
3473 /* Expand expression EXP, which is a call to the memset builtin.  Return
3474    NULL_RTX if we failed the caller should emit a normal call, otherwise
3475    try to get the result in TARGET, if convenient (and in mode MODE if that's
3476    convenient).  */
3477
3478 static rtx
3479 expand_builtin_memset (tree exp, rtx target, enum machine_mode mode)
3480 {
3481   if (!validate_arglist (exp,
3482                          POINTER_TYPE, INTEGER_TYPE, INTEGER_TYPE, VOID_TYPE))
3483     return NULL_RTX;
3484   else
3485     {
3486       tree dest = CALL_EXPR_ARG (exp, 0);
3487       tree val = CALL_EXPR_ARG (exp, 1);
3488       tree len = CALL_EXPR_ARG (exp, 2);
3489       return expand_builtin_memset_args (dest, val, len, target, mode, exp);
3490     }
3491 }
3492
3493 /* Helper function to do the actual work for expand_builtin_memset.  The
3494    arguments to the builtin_memset call DEST, VAL, and LEN are broken out
3495    so that this can also be called without constructing an actual CALL_EXPR.
3496    The other arguments and return value are the same as for
3497    expand_builtin_memset.  */
3498
3499 static rtx
3500 expand_builtin_memset_args (tree dest, tree val, tree len,
3501                             rtx target, enum machine_mode mode, tree orig_exp)
3502 {
3503   tree fndecl, fn;
3504   enum built_in_function fcode;
3505   enum machine_mode val_mode;
3506   char c;
3507   unsigned int dest_align;
3508   rtx dest_mem, dest_addr, len_rtx;
3509   HOST_WIDE_INT expected_size = -1;
3510   unsigned int expected_align = 0;
3511
3512   dest_align = get_pointer_alignment (dest);
3513
3514   /* If DEST is not a pointer type, don't do this operation in-line.  */
3515   if (dest_align == 0)
3516     return NULL_RTX;
3517
3518   if (currently_expanding_gimple_stmt)
3519     stringop_block_profile (currently_expanding_gimple_stmt,
3520                             &expected_align, &expected_size);
3521
3522   if (expected_align < dest_align)
3523     expected_align = dest_align;
3524
3525   /* If the LEN parameter is zero, return DEST.  */
3526   if (integer_zerop (len))
3527     {
3528       /* Evaluate and ignore VAL in case it has side-effects.  */
3529       expand_expr (val, const0_rtx, VOIDmode, EXPAND_NORMAL);
3530       return expand_expr (dest, target, mode, EXPAND_NORMAL);
3531     }
3532
3533   /* Stabilize the arguments in case we fail.  */
3534   dest = builtin_save_expr (dest);
3535   val = builtin_save_expr (val);
3536   len = builtin_save_expr (len);
3537
3538   len_rtx = expand_normal (len);
3539   dest_mem = get_memory_rtx (dest, len);
3540   val_mode = TYPE_MODE (unsigned_char_type_node);
3541
3542   if (TREE_CODE (val) != INTEGER_CST)
3543     {
3544       rtx val_rtx;
3545
3546       val_rtx = expand_normal (val);
3547       val_rtx = convert_to_mode (val_mode, val_rtx, 0);
3548
3549       /* Assume that we can memset by pieces if we can store
3550        * the coefficients by pieces (in the required modes).
3551        * We can't pass builtin_memset_gen_str as that emits RTL.  */
3552       c = 1;
3553       if (host_integerp (len, 1)
3554           && can_store_by_pieces (tree_low_cst (len, 1),
3555                                   builtin_memset_read_str, &c, dest_align,
3556                                   true))
3557         {
3558           val_rtx = force_reg (val_mode, val_rtx);
3559           store_by_pieces (dest_mem, tree_low_cst (len, 1),
3560                            builtin_memset_gen_str, val_rtx, dest_align,
3561                            true, 0);
3562         }
3563       else if (!set_storage_via_setmem (dest_mem, len_rtx, val_rtx,
3564                                         dest_align, expected_align,
3565                                         expected_size))
3566         goto do_libcall;
3567
3568       dest_mem = force_operand (XEXP (dest_mem, 0), NULL_RTX);
3569       dest_mem = convert_memory_address (ptr_mode, dest_mem);
3570       return dest_mem;
3571     }
3572
3573   if (target_char_cast (val, &c))
3574     goto do_libcall;
3575
3576   if (c)
3577     {
3578       if (host_integerp (len, 1)
3579           && can_store_by_pieces (tree_low_cst (len, 1),
3580                                   builtin_memset_read_str, &c, dest_align,
3581                                   true))
3582         store_by_pieces (dest_mem, tree_low_cst (len, 1),
3583                          builtin_memset_read_str, &c, dest_align, true, 0);
3584       else if (!set_storage_via_setmem (dest_mem, len_rtx,
3585                                         gen_int_mode (c, val_mode),
3586                                         dest_align, expected_align,
3587                                         expected_size))
3588         goto do_libcall;
3589
3590       dest_mem = force_operand (XEXP (dest_mem, 0), NULL_RTX);
3591       dest_mem = convert_memory_address (ptr_mode, dest_mem);
3592       return dest_mem;
3593     }
3594
3595   set_mem_align (dest_mem, dest_align);
3596   dest_addr = clear_storage_hints (dest_mem, len_rtx,
3597                                    CALL_EXPR_TAILCALL (orig_exp)
3598                                    ? BLOCK_OP_TAILCALL : BLOCK_OP_NORMAL,
3599                                    expected_align, expected_size);
3600
3601   if (dest_addr == 0)
3602     {
3603       dest_addr = force_operand (XEXP (dest_mem, 0), NULL_RTX);
3604       dest_addr = convert_memory_address (ptr_mode, dest_addr);
3605     }
3606
3607   return dest_addr;
3608
3609  do_libcall:
3610   fndecl = get_callee_fndecl (orig_exp);
3611   fcode = DECL_FUNCTION_CODE (fndecl);
3612   if (fcode == BUILT_IN_MEMSET)
3613     fn = build_call_nofold_loc (EXPR_LOCATION (orig_exp), fndecl, 3,
3614                                 dest, val, len);
3615   else if (fcode == BUILT_IN_BZERO)
3616     fn = build_call_nofold_loc (EXPR_LOCATION (orig_exp), fndecl, 2,
3617                                 dest, len);
3618   else
3619     gcc_unreachable ();
3620   gcc_assert (TREE_CODE (fn) == CALL_EXPR);
3621   CALL_EXPR_TAILCALL (fn) = CALL_EXPR_TAILCALL (orig_exp);
3622   return expand_call (fn, target, target == const0_rtx);
3623 }
3624
3625 /* Expand expression EXP, which is a call to the bzero builtin.  Return
3626    NULL_RTX if we failed the caller should emit a normal call.  */
3627
3628 static rtx
3629 expand_builtin_bzero (tree exp)
3630 {
3631   tree dest, size;
3632   location_t loc = EXPR_LOCATION (exp);
3633
3634   if (!validate_arglist (exp, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
3635     return NULL_RTX;
3636
3637   dest = CALL_EXPR_ARG (exp, 0);
3638   size = CALL_EXPR_ARG (exp, 1);
3639
3640   /* New argument list transforming bzero(ptr x, int y) to
3641      memset(ptr x, int 0, size_t y).   This is done this way
3642      so that if it isn't expanded inline, we fallback to
3643      calling bzero instead of memset.  */
3644
3645   return expand_builtin_memset_args (dest, integer_zero_node,
3646                                      fold_convert_loc (loc,
3647                                                        size_type_node, size),
3648                                      const0_rtx, VOIDmode, exp);
3649 }
3650
3651 /* Expand expression EXP, which is a call to the memcmp built-in function.
3652    Return NULL_RTX if we failed and the caller should emit a normal call,
3653    otherwise try to get the result in TARGET, if convenient (and in mode
3654    MODE, if that's convenient).  */
3655
3656 static rtx
3657 expand_builtin_memcmp (tree exp, ATTRIBUTE_UNUSED rtx target,
3658                        ATTRIBUTE_UNUSED enum machine_mode mode)
3659 {
3660   location_t loc ATTRIBUTE_UNUSED = EXPR_LOCATION (exp);
3661
3662   if (!validate_arglist (exp,
3663                          POINTER_TYPE, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
3664     return NULL_RTX;
3665
3666   /* Note: The cmpstrnsi pattern, if it exists, is not suitable for
3667      implementing memcmp because it will stop if it encounters two
3668      zero bytes.  */
3669 #if defined HAVE_cmpmemsi
3670   {
3671     rtx arg1_rtx, arg2_rtx, arg3_rtx;
3672     rtx result;
3673     rtx insn;
3674     tree arg1 = CALL_EXPR_ARG (exp, 0);
3675     tree arg2 = CALL_EXPR_ARG (exp, 1);
3676     tree len = CALL_EXPR_ARG (exp, 2);
3677
3678     unsigned int arg1_align = get_pointer_alignment (arg1) / BITS_PER_UNIT;
3679     unsigned int arg2_align = get_pointer_alignment (arg2) / BITS_PER_UNIT;
3680     enum machine_mode insn_mode;
3681
3682     if (HAVE_cmpmemsi)
3683       insn_mode = insn_data[(int) CODE_FOR_cmpmemsi].operand[0].mode;
3684     else
3685       return NULL_RTX;
3686
3687     /* If we don't have POINTER_TYPE, call the function.  */
3688     if (arg1_align == 0 || arg2_align == 0)
3689       return NULL_RTX;
3690
3691     /* Make a place to write the result of the instruction.  */
3692     result = target;
3693     if (! (result != 0
3694            && REG_P (result) && GET_MODE (result) == insn_mode
3695            && REGNO (result) >= FIRST_PSEUDO_REGISTER))
3696       result = gen_reg_rtx (insn_mode);
3697
3698     arg1_rtx = get_memory_rtx (arg1, len);
3699     arg2_rtx = get_memory_rtx (arg2, len);
3700     arg3_rtx = expand_normal (fold_convert_loc (loc, sizetype, len));
3701
3702     /* Set MEM_SIZE as appropriate.  */
3703     if (CONST_INT_P (arg3_rtx))
3704       {
3705         set_mem_size (arg1_rtx, INTVAL (arg3_rtx));
3706         set_mem_size (arg2_rtx, INTVAL (arg3_rtx));
3707       }
3708
3709     if (HAVE_cmpmemsi)
3710       insn = gen_cmpmemsi (result, arg1_rtx, arg2_rtx, arg3_rtx,
3711                            GEN_INT (MIN (arg1_align, arg2_align)));
3712     else
3713       gcc_unreachable ();
3714
3715     if (insn)
3716       emit_insn (insn);
3717     else
3718       emit_library_call_value (memcmp_libfunc, result, LCT_PURE,
3719                                TYPE_MODE (integer_type_node), 3,
3720                                XEXP (arg1_rtx, 0), Pmode,
3721                                XEXP (arg2_rtx, 0), Pmode,
3722                                convert_to_mode (TYPE_MODE (sizetype), arg3_rtx,
3723                                                 TYPE_UNSIGNED (sizetype)),
3724                                TYPE_MODE (sizetype));
3725
3726     /* Return the value in the proper mode for this function.  */
3727     mode = TYPE_MODE (TREE_TYPE (exp));
3728     if (GET_MODE (result) == mode)
3729       return result;
3730     else if (target != 0)
3731       {
3732         convert_move (target, result, 0);
3733         return target;
3734       }
3735     else
3736       return convert_to_mode (mode, result, 0);
3737   }
3738 #endif /* HAVE_cmpmemsi.  */
3739
3740   return NULL_RTX;
3741 }
3742
3743 /* Expand expression EXP, which is a call to the strcmp builtin.  Return NULL_RTX
3744    if we failed the caller should emit a normal call, otherwise try to get
3745    the result in TARGET, if convenient.  */
3746
3747 static rtx
3748 expand_builtin_strcmp (tree exp, ATTRIBUTE_UNUSED rtx target)
3749 {
3750   if (!validate_arglist (exp, POINTER_TYPE, POINTER_TYPE, VOID_TYPE))
3751     return NULL_RTX;
3752
3753 #if defined HAVE_cmpstrsi || defined HAVE_cmpstrnsi
3754   if (direct_optab_handler (cmpstr_optab, SImode) != CODE_FOR_nothing
3755       || direct_optab_handler (cmpstrn_optab, SImode) != CODE_FOR_nothing)
3756     {
3757       rtx arg1_rtx, arg2_rtx;
3758       rtx result, insn = NULL_RTX;
3759       tree fndecl, fn;
3760       tree arg1 = CALL_EXPR_ARG (exp, 0);
3761       tree arg2 = CALL_EXPR_ARG (exp, 1);
3762
3763       unsigned int arg1_align = get_pointer_alignment (arg1) / BITS_PER_UNIT;
3764       unsigned int arg2_align = get_pointer_alignment (arg2) / BITS_PER_UNIT;
3765
3766       /* If we don't have POINTER_TYPE, call the function.  */
3767       if (arg1_align == 0 || arg2_align == 0)
3768         return NULL_RTX;
3769
3770       /* Stabilize the arguments in case gen_cmpstr(n)si fail.  */
3771       arg1 = builtin_save_expr (arg1);
3772       arg2 = builtin_save_expr (arg2);
3773
3774       arg1_rtx = get_memory_rtx (arg1, NULL);
3775       arg2_rtx = get_memory_rtx (arg2, NULL);
3776
3777 #ifdef HAVE_cmpstrsi
3778       /* Try to call cmpstrsi.  */
3779       if (HAVE_cmpstrsi)
3780         {
3781           enum machine_mode insn_mode
3782             = insn_data[(int) CODE_FOR_cmpstrsi].operand[0].mode;
3783
3784           /* Make a place to write the result of the instruction.  */
3785           result = target;
3786           if (! (result != 0
3787                  && REG_P (result) && GET_MODE (result) == insn_mode
3788                  && REGNO (result) >= FIRST_PSEUDO_REGISTER))
3789             result = gen_reg_rtx (insn_mode);
3790
3791           insn = gen_cmpstrsi (result, arg1_rtx, arg2_rtx,
3792                                GEN_INT (MIN (arg1_align, arg2_align)));
3793         }
3794 #endif
3795 #ifdef HAVE_cmpstrnsi
3796       /* Try to determine at least one length and call cmpstrnsi.  */
3797       if (!insn && HAVE_cmpstrnsi)
3798         {
3799           tree len;
3800           rtx arg3_rtx;
3801
3802           enum machine_mode insn_mode
3803             = insn_data[(int) CODE_FOR_cmpstrnsi].operand[0].mode;
3804           tree len1 = c_strlen (arg1, 1);
3805           tree len2 = c_strlen (arg2, 1);
3806
3807           if (len1)
3808             len1 = size_binop (PLUS_EXPR, ssize_int (1), len1);
3809           if (len2)
3810             len2 = size_binop (PLUS_EXPR, ssize_int (1), len2);
3811
3812           /* If we don't have a constant length for the first, use the length
3813              of the second, if we know it.  We don't require a constant for
3814              this case; some cost analysis could be done if both are available
3815              but neither is constant.  For now, assume they're equally cheap,
3816              unless one has side effects.  If both strings have constant lengths,
3817              use the smaller.  */
3818
3819           if (!len1)
3820             len = len2;
3821           else if (!len2)
3822             len = len1;
3823           else if (TREE_SIDE_EFFECTS (len1))
3824             len = len2;
3825           else if (TREE_SIDE_EFFECTS (len2))
3826             len = len1;
3827           else if (TREE_CODE (len1) != INTEGER_CST)
3828             len = len2;
3829           else if (TREE_CODE (len2) != INTEGER_CST)
3830             len = len1;
3831           else if (tree_int_cst_lt (len1, len2))
3832             len = len1;
3833           else
3834             len = len2;
3835
3836           /* If both arguments have side effects, we cannot optimize.  */
3837           if (!len || TREE_SIDE_EFFECTS (len))
3838             goto do_libcall;
3839
3840           arg3_rtx = expand_normal (len);
3841
3842           /* Make a place to write the result of the instruction.  */
3843           result = target;
3844           if (! (result != 0
3845                  && REG_P (result) && GET_MODE (result) == insn_mode
3846                  && REGNO (result) >= FIRST_PSEUDO_REGISTER))
3847             result = gen_reg_rtx (insn_mode);
3848
3849           insn = gen_cmpstrnsi (result, arg1_rtx, arg2_rtx, arg3_rtx,
3850                                 GEN_INT (MIN (arg1_align, arg2_align)));
3851         }
3852 #endif
3853
3854       if (insn)
3855         {
3856           enum machine_mode mode;
3857           emit_insn (insn);
3858
3859           /* Return the value in the proper mode for this function.  */
3860           mode = TYPE_MODE (TREE_TYPE (exp));
3861           if (GET_MODE (result) == mode)
3862             return result;
3863           if (target == 0)
3864             return convert_to_mode (mode, result, 0);
3865           convert_move (target, result, 0);
3866           return target;
3867         }
3868
3869       /* Expand the library call ourselves using a stabilized argument
3870          list to avoid re-evaluating the function's arguments twice.  */
3871 #ifdef HAVE_cmpstrnsi
3872     do_libcall:
3873 #endif
3874       fndecl = get_callee_fndecl (exp);
3875       fn = build_call_nofold_loc (EXPR_LOCATION (exp), fndecl, 2, arg1, arg2);
3876       gcc_assert (TREE_CODE (fn) == CALL_EXPR);
3877       CALL_EXPR_TAILCALL (fn) = CALL_EXPR_TAILCALL (exp);
3878       return expand_call (fn, target, target == const0_rtx);
3879     }
3880 #endif
3881   return NULL_RTX;
3882 }
3883
3884 /* Expand expression EXP, which is a call to the strncmp builtin. Return
3885    NULL_RTX if we failed the caller should emit a normal call, otherwise try to get
3886    the result in TARGET, if convenient.  */
3887
3888 static rtx
3889 expand_builtin_strncmp (tree exp, ATTRIBUTE_UNUSED rtx target,
3890                         ATTRIBUTE_UNUSED enum machine_mode mode)
3891 {
3892   location_t loc ATTRIBUTE_UNUSED = EXPR_LOCATION (exp);
3893
3894   if (!validate_arglist (exp,
3895                          POINTER_TYPE, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
3896     return NULL_RTX;
3897
3898   /* If c_strlen can determine an expression for one of the string
3899      lengths, and it doesn't have side effects, then emit cmpstrnsi
3900      using length MIN(strlen(string)+1, arg3).  */
3901 #ifdef HAVE_cmpstrnsi
3902   if (HAVE_cmpstrnsi)
3903   {
3904     tree len, len1, len2;
3905     rtx arg1_rtx, arg2_rtx, arg3_rtx;
3906     rtx result, insn;
3907     tree fndecl, fn;
3908     tree arg1 = CALL_EXPR_ARG (exp, 0);
3909     tree arg2 = CALL_EXPR_ARG (exp, 1);
3910     tree arg3 = CALL_EXPR_ARG (exp, 2);
3911
3912     unsigned int arg1_align = get_pointer_alignment (arg1) / BITS_PER_UNIT;
3913     unsigned int arg2_align = get_pointer_alignment (arg2) / BITS_PER_UNIT;
3914     enum machine_mode insn_mode
3915       = insn_data[(int) CODE_FOR_cmpstrnsi].operand[0].mode;
3916
3917     len1 = c_strlen (arg1, 1);
3918     len2 = c_strlen (arg2, 1);
3919
3920     if (len1)
3921       len1 = size_binop_loc (loc, PLUS_EXPR, ssize_int (1), len1);
3922     if (len2)
3923       len2 = size_binop_loc (loc, PLUS_EXPR, ssize_int (1), len2);
3924
3925     /* If we don't have a constant length for the first, use the length
3926        of the second, if we know it.  We don't require a constant for
3927        this case; some cost analysis could be done if both are available
3928        but neither is constant.  For now, assume they're equally cheap,
3929        unless one has side effects.  If both strings have constant lengths,
3930        use the smaller.  */
3931
3932     if (!len1)
3933       len = len2;
3934     else if (!len2)
3935       len = len1;
3936     else if (TREE_SIDE_EFFECTS (len1))
3937       len = len2;
3938     else if (TREE_SIDE_EFFECTS (len2))
3939       len = len1;
3940     else if (TREE_CODE (len1) != INTEGER_CST)
3941       len = len2;
3942     else if (TREE_CODE (len2) != INTEGER_CST)
3943       len = len1;
3944     else if (tree_int_cst_lt (len1, len2))
3945       len = len1;
3946     else
3947       len = len2;
3948
3949     /* If both arguments have side effects, we cannot optimize.  */
3950     if (!len || TREE_SIDE_EFFECTS (len))
3951       return NULL_RTX;
3952
3953     /* The actual new length parameter is MIN(len,arg3).  */
3954     len = fold_build2_loc (loc, MIN_EXPR, TREE_TYPE (len), len,
3955                        fold_convert_loc (loc, TREE_TYPE (len), arg3));
3956
3957     /* If we don't have POINTER_TYPE, call the function.  */
3958     if (arg1_align == 0 || arg2_align == 0)
3959       return NULL_RTX;
3960
3961     /* Make a place to write the result of the instruction.  */
3962     result = target;
3963     if (! (result != 0
3964            && REG_P (result) && GET_MODE (result) == insn_mode
3965            && REGNO (result) >= FIRST_PSEUDO_REGISTER))
3966       result = gen_reg_rtx (insn_mode);
3967
3968     /* Stabilize the arguments in case gen_cmpstrnsi fails.  */
3969     arg1 = builtin_save_expr (arg1);
3970     arg2 = builtin_save_expr (arg2);
3971     len = builtin_save_expr (len);
3972
3973     arg1_rtx = get_memory_rtx (arg1, len);
3974     arg2_rtx = get_memory_rtx (arg2, len);
3975     arg3_rtx = expand_normal (len);
3976     insn = gen_cmpstrnsi (result, arg1_rtx, arg2_rtx, arg3_rtx,
3977                           GEN_INT (MIN (arg1_align, arg2_align)));
3978     if (insn)
3979       {
3980         emit_insn (insn);
3981
3982         /* Return the value in the proper mode for this function.  */
3983         mode = TYPE_MODE (TREE_TYPE (exp));
3984         if (GET_MODE (result) == mode)
3985           return result;
3986         if (target == 0)
3987           return convert_to_mode (mode, result, 0);
3988         convert_move (target, result, 0);
3989         return target;
3990       }
3991
3992     /* Expand the library call ourselves using a stabilized argument
3993        list to avoid re-evaluating the function's arguments twice.  */
3994     fndecl = get_callee_fndecl (exp);
3995     fn = build_call_nofold_loc (EXPR_LOCATION (exp), fndecl, 3,
3996                                 arg1, arg2, len);
3997     gcc_assert (TREE_CODE (fn) == CALL_EXPR);
3998     CALL_EXPR_TAILCALL (fn) = CALL_EXPR_TAILCALL (exp);
3999     return expand_call (fn, target, target == const0_rtx);
4000   }
4001 #endif
4002   return NULL_RTX;
4003 }
4004
4005 /* Expand a call to __builtin_saveregs, generating the result in TARGET,
4006    if that's convenient.  */
4007
4008 rtx
4009 expand_builtin_saveregs (void)
4010 {
4011   rtx val, seq;
4012
4013   /* Don't do __builtin_saveregs more than once in a function.
4014      Save the result of the first call and reuse it.  */
4015   if (saveregs_value != 0)
4016     return saveregs_value;
4017
4018   /* When this function is called, it means that registers must be
4019      saved on entry to this function.  So we migrate the call to the
4020      first insn of this function.  */
4021
4022   start_sequence ();
4023
4024   /* Do whatever the machine needs done in this case.  */
4025   val = targetm.calls.expand_builtin_saveregs ();
4026
4027   seq = get_insns ();
4028   end_sequence ();
4029
4030   saveregs_value = val;
4031
4032   /* Put the insns after the NOTE that starts the function.  If this
4033      is inside a start_sequence, make the outer-level insn chain current, so
4034      the code is placed at the start of the function.  */
4035   push_topmost_sequence ();
4036   emit_insn_after (seq, entry_of_function ());
4037   pop_topmost_sequence ();
4038
4039   return val;
4040 }
4041
4042 /* Expand a call to __builtin_next_arg.  */
4043
4044 static rtx
4045 expand_builtin_next_arg (void)
4046 {
4047   /* Checking arguments is already done in fold_builtin_next_arg
4048      that must be called before this function.  */
4049   return expand_binop (ptr_mode, add_optab,
4050                        crtl->args.internal_arg_pointer,
4051                        crtl->args.arg_offset_rtx,
4052                        NULL_RTX, 0, OPTAB_LIB_WIDEN);
4053 }
4054
4055 /* Make it easier for the backends by protecting the valist argument
4056    from multiple evaluations.  */
4057
4058 static tree
4059 stabilize_va_list_loc (location_t loc, tree valist, int needs_lvalue)
4060 {
4061   tree vatype = targetm.canonical_va_list_type (TREE_TYPE (valist));
4062
4063   /* The current way of determining the type of valist is completely
4064      bogus.  We should have the information on the va builtin instead.  */
4065   if (!vatype)
4066     vatype = targetm.fn_abi_va_list (cfun->decl);
4067
4068   if (TREE_CODE (vatype) == ARRAY_TYPE)
4069     {
4070       if (TREE_SIDE_EFFECTS (valist))
4071         valist = save_expr (valist);
4072
4073       /* For this case, the backends will be expecting a pointer to
4074          vatype, but it's possible we've actually been given an array
4075          (an actual TARGET_CANONICAL_VA_LIST_TYPE (valist)).
4076          So fix it.  */
4077       if (TREE_CODE (TREE_TYPE (valist)) == ARRAY_TYPE)
4078         {
4079           tree p1 = build_pointer_type (TREE_TYPE (vatype));
4080           valist = build_fold_addr_expr_with_type_loc (loc, valist, p1);
4081         }
4082     }
4083   else
4084     {
4085       tree pt = build_pointer_type (vatype);
4086
4087       if (! needs_lvalue)
4088         {
4089           if (! TREE_SIDE_EFFECTS (valist))
4090             return valist;
4091
4092           valist = fold_build1_loc (loc, ADDR_EXPR, pt, valist);
4093           TREE_SIDE_EFFECTS (valist) = 1;
4094         }
4095
4096       if (TREE_SIDE_EFFECTS (valist))
4097         valist = save_expr (valist);
4098       valist = fold_build2_loc (loc, MEM_REF,
4099                                 vatype, valist, build_int_cst (pt, 0));
4100     }
4101
4102   return valist;
4103 }
4104
4105 /* The "standard" definition of va_list is void*.  */
4106
4107 tree
4108 std_build_builtin_va_list (void)
4109 {
4110   return ptr_type_node;
4111 }
4112
4113 /* The "standard" abi va_list is va_list_type_node.  */
4114
4115 tree
4116 std_fn_abi_va_list (tree fndecl ATTRIBUTE_UNUSED)
4117 {
4118   return va_list_type_node;
4119 }
4120
4121 /* The "standard" type of va_list is va_list_type_node.  */
4122
4123 tree
4124 std_canonical_va_list_type (tree type)
4125 {
4126   tree wtype, htype;
4127
4128   if (INDIRECT_REF_P (type))
4129     type = TREE_TYPE (type);
4130   else if (POINTER_TYPE_P (type) && POINTER_TYPE_P (TREE_TYPE(type)))
4131     type = TREE_TYPE (type);
4132   wtype = va_list_type_node;
4133   htype = type;
4134   /* Treat structure va_list types.  */
4135   if (TREE_CODE (wtype) == RECORD_TYPE && POINTER_TYPE_P (htype))
4136     htype = TREE_TYPE (htype);
4137   else if (TREE_CODE (wtype) == ARRAY_TYPE)
4138     {
4139       /* If va_list is an array type, the argument may have decayed
4140          to a pointer type, e.g. by being passed to another function.
4141          In that case, unwrap both types so that we can compare the
4142          underlying records.  */
4143       if (TREE_CODE (htype) == ARRAY_TYPE
4144           || POINTER_TYPE_P (htype))
4145         {
4146           wtype = TREE_TYPE (wtype);
4147           htype = TREE_TYPE (htype);
4148         }
4149     }
4150   if (TYPE_MAIN_VARIANT (wtype) == TYPE_MAIN_VARIANT (htype))
4151     return va_list_type_node;
4152
4153   return NULL_TREE;
4154 }
4155
4156 /* The "standard" implementation of va_start: just assign `nextarg' to
4157    the variable.  */
4158
4159 void
4160 std_expand_builtin_va_start (tree valist, rtx nextarg)
4161 {
4162   rtx va_r = expand_expr (valist, NULL_RTX, VOIDmode, EXPAND_WRITE);
4163   convert_move (va_r, nextarg, 0);
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 /* The "standard" implementation of va_arg: read the value from the
4196    current (padded) address and increment by the (padded) size.  */
4197
4198 tree
4199 std_gimplify_va_arg_expr (tree valist, tree type, gimple_seq *pre_p,
4200                           gimple_seq *post_p)
4201 {
4202   tree addr, t, type_size, rounded_size, valist_tmp;
4203   unsigned HOST_WIDE_INT align, boundary;
4204   bool indirect;
4205
4206 #ifdef ARGS_GROW_DOWNWARD
4207   /* All of the alignment and movement below is for args-grow-up machines.
4208      As of 2004, there are only 3 ARGS_GROW_DOWNWARD targets, and they all
4209      implement their own specialized gimplify_va_arg_expr routines.  */
4210   gcc_unreachable ();
4211 #endif
4212
4213   indirect = pass_by_reference (NULL, TYPE_MODE (type), type, false);
4214   if (indirect)
4215     type = build_pointer_type (type);
4216
4217   align = PARM_BOUNDARY / BITS_PER_UNIT;
4218   boundary = targetm.calls.function_arg_boundary (TYPE_MODE (type), type);
4219
4220   /* When we align parameter on stack for caller, if the parameter
4221      alignment is beyond MAX_SUPPORTED_STACK_ALIGNMENT, it will be
4222      aligned at MAX_SUPPORTED_STACK_ALIGNMENT.  We will match callee
4223      here with caller.  */
4224   if (boundary > MAX_SUPPORTED_STACK_ALIGNMENT)
4225     boundary = MAX_SUPPORTED_STACK_ALIGNMENT;
4226
4227   boundary /= BITS_PER_UNIT;
4228
4229   /* Hoist the valist value into a temporary for the moment.  */
4230   valist_tmp = get_initialized_tmp_var (valist, pre_p, NULL);
4231
4232   /* va_list pointer is aligned to PARM_BOUNDARY.  If argument actually
4233      requires greater alignment, we must perform dynamic alignment.  */
4234   if (boundary > align
4235       && !integer_zerop (TYPE_SIZE (type)))
4236     {
4237       t = build2 (MODIFY_EXPR, TREE_TYPE (valist), valist_tmp,
4238                   fold_build_pointer_plus_hwi (valist_tmp, boundary - 1));
4239       gimplify_and_add (t, pre_p);
4240
4241       t = build2 (MODIFY_EXPR, TREE_TYPE (valist), valist_tmp,
4242                   fold_build2 (BIT_AND_EXPR, TREE_TYPE (valist),
4243                                valist_tmp,
4244                                build_int_cst (TREE_TYPE (valist), -boundary)));
4245       gimplify_and_add (t, pre_p);
4246     }
4247   else
4248     boundary = align;
4249
4250   /* If the actual alignment is less than the alignment of the type,
4251      adjust the type accordingly so that we don't assume strict alignment
4252      when dereferencing the pointer.  */
4253   boundary *= BITS_PER_UNIT;
4254   if (boundary < TYPE_ALIGN (type))
4255     {
4256       type = build_variant_type_copy (type);
4257       TYPE_ALIGN (type) = boundary;
4258     }
4259
4260   /* Compute the rounded size of the type.  */
4261   type_size = size_in_bytes (type);
4262   rounded_size = round_up (type_size, align);
4263
4264   /* Reduce rounded_size so it's sharable with the postqueue.  */
4265   gimplify_expr (&rounded_size, pre_p, post_p, is_gimple_val, fb_rvalue);
4266
4267   /* Get AP.  */
4268   addr = valist_tmp;
4269   if (PAD_VARARGS_DOWN && !integer_zerop (rounded_size))
4270     {
4271       /* Small args are padded downward.  */
4272       t = fold_build2_loc (input_location, GT_EXPR, sizetype,
4273                        rounded_size, size_int (align));
4274       t = fold_build3 (COND_EXPR, sizetype, t, size_zero_node,
4275                        size_binop (MINUS_EXPR, rounded_size, type_size));
4276       addr = fold_build_pointer_plus (addr, t);
4277     }
4278
4279   /* Compute new value for AP.  */
4280   t = fold_build_pointer_plus (valist_tmp, rounded_size);
4281   t = build2 (MODIFY_EXPR, TREE_TYPE (valist), valist, t);
4282   gimplify_and_add (t, pre_p);
4283
4284   addr = fold_convert (build_pointer_type (type), addr);
4285
4286   if (indirect)
4287     addr = build_va_arg_indirect_ref (addr);
4288
4289   return build_va_arg_indirect_ref (addr);
4290 }
4291
4292 /* Build an indirect-ref expression over the given TREE, which represents a
4293    piece of a va_arg() expansion.  */
4294 tree
4295 build_va_arg_indirect_ref (tree addr)
4296 {
4297   addr = build_simple_mem_ref_loc (EXPR_LOCATION (addr), addr);
4298
4299   if (flag_mudflap) /* Don't instrument va_arg INDIRECT_REF.  */
4300     mf_mark (addr);
4301
4302   return addr;
4303 }
4304
4305 /* Return a dummy expression of type TYPE in order to keep going after an
4306    error.  */
4307
4308 static tree
4309 dummy_object (tree type)
4310 {
4311   tree t = build_int_cst (build_pointer_type (type), 0);
4312   return build2 (MEM_REF, type, t, t);
4313 }
4314
4315 /* Gimplify __builtin_va_arg, aka VA_ARG_EXPR, which is not really a
4316    builtin function, but a very special sort of operator.  */
4317
4318 enum gimplify_status
4319 gimplify_va_arg_expr (tree *expr_p, gimple_seq *pre_p, gimple_seq *post_p)
4320 {
4321   tree promoted_type, have_va_type;
4322   tree valist = TREE_OPERAND (*expr_p, 0);
4323   tree type = TREE_TYPE (*expr_p);
4324   tree t;
4325   location_t loc = EXPR_LOCATION (*expr_p);
4326
4327   /* Verify that valist is of the proper type.  */
4328   have_va_type = TREE_TYPE (valist);
4329   if (have_va_type == error_mark_node)
4330     return GS_ERROR;
4331   have_va_type = targetm.canonical_va_list_type (have_va_type);
4332
4333   if (have_va_type == NULL_TREE)
4334     {
4335       error_at (loc, "first argument to %<va_arg%> not of type %<va_list%>");
4336       return GS_ERROR;
4337     }
4338
4339   /* Generate a diagnostic for requesting data of a type that cannot
4340      be passed through `...' due to type promotion at the call site.  */
4341   if ((promoted_type = lang_hooks.types.type_promotes_to (type))
4342            != type)
4343     {
4344       static bool gave_help;
4345       bool warned;
4346
4347       /* Unfortunately, this is merely undefined, rather than a constraint
4348          violation, so we cannot make this an error.  If this call is never
4349          executed, the program is still strictly conforming.  */
4350       warned = warning_at (loc, 0,
4351                            "%qT is promoted to %qT when passed through %<...%>",
4352                            type, promoted_type);
4353       if (!gave_help && warned)
4354         {
4355           gave_help = true;
4356           inform (loc, "(so you should pass %qT not %qT to %<va_arg%>)",
4357                   promoted_type, type);
4358         }
4359
4360       /* We can, however, treat "undefined" any way we please.
4361          Call abort to encourage the user to fix the program.  */
4362       if (warned)
4363         inform (loc, "if this code is reached, the program will abort");
4364       /* Before the abort, allow the evaluation of the va_list
4365          expression to exit or longjmp.  */
4366       gimplify_and_add (valist, pre_p);
4367       t = build_call_expr_loc (loc,
4368                                builtin_decl_implicit (BUILT_IN_TRAP), 0);
4369       gimplify_and_add (t, pre_p);
4370
4371       /* This is dead code, but go ahead and finish so that the
4372          mode of the result comes out right.  */
4373       *expr_p = dummy_object (type);
4374       return GS_ALL_DONE;
4375     }
4376   else
4377     {
4378       /* Make it easier for the backends by protecting the valist argument
4379          from multiple evaluations.  */
4380       if (TREE_CODE (have_va_type) == ARRAY_TYPE)
4381         {
4382           /* For this case, the backends will be expecting a pointer to
4383              TREE_TYPE (abi), but it's possible we've
4384              actually been given an array (an actual TARGET_FN_ABI_VA_LIST).
4385              So fix it.  */
4386           if (TREE_CODE (TREE_TYPE (valist)) == ARRAY_TYPE)
4387             {
4388               tree p1 = build_pointer_type (TREE_TYPE (have_va_type));
4389               valist = fold_convert_loc (loc, p1,
4390                                          build_fold_addr_expr_loc (loc, valist));
4391             }
4392
4393           gimplify_expr (&valist, pre_p, post_p, is_gimple_val, fb_rvalue);
4394         }
4395       else
4396         gimplify_expr (&valist, pre_p, post_p, is_gimple_min_lval, fb_lvalue);
4397
4398       if (!targetm.gimplify_va_arg_expr)
4399         /* FIXME: Once most targets are converted we should merely
4400            assert this is non-null.  */
4401         return GS_ALL_DONE;
4402
4403       *expr_p = targetm.gimplify_va_arg_expr (valist, type, pre_p, post_p);
4404       return GS_OK;
4405     }
4406 }
4407
4408 /* Expand EXP, a call to __builtin_va_end.  */
4409
4410 static rtx
4411 expand_builtin_va_end (tree exp)
4412 {
4413   tree valist = CALL_EXPR_ARG (exp, 0);
4414
4415   /* Evaluate for side effects, if needed.  I hate macros that don't
4416      do that.  */
4417   if (TREE_SIDE_EFFECTS (valist))
4418     expand_expr (valist, const0_rtx, VOIDmode, EXPAND_NORMAL);
4419
4420   return const0_rtx;
4421 }
4422
4423 /* Expand EXP, a call to __builtin_va_copy.  We do this as a
4424    builtin rather than just as an assignment in stdarg.h because of the
4425    nastiness of array-type va_list types.  */
4426
4427 static rtx
4428 expand_builtin_va_copy (tree exp)
4429 {
4430   tree dst, src, t;
4431   location_t loc = EXPR_LOCATION (exp);
4432
4433   dst = CALL_EXPR_ARG (exp, 0);
4434   src = CALL_EXPR_ARG (exp, 1);
4435
4436   dst = stabilize_va_list_loc (loc, dst, 1);
4437   src = stabilize_va_list_loc (loc, src, 0);
4438
4439   gcc_assert (cfun != NULL && cfun->decl != NULL_TREE);
4440
4441   if (TREE_CODE (targetm.fn_abi_va_list (cfun->decl)) != ARRAY_TYPE)
4442     {
4443       t = build2 (MODIFY_EXPR, targetm.fn_abi_va_list (cfun->decl), dst, src);
4444       TREE_SIDE_EFFECTS (t) = 1;
4445       expand_expr (t, const0_rtx, VOIDmode, EXPAND_NORMAL);
4446     }
4447   else
4448     {
4449       rtx dstb, srcb, size;
4450
4451       /* Evaluate to pointers.  */
4452       dstb = expand_expr (dst, NULL_RTX, Pmode, EXPAND_NORMAL);
4453       srcb = expand_expr (src, NULL_RTX, Pmode, EXPAND_NORMAL);
4454       size = expand_expr (TYPE_SIZE_UNIT (targetm.fn_abi_va_list (cfun->decl)),
4455                   NULL_RTX, VOIDmode, EXPAND_NORMAL);
4456
4457       dstb = convert_memory_address (Pmode, dstb);
4458       srcb = convert_memory_address (Pmode, srcb);
4459
4460       /* "Dereference" to BLKmode memories.  */
4461       dstb = gen_rtx_MEM (BLKmode, dstb);
4462       set_mem_alias_set (dstb, get_alias_set (TREE_TYPE (TREE_TYPE (dst))));
4463       set_mem_align (dstb, TYPE_ALIGN (targetm.fn_abi_va_list (cfun->decl)));
4464       srcb = gen_rtx_MEM (BLKmode, srcb);
4465       set_mem_alias_set (srcb, get_alias_set (TREE_TYPE (TREE_TYPE (src))));
4466       set_mem_align (srcb, TYPE_ALIGN (targetm.fn_abi_va_list (cfun->decl)));
4467
4468       /* Copy.  */
4469       emit_block_move (dstb, srcb, size, BLOCK_OP_NORMAL);
4470     }
4471
4472   return const0_rtx;
4473 }
4474
4475 /* Expand a call to one of the builtin functions __builtin_frame_address or
4476    __builtin_return_address.  */
4477
4478 static rtx
4479 expand_builtin_frame_address (tree fndecl, tree exp)
4480 {
4481   /* The argument must be a nonnegative integer constant.
4482      It counts the number of frames to scan up the stack.
4483      The value is the return address saved in that frame.  */
4484   if (call_expr_nargs (exp) == 0)
4485     /* Warning about missing arg was already issued.  */
4486     return const0_rtx;
4487   else if (! host_integerp (CALL_EXPR_ARG (exp, 0), 1))
4488     {
4489       if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_FRAME_ADDRESS)
4490         error ("invalid argument to %<__builtin_frame_address%>");
4491       else
4492         error ("invalid argument to %<__builtin_return_address%>");
4493       return const0_rtx;
4494     }
4495   else
4496     {
4497       rtx tem
4498         = expand_builtin_return_addr (DECL_FUNCTION_CODE (fndecl),
4499                                       tree_low_cst (CALL_EXPR_ARG (exp, 0), 1));
4500
4501       /* Some ports cannot access arbitrary stack frames.  */
4502       if (tem == NULL)
4503         {
4504           if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_FRAME_ADDRESS)
4505             warning (0, "unsupported argument to %<__builtin_frame_address%>");
4506           else
4507             warning (0, "unsupported argument to %<__builtin_return_address%>");
4508           return const0_rtx;
4509         }
4510
4511       /* For __builtin_frame_address, return what we've got.  */
4512       if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_FRAME_ADDRESS)
4513         return tem;
4514
4515       if (!REG_P (tem)
4516           && ! CONSTANT_P (tem))
4517         tem = copy_addr_to_reg (tem);
4518       return tem;
4519     }
4520 }
4521
4522 /* Expand EXP, a call to the alloca builtin.  Return NULL_RTX if we
4523    failed and the caller should emit a normal call.  CANNOT_ACCUMULATE
4524    is the same as for allocate_dynamic_stack_space.  */
4525
4526 static rtx
4527 expand_builtin_alloca (tree exp, bool cannot_accumulate)
4528 {
4529   rtx op0;
4530   rtx result;
4531   bool valid_arglist;
4532   unsigned int align;
4533   bool alloca_with_align = (DECL_FUNCTION_CODE (get_callee_fndecl (exp))
4534                             == BUILT_IN_ALLOCA_WITH_ALIGN);
4535
4536   /* Emit normal call if we use mudflap.  */
4537   if (flag_mudflap)
4538     return NULL_RTX;
4539
4540   valid_arglist
4541     = (alloca_with_align
4542        ? validate_arglist (exp, INTEGER_TYPE, INTEGER_TYPE, VOID_TYPE)
4543        : validate_arglist (exp, INTEGER_TYPE, VOID_TYPE));
4544
4545   if (!valid_arglist)
4546     return NULL_RTX;
4547
4548   /* Compute the argument.  */
4549   op0 = expand_normal (CALL_EXPR_ARG (exp, 0));
4550
4551   /* Compute the alignment.  */
4552   align = (alloca_with_align
4553            ? TREE_INT_CST_LOW (CALL_EXPR_ARG (exp, 1))
4554            : BIGGEST_ALIGNMENT);
4555
4556   /* Allocate the desired space.  */
4557   result = allocate_dynamic_stack_space (op0, 0, align, cannot_accumulate);
4558   result = convert_memory_address (ptr_mode, result);
4559
4560   return result;
4561 }
4562
4563 /* Expand a call to bswap builtin in EXP.
4564    Return NULL_RTX if a normal call should be emitted rather than expanding the
4565    function in-line.  If convenient, the result should be placed in TARGET.
4566    SUBTARGET may be used as the target for computing one of EXP's operands.  */
4567
4568 static rtx
4569 expand_builtin_bswap (enum machine_mode target_mode, tree exp, rtx target,
4570                       rtx subtarget)
4571 {
4572   tree arg;
4573   rtx op0;
4574
4575   if (!validate_arglist (exp, INTEGER_TYPE, VOID_TYPE))
4576     return NULL_RTX;
4577
4578   arg = CALL_EXPR_ARG (exp, 0);
4579   op0 = expand_expr (arg,
4580                      subtarget && GET_MODE (subtarget) == target_mode
4581                      ? subtarget : NULL_RTX,
4582                      target_mode, EXPAND_NORMAL);
4583   if (GET_MODE (op0) != target_mode)
4584     op0 = convert_to_mode (target_mode, op0, 1);
4585
4586   target = expand_unop (target_mode, bswap_optab, op0, target, 1);
4587
4588   gcc_assert (target);
4589
4590   return convert_to_mode (target_mode, target, 1);
4591 }
4592
4593 /* Expand a call to a unary builtin in EXP.
4594    Return NULL_RTX if a normal call should be emitted rather than expanding the
4595    function in-line.  If convenient, the result should be placed in TARGET.
4596    SUBTARGET may be used as the target for computing one of EXP's operands.  */
4597
4598 static rtx
4599 expand_builtin_unop (enum machine_mode target_mode, tree exp, rtx target,
4600                      rtx subtarget, optab op_optab)
4601 {
4602   rtx op0;
4603
4604   if (!validate_arglist (exp, INTEGER_TYPE, VOID_TYPE))
4605     return NULL_RTX;
4606
4607   /* Compute the argument.  */
4608   op0 = expand_expr (CALL_EXPR_ARG (exp, 0),
4609                      (subtarget
4610                       && (TYPE_MODE (TREE_TYPE (CALL_EXPR_ARG (exp, 0)))
4611                           == GET_MODE (subtarget))) ? subtarget : NULL_RTX,
4612                      VOIDmode, EXPAND_NORMAL);
4613   /* Compute op, into TARGET if possible.
4614      Set TARGET to wherever the result comes back.  */
4615   target = expand_unop (TYPE_MODE (TREE_TYPE (CALL_EXPR_ARG (exp, 0))),
4616                         op_optab, op0, target, op_optab != clrsb_optab);
4617   gcc_assert (target);
4618
4619   return convert_to_mode (target_mode, target, 0);
4620 }
4621
4622 /* Expand a call to __builtin_expect.  We just return our argument
4623    as the builtin_expect semantic should've been already executed by
4624    tree branch prediction pass. */
4625
4626 static rtx
4627 expand_builtin_expect (tree exp, rtx target)
4628 {
4629   tree arg;
4630
4631   if (call_expr_nargs (exp) < 2)
4632     return const0_rtx;
4633   arg = CALL_EXPR_ARG (exp, 0);
4634
4635   target = expand_expr (arg, target, VOIDmode, EXPAND_NORMAL);
4636   /* When guessing was done, the hints should be already stripped away.  */
4637   gcc_assert (!flag_guess_branch_prob
4638               || optimize == 0 || seen_error ());
4639   return target;
4640 }
4641
4642 /* Expand a call to __builtin_assume_aligned.  We just return our first
4643    argument as the builtin_assume_aligned semantic should've been already
4644    executed by CCP.  */
4645
4646 static rtx
4647 expand_builtin_assume_aligned (tree exp, rtx target)
4648 {
4649   if (call_expr_nargs (exp) < 2)
4650     return const0_rtx;
4651   target = expand_expr (CALL_EXPR_ARG (exp, 0), target, VOIDmode,
4652                         EXPAND_NORMAL);
4653   gcc_assert (!TREE_SIDE_EFFECTS (CALL_EXPR_ARG (exp, 1))
4654               && (call_expr_nargs (exp) < 3
4655                   || !TREE_SIDE_EFFECTS (CALL_EXPR_ARG (exp, 2))));
4656   return target;
4657 }
4658
4659 void
4660 expand_builtin_trap (void)
4661 {
4662 #ifdef HAVE_trap
4663   if (HAVE_trap)
4664     {
4665       rtx insn = emit_insn (gen_trap ());
4666       /* For trap insns when not accumulating outgoing args force
4667          REG_ARGS_SIZE note to prevent crossjumping of calls with
4668          different args sizes.  */
4669       if (!ACCUMULATE_OUTGOING_ARGS)
4670         add_reg_note (insn, REG_ARGS_SIZE, GEN_INT (stack_pointer_delta));
4671     }
4672   else
4673 #endif
4674     emit_library_call (abort_libfunc, LCT_NORETURN, VOIDmode, 0);
4675   emit_barrier ();
4676 }
4677
4678 /* Expand a call to __builtin_unreachable.  We do nothing except emit
4679    a barrier saying that control flow will not pass here.
4680
4681    It is the responsibility of the program being compiled to ensure
4682    that control flow does never reach __builtin_unreachable.  */
4683 static void
4684 expand_builtin_unreachable (void)
4685 {
4686   emit_barrier ();
4687 }
4688
4689 /* Expand EXP, a call to fabs, fabsf or fabsl.
4690    Return NULL_RTX if a normal call should be emitted rather than expanding
4691    the function inline.  If convenient, the result should be placed
4692    in TARGET.  SUBTARGET may be used as the target for computing
4693    the operand.  */
4694
4695 static rtx
4696 expand_builtin_fabs (tree exp, rtx target, rtx subtarget)
4697 {
4698   enum machine_mode mode;
4699   tree arg;
4700   rtx op0;
4701
4702   if (!validate_arglist (exp, REAL_TYPE, VOID_TYPE))
4703     return NULL_RTX;
4704
4705   arg = CALL_EXPR_ARG (exp, 0);
4706   CALL_EXPR_ARG (exp, 0) = arg = builtin_save_expr (arg);
4707   mode = TYPE_MODE (TREE_TYPE (arg));
4708   op0 = expand_expr (arg, subtarget, VOIDmode, EXPAND_NORMAL);
4709   return expand_abs (mode, op0, target, 0, safe_from_p (target, arg, 1));
4710 }
4711
4712 /* Expand EXP, a call to copysign, copysignf, or copysignl.
4713    Return NULL is a normal call should be emitted rather than expanding the
4714    function inline.  If convenient, the result should be placed in TARGET.
4715    SUBTARGET may be used as the target for computing the operand.  */
4716
4717 static rtx
4718 expand_builtin_copysign (tree exp, rtx target, rtx subtarget)
4719 {
4720   rtx op0, op1;
4721   tree arg;
4722
4723   if (!validate_arglist (exp, REAL_TYPE, REAL_TYPE, VOID_TYPE))
4724     return NULL_RTX;
4725
4726   arg = CALL_EXPR_ARG (exp, 0);
4727   op0 = expand_expr (arg, subtarget, VOIDmode, EXPAND_NORMAL);
4728
4729   arg = CALL_EXPR_ARG (exp, 1);
4730   op1 = expand_normal (arg);
4731
4732   return expand_copysign (op0, op1, target);
4733 }
4734
4735 /* Create a new constant string literal and return a char* pointer to it.
4736    The STRING_CST value is the LEN characters at STR.  */
4737 tree
4738 build_string_literal (int len, const char *str)
4739 {
4740   tree t, elem, index, type;
4741
4742   t = build_string (len, str);
4743   elem = build_type_variant (char_type_node, 1, 0);
4744   index = build_index_type (size_int (len - 1));
4745   type = build_array_type (elem, index);
4746   TREE_TYPE (t) = type;
4747   TREE_CONSTANT (t) = 1;
4748   TREE_READONLY (t) = 1;
4749   TREE_STATIC (t) = 1;
4750
4751   type = build_pointer_type (elem);
4752   t = build1 (ADDR_EXPR, type,
4753               build4 (ARRAY_REF, elem,
4754                       t, integer_zero_node, NULL_TREE, NULL_TREE));
4755   return t;
4756 }
4757
4758 /* Expand a call to __builtin___clear_cache.  */
4759
4760 static rtx
4761 expand_builtin___clear_cache (tree exp ATTRIBUTE_UNUSED)
4762 {
4763 #ifndef HAVE_clear_cache
4764 #ifdef CLEAR_INSN_CACHE
4765   /* There is no "clear_cache" insn, and __clear_cache() in libgcc
4766      does something.  Just do the default expansion to a call to
4767      __clear_cache().  */
4768   return NULL_RTX;
4769 #else
4770   /* There is no "clear_cache" insn, and __clear_cache() in libgcc
4771      does nothing.  There is no need to call it.  Do nothing.  */
4772   return const0_rtx;
4773 #endif /* CLEAR_INSN_CACHE */
4774 #else
4775   /* We have a "clear_cache" insn, and it will handle everything.  */
4776   tree begin, end;
4777   rtx begin_rtx, end_rtx;
4778
4779   /* We must not expand to a library call.  If we did, any
4780      fallback library function in libgcc that might contain a call to
4781      __builtin___clear_cache() would recurse infinitely.  */
4782   if (!validate_arglist (exp, POINTER_TYPE, POINTER_TYPE, VOID_TYPE))
4783     {
4784       error ("both arguments to %<__builtin___clear_cache%> must be pointers");
4785       return const0_rtx;
4786     }
4787
4788   if (HAVE_clear_cache)
4789     {
4790       struct expand_operand ops[2];
4791
4792       begin = CALL_EXPR_ARG (exp, 0);
4793       begin_rtx = expand_expr (begin, NULL_RTX, Pmode, EXPAND_NORMAL);
4794
4795       end = CALL_EXPR_ARG (exp, 1);
4796       end_rtx = expand_expr (end, NULL_RTX, Pmode, EXPAND_NORMAL);
4797
4798       create_address_operand (&ops[0], begin_rtx);
4799       create_address_operand (&ops[1], end_rtx);
4800       if (maybe_expand_insn (CODE_FOR_clear_cache, 2, ops))
4801         return const0_rtx;
4802     }
4803   return const0_rtx;
4804 #endif /* HAVE_clear_cache */
4805 }
4806
4807 /* Given a trampoline address, make sure it satisfies TRAMPOLINE_ALIGNMENT.  */
4808
4809 static rtx
4810 round_trampoline_addr (rtx tramp)
4811 {
4812   rtx temp, addend, mask;
4813
4814   /* If we don't need too much alignment, we'll have been guaranteed
4815      proper alignment by get_trampoline_type.  */
4816   if (TRAMPOLINE_ALIGNMENT <= STACK_BOUNDARY)
4817     return tramp;
4818
4819   /* Round address up to desired boundary.  */
4820   temp = gen_reg_rtx (Pmode);
4821   addend = GEN_INT (TRAMPOLINE_ALIGNMENT / BITS_PER_UNIT - 1);
4822   mask = GEN_INT (-TRAMPOLINE_ALIGNMENT / BITS_PER_UNIT);
4823
4824   temp  = expand_simple_binop (Pmode, PLUS, tramp, addend,
4825                                temp, 0, OPTAB_LIB_WIDEN);
4826   tramp = expand_simple_binop (Pmode, AND, temp, mask,
4827                                temp, 0, OPTAB_LIB_WIDEN);
4828
4829   return tramp;
4830 }
4831
4832 static rtx
4833 expand_builtin_init_trampoline (tree exp, bool onstack)
4834 {
4835   tree t_tramp, t_func, t_chain;
4836   rtx m_tramp, r_tramp, r_chain, tmp;
4837
4838   if (!validate_arglist (exp, POINTER_TYPE, POINTER_TYPE,
4839                          POINTER_TYPE, VOID_TYPE))
4840     return NULL_RTX;
4841
4842   t_tramp = CALL_EXPR_ARG (exp, 0);
4843   t_func = CALL_EXPR_ARG (exp, 1);
4844   t_chain = CALL_EXPR_ARG (exp, 2);
4845
4846   r_tramp = expand_normal (t_tramp);
4847   m_tramp = gen_rtx_MEM (BLKmode, r_tramp);
4848   MEM_NOTRAP_P (m_tramp) = 1;
4849
4850   /* If ONSTACK, the TRAMP argument should be the address of a field
4851      within the local function's FRAME decl.  Either way, let's see if
4852      we can fill in the MEM_ATTRs for this memory.  */
4853   if (TREE_CODE (t_tramp) == ADDR_EXPR)
4854     set_mem_attributes (m_tramp, TREE_OPERAND (t_tramp, 0), true);
4855
4856   /* Creator of a heap trampoline is responsible for making sure the
4857      address is aligned to at least STACK_BOUNDARY.  Normally malloc
4858      will ensure this anyhow.  */
4859   tmp = round_trampoline_addr (r_tramp);
4860   if (tmp != r_tramp)
4861     {
4862       m_tramp = change_address (m_tramp, BLKmode, tmp);
4863       set_mem_align (m_tramp, TRAMPOLINE_ALIGNMENT);
4864       set_mem_size (m_tramp, TRAMPOLINE_SIZE);
4865     }
4866
4867   /* The FUNC argument should be the address of the nested function.
4868      Extract the actual function decl to pass to the hook.  */
4869   gcc_assert (TREE_CODE (t_func) == ADDR_EXPR);
4870   t_func = TREE_OPERAND (t_func, 0);
4871   gcc_assert (TREE_CODE (t_func) == FUNCTION_DECL);
4872
4873   r_chain = expand_normal (t_chain);
4874
4875   /* Generate insns to initialize the trampoline.  */
4876   targetm.calls.trampoline_init (m_tramp, t_func, r_chain);
4877
4878   if (onstack)
4879     {
4880       trampolines_created = 1;
4881
4882       warning_at (DECL_SOURCE_LOCATION (t_func), OPT_Wtrampolines,
4883                   "trampoline generated for nested function %qD", t_func);
4884     }
4885
4886   return const0_rtx;
4887 }
4888
4889 static rtx
4890 expand_builtin_adjust_trampoline (tree exp)
4891 {
4892   rtx tramp;
4893
4894   if (!validate_arglist (exp, POINTER_TYPE, VOID_TYPE))
4895     return NULL_RTX;
4896
4897   tramp = expand_normal (CALL_EXPR_ARG (exp, 0));
4898   tramp = round_trampoline_addr (tramp);
4899   if (targetm.calls.trampoline_adjust_address)
4900     tramp = targetm.calls.trampoline_adjust_address (tramp);
4901
4902   return tramp;
4903 }
4904
4905 /* Expand the call EXP to the built-in signbit, signbitf or signbitl
4906    function.  The function first checks whether the back end provides
4907    an insn to implement signbit for the respective mode.  If not, it
4908    checks whether the floating point format of the value is such that
4909    the sign bit can be extracted.  If that is not the case, the
4910    function returns NULL_RTX to indicate that a normal call should be
4911    emitted rather than expanding the function in-line.  EXP is the
4912    expression that is a call to the builtin function; if convenient,
4913    the result should be placed in TARGET.  */
4914 static rtx
4915 expand_builtin_signbit (tree exp, rtx target)
4916 {
4917   const struct real_format *fmt;
4918   enum machine_mode fmode, imode, rmode;
4919   tree arg;
4920   int word, bitpos;
4921   enum insn_code icode;
4922   rtx temp;
4923   location_t loc = EXPR_LOCATION (exp);
4924
4925   if (!validate_arglist (exp, REAL_TYPE, VOID_TYPE))
4926     return NULL_RTX;
4927
4928   arg = CALL_EXPR_ARG (exp, 0);
4929   fmode = TYPE_MODE (TREE_TYPE (arg));
4930   rmode = TYPE_MODE (TREE_TYPE (exp));
4931   fmt = REAL_MODE_FORMAT (fmode);
4932
4933   arg = builtin_save_expr (arg);
4934
4935   /* Expand the argument yielding a RTX expression. */
4936   temp = expand_normal (arg);
4937
4938   /* Check if the back end provides an insn that handles signbit for the
4939      argument's mode. */
4940   icode = optab_handler (signbit_optab, fmode);
4941   if (icode != CODE_FOR_nothing)
4942     {
4943       rtx last = get_last_insn ();
4944       target = gen_reg_rtx (TYPE_MODE (TREE_TYPE (exp)));
4945       if (maybe_emit_unop_insn (icode, target, temp, UNKNOWN))
4946         return target;
4947       delete_insns_since (last);
4948     }
4949
4950   /* For floating point formats without a sign bit, implement signbit
4951      as "ARG < 0.0".  */
4952   bitpos = fmt->signbit_ro;
4953   if (bitpos < 0)
4954   {
4955     /* But we can't do this if the format supports signed zero.  */
4956     if (fmt->has_signed_zero && HONOR_SIGNED_ZEROS (fmode))
4957       return NULL_RTX;
4958
4959     arg = fold_build2_loc (loc, LT_EXPR, TREE_TYPE (exp), arg,
4960                        build_real (TREE_TYPE (arg), dconst0));
4961     return expand_expr (arg, target, VOIDmode, EXPAND_NORMAL);
4962   }
4963
4964   if (GET_MODE_SIZE (fmode) <= UNITS_PER_WORD)
4965     {
4966       imode = int_mode_for_mode (fmode);
4967       if (imode == BLKmode)
4968         return NULL_RTX;
4969       temp = gen_lowpart (imode, temp);
4970     }
4971   else
4972     {
4973       imode = word_mode;
4974       /* Handle targets with different FP word orders.  */
4975       if (FLOAT_WORDS_BIG_ENDIAN)
4976         word = (GET_MODE_BITSIZE (fmode) - bitpos) / BITS_PER_WORD;
4977       else
4978         word = bitpos / BITS_PER_WORD;
4979       temp = operand_subword_force (temp, word, fmode);
4980       bitpos = bitpos % BITS_PER_WORD;
4981     }
4982
4983   /* Force the intermediate word_mode (or narrower) result into a
4984      register.  This avoids attempting to create paradoxical SUBREGs
4985      of floating point modes below.  */
4986   temp = force_reg (imode, temp);
4987
4988   /* If the bitpos is within the "result mode" lowpart, the operation
4989      can be implement with a single bitwise AND.  Otherwise, we need
4990      a right shift and an AND.  */
4991
4992   if (bitpos < GET_MODE_BITSIZE (rmode))
4993     {
4994       double_int mask = double_int_zero.set_bit (bitpos);
4995
4996       if (GET_MODE_SIZE (imode) > GET_MODE_SIZE (rmode))
4997         temp = gen_lowpart (rmode, temp);
4998       temp = expand_binop (rmode, and_optab, temp,
4999                            immed_double_int_const (mask, rmode),
5000                            NULL_RTX, 1, OPTAB_LIB_WIDEN);
5001     }
5002   else
5003     {
5004       /* Perform a logical right shift to place the signbit in the least
5005          significant bit, then truncate the result to the desired mode
5006          and mask just this bit.  */
5007       temp = expand_shift (RSHIFT_EXPR, imode, temp, bitpos, NULL_RTX, 1);
5008       temp = gen_lowpart (rmode, temp);
5009       temp = expand_binop (rmode, and_optab, temp, const1_rtx,
5010                            NULL_RTX, 1, OPTAB_LIB_WIDEN);
5011     }
5012
5013   return temp;
5014 }
5015
5016 /* Expand fork or exec calls.  TARGET is the desired target of the
5017    call.  EXP is the call. FN is the
5018    identificator of the actual function.  IGNORE is nonzero if the
5019    value is to be ignored.  */
5020
5021 static rtx
5022 expand_builtin_fork_or_exec (tree fn, tree exp, rtx target, int ignore)
5023 {
5024   tree id, decl;
5025   tree call;
5026
5027   /* If we are not profiling, just call the function.  */
5028   if (!profile_arc_flag)
5029     return NULL_RTX;
5030
5031   /* Otherwise call the wrapper.  This should be equivalent for the rest of
5032      compiler, so the code does not diverge, and the wrapper may run the
5033      code necessary for keeping the profiling sane.  */
5034
5035   switch (DECL_FUNCTION_CODE (fn))
5036     {
5037     case BUILT_IN_FORK:
5038       id = get_identifier ("__gcov_fork");
5039       break;
5040
5041     case BUILT_IN_EXECL:
5042       id = get_identifier ("__gcov_execl");
5043       break;
5044
5045     case BUILT_IN_EXECV:
5046       id = get_identifier ("__gcov_execv");
5047       break;
5048
5049     case BUILT_IN_EXECLP:
5050       id = get_identifier ("__gcov_execlp");
5051       break;
5052
5053     case BUILT_IN_EXECLE:
5054       id = get_identifier ("__gcov_execle");
5055       break;
5056
5057     case BUILT_IN_EXECVP:
5058       id = get_identifier ("__gcov_execvp");
5059       break;
5060
5061     case BUILT_IN_EXECVE:
5062       id = get_identifier ("__gcov_execve");
5063       break;
5064
5065     default:
5066       gcc_unreachable ();
5067     }
5068
5069   decl = build_decl (DECL_SOURCE_LOCATION (fn),
5070                      FUNCTION_DECL, id, TREE_TYPE (fn));
5071   DECL_EXTERNAL (decl) = 1;
5072   TREE_PUBLIC (decl) = 1;
5073   DECL_ARTIFICIAL (decl) = 1;
5074   TREE_NOTHROW (decl) = 1;
5075   DECL_VISIBILITY (decl) = VISIBILITY_DEFAULT;
5076   DECL_VISIBILITY_SPECIFIED (decl) = 1;
5077   call = rewrite_call_expr (EXPR_LOCATION (exp), exp, 0, decl, 0);
5078   return expand_call (call, target, ignore);
5079  }
5080
5081
5082 \f
5083 /* Reconstitute a mode for a __sync intrinsic operation.  Since the type of
5084    the pointer in these functions is void*, the tree optimizers may remove
5085    casts.  The mode computed in expand_builtin isn't reliable either, due
5086    to __sync_bool_compare_and_swap.
5087
5088    FCODE_DIFF should be fcode - base, where base is the FOO_1 code for the
5089    group of builtins.  This gives us log2 of the mode size.  */
5090
5091 static inline enum machine_mode
5092 get_builtin_sync_mode (int fcode_diff)
5093 {
5094   /* The size is not negotiable, so ask not to get BLKmode in return
5095      if the target indicates that a smaller size would be better.  */
5096   return mode_for_size (BITS_PER_UNIT << fcode_diff, MODE_INT, 0);
5097 }
5098
5099 /* Expand the memory expression LOC and return the appropriate memory operand
5100    for the builtin_sync operations.  */
5101
5102 static rtx
5103 get_builtin_sync_mem (tree loc, enum machine_mode mode)
5104 {
5105   rtx addr, mem;
5106
5107   addr = expand_expr (loc, NULL_RTX, ptr_mode, EXPAND_SUM);
5108   addr = convert_memory_address (Pmode, addr);
5109
5110   /* Note that we explicitly do not want any alias information for this
5111      memory, so that we kill all other live memories.  Otherwise we don't
5112      satisfy the full barrier semantics of the intrinsic.  */
5113   mem = validize_mem (gen_rtx_MEM (mode, addr));
5114
5115   /* The alignment needs to be at least according to that of the mode.  */
5116   set_mem_align (mem, MAX (GET_MODE_ALIGNMENT (mode),
5117                            get_pointer_alignment (loc)));
5118   set_mem_alias_set (mem, ALIAS_SET_MEMORY_BARRIER);
5119   MEM_VOLATILE_P (mem) = 1;
5120
5121   return mem;
5122 }
5123
5124 /* Make sure an argument is in the right mode.
5125    EXP is the tree argument. 
5126    MODE is the mode it should be in.  */
5127
5128 static rtx
5129 expand_expr_force_mode (tree exp, enum machine_mode mode)
5130 {
5131   rtx val;
5132   enum machine_mode old_mode;
5133
5134   val = expand_expr (exp, NULL_RTX, mode, EXPAND_NORMAL);
5135   /* If VAL is promoted to a wider mode, convert it back to MODE.  Take care
5136      of CONST_INTs, where we know the old_mode only from the call argument.  */
5137
5138   old_mode = GET_MODE (val);
5139   if (old_mode == VOIDmode)
5140     old_mode = TYPE_MODE (TREE_TYPE (exp));
5141   val = convert_modes (mode, old_mode, val, 1);
5142   return val;
5143 }
5144
5145
5146 /* Expand the __sync_xxx_and_fetch and __sync_fetch_and_xxx intrinsics.
5147    EXP is the CALL_EXPR.  CODE is the rtx code
5148    that corresponds to the arithmetic or logical operation from the name;
5149    an exception here is that NOT actually means NAND.  TARGET is an optional
5150    place for us to store the results; AFTER is true if this is the
5151    fetch_and_xxx form.  */
5152
5153 static rtx
5154 expand_builtin_sync_operation (enum machine_mode mode, tree exp,
5155                                enum rtx_code code, bool after,
5156                                rtx target)
5157 {
5158   rtx val, mem;
5159   location_t loc = EXPR_LOCATION (exp);
5160
5161   if (code == NOT && warn_sync_nand)
5162     {
5163       tree fndecl = get_callee_fndecl (exp);
5164       enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
5165
5166       static bool warned_f_a_n, warned_n_a_f;
5167
5168       switch (fcode)
5169         {
5170         case BUILT_IN_SYNC_FETCH_AND_NAND_1:
5171         case BUILT_IN_SYNC_FETCH_AND_NAND_2:
5172         case BUILT_IN_SYNC_FETCH_AND_NAND_4:
5173         case BUILT_IN_SYNC_FETCH_AND_NAND_8:
5174         case BUILT_IN_SYNC_FETCH_AND_NAND_16:
5175           if (warned_f_a_n)
5176             break;
5177
5178           fndecl = builtin_decl_implicit (BUILT_IN_SYNC_FETCH_AND_NAND_N);
5179           inform (loc, "%qD changed semantics in GCC 4.4", fndecl);
5180           warned_f_a_n = true;
5181           break;
5182
5183         case BUILT_IN_SYNC_NAND_AND_FETCH_1:
5184         case BUILT_IN_SYNC_NAND_AND_FETCH_2:
5185         case BUILT_IN_SYNC_NAND_AND_FETCH_4:
5186         case BUILT_IN_SYNC_NAND_AND_FETCH_8:
5187         case BUILT_IN_SYNC_NAND_AND_FETCH_16:
5188           if (warned_n_a_f)
5189             break;
5190
5191          fndecl = builtin_decl_implicit (BUILT_IN_SYNC_NAND_AND_FETCH_N);
5192           inform (loc, "%qD changed semantics in GCC 4.4", fndecl);
5193           warned_n_a_f = true;
5194           break;
5195
5196         default:
5197           gcc_unreachable ();
5198         }
5199     }
5200
5201   /* Expand the operands.  */
5202   mem = get_builtin_sync_mem (CALL_EXPR_ARG (exp, 0), mode);
5203   val = expand_expr_force_mode (CALL_EXPR_ARG (exp, 1), mode);
5204
5205   return expand_atomic_fetch_op (target, mem, val, code, MEMMODEL_SEQ_CST,
5206                                  after);
5207 }
5208
5209 /* Expand the __sync_val_compare_and_swap and __sync_bool_compare_and_swap
5210    intrinsics. EXP is the CALL_EXPR.  IS_BOOL is
5211    true if this is the boolean form.  TARGET is a place for us to store the
5212    results; this is NOT optional if IS_BOOL is true.  */
5213
5214 static rtx
5215 expand_builtin_compare_and_swap (enum machine_mode mode, tree exp,
5216                                  bool is_bool, rtx target)
5217 {
5218   rtx old_val, new_val, mem;
5219   rtx *pbool, *poval;
5220
5221   /* Expand the operands.  */
5222   mem = get_builtin_sync_mem (CALL_EXPR_ARG (exp, 0), mode);
5223   old_val = expand_expr_force_mode (CALL_EXPR_ARG (exp, 1), mode);
5224   new_val = expand_expr_force_mode (CALL_EXPR_ARG (exp, 2), mode);
5225
5226   pbool = poval = NULL;
5227   if (target != const0_rtx)
5228     {
5229       if (is_bool)
5230         pbool = &target;
5231       else
5232         poval = &target;
5233     }
5234   if (!expand_atomic_compare_and_swap (pbool, poval, mem, old_val, new_val,
5235                                        false, MEMMODEL_SEQ_CST,
5236                                        MEMMODEL_SEQ_CST))
5237     return NULL_RTX;
5238
5239   return target;
5240 }
5241
5242 /* Expand the __sync_lock_test_and_set intrinsic.  Note that the most
5243    general form is actually an atomic exchange, and some targets only
5244    support a reduced form with the second argument being a constant 1.
5245    EXP is the CALL_EXPR; TARGET is an optional place for us to store
5246    the results.  */
5247
5248 static rtx
5249 expand_builtin_sync_lock_test_and_set (enum machine_mode mode, tree exp,
5250                                        rtx target)
5251 {
5252   rtx val, mem;
5253
5254   /* Expand the operands.  */
5255   mem = get_builtin_sync_mem (CALL_EXPR_ARG (exp, 0), mode);
5256   val = expand_expr_force_mode (CALL_EXPR_ARG (exp, 1), mode);
5257
5258   return expand_sync_lock_test_and_set (target, mem, val);
5259 }
5260
5261 /* Expand the __sync_lock_release intrinsic.  EXP is the CALL_EXPR.  */
5262
5263 static void
5264 expand_builtin_sync_lock_release (enum machine_mode mode, tree exp)
5265 {
5266   rtx mem;
5267
5268   /* Expand the operands.  */
5269   mem = get_builtin_sync_mem (CALL_EXPR_ARG (exp, 0), mode);
5270
5271   expand_atomic_store (mem, const0_rtx, MEMMODEL_RELEASE, true);
5272 }
5273
5274 /* Given an integer representing an ``enum memmodel'', verify its
5275    correctness and return the memory model enum.  */
5276
5277 static enum memmodel
5278 get_memmodel (tree exp)
5279 {
5280   rtx op;
5281   unsigned HOST_WIDE_INT val;
5282
5283   /* If the parameter is not a constant, it's a run time value so we'll just
5284      convert it to MEMMODEL_SEQ_CST to avoid annoying runtime checking.  */
5285   if (TREE_CODE (exp) != INTEGER_CST)
5286     return MEMMODEL_SEQ_CST;
5287
5288   op = expand_normal (exp);
5289
5290   val = INTVAL (op);
5291   if (targetm.memmodel_check)
5292     val = targetm.memmodel_check (val);
5293   else if (val & ~MEMMODEL_MASK)
5294     {
5295       warning (OPT_Winvalid_memory_model,
5296                "Unknown architecture specifier in memory model to builtin.");
5297       return MEMMODEL_SEQ_CST;
5298     }
5299
5300   if ((INTVAL(op) & MEMMODEL_MASK) >= MEMMODEL_LAST)
5301     {
5302       warning (OPT_Winvalid_memory_model,
5303                "invalid memory model argument to builtin");
5304       return MEMMODEL_SEQ_CST;
5305     }
5306
5307   return (enum memmodel) val;
5308 }
5309
5310 /* Expand the __atomic_exchange intrinsic:
5311         TYPE __atomic_exchange (TYPE *object, TYPE desired, enum memmodel)
5312    EXP is the CALL_EXPR.
5313    TARGET is an optional place for us to store the results.  */
5314
5315 static rtx
5316 expand_builtin_atomic_exchange (enum machine_mode mode, tree exp, rtx target)
5317 {
5318   rtx val, mem;
5319   enum memmodel model;
5320
5321   model = get_memmodel (CALL_EXPR_ARG (exp, 2));
5322   if ((model & MEMMODEL_MASK) == MEMMODEL_CONSUME)
5323     {
5324       error ("invalid memory model for %<__atomic_exchange%>");
5325       return NULL_RTX;
5326     }
5327
5328   if (!flag_inline_atomics)
5329     return NULL_RTX;
5330
5331   /* Expand the operands.  */
5332   mem = get_builtin_sync_mem (CALL_EXPR_ARG (exp, 0), mode);
5333   val = expand_expr_force_mode (CALL_EXPR_ARG (exp, 1), mode);
5334
5335   return expand_atomic_exchange (target, mem, val, model);
5336 }
5337
5338 /* Expand the __atomic_compare_exchange intrinsic:
5339         bool __atomic_compare_exchange (TYPE *object, TYPE *expect, 
5340                                         TYPE desired, BOOL weak, 
5341                                         enum memmodel success,
5342                                         enum memmodel failure)
5343    EXP is the CALL_EXPR.
5344    TARGET is an optional place for us to store the results.  */
5345
5346 static rtx
5347 expand_builtin_atomic_compare_exchange (enum machine_mode mode, tree exp, 
5348                                         rtx target)
5349 {
5350   rtx expect, desired, mem, oldval;
5351   enum memmodel success, failure;
5352   tree weak;
5353   bool is_weak;
5354
5355   success = get_memmodel (CALL_EXPR_ARG (exp, 4));
5356   failure = get_memmodel (CALL_EXPR_ARG (exp, 5));
5357
5358   if ((failure & MEMMODEL_MASK) == MEMMODEL_RELEASE
5359       || (failure & MEMMODEL_MASK) == MEMMODEL_ACQ_REL)
5360     {
5361       error ("invalid failure memory model for %<__atomic_compare_exchange%>");
5362       return NULL_RTX;
5363     }
5364
5365   if (failure > success)
5366     {
5367       error ("failure memory model cannot be stronger than success "
5368              "memory model for %<__atomic_compare_exchange%>");
5369       return NULL_RTX;
5370     }
5371   
5372   if (!flag_inline_atomics)
5373     return NULL_RTX;
5374
5375   /* Expand the operands.  */
5376   mem = get_builtin_sync_mem (CALL_EXPR_ARG (exp, 0), mode);
5377
5378   expect = expand_normal (CALL_EXPR_ARG (exp, 1));
5379   expect = convert_memory_address (Pmode, expect);
5380   expect = gen_rtx_MEM (mode, expect);
5381   desired = expand_expr_force_mode (CALL_EXPR_ARG (exp, 2), mode);
5382
5383   weak = CALL_EXPR_ARG (exp, 3);
5384   is_weak = false;
5385   if (host_integerp (weak, 0) && tree_low_cst (weak, 0) != 0)
5386     is_weak = true;
5387
5388   oldval = expect;
5389   if (!expand_atomic_compare_and_swap ((target == const0_rtx ? NULL : &target),
5390                                        &oldval, mem, oldval, desired,
5391                                        is_weak, success, failure))
5392     return NULL_RTX;
5393
5394   if (oldval != expect)
5395     emit_move_insn (expect, oldval);
5396
5397   return target;
5398 }
5399
5400 /* Expand the __atomic_load intrinsic:
5401         TYPE __atomic_load (TYPE *object, enum memmodel)
5402    EXP is the CALL_EXPR.
5403    TARGET is an optional place for us to store the results.  */
5404
5405 static rtx
5406 expand_builtin_atomic_load (enum machine_mode mode, tree exp, rtx target)
5407 {
5408   rtx mem;
5409   enum memmodel model;
5410
5411   model = get_memmodel (CALL_EXPR_ARG (exp, 1));
5412   if ((model & MEMMODEL_MASK) == MEMMODEL_RELEASE
5413       || (model & MEMMODEL_MASK) == MEMMODEL_ACQ_REL)
5414     {
5415       error ("invalid memory model for %<__atomic_load%>");
5416       return NULL_RTX;
5417     }
5418
5419   if (!flag_inline_atomics)
5420     return NULL_RTX;
5421
5422   /* Expand the operand.  */
5423   mem = get_builtin_sync_mem (CALL_EXPR_ARG (exp, 0), mode);
5424
5425   return expand_atomic_load (target, mem, model);
5426 }
5427
5428
5429 /* Expand the __atomic_store intrinsic:
5430         void __atomic_store (TYPE *object, TYPE desired, enum memmodel)
5431    EXP is the CALL_EXPR.
5432    TARGET is an optional place for us to store the results.  */
5433
5434 static rtx
5435 expand_builtin_atomic_store (enum machine_mode mode, tree exp)
5436 {
5437   rtx mem, val;
5438   enum memmodel model;
5439
5440   model = get_memmodel (CALL_EXPR_ARG (exp, 2));
5441   if ((model & MEMMODEL_MASK) != MEMMODEL_RELAXED
5442       && (model & MEMMODEL_MASK) != MEMMODEL_SEQ_CST
5443       && (model & MEMMODEL_MASK) != MEMMODEL_RELEASE)
5444     {
5445       error ("invalid memory model for %<__atomic_store%>");
5446       return NULL_RTX;
5447     }
5448
5449   if (!flag_inline_atomics)
5450     return NULL_RTX;
5451
5452   /* Expand the operands.  */
5453   mem = get_builtin_sync_mem (CALL_EXPR_ARG (exp, 0), mode);
5454   val = expand_expr_force_mode (CALL_EXPR_ARG (exp, 1), mode);
5455
5456   return expand_atomic_store (mem, val, model, false);
5457 }
5458
5459 /* Expand the __atomic_fetch_XXX intrinsic:
5460         TYPE __atomic_fetch_XXX (TYPE *object, TYPE val, enum memmodel)
5461    EXP is the CALL_EXPR.
5462    TARGET is an optional place for us to store the results.
5463    CODE is the operation, PLUS, MINUS, ADD, XOR, or IOR.
5464    FETCH_AFTER is true if returning the result of the operation.
5465    FETCH_AFTER is false if returning the value before the operation.
5466    IGNORE is true if the result is not used.
5467    EXT_CALL is the correct builtin for an external call if this cannot be
5468    resolved to an instruction sequence.  */
5469
5470 static rtx
5471 expand_builtin_atomic_fetch_op (enum machine_mode mode, tree exp, rtx target,
5472                                 enum rtx_code code, bool fetch_after,
5473                                 bool ignore, enum built_in_function ext_call)
5474 {
5475   rtx val, mem, ret;
5476   enum memmodel model;
5477   tree fndecl;
5478   tree addr;
5479
5480   model = get_memmodel (CALL_EXPR_ARG (exp, 2));
5481
5482   /* Expand the operands.  */
5483   mem = get_builtin_sync_mem (CALL_EXPR_ARG (exp, 0), mode);
5484   val = expand_expr_force_mode (CALL_EXPR_ARG (exp, 1), mode);
5485
5486   /* Only try generating instructions if inlining is turned on.  */
5487   if (flag_inline_atomics)
5488     {
5489       ret = expand_atomic_fetch_op (target, mem, val, code, model, fetch_after);
5490       if (ret)
5491         return ret;
5492     }
5493
5494   /* Return if a different routine isn't needed for the library call.  */
5495   if (ext_call == BUILT_IN_NONE)
5496     return NULL_RTX;
5497
5498   /* Change the call to the specified function.  */
5499   fndecl = get_callee_fndecl (exp);
5500   addr = CALL_EXPR_FN (exp);
5501   STRIP_NOPS (addr);
5502
5503   gcc_assert (TREE_OPERAND (addr, 0) == fndecl);
5504   TREE_OPERAND (addr, 0) = builtin_decl_explicit(ext_call);
5505
5506   /* Expand the call here so we can emit trailing code.  */
5507   ret = expand_call (exp, target, ignore);
5508
5509   /* Replace the original function just in case it matters.  */
5510   TREE_OPERAND (addr, 0) = fndecl;
5511
5512   /* Then issue the arithmetic correction to return the right result.  */
5513   if (!ignore)
5514     {
5515       if (code == NOT)
5516         {
5517           ret = expand_simple_binop (mode, AND, ret, val, NULL_RTX, true,
5518                                      OPTAB_LIB_WIDEN);
5519           ret = expand_simple_unop (mode, NOT, ret, target, true);
5520         }
5521       else
5522         ret = expand_simple_binop (mode, code, ret, val, target, true,
5523                                    OPTAB_LIB_WIDEN);
5524     }
5525   return ret;
5526 }
5527
5528
5529 #ifndef HAVE_atomic_clear
5530 # define HAVE_atomic_clear 0
5531 # define gen_atomic_clear(x,y) (gcc_unreachable (), NULL_RTX)
5532 #endif
5533
5534 /* Expand an atomic clear operation.
5535         void _atomic_clear (BOOL *obj, enum memmodel)
5536    EXP is the call expression.  */
5537
5538 static rtx
5539 expand_builtin_atomic_clear (tree exp) 
5540 {
5541   enum machine_mode mode;
5542   rtx mem, ret;
5543   enum memmodel model;
5544
5545   mode = mode_for_size (BOOL_TYPE_SIZE, MODE_INT, 0);
5546   mem = get_builtin_sync_mem (CALL_EXPR_ARG (exp, 0), mode);
5547   model = get_memmodel (CALL_EXPR_ARG (exp, 1));
5548
5549   if ((model & MEMMODEL_MASK) == MEMMODEL_ACQUIRE
5550       || (model & MEMMODEL_MASK) == MEMMODEL_ACQ_REL)
5551     {
5552       error ("invalid memory model for %<__atomic_store%>");
5553       return const0_rtx;
5554     }
5555
5556   if (HAVE_atomic_clear)
5557     {
5558       emit_insn (gen_atomic_clear (mem, model));
5559       return const0_rtx;
5560     }
5561
5562   /* Try issuing an __atomic_store, and allow fallback to __sync_lock_release.
5563      Failing that, a store is issued by __atomic_store.  The only way this can
5564      fail is if the bool type is larger than a word size.  Unlikely, but
5565      handle it anyway for completeness.  Assume a single threaded model since
5566      there is no atomic support in this case, and no barriers are required.  */
5567   ret = expand_atomic_store (mem, const0_rtx, model, true);
5568   if (!ret)
5569     emit_move_insn (mem, const0_rtx);
5570   return const0_rtx;
5571 }
5572
5573 /* Expand an atomic test_and_set operation.
5574         bool _atomic_test_and_set (BOOL *obj, enum memmodel)
5575    EXP is the call expression.  */
5576
5577 static rtx
5578 expand_builtin_atomic_test_and_set (tree exp, rtx target)
5579 {
5580   rtx mem;
5581   enum memmodel model;
5582   enum machine_mode mode;
5583
5584   mode = mode_for_size (BOOL_TYPE_SIZE, MODE_INT, 0);
5585   mem = get_builtin_sync_mem (CALL_EXPR_ARG (exp, 0), mode);
5586   model = get_memmodel (CALL_EXPR_ARG (exp, 1));
5587
5588   return expand_atomic_test_and_set (target, mem, model);
5589 }
5590
5591
5592 /* Return true if (optional) argument ARG1 of size ARG0 is always lock free on
5593    this architecture.  If ARG1 is NULL, use typical alignment for size ARG0.  */
5594
5595 static tree
5596 fold_builtin_atomic_always_lock_free (tree arg0, tree arg1)
5597 {
5598   int size;
5599   enum machine_mode mode;
5600   unsigned int mode_align, type_align;
5601
5602   if (TREE_CODE (arg0) != INTEGER_CST)
5603     return NULL_TREE;
5604
5605   size = INTVAL (expand_normal (arg0)) * BITS_PER_UNIT;
5606   mode = mode_for_size (size, MODE_INT, 0);
5607   mode_align = GET_MODE_ALIGNMENT (mode);
5608
5609   if (TREE_CODE (arg1) == INTEGER_CST && INTVAL (expand_normal (arg1)) == 0)
5610     type_align = mode_align;
5611   else
5612     {
5613       tree ttype = TREE_TYPE (arg1);
5614
5615       /* This function is usually invoked and folded immediately by the front
5616          end before anything else has a chance to look at it.  The pointer
5617          parameter at this point is usually cast to a void *, so check for that
5618          and look past the cast.  */
5619       if (TREE_CODE (arg1) == NOP_EXPR && POINTER_TYPE_P (ttype)
5620           && VOID_TYPE_P (TREE_TYPE (ttype)))
5621         arg1 = TREE_OPERAND (arg1, 0);
5622
5623       ttype = TREE_TYPE (arg1);
5624       gcc_assert (POINTER_TYPE_P (ttype));
5625
5626       /* Get the underlying type of the object.  */
5627       ttype = TREE_TYPE (ttype);
5628       type_align = TYPE_ALIGN (ttype);
5629     }
5630
5631   /* If the object has smaller alignment, the the lock free routines cannot
5632      be used.  */
5633   if (type_align < mode_align)
5634     return boolean_false_node;
5635
5636   /* Check if a compare_and_swap pattern exists for the mode which represents
5637      the required size.  The pattern is not allowed to fail, so the existence
5638      of the pattern indicates support is present.  */
5639   if (can_compare_and_swap_p (mode, true))
5640     return boolean_true_node;
5641   else
5642     return boolean_false_node;
5643 }
5644
5645 /* Return true if the parameters to call EXP represent an object which will
5646    always generate lock free instructions.  The first argument represents the
5647    size of the object, and the second parameter is a pointer to the object 
5648    itself.  If NULL is passed for the object, then the result is based on 
5649    typical alignment for an object of the specified size.  Otherwise return 
5650    false.  */
5651
5652 static rtx
5653 expand_builtin_atomic_always_lock_free (tree exp)
5654 {
5655   tree size;
5656   tree arg0 = CALL_EXPR_ARG (exp, 0);
5657   tree arg1 = CALL_EXPR_ARG (exp, 1);
5658
5659   if (TREE_CODE (arg0) != INTEGER_CST)
5660     {
5661       error ("non-constant argument 1 to __atomic_always_lock_free");
5662       return const0_rtx;
5663     }
5664
5665   size = fold_builtin_atomic_always_lock_free (arg0, arg1);
5666   if (size == boolean_true_node)
5667     return const1_rtx;
5668   return const0_rtx;
5669 }
5670
5671 /* Return a one or zero if it can be determined that object ARG1 of size ARG 
5672    is lock free on this architecture.  */
5673
5674 static tree
5675 fold_builtin_atomic_is_lock_free (tree arg0, tree arg1)
5676 {
5677   if (!flag_inline_atomics)
5678     return NULL_TREE;
5679   
5680   /* If it isn't always lock free, don't generate a result.  */
5681   if (fold_builtin_atomic_always_lock_free (arg0, arg1) == boolean_true_node)
5682     return boolean_true_node;
5683
5684   return NULL_TREE;
5685 }
5686
5687 /* Return true if the parameters to call EXP represent an object which will
5688    always generate lock free instructions.  The first argument represents the
5689    size of the object, and the second parameter is a pointer to the object 
5690    itself.  If NULL is passed for the object, then the result is based on 
5691    typical alignment for an object of the specified size.  Otherwise return 
5692    NULL*/
5693
5694 static rtx
5695 expand_builtin_atomic_is_lock_free (tree exp)
5696 {
5697   tree size;
5698   tree arg0 = CALL_EXPR_ARG (exp, 0);
5699   tree arg1 = CALL_EXPR_ARG (exp, 1);
5700
5701   if (!INTEGRAL_TYPE_P (TREE_TYPE (arg0)))
5702     {
5703       error ("non-integer argument 1 to __atomic_is_lock_free");
5704       return NULL_RTX;
5705     }
5706
5707   if (!flag_inline_atomics)
5708     return NULL_RTX; 
5709
5710   /* If the value is known at compile time, return the RTX for it.  */
5711   size = fold_builtin_atomic_is_lock_free (arg0, arg1);
5712   if (size == boolean_true_node)
5713     return const1_rtx;
5714
5715   return NULL_RTX;
5716 }
5717
5718 /* Expand the __atomic_thread_fence intrinsic:
5719         void __atomic_thread_fence (enum memmodel)
5720    EXP is the CALL_EXPR.  */
5721
5722 static void
5723 expand_builtin_atomic_thread_fence (tree exp)
5724 {
5725   enum memmodel model = get_memmodel (CALL_EXPR_ARG (exp, 0));
5726   expand_mem_thread_fence (model);
5727 }
5728
5729 /* Expand the __atomic_signal_fence intrinsic:
5730         void __atomic_signal_fence (enum memmodel)
5731    EXP is the CALL_EXPR.  */
5732
5733 static void
5734 expand_builtin_atomic_signal_fence (tree exp)
5735 {
5736   enum memmodel model = get_memmodel (CALL_EXPR_ARG (exp, 0));
5737   expand_mem_signal_fence (model);
5738 }
5739
5740 /* Expand the __sync_synchronize intrinsic.  */
5741
5742 static void
5743 expand_builtin_sync_synchronize (void)
5744 {
5745   expand_mem_thread_fence (MEMMODEL_SEQ_CST);
5746 }
5747
5748 static rtx
5749 expand_builtin_thread_pointer (tree exp, rtx target)
5750 {
5751   enum insn_code icode;
5752   if (!validate_arglist (exp, VOID_TYPE))
5753     return const0_rtx;
5754   icode = direct_optab_handler (get_thread_pointer_optab, Pmode);
5755   if (icode != CODE_FOR_nothing)
5756     {
5757       struct expand_operand op;
5758       if (!REG_P (target) || GET_MODE (target) != Pmode)
5759         target = gen_reg_rtx (Pmode);
5760       create_output_operand (&op, target, Pmode);
5761       expand_insn (icode, 1, &op);
5762       return target;
5763     }
5764   error ("__builtin_thread_pointer is not supported on this target");
5765   return const0_rtx;
5766 }
5767
5768 static void
5769 expand_builtin_set_thread_pointer (tree exp)
5770 {
5771   enum insn_code icode;
5772   if (!validate_arglist (exp, POINTER_TYPE, VOID_TYPE))
5773     return;
5774   icode = direct_optab_handler (set_thread_pointer_optab, Pmode);
5775   if (icode != CODE_FOR_nothing)
5776     {
5777       struct expand_operand op;
5778       rtx val = expand_expr (CALL_EXPR_ARG (exp, 0), NULL_RTX,
5779                              Pmode, EXPAND_NORMAL);      
5780       create_input_operand (&op, val, Pmode);
5781       expand_insn (icode, 1, &op);
5782       return;
5783     }
5784   error ("__builtin_set_thread_pointer is not supported on this target");
5785 }
5786
5787 \f
5788 /* Expand an expression EXP that calls a built-in function,
5789    with result going to TARGET if that's convenient
5790    (and in mode MODE if that's convenient).
5791    SUBTARGET may be used as the target for computing one of EXP's operands.
5792    IGNORE is nonzero if the value is to be ignored.  */
5793
5794 rtx
5795 expand_builtin (tree exp, rtx target, rtx subtarget, enum machine_mode mode,
5796                 int ignore)
5797 {
5798   tree fndecl = get_callee_fndecl (exp);
5799   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
5800   enum machine_mode target_mode = TYPE_MODE (TREE_TYPE (exp));
5801   int flags;
5802
5803   if (DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_MD)
5804     return targetm.expand_builtin (exp, target, subtarget, mode, ignore);
5805
5806   /* When not optimizing, generate calls to library functions for a certain
5807      set of builtins.  */
5808   if (!optimize
5809       && !called_as_built_in (fndecl)
5810       && fcode != BUILT_IN_ALLOCA
5811       && fcode != BUILT_IN_ALLOCA_WITH_ALIGN
5812       && fcode != BUILT_IN_FREE)
5813     return expand_call (exp, target, ignore);
5814
5815   /* The built-in function expanders test for target == const0_rtx
5816      to determine whether the function's result will be ignored.  */
5817   if (ignore)
5818     target = const0_rtx;
5819
5820   /* If the result of a pure or const built-in function is ignored, and
5821      none of its arguments are volatile, we can avoid expanding the
5822      built-in call and just evaluate the arguments for side-effects.  */
5823   if (target == const0_rtx
5824       && ((flags = flags_from_decl_or_type (fndecl)) & (ECF_CONST | ECF_PURE))
5825       && !(flags & ECF_LOOPING_CONST_OR_PURE))
5826     {
5827       bool volatilep = false;
5828       tree arg;
5829       call_expr_arg_iterator iter;
5830
5831       FOR_EACH_CALL_EXPR_ARG (arg, iter, exp)
5832         if (TREE_THIS_VOLATILE (arg))
5833           {
5834             volatilep = true;
5835             break;
5836           }
5837
5838       if (! volatilep)
5839         {
5840           FOR_EACH_CALL_EXPR_ARG (arg, iter, exp)
5841             expand_expr (arg, const0_rtx, VOIDmode, EXPAND_NORMAL);
5842           return const0_rtx;
5843         }
5844     }
5845
5846   switch (fcode)
5847     {
5848     CASE_FLT_FN (BUILT_IN_FABS):
5849       target = expand_builtin_fabs (exp, target, subtarget);
5850       if (target)
5851         return target;
5852       break;
5853
5854     CASE_FLT_FN (BUILT_IN_COPYSIGN):
5855       target = expand_builtin_copysign (exp, target, subtarget);
5856       if (target)
5857         return target;
5858       break;
5859
5860       /* Just do a normal library call if we were unable to fold
5861          the values.  */
5862     CASE_FLT_FN (BUILT_IN_CABS):
5863       break;
5864
5865     CASE_FLT_FN (BUILT_IN_EXP):
5866     CASE_FLT_FN (BUILT_IN_EXP10):
5867     CASE_FLT_FN (BUILT_IN_POW10):
5868     CASE_FLT_FN (BUILT_IN_EXP2):
5869     CASE_FLT_FN (BUILT_IN_EXPM1):
5870     CASE_FLT_FN (BUILT_IN_LOGB):
5871     CASE_FLT_FN (BUILT_IN_LOG):
5872     CASE_FLT_FN (BUILT_IN_LOG10):
5873     CASE_FLT_FN (BUILT_IN_LOG2):
5874     CASE_FLT_FN (BUILT_IN_LOG1P):
5875     CASE_FLT_FN (BUILT_IN_TAN):
5876     CASE_FLT_FN (BUILT_IN_ASIN):
5877     CASE_FLT_FN (BUILT_IN_ACOS):
5878     CASE_FLT_FN (BUILT_IN_ATAN):
5879     CASE_FLT_FN (BUILT_IN_SIGNIFICAND):
5880       /* Treat these like sqrt only if unsafe math optimizations are allowed,
5881          because of possible accuracy problems.  */
5882       if (! flag_unsafe_math_optimizations)
5883         break;
5884     CASE_FLT_FN (BUILT_IN_SQRT):
5885     CASE_FLT_FN (BUILT_IN_FLOOR):
5886     CASE_FLT_FN (BUILT_IN_CEIL):
5887     CASE_FLT_FN (BUILT_IN_TRUNC):
5888     CASE_FLT_FN (BUILT_IN_ROUND):
5889     CASE_FLT_FN (BUILT_IN_NEARBYINT):
5890     CASE_FLT_FN (BUILT_IN_RINT):
5891       target = expand_builtin_mathfn (exp, target, subtarget);
5892       if (target)
5893         return target;
5894       break;
5895
5896     CASE_FLT_FN (BUILT_IN_FMA):
5897       target = expand_builtin_mathfn_ternary (exp, target, subtarget);
5898       if (target)
5899         return target;
5900       break;
5901
5902     CASE_FLT_FN (BUILT_IN_ILOGB):
5903       if (! flag_unsafe_math_optimizations)
5904         break;
5905     CASE_FLT_FN (BUILT_IN_ISINF):
5906     CASE_FLT_FN (BUILT_IN_FINITE):
5907     case BUILT_IN_ISFINITE:
5908     case BUILT_IN_ISNORMAL:
5909       target = expand_builtin_interclass_mathfn (exp, target);
5910       if (target)
5911         return target;
5912       break;
5913
5914     CASE_FLT_FN (BUILT_IN_ICEIL):
5915     CASE_FLT_FN (BUILT_IN_LCEIL):
5916     CASE_FLT_FN (BUILT_IN_LLCEIL):
5917     CASE_FLT_FN (BUILT_IN_LFLOOR):
5918     CASE_FLT_FN (BUILT_IN_IFLOOR):
5919     CASE_FLT_FN (BUILT_IN_LLFLOOR):
5920       target = expand_builtin_int_roundingfn (exp, target);
5921       if (target)
5922         return target;
5923       break;
5924
5925     CASE_FLT_FN (BUILT_IN_IRINT):
5926     CASE_FLT_FN (BUILT_IN_LRINT):
5927     CASE_FLT_FN (BUILT_IN_LLRINT):
5928     CASE_FLT_FN (BUILT_IN_IROUND):
5929     CASE_FLT_FN (BUILT_IN_LROUND):
5930     CASE_FLT_FN (BUILT_IN_LLROUND):
5931       target = expand_builtin_int_roundingfn_2 (exp, target);
5932       if (target)
5933         return target;
5934       break;
5935
5936     CASE_FLT_FN (BUILT_IN_POWI):
5937       target = expand_builtin_powi (exp, target);
5938       if (target)
5939         return target;
5940       break;
5941
5942     CASE_FLT_FN (BUILT_IN_ATAN2):
5943     CASE_FLT_FN (BUILT_IN_LDEXP):
5944     CASE_FLT_FN (BUILT_IN_SCALB):
5945     CASE_FLT_FN (BUILT_IN_SCALBN):
5946     CASE_FLT_FN (BUILT_IN_SCALBLN):
5947       if (! flag_unsafe_math_optimizations)
5948         break;
5949
5950     CASE_FLT_FN (BUILT_IN_FMOD):
5951     CASE_FLT_FN (BUILT_IN_REMAINDER):
5952     CASE_FLT_FN (BUILT_IN_DREM):
5953     CASE_FLT_FN (BUILT_IN_POW):
5954       target = expand_builtin_mathfn_2 (exp, target, subtarget);
5955       if (target)
5956         return target;
5957       break;
5958
5959     CASE_FLT_FN (BUILT_IN_CEXPI):
5960       target = expand_builtin_cexpi (exp, target);
5961       gcc_assert (target);
5962       return target;
5963
5964     CASE_FLT_FN (BUILT_IN_SIN):
5965     CASE_FLT_FN (BUILT_IN_COS):
5966       if (! flag_unsafe_math_optimizations)
5967         break;
5968       target = expand_builtin_mathfn_3 (exp, target, subtarget);
5969       if (target)
5970         return target;
5971       break;
5972
5973     CASE_FLT_FN (BUILT_IN_SINCOS):
5974       if (! flag_unsafe_math_optimizations)
5975         break;
5976       target = expand_builtin_sincos (exp);
5977       if (target)
5978         return target;
5979       break;
5980
5981     case BUILT_IN_APPLY_ARGS:
5982       return expand_builtin_apply_args ();
5983
5984       /* __builtin_apply (FUNCTION, ARGUMENTS, ARGSIZE) invokes
5985          FUNCTION with a copy of the parameters described by
5986          ARGUMENTS, and ARGSIZE.  It returns a block of memory
5987          allocated on the stack into which is stored all the registers
5988          that might possibly be used for returning the result of a
5989          function.  ARGUMENTS is the value returned by
5990          __builtin_apply_args.  ARGSIZE is the number of bytes of
5991          arguments that must be copied.  ??? How should this value be
5992          computed?  We'll also need a safe worst case value for varargs
5993          functions.  */
5994     case BUILT_IN_APPLY:
5995       if (!validate_arglist (exp, POINTER_TYPE,
5996                              POINTER_TYPE, INTEGER_TYPE, VOID_TYPE)
5997           && !validate_arglist (exp, REFERENCE_TYPE,
5998                                 POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
5999         return const0_rtx;
6000       else
6001         {
6002           rtx ops[3];
6003
6004           ops[0] = expand_normal (CALL_EXPR_ARG (exp, 0));
6005           ops[1] = expand_normal (CALL_EXPR_ARG (exp, 1));
6006           ops[2] = expand_normal (CALL_EXPR_ARG (exp, 2));
6007
6008           return expand_builtin_apply (ops[0], ops[1], ops[2]);
6009         }
6010
6011       /* __builtin_return (RESULT) causes the function to return the
6012          value described by RESULT.  RESULT is address of the block of
6013          memory returned by __builtin_apply.  */
6014     case BUILT_IN_RETURN:
6015       if (validate_arglist (exp, POINTER_TYPE, VOID_TYPE))
6016         expand_builtin_return (expand_normal (CALL_EXPR_ARG (exp, 0)));
6017       return const0_rtx;
6018
6019     case BUILT_IN_SAVEREGS:
6020       return expand_builtin_saveregs ();
6021
6022     case BUILT_IN_VA_ARG_PACK:
6023       /* All valid uses of __builtin_va_arg_pack () are removed during
6024          inlining.  */
6025       error ("%Kinvalid use of %<__builtin_va_arg_pack ()%>", exp);
6026       return const0_rtx;
6027
6028     case BUILT_IN_VA_ARG_PACK_LEN:
6029       /* All valid uses of __builtin_va_arg_pack_len () are removed during
6030          inlining.  */
6031       error ("%Kinvalid use of %<__builtin_va_arg_pack_len ()%>", exp);
6032       return const0_rtx;
6033
6034       /* Return the address of the first anonymous stack arg.  */
6035     case BUILT_IN_NEXT_ARG:
6036       if (fold_builtin_next_arg (exp, false))
6037         return const0_rtx;
6038       return expand_builtin_next_arg ();
6039
6040     case BUILT_IN_CLEAR_CACHE:
6041       target = expand_builtin___clear_cache (exp);
6042       if (target)
6043         return target;
6044       break;
6045
6046     case BUILT_IN_CLASSIFY_TYPE:
6047       return expand_builtin_classify_type (exp);
6048
6049     case BUILT_IN_CONSTANT_P:
6050       return const0_rtx;
6051
6052     case BUILT_IN_FRAME_ADDRESS:
6053     case BUILT_IN_RETURN_ADDRESS:
6054       return expand_builtin_frame_address (fndecl, exp);
6055
6056     /* Returns the address of the area where the structure is returned.
6057        0 otherwise.  */
6058     case BUILT_IN_AGGREGATE_INCOMING_ADDRESS:
6059       if (call_expr_nargs (exp) != 0
6060           || ! AGGREGATE_TYPE_P (TREE_TYPE (TREE_TYPE (current_function_decl)))
6061           || !MEM_P (DECL_RTL (DECL_RESULT (current_function_decl))))
6062         return const0_rtx;
6063       else
6064         return XEXP (DECL_RTL (DECL_RESULT (current_function_decl)), 0);
6065
6066     case BUILT_IN_ALLOCA:
6067     case BUILT_IN_ALLOCA_WITH_ALIGN:
6068       /* If the allocation stems from the declaration of a variable-sized
6069          object, it cannot accumulate.  */
6070       target = expand_builtin_alloca (exp, CALL_ALLOCA_FOR_VAR_P (exp));
6071       if (target)
6072         return target;
6073       break;
6074
6075     case BUILT_IN_STACK_SAVE:
6076       return expand_stack_save ();
6077
6078     case BUILT_IN_STACK_RESTORE:
6079       expand_stack_restore (CALL_EXPR_ARG (exp, 0));
6080       return const0_rtx;
6081
6082     case BUILT_IN_BSWAP16:
6083     case BUILT_IN_BSWAP32:
6084     case BUILT_IN_BSWAP64:
6085       target = expand_builtin_bswap (target_mode, exp, target, subtarget);
6086       if (target)
6087         return target;
6088       break;
6089
6090     CASE_INT_FN (BUILT_IN_FFS):
6091     case BUILT_IN_FFSIMAX:
6092       target = expand_builtin_unop (target_mode, exp, target,
6093                                     subtarget, ffs_optab);
6094       if (target)
6095         return target;
6096       break;
6097
6098     CASE_INT_FN (BUILT_IN_CLZ):
6099     case BUILT_IN_CLZIMAX:
6100       target = expand_builtin_unop (target_mode, exp, target,
6101                                     subtarget, clz_optab);
6102       if (target)
6103         return target;
6104       break;
6105
6106     CASE_INT_FN (BUILT_IN_CTZ):
6107     case BUILT_IN_CTZIMAX:
6108       target = expand_builtin_unop (target_mode, exp, target,
6109                                     subtarget, ctz_optab);
6110       if (target)
6111         return target;
6112       break;
6113
6114     CASE_INT_FN (BUILT_IN_CLRSB):
6115     case BUILT_IN_CLRSBIMAX:
6116       target = expand_builtin_unop (target_mode, exp, target,
6117                                     subtarget, clrsb_optab);
6118       if (target)
6119         return target;
6120       break;
6121
6122     CASE_INT_FN (BUILT_IN_POPCOUNT):
6123     case BUILT_IN_POPCOUNTIMAX:
6124       target = expand_builtin_unop (target_mode, exp, target,
6125                                     subtarget, popcount_optab);
6126       if (target)
6127         return target;
6128       break;
6129
6130     CASE_INT_FN (BUILT_IN_PARITY):
6131     case BUILT_IN_PARITYIMAX:
6132       target = expand_builtin_unop (target_mode, exp, target,
6133                                     subtarget, parity_optab);
6134       if (target)
6135         return target;
6136       break;
6137
6138     case BUILT_IN_STRLEN:
6139       target = expand_builtin_strlen (exp, target, target_mode);
6140       if (target)
6141         return target;
6142       break;
6143
6144     case BUILT_IN_STRCPY:
6145       target = expand_builtin_strcpy (exp, target);
6146       if (target)
6147         return target;
6148       break;
6149
6150     case BUILT_IN_STRNCPY:
6151       target = expand_builtin_strncpy (exp, target);
6152       if (target)
6153         return target;
6154       break;
6155
6156     case BUILT_IN_STPCPY:
6157       target = expand_builtin_stpcpy (exp, target, mode);
6158       if (target)
6159         return target;
6160       break;
6161
6162     case BUILT_IN_MEMCPY:
6163       target = expand_builtin_memcpy (exp, target);
6164       if (target)
6165         return target;
6166       break;
6167
6168     case BUILT_IN_MEMPCPY:
6169       target = expand_builtin_mempcpy (exp, target, mode);
6170       if (target)
6171         return target;
6172       break;
6173
6174     case BUILT_IN_MEMSET:
6175       target = expand_builtin_memset (exp, target, mode);
6176       if (target)
6177         return target;
6178       break;
6179
6180     case BUILT_IN_BZERO:
6181       target = expand_builtin_bzero (exp);
6182       if (target)
6183         return target;
6184       break;
6185
6186     case BUILT_IN_STRCMP:
6187       target = expand_builtin_strcmp (exp, target);
6188       if (target)
6189         return target;
6190       break;
6191
6192     case BUILT_IN_STRNCMP:
6193       target = expand_builtin_strncmp (exp, target, mode);
6194       if (target)
6195         return target;
6196       break;
6197
6198     case BUILT_IN_BCMP:
6199     case BUILT_IN_MEMCMP:
6200       target = expand_builtin_memcmp (exp, target, mode);
6201       if (target)
6202         return target;
6203       break;
6204
6205     case BUILT_IN_SETJMP:
6206       /* This should have been lowered to the builtins below.  */
6207       gcc_unreachable ();
6208
6209     case BUILT_IN_SETJMP_SETUP:
6210       /* __builtin_setjmp_setup is passed a pointer to an array of five words
6211           and the receiver label.  */
6212       if (validate_arglist (exp, POINTER_TYPE, POINTER_TYPE, VOID_TYPE))
6213         {
6214           rtx buf_addr = expand_expr (CALL_EXPR_ARG (exp, 0), subtarget,
6215                                       VOIDmode, EXPAND_NORMAL);
6216           tree label = TREE_OPERAND (CALL_EXPR_ARG (exp, 1), 0);
6217           rtx label_r = label_rtx (label);
6218
6219           /* This is copied from the handling of non-local gotos.  */
6220           expand_builtin_setjmp_setup (buf_addr, label_r);
6221           nonlocal_goto_handler_labels
6222             = gen_rtx_EXPR_LIST (VOIDmode, label_r,
6223                                  nonlocal_goto_handler_labels);
6224           /* ??? Do not let expand_label treat us as such since we would
6225              not want to be both on the list of non-local labels and on
6226              the list of forced labels.  */
6227           FORCED_LABEL (label) = 0;
6228           return const0_rtx;
6229         }
6230       break;
6231
6232     case BUILT_IN_SETJMP_DISPATCHER:
6233        /* __builtin_setjmp_dispatcher is passed the dispatcher label.  */
6234       if (validate_arglist (exp, POINTER_TYPE, VOID_TYPE))
6235         {
6236           tree label = TREE_OPERAND (CALL_EXPR_ARG (exp, 0), 0);
6237           rtx label_r = label_rtx (label);
6238
6239           /* Remove the dispatcher label from the list of non-local labels
6240              since the receiver labels have been added to it above.  */
6241           remove_node_from_expr_list (label_r, &nonlocal_goto_handler_labels);
6242           return const0_rtx;
6243         }
6244       break;
6245
6246     case BUILT_IN_SETJMP_RECEIVER:
6247        /* __builtin_setjmp_receiver is passed the receiver label.  */
6248       if (validate_arglist (exp, POINTER_TYPE, VOID_TYPE))
6249         {
6250           tree label = TREE_OPERAND (CALL_EXPR_ARG (exp, 0), 0);
6251           rtx label_r = label_rtx (label);
6252
6253           expand_builtin_setjmp_receiver (label_r);
6254           return const0_rtx;
6255         }
6256       break;
6257
6258       /* __builtin_longjmp is passed a pointer to an array of five words.
6259          It's similar to the C library longjmp function but works with
6260          __builtin_setjmp above.  */
6261     case BUILT_IN_LONGJMP:
6262       if (validate_arglist (exp, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
6263         {
6264           rtx buf_addr = expand_expr (CALL_EXPR_ARG (exp, 0), subtarget,
6265                                       VOIDmode, EXPAND_NORMAL);
6266           rtx value = expand_normal (CALL_EXPR_ARG (exp, 1));
6267
6268           if (value != const1_rtx)
6269             {
6270               error ("%<__builtin_longjmp%> second argument must be 1");
6271               return const0_rtx;
6272             }
6273
6274           expand_builtin_longjmp (buf_addr, value);
6275           return const0_rtx;
6276         }
6277       break;
6278
6279     case BUILT_IN_NONLOCAL_GOTO:
6280       target = expand_builtin_nonlocal_goto (exp);
6281       if (target)
6282         return target;
6283       break;
6284
6285       /* This updates the setjmp buffer that is its argument with the value
6286          of the current stack pointer.  */
6287     case BUILT_IN_UPDATE_SETJMP_BUF:
6288       if (validate_arglist (exp, POINTER_TYPE, VOID_TYPE))
6289         {
6290           rtx buf_addr
6291             = expand_normal (CALL_EXPR_ARG (exp, 0));
6292
6293           expand_builtin_update_setjmp_buf (buf_addr);
6294           return const0_rtx;
6295         }
6296       break;
6297
6298     case BUILT_IN_TRAP:
6299       expand_builtin_trap ();
6300       return const0_rtx;
6301
6302     case BUILT_IN_UNREACHABLE:
6303       expand_builtin_unreachable ();
6304       return const0_rtx;
6305
6306     CASE_FLT_FN (BUILT_IN_SIGNBIT):
6307     case BUILT_IN_SIGNBITD32:
6308     case BUILT_IN_SIGNBITD64:
6309     case BUILT_IN_SIGNBITD128:
6310       target = expand_builtin_signbit (exp, target);
6311       if (target)
6312         return target;
6313       break;
6314
6315       /* Various hooks for the DWARF 2 __throw routine.  */
6316     case BUILT_IN_UNWIND_INIT:
6317       expand_builtin_unwind_init ();
6318       return const0_rtx;
6319     case BUILT_IN_DWARF_CFA:
6320       return virtual_cfa_rtx;
6321 #ifdef DWARF2_UNWIND_INFO
6322     case BUILT_IN_DWARF_SP_COLUMN:
6323       return expand_builtin_dwarf_sp_column ();
6324     case BUILT_IN_INIT_DWARF_REG_SIZES:
6325       expand_builtin_init_dwarf_reg_sizes (CALL_EXPR_ARG (exp, 0));
6326       return const0_rtx;
6327 #endif
6328     case BUILT_IN_FROB_RETURN_ADDR:
6329       return expand_builtin_frob_return_addr (CALL_EXPR_ARG (exp, 0));
6330     case BUILT_IN_EXTRACT_RETURN_ADDR:
6331       return expand_builtin_extract_return_addr (CALL_EXPR_ARG (exp, 0));
6332     case BUILT_IN_EH_RETURN:
6333       expand_builtin_eh_return (CALL_EXPR_ARG (exp, 0),
6334                                 CALL_EXPR_ARG (exp, 1));
6335       return const0_rtx;
6336 #ifdef EH_RETURN_DATA_REGNO
6337     case BUILT_IN_EH_RETURN_DATA_REGNO:
6338       return expand_builtin_eh_return_data_regno (exp);
6339 #endif
6340     case BUILT_IN_EXTEND_POINTER:
6341       return expand_builtin_extend_pointer (CALL_EXPR_ARG (exp, 0));
6342     case BUILT_IN_EH_POINTER:
6343       return expand_builtin_eh_pointer (exp);
6344     case BUILT_IN_EH_FILTER:
6345       return expand_builtin_eh_filter (exp);
6346     case BUILT_IN_EH_COPY_VALUES:
6347       return expand_builtin_eh_copy_values (exp);
6348
6349     case BUILT_IN_VA_START:
6350       return expand_builtin_va_start (exp);
6351     case BUILT_IN_VA_END:
6352       return expand_builtin_va_end (exp);
6353     case BUILT_IN_VA_COPY:
6354       return expand_builtin_va_copy (exp);
6355     case BUILT_IN_EXPECT:
6356       return expand_builtin_expect (exp, target);
6357     case BUILT_IN_ASSUME_ALIGNED:
6358       return expand_builtin_assume_aligned (exp, target);
6359     case BUILT_IN_PREFETCH:
6360       expand_builtin_prefetch (exp);
6361       return const0_rtx;
6362
6363     case BUILT_IN_INIT_TRAMPOLINE:
6364       return expand_builtin_init_trampoline (exp, true);
6365     case BUILT_IN_INIT_HEAP_TRAMPOLINE:
6366       return expand_builtin_init_trampoline (exp, false);
6367     case BUILT_IN_ADJUST_TRAMPOLINE:
6368       return expand_builtin_adjust_trampoline (exp);
6369
6370     case BUILT_IN_FORK:
6371     case BUILT_IN_EXECL:
6372     case BUILT_IN_EXECV:
6373     case BUILT_IN_EXECLP:
6374     case BUILT_IN_EXECLE:
6375     case BUILT_IN_EXECVP:
6376     case BUILT_IN_EXECVE:
6377       target = expand_builtin_fork_or_exec (fndecl, exp, target, ignore);
6378       if (target)
6379         return target;
6380       break;
6381
6382     case BUILT_IN_SYNC_FETCH_AND_ADD_1:
6383     case BUILT_IN_SYNC_FETCH_AND_ADD_2:
6384     case BUILT_IN_SYNC_FETCH_AND_ADD_4:
6385     case BUILT_IN_SYNC_FETCH_AND_ADD_8:
6386     case BUILT_IN_SYNC_FETCH_AND_ADD_16:
6387       mode = get_builtin_sync_mode (fcode - BUILT_IN_SYNC_FETCH_AND_ADD_1);
6388       target = expand_builtin_sync_operation (mode, exp, PLUS, false, target);
6389       if (target)
6390         return target;
6391       break;
6392
6393     case BUILT_IN_SYNC_FETCH_AND_SUB_1:
6394     case BUILT_IN_SYNC_FETCH_AND_SUB_2:
6395     case BUILT_IN_SYNC_FETCH_AND_SUB_4:
6396     case BUILT_IN_SYNC_FETCH_AND_SUB_8:
6397     case BUILT_IN_SYNC_FETCH_AND_SUB_16:
6398       mode = get_builtin_sync_mode (fcode - BUILT_IN_SYNC_FETCH_AND_SUB_1);
6399       target = expand_builtin_sync_operation (mode, exp, MINUS, false, target);
6400       if (target)
6401         return target;
6402       break;
6403
6404     case BUILT_IN_SYNC_FETCH_AND_OR_1:
6405     case BUILT_IN_SYNC_FETCH_AND_OR_2:
6406     case BUILT_IN_SYNC_FETCH_AND_OR_4:
6407     case BUILT_IN_SYNC_FETCH_AND_OR_8:
6408     case BUILT_IN_SYNC_FETCH_AND_OR_16:
6409       mode = get_builtin_sync_mode (fcode - BUILT_IN_SYNC_FETCH_AND_OR_1);
6410       target = expand_builtin_sync_operation (mode, exp, IOR, false, target);
6411       if (target)
6412         return target;
6413       break;
6414
6415     case BUILT_IN_SYNC_FETCH_AND_AND_1:
6416     case BUILT_IN_SYNC_FETCH_AND_AND_2:
6417     case BUILT_IN_SYNC_FETCH_AND_AND_4:
6418     case BUILT_IN_SYNC_FETCH_AND_AND_8:
6419     case BUILT_IN_SYNC_FETCH_AND_AND_16:
6420       mode = get_builtin_sync_mode (fcode - BUILT_IN_SYNC_FETCH_AND_AND_1);
6421       target = expand_builtin_sync_operation (mode, exp, AND, false, target);
6422       if (target)
6423         return target;
6424       break;
6425
6426     case BUILT_IN_SYNC_FETCH_AND_XOR_1:
6427     case BUILT_IN_SYNC_FETCH_AND_XOR_2:
6428     case BUILT_IN_SYNC_FETCH_AND_XOR_4:
6429     case BUILT_IN_SYNC_FETCH_AND_XOR_8:
6430     case BUILT_IN_SYNC_FETCH_AND_XOR_16:
6431       mode = get_builtin_sync_mode (fcode - BUILT_IN_SYNC_FETCH_AND_XOR_1);
6432       target = expand_builtin_sync_operation (mode, exp, XOR, false, target);
6433       if (target)
6434         return target;
6435       break;
6436
6437     case BUILT_IN_SYNC_FETCH_AND_NAND_1:
6438     case BUILT_IN_SYNC_FETCH_AND_NAND_2:
6439     case BUILT_IN_SYNC_FETCH_AND_NAND_4:
6440     case BUILT_IN_SYNC_FETCH_AND_NAND_8:
6441     case BUILT_IN_SYNC_FETCH_AND_NAND_16:
6442       mode = get_builtin_sync_mode (fcode - BUILT_IN_SYNC_FETCH_AND_NAND_1);
6443       target = expand_builtin_sync_operation (mode, exp, NOT, false, target);
6444       if (target)
6445         return target;
6446       break;
6447
6448     case BUILT_IN_SYNC_ADD_AND_FETCH_1:
6449     case BUILT_IN_SYNC_ADD_AND_FETCH_2:
6450     case BUILT_IN_SYNC_ADD_AND_FETCH_4:
6451     case BUILT_IN_SYNC_ADD_AND_FETCH_8:
6452     case BUILT_IN_SYNC_ADD_AND_FETCH_16:
6453       mode = get_builtin_sync_mode (fcode - BUILT_IN_SYNC_ADD_AND_FETCH_1);
6454       target = expand_builtin_sync_operation (mode, exp, PLUS, true, target);
6455       if (target)
6456         return target;
6457       break;
6458
6459     case BUILT_IN_SYNC_SUB_AND_FETCH_1:
6460     case BUILT_IN_SYNC_SUB_AND_FETCH_2:
6461     case BUILT_IN_SYNC_SUB_AND_FETCH_4:
6462     case BUILT_IN_SYNC_SUB_AND_FETCH_8:
6463     case BUILT_IN_SYNC_SUB_AND_FETCH_16:
6464       mode = get_builtin_sync_mode (fcode - BUILT_IN_SYNC_SUB_AND_FETCH_1);
6465       target = expand_builtin_sync_operation (mode, exp, MINUS, true, target);
6466       if (target)
6467         return target;
6468       break;
6469
6470     case BUILT_IN_SYNC_OR_AND_FETCH_1:
6471     case BUILT_IN_SYNC_OR_AND_FETCH_2:
6472     case BUILT_IN_SYNC_OR_AND_FETCH_4:
6473     case BUILT_IN_SYNC_OR_AND_FETCH_8:
6474     case BUILT_IN_SYNC_OR_AND_FETCH_16:
6475       mode = get_builtin_sync_mode (fcode - BUILT_IN_SYNC_OR_AND_FETCH_1);
6476       target = expand_builtin_sync_operation (mode, exp, IOR, true, target);
6477       if (target)
6478         return target;
6479       break;
6480
6481     case BUILT_IN_SYNC_AND_AND_FETCH_1:
6482     case BUILT_IN_SYNC_AND_AND_FETCH_2:
6483     case BUILT_IN_SYNC_AND_AND_FETCH_4:
6484     case BUILT_IN_SYNC_AND_AND_FETCH_8:
6485     case BUILT_IN_SYNC_AND_AND_FETCH_16:
6486       mode = get_builtin_sync_mode (fcode - BUILT_IN_SYNC_AND_AND_FETCH_1);
6487       target = expand_builtin_sync_operation (mode, exp, AND, true, target);
6488       if (target)
6489         return target;
6490       break;
6491
6492     case BUILT_IN_SYNC_XOR_AND_FETCH_1:
6493     case BUILT_IN_SYNC_XOR_AND_FETCH_2:
6494     case BUILT_IN_SYNC_XOR_AND_FETCH_4:
6495     case BUILT_IN_SYNC_XOR_AND_FETCH_8:
6496     case BUILT_IN_SYNC_XOR_AND_FETCH_16:
6497       mode = get_builtin_sync_mode (fcode - BUILT_IN_SYNC_XOR_AND_FETCH_1);
6498       target = expand_builtin_sync_operation (mode, exp, XOR, true, target);
6499       if (target)
6500         return target;
6501       break;
6502
6503     case BUILT_IN_SYNC_NAND_AND_FETCH_1:
6504     case BUILT_IN_SYNC_NAND_AND_FETCH_2:
6505     case BUILT_IN_SYNC_NAND_AND_FETCH_4:
6506     case BUILT_IN_SYNC_NAND_AND_FETCH_8:
6507     case BUILT_IN_SYNC_NAND_AND_FETCH_16:
6508       mode = get_builtin_sync_mode (fcode - BUILT_IN_SYNC_NAND_AND_FETCH_1);
6509       target = expand_builtin_sync_operation (mode, exp, NOT, true, target);
6510       if (target)
6511         return target;
6512       break;
6513
6514     case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_1:
6515     case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_2:
6516     case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_4:
6517     case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_8:
6518     case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_16:
6519       if (mode == VOIDmode)
6520         mode = TYPE_MODE (boolean_type_node);
6521       if (!target || !register_operand (target, mode))
6522         target = gen_reg_rtx (mode);
6523
6524       mode = get_builtin_sync_mode 
6525                                 (fcode - BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_1);
6526       target = expand_builtin_compare_and_swap (mode, exp, true, target);
6527       if (target)
6528         return target;
6529       break;
6530
6531     case BUILT_IN_SYNC_VAL_COMPARE_AND_SWAP_1:
6532     case BUILT_IN_SYNC_VAL_COMPARE_AND_SWAP_2:
6533     case BUILT_IN_SYNC_VAL_COMPARE_AND_SWAP_4:
6534     case BUILT_IN_SYNC_VAL_COMPARE_AND_SWAP_8:
6535     case BUILT_IN_SYNC_VAL_COMPARE_AND_SWAP_16:
6536       mode = get_builtin_sync_mode 
6537                                 (fcode - BUILT_IN_SYNC_VAL_COMPARE_AND_SWAP_1);
6538       target = expand_builtin_compare_and_swap (mode, exp, false, target);
6539       if (target)
6540         return target;
6541       break;
6542
6543     case BUILT_IN_SYNC_LOCK_TEST_AND_SET_1:
6544     case BUILT_IN_SYNC_LOCK_TEST_AND_SET_2:
6545     case BUILT_IN_SYNC_LOCK_TEST_AND_SET_4:
6546     case BUILT_IN_SYNC_LOCK_TEST_AND_SET_8:
6547     case BUILT_IN_SYNC_LOCK_TEST_AND_SET_16:
6548       mode = get_builtin_sync_mode (fcode - BUILT_IN_SYNC_LOCK_TEST_AND_SET_1);
6549       target = expand_builtin_sync_lock_test_and_set (mode, exp, target);
6550       if (target)
6551         return target;
6552       break;
6553
6554     case BUILT_IN_SYNC_LOCK_RELEASE_1:
6555     case BUILT_IN_SYNC_LOCK_RELEASE_2:
6556     case BUILT_IN_SYNC_LOCK_RELEASE_4:
6557     case BUILT_IN_SYNC_LOCK_RELEASE_8:
6558     case BUILT_IN_SYNC_LOCK_RELEASE_16:
6559       mode = get_builtin_sync_mode (fcode - BUILT_IN_SYNC_LOCK_RELEASE_1);
6560       expand_builtin_sync_lock_release (mode, exp);
6561       return const0_rtx;
6562
6563     case BUILT_IN_SYNC_SYNCHRONIZE:
6564       expand_builtin_sync_synchronize ();
6565       return const0_rtx;
6566
6567     case BUILT_IN_ATOMIC_EXCHANGE_1:
6568     case BUILT_IN_ATOMIC_EXCHANGE_2:
6569     case BUILT_IN_ATOMIC_EXCHANGE_4:
6570     case BUILT_IN_ATOMIC_EXCHANGE_8:
6571     case BUILT_IN_ATOMIC_EXCHANGE_16:
6572       mode = get_builtin_sync_mode (fcode - BUILT_IN_ATOMIC_EXCHANGE_1);
6573       target = expand_builtin_atomic_exchange (mode, exp, target);
6574       if (target)
6575         return target;
6576       break;
6577
6578     case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_1:
6579     case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_2:
6580     case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_4:
6581     case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_8:
6582     case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_16:
6583       {
6584         unsigned int nargs, z;
6585         vec<tree, va_gc> *vec;
6586
6587         mode = 
6588             get_builtin_sync_mode (fcode - BUILT_IN_ATOMIC_COMPARE_EXCHANGE_1);
6589         target = expand_builtin_atomic_compare_exchange (mode, exp, target);
6590         if (target)
6591           return target;
6592
6593         /* If this is turned into an external library call, the weak parameter
6594            must be dropped to match the expected parameter list.  */
6595         nargs = call_expr_nargs (exp);
6596         vec_alloc (vec, nargs - 1);
6597         for (z = 0; z < 3; z++)
6598           vec->quick_push (CALL_EXPR_ARG (exp, z));
6599         /* Skip the boolean weak parameter.  */
6600         for (z = 4; z < 6; z++)
6601           vec->quick_push (CALL_EXPR_ARG (exp, z));
6602         exp = build_call_vec (TREE_TYPE (exp), CALL_EXPR_FN (exp), vec);
6603         break;
6604       }
6605
6606     case BUILT_IN_ATOMIC_LOAD_1:
6607     case BUILT_IN_ATOMIC_LOAD_2:
6608     case BUILT_IN_ATOMIC_LOAD_4:
6609     case BUILT_IN_ATOMIC_LOAD_8:
6610     case BUILT_IN_ATOMIC_LOAD_16:
6611       mode = get_builtin_sync_mode (fcode - BUILT_IN_ATOMIC_LOAD_1);
6612       target = expand_builtin_atomic_load (mode, exp, target);
6613       if (target)
6614         return target;
6615       break;
6616
6617     case BUILT_IN_ATOMIC_STORE_1:
6618     case BUILT_IN_ATOMIC_STORE_2:
6619     case BUILT_IN_ATOMIC_STORE_4:
6620     case BUILT_IN_ATOMIC_STORE_8:
6621     case BUILT_IN_ATOMIC_STORE_16:
6622       mode = get_builtin_sync_mode (fcode - BUILT_IN_ATOMIC_STORE_1);
6623       target = expand_builtin_atomic_store (mode, exp);
6624       if (target)
6625         return const0_rtx;
6626       break;
6627
6628     case BUILT_IN_ATOMIC_ADD_FETCH_1:
6629     case BUILT_IN_ATOMIC_ADD_FETCH_2:
6630     case BUILT_IN_ATOMIC_ADD_FETCH_4:
6631     case BUILT_IN_ATOMIC_ADD_FETCH_8:
6632     case BUILT_IN_ATOMIC_ADD_FETCH_16:
6633       {
6634         enum built_in_function lib;
6635         mode = get_builtin_sync_mode (fcode - BUILT_IN_ATOMIC_ADD_FETCH_1);
6636         lib = (enum built_in_function)((int)BUILT_IN_ATOMIC_FETCH_ADD_1 + 
6637                                        (fcode - BUILT_IN_ATOMIC_ADD_FETCH_1));
6638         target = expand_builtin_atomic_fetch_op (mode, exp, target, PLUS, true,
6639                                                  ignore, lib);
6640         if (target)
6641           return target;
6642         break;
6643       }
6644     case BUILT_IN_ATOMIC_SUB_FETCH_1:
6645     case BUILT_IN_ATOMIC_SUB_FETCH_2:
6646     case BUILT_IN_ATOMIC_SUB_FETCH_4:
6647     case BUILT_IN_ATOMIC_SUB_FETCH_8:
6648     case BUILT_IN_ATOMIC_SUB_FETCH_16:
6649       {
6650         enum built_in_function lib;
6651         mode = get_builtin_sync_mode (fcode - BUILT_IN_ATOMIC_SUB_FETCH_1);
6652         lib = (enum built_in_function)((int)BUILT_IN_ATOMIC_FETCH_SUB_1 + 
6653                                        (fcode - BUILT_IN_ATOMIC_SUB_FETCH_1));
6654         target = expand_builtin_atomic_fetch_op (mode, exp, target, MINUS, true,
6655                                                  ignore, lib);
6656         if (target)
6657           return target;
6658         break;
6659       }
6660     case BUILT_IN_ATOMIC_AND_FETCH_1:
6661     case BUILT_IN_ATOMIC_AND_FETCH_2:
6662     case BUILT_IN_ATOMIC_AND_FETCH_4:
6663     case BUILT_IN_ATOMIC_AND_FETCH_8:
6664     case BUILT_IN_ATOMIC_AND_FETCH_16:
6665       {
6666         enum built_in_function lib;
6667         mode = get_builtin_sync_mode (fcode - BUILT_IN_ATOMIC_AND_FETCH_1);
6668         lib = (enum built_in_function)((int)BUILT_IN_ATOMIC_FETCH_AND_1 + 
6669                                        (fcode - BUILT_IN_ATOMIC_AND_FETCH_1));
6670         target = expand_builtin_atomic_fetch_op (mode, exp, target, AND, true,
6671                                                  ignore, lib);
6672         if (target)
6673           return target;
6674         break;
6675       }
6676     case BUILT_IN_ATOMIC_NAND_FETCH_1:
6677     case BUILT_IN_ATOMIC_NAND_FETCH_2:
6678     case BUILT_IN_ATOMIC_NAND_FETCH_4:
6679     case BUILT_IN_ATOMIC_NAND_FETCH_8:
6680     case BUILT_IN_ATOMIC_NAND_FETCH_16:
6681       {
6682         enum built_in_function lib;
6683         mode = get_builtin_sync_mode (fcode - BUILT_IN_ATOMIC_NAND_FETCH_1);
6684         lib = (enum built_in_function)((int)BUILT_IN_ATOMIC_FETCH_NAND_1 + 
6685                                        (fcode - BUILT_IN_ATOMIC_NAND_FETCH_1));
6686         target = expand_builtin_atomic_fetch_op (mode, exp, target, NOT, true,
6687                                                  ignore, lib);
6688         if (target)
6689           return target;
6690         break;
6691       }
6692     case BUILT_IN_ATOMIC_XOR_FETCH_1:
6693     case BUILT_IN_ATOMIC_XOR_FETCH_2:
6694     case BUILT_IN_ATOMIC_XOR_FETCH_4:
6695     case BUILT_IN_ATOMIC_XOR_FETCH_8:
6696     case BUILT_IN_ATOMIC_XOR_FETCH_16:
6697       {
6698         enum built_in_function lib;
6699         mode = get_builtin_sync_mode (fcode - BUILT_IN_ATOMIC_XOR_FETCH_1);
6700         lib = (enum built_in_function)((int)BUILT_IN_ATOMIC_FETCH_XOR_1 + 
6701                                        (fcode - BUILT_IN_ATOMIC_XOR_FETCH_1));
6702         target = expand_builtin_atomic_fetch_op (mode, exp, target, XOR, true,
6703                                                  ignore, lib);
6704         if (target)
6705           return target;
6706         break;
6707       }
6708     case BUILT_IN_ATOMIC_OR_FETCH_1:
6709     case BUILT_IN_ATOMIC_OR_FETCH_2:
6710     case BUILT_IN_ATOMIC_OR_FETCH_4:
6711     case BUILT_IN_ATOMIC_OR_FETCH_8:
6712     case BUILT_IN_ATOMIC_OR_FETCH_16:
6713       {
6714         enum built_in_function lib;
6715         mode = get_builtin_sync_mode (fcode - BUILT_IN_ATOMIC_OR_FETCH_1);
6716         lib = (enum built_in_function)((int)BUILT_IN_ATOMIC_FETCH_OR_1 + 
6717                                        (fcode - BUILT_IN_ATOMIC_OR_FETCH_1));
6718         target = expand_builtin_atomic_fetch_op (mode, exp, target, IOR, true,
6719                                                  ignore, lib);
6720         if (target)
6721           return target;
6722         break;
6723       }
6724     case BUILT_IN_ATOMIC_FETCH_ADD_1:
6725     case BUILT_IN_ATOMIC_FETCH_ADD_2:
6726     case BUILT_IN_ATOMIC_FETCH_ADD_4:
6727     case BUILT_IN_ATOMIC_FETCH_ADD_8:
6728     case BUILT_IN_ATOMIC_FETCH_ADD_16:
6729       mode = get_builtin_sync_mode (fcode - BUILT_IN_ATOMIC_FETCH_ADD_1);
6730       target = expand_builtin_atomic_fetch_op (mode, exp, target, PLUS, false,
6731                                                ignore, BUILT_IN_NONE);
6732       if (target)
6733         return target;
6734       break;
6735  
6736     case BUILT_IN_ATOMIC_FETCH_SUB_1:
6737     case BUILT_IN_ATOMIC_FETCH_SUB_2:
6738     case BUILT_IN_ATOMIC_FETCH_SUB_4:
6739     case BUILT_IN_ATOMIC_FETCH_SUB_8:
6740     case BUILT_IN_ATOMIC_FETCH_SUB_16:
6741       mode = get_builtin_sync_mode (fcode - BUILT_IN_ATOMIC_FETCH_SUB_1);
6742       target = expand_builtin_atomic_fetch_op (mode, exp, target, MINUS, false,
6743                                                ignore, BUILT_IN_NONE);
6744       if (target)
6745         return target;
6746       break;
6747
6748     case BUILT_IN_ATOMIC_FETCH_AND_1:
6749     case BUILT_IN_ATOMIC_FETCH_AND_2:
6750     case BUILT_IN_ATOMIC_FETCH_AND_4:
6751     case BUILT_IN_ATOMIC_FETCH_AND_8:
6752     case BUILT_IN_ATOMIC_FETCH_AND_16:
6753       mode = get_builtin_sync_mode (fcode - BUILT_IN_ATOMIC_FETCH_AND_1);
6754       target = expand_builtin_atomic_fetch_op (mode, exp, target, AND, false,
6755                                                ignore, BUILT_IN_NONE);
6756       if (target)
6757         return target;
6758       break;
6759   
6760     case BUILT_IN_ATOMIC_FETCH_NAND_1:
6761     case BUILT_IN_ATOMIC_FETCH_NAND_2:
6762     case BUILT_IN_ATOMIC_FETCH_NAND_4:
6763     case BUILT_IN_ATOMIC_FETCH_NAND_8:
6764     case BUILT_IN_ATOMIC_FETCH_NAND_16:
6765       mode = get_builtin_sync_mode (fcode - BUILT_IN_ATOMIC_FETCH_NAND_1);
6766       target = expand_builtin_atomic_fetch_op (mode, exp, target, NOT, false,
6767                                                ignore, BUILT_IN_NONE);
6768       if (target)
6769         return target;
6770       break;
6771  
6772     case BUILT_IN_ATOMIC_FETCH_XOR_1:
6773     case BUILT_IN_ATOMIC_FETCH_XOR_2:
6774     case BUILT_IN_ATOMIC_FETCH_XOR_4:
6775     case BUILT_IN_ATOMIC_FETCH_XOR_8:
6776     case BUILT_IN_ATOMIC_FETCH_XOR_16:
6777       mode = get_builtin_sync_mode (fcode - BUILT_IN_ATOMIC_FETCH_XOR_1);
6778       target = expand_builtin_atomic_fetch_op (mode, exp, target, XOR, false,
6779                                                ignore, BUILT_IN_NONE);
6780       if (target)
6781         return target;
6782       break;
6783  
6784     case BUILT_IN_ATOMIC_FETCH_OR_1:
6785     case BUILT_IN_ATOMIC_FETCH_OR_2:
6786     case BUILT_IN_ATOMIC_FETCH_OR_4:
6787     case BUILT_IN_ATOMIC_FETCH_OR_8:
6788     case BUILT_IN_ATOMIC_FETCH_OR_16:
6789       mode = get_builtin_sync_mode (fcode - BUILT_IN_ATOMIC_FETCH_OR_1);
6790       target = expand_builtin_atomic_fetch_op (mode, exp, target, IOR, false,
6791                                                ignore, BUILT_IN_NONE);
6792       if (target)
6793         return target;
6794       break;
6795
6796     case BUILT_IN_ATOMIC_TEST_AND_SET:
6797       return expand_builtin_atomic_test_and_set (exp, target);
6798
6799     case BUILT_IN_ATOMIC_CLEAR:
6800       return expand_builtin_atomic_clear (exp);
6801  
6802     case BUILT_IN_ATOMIC_ALWAYS_LOCK_FREE:
6803       return expand_builtin_atomic_always_lock_free (exp);
6804
6805     case BUILT_IN_ATOMIC_IS_LOCK_FREE:
6806       target = expand_builtin_atomic_is_lock_free (exp);
6807       if (target)
6808         return target;
6809       break;
6810
6811     case BUILT_IN_ATOMIC_THREAD_FENCE:
6812       expand_builtin_atomic_thread_fence (exp);
6813       return const0_rtx;
6814
6815     case BUILT_IN_ATOMIC_SIGNAL_FENCE:
6816       expand_builtin_atomic_signal_fence (exp);
6817       return const0_rtx;
6818
6819     case BUILT_IN_OBJECT_SIZE:
6820       return expand_builtin_object_size (exp);
6821
6822     case BUILT_IN_MEMCPY_CHK:
6823     case BUILT_IN_MEMPCPY_CHK:
6824     case BUILT_IN_MEMMOVE_CHK:
6825     case BUILT_IN_MEMSET_CHK:
6826       target = expand_builtin_memory_chk (exp, target, mode, fcode);
6827       if (target)
6828         return target;
6829       break;
6830
6831     case BUILT_IN_STRCPY_CHK:
6832     case BUILT_IN_STPCPY_CHK:
6833     case BUILT_IN_STRNCPY_CHK:
6834     case BUILT_IN_STPNCPY_CHK:
6835     case BUILT_IN_STRCAT_CHK:
6836     case BUILT_IN_STRNCAT_CHK:
6837     case BUILT_IN_SNPRINTF_CHK:
6838     case BUILT_IN_VSNPRINTF_CHK:
6839       maybe_emit_chk_warning (exp, fcode);
6840       break;
6841
6842     case BUILT_IN_SPRINTF_CHK:
6843     case BUILT_IN_VSPRINTF_CHK:
6844       maybe_emit_sprintf_chk_warning (exp, fcode);
6845       break;
6846
6847     case BUILT_IN_FREE:
6848       if (warn_free_nonheap_object)
6849         maybe_emit_free_warning (exp);
6850       break;
6851
6852     case BUILT_IN_THREAD_POINTER:
6853       return expand_builtin_thread_pointer (exp, target);
6854
6855     case BUILT_IN_SET_THREAD_POINTER:
6856       expand_builtin_set_thread_pointer (exp);
6857       return const0_rtx;
6858
6859     default:    /* just do library call, if unknown builtin */
6860       break;
6861     }
6862
6863   /* The switch statement above can drop through to cause the function
6864      to be called normally.  */
6865   return expand_call (exp, target, ignore);
6866 }
6867
6868 /* Determine whether a tree node represents a call to a built-in
6869    function.  If the tree T is a call to a built-in function with
6870    the right number of arguments of the appropriate types, return
6871    the DECL_FUNCTION_CODE of the call, e.g. BUILT_IN_SQRT.
6872    Otherwise the return value is END_BUILTINS.  */
6873
6874 enum built_in_function
6875 builtin_mathfn_code (const_tree t)
6876 {
6877   const_tree fndecl, arg, parmlist;
6878   const_tree argtype, parmtype;
6879   const_call_expr_arg_iterator iter;
6880
6881   if (TREE_CODE (t) != CALL_EXPR
6882       || TREE_CODE (CALL_EXPR_FN (t)) != ADDR_EXPR)
6883     return END_BUILTINS;
6884
6885   fndecl = get_callee_fndecl (t);
6886   if (fndecl == NULL_TREE
6887       || TREE_CODE (fndecl) != FUNCTION_DECL
6888       || ! DECL_BUILT_IN (fndecl)
6889       || DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_MD)
6890     return END_BUILTINS;
6891
6892   parmlist = TYPE_ARG_TYPES (TREE_TYPE (fndecl));
6893   init_const_call_expr_arg_iterator (t, &iter);
6894   for (; parmlist; parmlist = TREE_CHAIN (parmlist))
6895     {
6896       /* If a function doesn't take a variable number of arguments,
6897          the last element in the list will have type `void'.  */
6898       parmtype = TREE_VALUE (parmlist);
6899       if (VOID_TYPE_P (parmtype))
6900         {
6901           if (more_const_call_expr_args_p (&iter))
6902             return END_BUILTINS;
6903           return DECL_FUNCTION_CODE (fndecl);
6904         }
6905
6906       if (! more_const_call_expr_args_p (&iter))
6907         return END_BUILTINS;
6908
6909       arg = next_const_call_expr_arg (&iter);
6910       argtype = TREE_TYPE (arg);
6911
6912       if (SCALAR_FLOAT_TYPE_P (parmtype))
6913         {
6914           if (! SCALAR_FLOAT_TYPE_P (argtype))
6915             return END_BUILTINS;
6916         }
6917       else if (COMPLEX_FLOAT_TYPE_P (parmtype))
6918         {
6919           if (! COMPLEX_FLOAT_TYPE_P (argtype))
6920             return END_BUILTINS;
6921         }
6922       else if (POINTER_TYPE_P (parmtype))
6923         {
6924           if (! POINTER_TYPE_P (argtype))
6925             return END_BUILTINS;
6926         }
6927       else if (INTEGRAL_TYPE_P (parmtype))
6928         {
6929           if (! INTEGRAL_TYPE_P (argtype))
6930             return END_BUILTINS;
6931         }
6932       else
6933         return END_BUILTINS;
6934     }
6935
6936   /* Variable-length argument list.  */
6937   return DECL_FUNCTION_CODE (fndecl);
6938 }
6939
6940 /* Fold a call to __builtin_constant_p, if we know its argument ARG will
6941    evaluate to a constant.  */
6942
6943 static tree
6944 fold_builtin_constant_p (tree arg)
6945 {
6946   /* We return 1 for a numeric type that's known to be a constant
6947      value at compile-time or for an aggregate type that's a
6948      literal constant.  */
6949   STRIP_NOPS (arg);
6950
6951   /* If we know this is a constant, emit the constant of one.  */
6952   if (CONSTANT_CLASS_P (arg)
6953       || (TREE_CODE (arg) == CONSTRUCTOR
6954           && TREE_CONSTANT (arg)))
6955     return integer_one_node;
6956   if (TREE_CODE (arg) == ADDR_EXPR)
6957     {
6958        tree op = TREE_OPERAND (arg, 0);
6959        if (TREE_CODE (op) == STRING_CST
6960            || (TREE_CODE (op) == ARRAY_REF
6961                && integer_zerop (TREE_OPERAND (op, 1))
6962                && TREE_CODE (TREE_OPERAND (op, 0)) == STRING_CST))
6963          return integer_one_node;
6964     }
6965
6966   /* If this expression has side effects, show we don't know it to be a
6967      constant.  Likewise if it's a pointer or aggregate type since in
6968      those case we only want literals, since those are only optimized
6969      when generating RTL, not later.
6970      And finally, if we are compiling an initializer, not code, we
6971      need to return a definite result now; there's not going to be any
6972      more optimization done.  */
6973   if (TREE_SIDE_EFFECTS (arg)
6974       || AGGREGATE_TYPE_P (TREE_TYPE (arg))
6975       || POINTER_TYPE_P (TREE_TYPE (arg))
6976       || cfun == 0
6977       || folding_initializer)
6978     return integer_zero_node;
6979
6980   return NULL_TREE;
6981 }
6982
6983 /* Create builtin_expect with PRED and EXPECTED as its arguments and
6984    return it as a truthvalue.  */
6985
6986 static tree
6987 build_builtin_expect_predicate (location_t loc, tree pred, tree expected)
6988 {
6989   tree fn, arg_types, pred_type, expected_type, call_expr, ret_type;
6990
6991   fn = builtin_decl_explicit (BUILT_IN_EXPECT);
6992   arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
6993   ret_type = TREE_TYPE (TREE_TYPE (fn));
6994   pred_type = TREE_VALUE (arg_types);
6995   expected_type = TREE_VALUE (TREE_CHAIN (arg_types));
6996
6997   pred = fold_convert_loc (loc, pred_type, pred);
6998   expected = fold_convert_loc (loc, expected_type, expected);
6999   call_expr = build_call_expr_loc (loc, fn, 2, pred, expected);
7000
7001   return build2 (NE_EXPR, TREE_TYPE (pred), call_expr,
7002                  build_int_cst (ret_type, 0));
7003 }
7004
7005 /* Fold a call to builtin_expect with arguments ARG0 and ARG1.  Return
7006    NULL_TREE if no simplification is possible.  */
7007
7008 static tree
7009 fold_builtin_expect (location_t loc, tree arg0, tree arg1)
7010 {
7011   tree inner, fndecl, inner_arg0;
7012   enum tree_code code;
7013
7014   /* Distribute the expected value over short-circuiting operators.
7015      See through the cast from truthvalue_type_node to long.  */
7016   inner_arg0 = arg0;
7017   while (TREE_CODE (inner_arg0) == NOP_EXPR
7018          && INTEGRAL_TYPE_P (TREE_TYPE (inner_arg0))
7019          && INTEGRAL_TYPE_P (TREE_TYPE (TREE_OPERAND (inner_arg0, 0))))
7020     inner_arg0 = TREE_OPERAND (inner_arg0, 0);
7021
7022   /* If this is a builtin_expect within a builtin_expect keep the
7023      inner one.  See through a comparison against a constant.  It
7024      might have been added to create a thruthvalue.  */
7025   inner = inner_arg0;
7026
7027   if (COMPARISON_CLASS_P (inner)
7028       && TREE_CODE (TREE_OPERAND (inner, 1)) == INTEGER_CST)
7029     inner = TREE_OPERAND (inner, 0);
7030
7031   if (TREE_CODE (inner) == CALL_EXPR
7032       && (fndecl = get_callee_fndecl (inner))
7033       && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL
7034       && DECL_FUNCTION_CODE (fndecl) == BUILT_IN_EXPECT)
7035     return arg0;
7036
7037   inner = inner_arg0;
7038   code = TREE_CODE (inner);
7039   if (code == TRUTH_ANDIF_EXPR || code == TRUTH_ORIF_EXPR)
7040     {
7041       tree op0 = TREE_OPERAND (inner, 0);
7042       tree op1 = TREE_OPERAND (inner, 1);
7043
7044       op0 = build_builtin_expect_predicate (loc, op0, arg1);
7045       op1 = build_builtin_expect_predicate (loc, op1, arg1);
7046       inner = build2 (code, TREE_TYPE (inner), op0, op1);
7047
7048       return fold_convert_loc (loc, TREE_TYPE (arg0), inner);
7049     }
7050
7051   /* If the argument isn't invariant then there's nothing else we can do.  */
7052   if (!TREE_CONSTANT (inner_arg0))
7053     return NULL_TREE;
7054
7055   /* If we expect that a comparison against the argument will fold to
7056      a constant return the constant.  In practice, this means a true
7057      constant or the address of a non-weak symbol.  */
7058   inner = inner_arg0;
7059   STRIP_NOPS (inner);
7060   if (TREE_CODE (inner) == ADDR_EXPR)
7061     {
7062       do
7063         {
7064           inner = TREE_OPERAND (inner, 0);
7065         }
7066       while (TREE_CODE (inner) == COMPONENT_REF
7067              || TREE_CODE (inner) == ARRAY_REF);
7068       if ((TREE_CODE (inner) == VAR_DECL
7069            || TREE_CODE (inner) == FUNCTION_DECL)
7070           && DECL_WEAK (inner))
7071         return NULL_TREE;
7072     }
7073
7074   /* Otherwise, ARG0 already has the proper type for the return value.  */
7075   return arg0;
7076 }
7077
7078 /* Fold a call to __builtin_classify_type with argument ARG.  */
7079
7080 static tree
7081 fold_builtin_classify_type (tree arg)
7082 {
7083   if (arg == 0)
7084     return build_int_cst (integer_type_node, no_type_class);
7085
7086   return build_int_cst (integer_type_node, type_to_class (TREE_TYPE (arg)));
7087 }
7088
7089 /* Fold a call to __builtin_strlen with argument ARG.  */
7090
7091 static tree
7092 fold_builtin_strlen (location_t loc, tree type, tree arg)
7093 {
7094   if (!validate_arg (arg, POINTER_TYPE))
7095     return NULL_TREE;
7096   else
7097     {
7098       tree len = c_strlen (arg, 0);
7099
7100       if (len)
7101         return fold_convert_loc (loc, type, len);
7102
7103       return NULL_TREE;
7104     }
7105 }
7106
7107 /* Fold a call to __builtin_inf or __builtin_huge_val.  */
7108
7109 static tree
7110 fold_builtin_inf (location_t loc, tree type, int warn)
7111 {
7112   REAL_VALUE_TYPE real;
7113
7114   /* __builtin_inff is intended to be usable to define INFINITY on all
7115      targets.  If an infinity is not available, INFINITY expands "to a
7116      positive constant of type float that overflows at translation
7117      time", footnote "In this case, using INFINITY will violate the
7118      constraint in 6.4.4 and thus require a diagnostic." (C99 7.12#4).
7119      Thus we pedwarn to ensure this constraint violation is
7120      diagnosed.  */
7121   if (!MODE_HAS_INFINITIES (TYPE_MODE (type)) && warn)
7122     pedwarn (loc, 0, "target format does not support infinity");
7123
7124   real_inf (&real);
7125   return build_real (type, real);
7126 }
7127
7128 /* Fold a call to __builtin_nan or __builtin_nans with argument ARG.  */
7129
7130 static tree
7131 fold_builtin_nan (tree arg, tree type, int quiet)
7132 {
7133   REAL_VALUE_TYPE real;
7134   const char *str;
7135
7136   if (!validate_arg (arg, POINTER_TYPE))
7137     return NULL_TREE;
7138   str = c_getstr (arg);
7139   if (!str)
7140     return NULL_TREE;
7141
7142   if (!real_nan (&real, str, quiet, TYPE_MODE (type)))
7143     return NULL_TREE;
7144
7145   return build_real (type, real);
7146 }
7147
7148 /* Return true if the floating point expression T has an integer value.
7149    We also allow +Inf, -Inf and NaN to be considered integer values.  */
7150
7151 static bool
7152 integer_valued_real_p (tree t)
7153 {
7154   switch (TREE_CODE (t))
7155     {
7156     case FLOAT_EXPR:
7157       return true;
7158
7159     case ABS_EXPR:
7160     case SAVE_EXPR:
7161       return integer_valued_real_p (TREE_OPERAND (t, 0));
7162
7163     case COMPOUND_EXPR:
7164     case MODIFY_EXPR:
7165     case BIND_EXPR:
7166       return integer_valued_real_p (TREE_OPERAND (t, 1));
7167
7168     case PLUS_EXPR:
7169     case MINUS_EXPR:
7170     case MULT_EXPR:
7171     case MIN_EXPR:
7172     case MAX_EXPR:
7173       return integer_valued_real_p (TREE_OPERAND (t, 0))
7174              && integer_valued_real_p (TREE_OPERAND (t, 1));
7175
7176     case COND_EXPR:
7177       return integer_valued_real_p (TREE_OPERAND (t, 1))
7178              && integer_valued_real_p (TREE_OPERAND (t, 2));
7179
7180     case REAL_CST:
7181       return real_isinteger (TREE_REAL_CST_PTR (t), TYPE_MODE (TREE_TYPE (t)));
7182
7183     case NOP_EXPR:
7184       {
7185         tree type = TREE_TYPE (TREE_OPERAND (t, 0));
7186         if (TREE_CODE (type) == INTEGER_TYPE)
7187           return true;
7188         if (TREE_CODE (type) == REAL_TYPE)
7189           return integer_valued_real_p (TREE_OPERAND (t, 0));
7190         break;
7191       }
7192
7193     case CALL_EXPR:
7194       switch (builtin_mathfn_code (t))
7195         {
7196         CASE_FLT_FN (BUILT_IN_CEIL):
7197         CASE_FLT_FN (BUILT_IN_FLOOR):
7198         CASE_FLT_FN (BUILT_IN_NEARBYINT):
7199         CASE_FLT_FN (BUILT_IN_RINT):
7200         CASE_FLT_FN (BUILT_IN_ROUND):
7201         CASE_FLT_FN (BUILT_IN_TRUNC):
7202           return true;
7203
7204         CASE_FLT_FN (BUILT_IN_FMIN):
7205         CASE_FLT_FN (BUILT_IN_FMAX):
7206           return integer_valued_real_p (CALL_EXPR_ARG (t, 0))
7207             && integer_valued_real_p (CALL_EXPR_ARG (t, 1));
7208
7209         default:
7210           break;
7211         }
7212       break;
7213
7214     default:
7215       break;
7216     }
7217   return false;
7218 }
7219
7220 /* FNDECL is assumed to be a builtin where truncation can be propagated
7221    across (for instance floor((double)f) == (double)floorf (f).
7222    Do the transformation for a call with argument ARG.  */
7223
7224 static tree
7225 fold_trunc_transparent_mathfn (location_t loc, tree fndecl, tree arg)
7226 {
7227   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
7228
7229   if (!validate_arg (arg, REAL_TYPE))
7230     return NULL_TREE;
7231
7232   /* Integer rounding functions are idempotent.  */
7233   if (fcode == builtin_mathfn_code (arg))
7234     return arg;
7235
7236   /* If argument is already integer valued, and we don't need to worry
7237      about setting errno, there's no need to perform rounding.  */
7238   if (! flag_errno_math && integer_valued_real_p (arg))
7239     return arg;
7240
7241   if (optimize)
7242     {
7243       tree arg0 = strip_float_extensions (arg);
7244       tree ftype = TREE_TYPE (TREE_TYPE (fndecl));
7245       tree newtype = TREE_TYPE (arg0);
7246       tree decl;
7247
7248       if (TYPE_PRECISION (newtype) < TYPE_PRECISION (ftype)
7249           && (decl = mathfn_built_in (newtype, fcode)))
7250         return fold_convert_loc (loc, ftype,
7251                                  build_call_expr_loc (loc, decl, 1,
7252                                                   fold_convert_loc (loc,
7253                                                                     newtype,
7254                                                                     arg0)));
7255     }
7256   return NULL_TREE;
7257 }
7258
7259 /* FNDECL is assumed to be builtin which can narrow the FP type of
7260    the argument, for instance lround((double)f) -> lroundf (f).
7261    Do the transformation for a call with argument ARG.  */
7262
7263 static tree
7264 fold_fixed_mathfn (location_t loc, tree fndecl, tree arg)
7265 {
7266   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
7267
7268   if (!validate_arg (arg, REAL_TYPE))
7269     return NULL_TREE;
7270
7271   /* If argument is already integer valued, and we don't need to worry
7272      about setting errno, there's no need to perform rounding.  */
7273   if (! flag_errno_math && integer_valued_real_p (arg))
7274     return fold_build1_loc (loc, FIX_TRUNC_EXPR,
7275                         TREE_TYPE (TREE_TYPE (fndecl)), arg);
7276
7277   if (optimize)
7278     {
7279       tree ftype = TREE_TYPE (arg);
7280       tree arg0 = strip_float_extensions (arg);
7281       tree newtype = TREE_TYPE (arg0);
7282       tree decl;
7283
7284       if (TYPE_PRECISION (newtype) < TYPE_PRECISION (ftype)
7285           && (decl = mathfn_built_in (newtype, fcode)))
7286         return build_call_expr_loc (loc, decl, 1,
7287                                 fold_convert_loc (loc, newtype, arg0));
7288     }
7289
7290   /* Canonicalize iround (x) to lround (x) on ILP32 targets where
7291      sizeof (int) == sizeof (long).  */
7292   if (TYPE_PRECISION (integer_type_node)
7293       == TYPE_PRECISION (long_integer_type_node))
7294     {
7295       tree newfn = NULL_TREE;
7296       switch (fcode)
7297         {
7298         CASE_FLT_FN (BUILT_IN_ICEIL):
7299           newfn = mathfn_built_in (TREE_TYPE (arg), BUILT_IN_LCEIL);
7300           break;
7301
7302         CASE_FLT_FN (BUILT_IN_IFLOOR):
7303           newfn = mathfn_built_in (TREE_TYPE (arg), BUILT_IN_LFLOOR);
7304           break;
7305
7306         CASE_FLT_FN (BUILT_IN_IROUND):
7307           newfn = mathfn_built_in (TREE_TYPE (arg), BUILT_IN_LROUND);
7308           break;
7309
7310         CASE_FLT_FN (BUILT_IN_IRINT):
7311           newfn = mathfn_built_in (TREE_TYPE (arg), BUILT_IN_LRINT);
7312           break;
7313
7314         default:
7315           break;
7316         }
7317
7318       if (newfn)
7319         {
7320           tree newcall = build_call_expr_loc (loc, newfn, 1, arg);
7321           return fold_convert_loc (loc,
7322                                    TREE_TYPE (TREE_TYPE (fndecl)), newcall);
7323         }
7324     }
7325
7326   /* Canonicalize llround (x) to lround (x) on LP64 targets where
7327      sizeof (long long) == sizeof (long).  */
7328   if (TYPE_PRECISION (long_long_integer_type_node)
7329       == TYPE_PRECISION (long_integer_type_node))
7330     {
7331       tree newfn = NULL_TREE;
7332       switch (fcode)
7333         {
7334         CASE_FLT_FN (BUILT_IN_LLCEIL):
7335           newfn = mathfn_built_in (TREE_TYPE (arg), BUILT_IN_LCEIL);
7336           break;
7337
7338         CASE_FLT_FN (BUILT_IN_LLFLOOR):
7339           newfn = mathfn_built_in (TREE_TYPE (arg), BUILT_IN_LFLOOR);
7340           break;
7341
7342         CASE_FLT_FN (BUILT_IN_LLROUND):
7343           newfn = mathfn_built_in (TREE_TYPE (arg), BUILT_IN_LROUND);
7344           break;
7345
7346         CASE_FLT_FN (BUILT_IN_LLRINT):
7347           newfn = mathfn_built_in (TREE_TYPE (arg), BUILT_IN_LRINT);
7348           break;
7349
7350         default:
7351           break;
7352         }
7353
7354       if (newfn)
7355         {
7356           tree newcall = build_call_expr_loc (loc, newfn, 1, arg);
7357           return fold_convert_loc (loc,
7358                                    TREE_TYPE (TREE_TYPE (fndecl)), newcall);
7359         }
7360     }
7361
7362   return NULL_TREE;
7363 }
7364
7365 /* Fold call to builtin cabs, cabsf or cabsl with argument ARG.  TYPE is the
7366    return type.  Return NULL_TREE if no simplification can be made.  */
7367
7368 static tree
7369 fold_builtin_cabs (location_t loc, tree arg, tree type, tree fndecl)
7370 {
7371   tree res;
7372
7373   if (!validate_arg (arg, COMPLEX_TYPE)
7374       || TREE_CODE (TREE_TYPE (TREE_TYPE (arg))) != REAL_TYPE)
7375     return NULL_TREE;
7376
7377   /* Calculate the result when the argument is a constant.  */
7378   if (TREE_CODE (arg) == COMPLEX_CST
7379       && (res = do_mpfr_arg2 (TREE_REALPART (arg), TREE_IMAGPART (arg),
7380                               type, mpfr_hypot)))
7381     return res;
7382
7383   if (TREE_CODE (arg) == COMPLEX_EXPR)
7384     {
7385       tree real = TREE_OPERAND (arg, 0);
7386       tree imag = TREE_OPERAND (arg, 1);
7387
7388       /* If either part is zero, cabs is fabs of the other.  */
7389       if (real_zerop (real))
7390         return fold_build1_loc (loc, ABS_EXPR, type, imag);
7391       if (real_zerop (imag))
7392         return fold_build1_loc (loc, ABS_EXPR, type, real);
7393
7394       /* cabs(x+xi) -> fabs(x)*sqrt(2).  */
7395       if (flag_unsafe_math_optimizations
7396           && operand_equal_p (real, imag, OEP_PURE_SAME))
7397         {
7398           const REAL_VALUE_TYPE sqrt2_trunc
7399             = real_value_truncate (TYPE_MODE (type), dconst_sqrt2 ());
7400           STRIP_NOPS (real);
7401           return fold_build2_loc (loc, MULT_EXPR, type,
7402                               fold_build1_loc (loc, ABS_EXPR, type, real),
7403                               build_real (type, sqrt2_trunc));
7404         }
7405     }
7406
7407   /* Optimize cabs(-z) and cabs(conj(z)) as cabs(z).  */
7408   if (TREE_CODE (arg) == NEGATE_EXPR
7409       || TREE_CODE (arg) == CONJ_EXPR)
7410     return build_call_expr_loc (loc, fndecl, 1, TREE_OPERAND (arg, 0));
7411
7412   /* Don't do this when optimizing for size.  */
7413   if (flag_unsafe_math_optimizations
7414       && optimize && optimize_function_for_speed_p (cfun))
7415     {
7416       tree sqrtfn = mathfn_built_in (type, BUILT_IN_SQRT);
7417
7418       if (sqrtfn != NULL_TREE)
7419         {
7420           tree rpart, ipart, result;
7421
7422           arg = builtin_save_expr (arg);
7423
7424           rpart = fold_build1_loc (loc, REALPART_EXPR, type, arg);
7425           ipart = fold_build1_loc (loc, IMAGPART_EXPR, type, arg);
7426
7427           rpart = builtin_save_expr (rpart);
7428           ipart = builtin_save_expr (ipart);
7429
7430           result = fold_build2_loc (loc, PLUS_EXPR, type,
7431                                 fold_build2_loc (loc, MULT_EXPR, type,
7432                                              rpart, rpart),
7433                                 fold_build2_loc (loc, MULT_EXPR, type,
7434                                              ipart, ipart));
7435
7436           return build_call_expr_loc (loc, sqrtfn, 1, result);
7437         }
7438     }
7439
7440   return NULL_TREE;
7441 }
7442
7443 /* Build a complex (inf +- 0i) for the result of cproj.  TYPE is the
7444    complex tree type of the result.  If NEG is true, the imaginary
7445    zero is negative.  */
7446
7447 static tree
7448 build_complex_cproj (tree type, bool neg)
7449 {
7450   REAL_VALUE_TYPE rinf, rzero = dconst0;
7451   
7452   real_inf (&rinf);
7453   rzero.sign = neg;
7454   return build_complex (type, build_real (TREE_TYPE (type), rinf),
7455                         build_real (TREE_TYPE (type), rzero));
7456 }
7457
7458 /* Fold call to builtin cproj, cprojf or cprojl with argument ARG.  TYPE is the
7459    return type.  Return NULL_TREE if no simplification can be made.  */
7460
7461 static tree
7462 fold_builtin_cproj (location_t loc, tree arg, tree type)
7463 {
7464   if (!validate_arg (arg, COMPLEX_TYPE)
7465       || TREE_CODE (TREE_TYPE (TREE_TYPE (arg))) != REAL_TYPE)
7466     return NULL_TREE;
7467
7468   /* If there are no infinities, return arg.  */
7469   if (! HONOR_INFINITIES (TYPE_MODE (TREE_TYPE (type))))
7470     return non_lvalue_loc (loc, arg);
7471
7472   /* Calculate the result when the argument is a constant.  */
7473   if (TREE_CODE (arg) == COMPLEX_CST)
7474     {
7475       const REAL_VALUE_TYPE *real = TREE_REAL_CST_PTR (TREE_REALPART (arg));
7476       const REAL_VALUE_TYPE *imag = TREE_REAL_CST_PTR (TREE_IMAGPART (arg));
7477       
7478       if (real_isinf (real) || real_isinf (imag))
7479         return build_complex_cproj (type, imag->sign);
7480       else
7481         return arg;
7482     }
7483   else if (TREE_CODE (arg) == COMPLEX_EXPR)
7484     {
7485       tree real = TREE_OPERAND (arg, 0);
7486       tree imag = TREE_OPERAND (arg, 1);
7487
7488       STRIP_NOPS (real);
7489       STRIP_NOPS (imag);
7490       
7491       /* If the real part is inf and the imag part is known to be
7492          nonnegative, return (inf + 0i).  Remember side-effects are
7493          possible in the imag part.  */
7494       if (TREE_CODE (real) == REAL_CST
7495           && real_isinf (TREE_REAL_CST_PTR (real))
7496           && tree_expr_nonnegative_p (imag))
7497         return omit_one_operand_loc (loc, type,
7498                                      build_complex_cproj (type, false),
7499                                      arg);
7500       
7501       /* If the imag part is inf, return (inf+I*copysign(0,imag)).
7502          Remember side-effects are possible in the real part.  */
7503       if (TREE_CODE (imag) == REAL_CST
7504           && real_isinf (TREE_REAL_CST_PTR (imag)))
7505         return
7506           omit_one_operand_loc (loc, type,
7507                                 build_complex_cproj (type, TREE_REAL_CST_PTR
7508                                                      (imag)->sign), arg);
7509     }
7510
7511   return NULL_TREE;
7512 }
7513
7514 /* Fold a builtin function call to sqrt, sqrtf, or sqrtl with argument ARG.
7515    Return NULL_TREE if no simplification can be made.  */
7516
7517 static tree
7518 fold_builtin_sqrt (location_t loc, tree arg, tree type)
7519 {
7520
7521   enum built_in_function fcode;
7522   tree res;
7523
7524   if (!validate_arg (arg, REAL_TYPE))
7525     return NULL_TREE;
7526
7527   /* Calculate the result when the argument is a constant.  */
7528   if ((res = do_mpfr_arg1 (arg, type, mpfr_sqrt, &dconst0, NULL, true)))
7529     return res;
7530
7531   /* Optimize sqrt(expN(x)) = expN(x*0.5).  */
7532   fcode = builtin_mathfn_code (arg);
7533   if (flag_unsafe_math_optimizations && BUILTIN_EXPONENT_P (fcode))
7534     {
7535       tree expfn = TREE_OPERAND (CALL_EXPR_FN (arg), 0);
7536       arg = fold_build2_loc (loc, MULT_EXPR, type,
7537                          CALL_EXPR_ARG (arg, 0),
7538                          build_real (type, dconsthalf));
7539       return build_call_expr_loc (loc, expfn, 1, arg);
7540     }
7541
7542   /* Optimize sqrt(Nroot(x)) -> pow(x,1/(2*N)).  */
7543   if (flag_unsafe_math_optimizations && BUILTIN_ROOT_P (fcode))
7544     {
7545       tree powfn = mathfn_built_in (type, BUILT_IN_POW);
7546
7547       if (powfn)
7548         {
7549           tree arg0 = CALL_EXPR_ARG (arg, 0);
7550           tree tree_root;
7551           /* The inner root was either sqrt or cbrt.  */
7552           /* This was a conditional expression but it triggered a bug
7553              in Sun C 5.5.  */
7554           REAL_VALUE_TYPE dconstroot;
7555           if (BUILTIN_SQRT_P (fcode))
7556             dconstroot = dconsthalf;
7557           else
7558             dconstroot = dconst_third ();
7559
7560           /* Adjust for the outer root.  */
7561           SET_REAL_EXP (&dconstroot, REAL_EXP (&dconstroot) - 1);
7562           dconstroot = real_value_truncate (TYPE_MODE (type), dconstroot);
7563           tree_root = build_real (type, dconstroot);
7564           return build_call_expr_loc (loc, powfn, 2, arg0, tree_root);
7565         }
7566     }
7567
7568   /* Optimize sqrt(pow(x,y)) = pow(|x|,y*0.5).  */
7569   if (flag_unsafe_math_optimizations
7570       && (fcode == BUILT_IN_POW
7571           || fcode == BUILT_IN_POWF
7572           || fcode == BUILT_IN_POWL))
7573     {
7574       tree powfn = TREE_OPERAND (CALL_EXPR_FN (arg), 0);
7575       tree arg0 = CALL_EXPR_ARG (arg, 0);
7576       tree arg1 = CALL_EXPR_ARG (arg, 1);
7577       tree narg1;
7578       if (!tree_expr_nonnegative_p (arg0))
7579         arg0 = build1 (ABS_EXPR, type, arg0);
7580       narg1 = fold_build2_loc (loc, MULT_EXPR, type, arg1,
7581                            build_real (type, dconsthalf));
7582       return build_call_expr_loc (loc, powfn, 2, arg0, narg1);
7583     }
7584
7585   return NULL_TREE;
7586 }
7587
7588 /* Fold a builtin function call to cbrt, cbrtf, or cbrtl with argument ARG.
7589    Return NULL_TREE if no simplification can be made.  */
7590
7591 static tree
7592 fold_builtin_cbrt (location_t loc, tree arg, tree type)
7593 {
7594   const enum built_in_function fcode = builtin_mathfn_code (arg);
7595   tree res;
7596
7597   if (!validate_arg (arg, REAL_TYPE))
7598     return NULL_TREE;
7599
7600   /* Calculate the result when the argument is a constant.  */
7601   if ((res = do_mpfr_arg1 (arg, type, mpfr_cbrt, NULL, NULL, 0)))
7602     return res;
7603
7604   if (flag_unsafe_math_optimizations)
7605     {
7606       /* Optimize cbrt(expN(x)) -> expN(x/3).  */
7607       if (BUILTIN_EXPONENT_P (fcode))
7608         {
7609           tree expfn = TREE_OPERAND (CALL_EXPR_FN (arg), 0);
7610           const REAL_VALUE_TYPE third_trunc =
7611             real_value_truncate (TYPE_MODE (type), dconst_third ());
7612           arg = fold_build2_loc (loc, MULT_EXPR, type,
7613                              CALL_EXPR_ARG (arg, 0),
7614                              build_real (type, third_trunc));
7615           return build_call_expr_loc (loc, expfn, 1, arg);
7616         }
7617
7618       /* Optimize cbrt(sqrt(x)) -> pow(x,1/6).  */
7619       if (BUILTIN_SQRT_P (fcode))
7620         {
7621           tree powfn = mathfn_built_in (type, BUILT_IN_POW);
7622
7623           if (powfn)
7624             {
7625               tree arg0 = CALL_EXPR_ARG (arg, 0);
7626               tree tree_root;
7627               REAL_VALUE_TYPE dconstroot = dconst_third ();
7628
7629               SET_REAL_EXP (&dconstroot, REAL_EXP (&dconstroot) - 1);
7630               dconstroot = real_value_truncate (TYPE_MODE (type), dconstroot);
7631               tree_root = build_real (type, dconstroot);
7632               return build_call_expr_loc (loc, powfn, 2, arg0, tree_root);
7633             }
7634         }
7635
7636       /* Optimize cbrt(cbrt(x)) -> pow(x,1/9) iff x is nonnegative.  */
7637       if (BUILTIN_CBRT_P (fcode))
7638         {
7639           tree arg0 = CALL_EXPR_ARG (arg, 0);
7640           if (tree_expr_nonnegative_p (arg0))
7641             {
7642               tree powfn = mathfn_built_in (type, BUILT_IN_POW);
7643
7644               if (powfn)
7645                 {
7646                   tree tree_root;
7647                   REAL_VALUE_TYPE dconstroot;
7648
7649                   real_arithmetic (&dconstroot, MULT_EXPR,
7650                                    dconst_third_ptr (), dconst_third_ptr ());
7651                   dconstroot = real_value_truncate (TYPE_MODE (type), dconstroot);
7652                   tree_root = build_real (type, dconstroot);
7653                   return build_call_expr_loc (loc, powfn, 2, arg0, tree_root);
7654                 }
7655             }
7656         }
7657
7658       /* Optimize cbrt(pow(x,y)) -> pow(x,y/3) iff x is nonnegative.  */
7659       if (fcode == BUILT_IN_POW
7660           || fcode == BUILT_IN_POWF
7661           || fcode == BUILT_IN_POWL)
7662         {
7663           tree arg00 = CALL_EXPR_ARG (arg, 0);
7664           tree arg01 = CALL_EXPR_ARG (arg, 1);
7665           if (tree_expr_nonnegative_p (arg00))
7666             {
7667               tree powfn = TREE_OPERAND (CALL_EXPR_FN (arg), 0);
7668               const REAL_VALUE_TYPE dconstroot
7669                 = real_value_truncate (TYPE_MODE (type), dconst_third ());
7670               tree narg01 = fold_build2_loc (loc, MULT_EXPR, type, arg01,
7671                                          build_real (type, dconstroot));
7672               return build_call_expr_loc (loc, powfn, 2, arg00, narg01);
7673             }
7674         }
7675     }
7676   return NULL_TREE;
7677 }
7678
7679 /* Fold function call to builtin cos, cosf, or cosl with argument ARG.
7680    TYPE is the type of the return value.  Return NULL_TREE if no
7681    simplification can be made.  */
7682
7683 static tree
7684 fold_builtin_cos (location_t loc,
7685                   tree arg, tree type, tree fndecl)
7686 {
7687   tree res, narg;
7688
7689   if (!validate_arg (arg, REAL_TYPE))
7690     return NULL_TREE;
7691
7692   /* Calculate the result when the argument is a constant.  */
7693   if ((res = do_mpfr_arg1 (arg, type, mpfr_cos, NULL, NULL, 0)))
7694     return res;
7695
7696   /* Optimize cos(-x) into cos (x).  */
7697   if ((narg = fold_strip_sign_ops (arg)))
7698     return build_call_expr_loc (loc, fndecl, 1, narg);
7699
7700   return NULL_TREE;
7701 }
7702
7703 /* Fold function call to builtin cosh, coshf, or coshl with argument ARG.
7704    Return NULL_TREE if no simplification can be made.  */
7705
7706 static tree
7707 fold_builtin_cosh (location_t loc, tree arg, tree type, tree fndecl)
7708 {
7709   if (validate_arg (arg, REAL_TYPE))
7710     {
7711       tree res, narg;
7712
7713       /* Calculate the result when the argument is a constant.  */
7714       if ((res = do_mpfr_arg1 (arg, type, mpfr_cosh, NULL, NULL, 0)))
7715         return res;
7716
7717       /* Optimize cosh(-x) into cosh (x).  */
7718       if ((narg = fold_strip_sign_ops (arg)))
7719         return build_call_expr_loc (loc, fndecl, 1, narg);
7720     }
7721
7722   return NULL_TREE;
7723 }
7724
7725 /* Fold function call to builtin ccos (or ccosh if HYPER is TRUE) with
7726    argument ARG.  TYPE is the type of the return value.  Return
7727    NULL_TREE if no simplification can be made.  */
7728
7729 static tree
7730 fold_builtin_ccos (location_t loc, tree arg, tree type, tree fndecl,
7731                    bool hyper)
7732 {
7733   if (validate_arg (arg, COMPLEX_TYPE)
7734       && TREE_CODE (TREE_TYPE (TREE_TYPE (arg))) == REAL_TYPE)
7735     {
7736       tree tmp;
7737
7738       /* Calculate the result when the argument is a constant.  */
7739       if ((tmp = do_mpc_arg1 (arg, type, (hyper ? mpc_cosh : mpc_cos))))
7740         return tmp;
7741
7742       /* Optimize fn(-x) into fn(x).  */
7743       if ((tmp = fold_strip_sign_ops (arg)))
7744         return build_call_expr_loc (loc, fndecl, 1, tmp);
7745     }
7746
7747   return NULL_TREE;
7748 }
7749
7750 /* Fold function call to builtin tan, tanf, or tanl with argument ARG.
7751    Return NULL_TREE if no simplification can be made.  */
7752
7753 static tree
7754 fold_builtin_tan (tree arg, tree type)
7755 {
7756   enum built_in_function fcode;
7757   tree res;
7758
7759   if (!validate_arg (arg, REAL_TYPE))
7760     return NULL_TREE;
7761
7762   /* Calculate the result when the argument is a constant.  */
7763   if ((res = do_mpfr_arg1 (arg, type, mpfr_tan, NULL, NULL, 0)))
7764     return res;
7765
7766   /* Optimize tan(atan(x)) = x.  */
7767   fcode = builtin_mathfn_code (arg);
7768   if (flag_unsafe_math_optimizations
7769       && (fcode == BUILT_IN_ATAN
7770           || fcode == BUILT_IN_ATANF
7771           || fcode == BUILT_IN_ATANL))
7772     return CALL_EXPR_ARG (arg, 0);
7773
7774   return NULL_TREE;
7775 }
7776
7777 /* Fold function call to builtin sincos, sincosf, or sincosl.  Return
7778    NULL_TREE if no simplification can be made.  */
7779
7780 static tree
7781 fold_builtin_sincos (location_t loc,
7782                      tree arg0, tree arg1, tree arg2)
7783 {
7784   tree type;
7785   tree res, fn, call;
7786
7787   if (!validate_arg (arg0, REAL_TYPE)
7788       || !validate_arg (arg1, POINTER_TYPE)
7789       || !validate_arg (arg2, POINTER_TYPE))
7790     return NULL_TREE;
7791
7792   type = TREE_TYPE (arg0);
7793
7794   /* Calculate the result when the argument is a constant.  */
7795   if ((res = do_mpfr_sincos (arg0, arg1, arg2)))
7796     return res;
7797
7798   /* Canonicalize sincos to cexpi.  */
7799   if (!TARGET_C99_FUNCTIONS)
7800     return NULL_TREE;
7801   fn = mathfn_built_in (type, BUILT_IN_CEXPI);
7802   if (!fn)
7803     return NULL_TREE;
7804
7805   call = build_call_expr_loc (loc, fn, 1, arg0);
7806   call = builtin_save_expr (call);
7807
7808   return build2 (COMPOUND_EXPR, void_type_node,
7809                  build2 (MODIFY_EXPR, void_type_node,
7810                          build_fold_indirect_ref_loc (loc, arg1),
7811                          build1 (IMAGPART_EXPR, type, call)),
7812                  build2 (MODIFY_EXPR, void_type_node,
7813                          build_fold_indirect_ref_loc (loc, arg2),
7814                          build1 (REALPART_EXPR, type, call)));
7815 }
7816
7817 /* Fold function call to builtin cexp, cexpf, or cexpl.  Return
7818    NULL_TREE if no simplification can be made.  */
7819
7820 static tree
7821 fold_builtin_cexp (location_t loc, tree arg0, tree type)
7822 {
7823   tree rtype;
7824   tree realp, imagp, ifn;
7825   tree res;
7826
7827   if (!validate_arg (arg0, COMPLEX_TYPE)
7828       || TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) != REAL_TYPE)
7829     return NULL_TREE;
7830
7831   /* Calculate the result when the argument is a constant.  */
7832   if ((res = do_mpc_arg1 (arg0, type, mpc_exp)))
7833     return res;
7834
7835   rtype = TREE_TYPE (TREE_TYPE (arg0));
7836
7837   /* In case we can figure out the real part of arg0 and it is constant zero
7838      fold to cexpi.  */
7839   if (!TARGET_C99_FUNCTIONS)
7840     return NULL_TREE;
7841   ifn = mathfn_built_in (rtype, BUILT_IN_CEXPI);
7842   if (!ifn)
7843     return NULL_TREE;
7844
7845   if ((realp = fold_unary_loc (loc, REALPART_EXPR, rtype, arg0))
7846       && real_zerop (realp))
7847     {
7848       tree narg = fold_build1_loc (loc, IMAGPART_EXPR, rtype, arg0);
7849       return build_call_expr_loc (loc, ifn, 1, narg);
7850     }
7851
7852   /* In case we can easily decompose real and imaginary parts split cexp
7853      to exp (r) * cexpi (i).  */
7854   if (flag_unsafe_math_optimizations
7855       && realp)
7856     {
7857       tree rfn, rcall, icall;
7858
7859       rfn = mathfn_built_in (rtype, BUILT_IN_EXP);
7860       if (!rfn)
7861         return NULL_TREE;
7862
7863       imagp = fold_unary_loc (loc, IMAGPART_EXPR, rtype, arg0);
7864       if (!imagp)
7865         return NULL_TREE;
7866
7867       icall = build_call_expr_loc (loc, ifn, 1, imagp);
7868       icall = builtin_save_expr (icall);
7869       rcall = build_call_expr_loc (loc, rfn, 1, realp);
7870       rcall = builtin_save_expr (rcall);
7871       return fold_build2_loc (loc, COMPLEX_EXPR, type,
7872                           fold_build2_loc (loc, MULT_EXPR, rtype,
7873                                        rcall,
7874                                        fold_build1_loc (loc, REALPART_EXPR,
7875                                                     rtype, icall)),
7876                           fold_build2_loc (loc, MULT_EXPR, rtype,
7877                                        rcall,
7878                                        fold_build1_loc (loc, IMAGPART_EXPR,
7879                                                     rtype, icall)));
7880     }
7881
7882   return NULL_TREE;
7883 }
7884
7885 /* Fold function call to builtin trunc, truncf or truncl with argument ARG.
7886    Return NULL_TREE if no simplification can be made.  */
7887
7888 static tree
7889 fold_builtin_trunc (location_t loc, tree fndecl, tree arg)
7890 {
7891   if (!validate_arg (arg, REAL_TYPE))
7892     return NULL_TREE;
7893
7894   /* Optimize trunc of constant value.  */
7895   if (TREE_CODE (arg) == REAL_CST && !TREE_OVERFLOW (arg))
7896     {
7897       REAL_VALUE_TYPE r, x;
7898       tree type = TREE_TYPE (TREE_TYPE (fndecl));
7899
7900       x = TREE_REAL_CST (arg);
7901       real_trunc (&r, TYPE_MODE (type), &x);
7902       return build_real (type, r);
7903     }
7904
7905   return fold_trunc_transparent_mathfn (loc, fndecl, arg);
7906 }
7907
7908 /* Fold function call to builtin floor, floorf or floorl with argument ARG.
7909    Return NULL_TREE if no simplification can be made.  */
7910
7911 static tree
7912 fold_builtin_floor (location_t loc, tree fndecl, tree arg)
7913 {
7914   if (!validate_arg (arg, REAL_TYPE))
7915     return NULL_TREE;
7916
7917   /* Optimize floor of constant value.  */
7918   if (TREE_CODE (arg) == REAL_CST && !TREE_OVERFLOW (arg))
7919     {
7920       REAL_VALUE_TYPE x;
7921
7922       x = TREE_REAL_CST (arg);
7923       if (! REAL_VALUE_ISNAN (x) || ! flag_errno_math)
7924         {
7925           tree type = TREE_TYPE (TREE_TYPE (fndecl));
7926           REAL_VALUE_TYPE r;
7927
7928           real_floor (&r, TYPE_MODE (type), &x);
7929           return build_real (type, r);
7930         }
7931     }
7932
7933   /* Fold floor (x) where x is nonnegative to trunc (x).  */
7934   if (tree_expr_nonnegative_p (arg))
7935     {
7936       tree truncfn = mathfn_built_in (TREE_TYPE (arg), BUILT_IN_TRUNC);
7937       if (truncfn)
7938         return build_call_expr_loc (loc, truncfn, 1, arg);
7939     }
7940
7941   return fold_trunc_transparent_mathfn (loc, fndecl, arg);
7942 }
7943
7944 /* Fold function call to builtin ceil, ceilf or ceill with argument ARG.
7945    Return NULL_TREE if no simplification can be made.  */
7946
7947 static tree
7948 fold_builtin_ceil (location_t loc, tree fndecl, tree arg)
7949 {
7950   if (!validate_arg (arg, REAL_TYPE))
7951     return NULL_TREE;
7952
7953   /* Optimize ceil of constant value.  */
7954   if (TREE_CODE (arg) == REAL_CST && !TREE_OVERFLOW (arg))
7955     {
7956       REAL_VALUE_TYPE x;
7957
7958       x = TREE_REAL_CST (arg);
7959       if (! REAL_VALUE_ISNAN (x) || ! flag_errno_math)
7960         {
7961           tree type = TREE_TYPE (TREE_TYPE (fndecl));
7962           REAL_VALUE_TYPE r;
7963
7964           real_ceil (&r, TYPE_MODE (type), &x);
7965           return build_real (type, r);
7966         }
7967     }
7968
7969   return fold_trunc_transparent_mathfn (loc, fndecl, arg);
7970 }
7971
7972 /* Fold function call to builtin round, roundf or roundl with argument ARG.
7973    Return NULL_TREE if no simplification can be made.  */
7974
7975 static tree
7976 fold_builtin_round (location_t loc, tree fndecl, tree arg)
7977 {
7978   if (!validate_arg (arg, REAL_TYPE))
7979     return NULL_TREE;
7980
7981   /* Optimize round of constant value.  */
7982   if (TREE_CODE (arg) == REAL_CST && !TREE_OVERFLOW (arg))
7983     {
7984       REAL_VALUE_TYPE x;
7985
7986       x = TREE_REAL_CST (arg);
7987       if (! REAL_VALUE_ISNAN (x) || ! flag_errno_math)
7988         {
7989           tree type = TREE_TYPE (TREE_TYPE (fndecl));
7990           REAL_VALUE_TYPE r;
7991
7992           real_round (&r, TYPE_MODE (type), &x);
7993           return build_real (type, r);
7994         }
7995     }
7996
7997   return fold_trunc_transparent_mathfn (loc, fndecl, arg);
7998 }
7999
8000 /* Fold function call to builtin lround, lroundf or lroundl (or the
8001    corresponding long long versions) and other rounding functions.  ARG
8002    is the argument to the call.  Return NULL_TREE if no simplification
8003    can be made.  */
8004
8005 static tree
8006 fold_builtin_int_roundingfn (location_t loc, tree fndecl, tree arg)
8007 {
8008   if (!validate_arg (arg, REAL_TYPE))
8009     return NULL_TREE;
8010
8011   /* Optimize lround of constant value.  */
8012   if (TREE_CODE (arg) == REAL_CST && !TREE_OVERFLOW (arg))
8013     {
8014       const REAL_VALUE_TYPE x = TREE_REAL_CST (arg);
8015
8016       if (real_isfinite (&x))
8017         {
8018           tree itype = TREE_TYPE (TREE_TYPE (fndecl));
8019           tree ftype = TREE_TYPE (arg);
8020           double_int val;
8021           REAL_VALUE_TYPE r;
8022
8023           switch (DECL_FUNCTION_CODE (fndecl))
8024             {
8025             CASE_FLT_FN (BUILT_IN_IFLOOR):
8026             CASE_FLT_FN (BUILT_IN_LFLOOR):
8027             CASE_FLT_FN (BUILT_IN_LLFLOOR):
8028               real_floor (&r, TYPE_MODE (ftype), &x);
8029               break;
8030
8031             CASE_FLT_FN (BUILT_IN_ICEIL):
8032             CASE_FLT_FN (BUILT_IN_LCEIL):
8033             CASE_FLT_FN (BUILT_IN_LLCEIL):
8034               real_ceil (&r, TYPE_MODE (ftype), &x);
8035               break;
8036
8037             CASE_FLT_FN (BUILT_IN_IROUND):
8038             CASE_FLT_FN (BUILT_IN_LROUND):
8039             CASE_FLT_FN (BUILT_IN_LLROUND):
8040               real_round (&r, TYPE_MODE (ftype), &x);
8041               break;
8042
8043             default:
8044               gcc_unreachable ();
8045             }
8046
8047           real_to_integer2 ((HOST_WIDE_INT *)&val.low, &val.high, &r);
8048           if (double_int_fits_to_tree_p (itype, val))
8049             return double_int_to_tree (itype, val);
8050         }
8051     }
8052
8053   switch (DECL_FUNCTION_CODE (fndecl))
8054     {
8055     CASE_FLT_FN (BUILT_IN_LFLOOR):
8056     CASE_FLT_FN (BUILT_IN_LLFLOOR):
8057       /* Fold lfloor (x) where x is nonnegative to FIX_TRUNC (x).  */
8058       if (tree_expr_nonnegative_p (arg))
8059         return fold_build1_loc (loc, FIX_TRUNC_EXPR,
8060                             TREE_TYPE (TREE_TYPE (fndecl)), arg);
8061       break;
8062     default:;
8063     }
8064
8065   return fold_fixed_mathfn (loc, fndecl, arg);
8066 }
8067
8068 /* Fold function call to builtin ffs, clz, ctz, popcount and parity
8069    and their long and long long variants (i.e. ffsl and ffsll).  ARG is
8070    the argument to the call.  Return NULL_TREE if no simplification can
8071    be made.  */
8072
8073 static tree
8074 fold_builtin_bitop (tree fndecl, tree arg)
8075 {
8076   if (!validate_arg (arg, INTEGER_TYPE))
8077     return NULL_TREE;
8078
8079   /* Optimize for constant argument.  */
8080   if (TREE_CODE (arg) == INTEGER_CST && !TREE_OVERFLOW (arg))
8081     {
8082       HOST_WIDE_INT hi, width, result;
8083       unsigned HOST_WIDE_INT lo;
8084       tree type;
8085
8086       type = TREE_TYPE (arg);
8087       width = TYPE_PRECISION (type);
8088       lo = TREE_INT_CST_LOW (arg);
8089
8090       /* Clear all the bits that are beyond the type's precision.  */
8091       if (width > HOST_BITS_PER_WIDE_INT)
8092         {
8093           hi = TREE_INT_CST_HIGH (arg);
8094           if (width < HOST_BITS_PER_DOUBLE_INT)
8095             hi &= ~((unsigned HOST_WIDE_INT) (-1)
8096                     << (width - HOST_BITS_PER_WIDE_INT));
8097         }
8098       else
8099         {
8100           hi = 0;
8101           if (width < HOST_BITS_PER_WIDE_INT)
8102             lo &= ~((unsigned HOST_WIDE_INT) (-1) << width);
8103         }
8104
8105       switch (DECL_FUNCTION_CODE (fndecl))
8106         {
8107         CASE_INT_FN (BUILT_IN_FFS):
8108           if (lo != 0)
8109             result = ffs_hwi (lo);
8110           else if (hi != 0)
8111             result = HOST_BITS_PER_WIDE_INT + ffs_hwi (hi);
8112           else
8113             result = 0;
8114           break;
8115
8116         CASE_INT_FN (BUILT_IN_CLZ):
8117           if (hi != 0)
8118             result = width - floor_log2 (hi) - 1 - HOST_BITS_PER_WIDE_INT;
8119           else if (lo != 0)
8120             result = width - floor_log2 (lo) - 1;
8121           else if (! CLZ_DEFINED_VALUE_AT_ZERO (TYPE_MODE (type), result))
8122             result = width;
8123           break;
8124
8125         CASE_INT_FN (BUILT_IN_CTZ):
8126           if (lo != 0)
8127             result = ctz_hwi (lo);
8128           else if (hi != 0)
8129             result = HOST_BITS_PER_WIDE_INT + ctz_hwi (hi);
8130           else if (! CTZ_DEFINED_VALUE_AT_ZERO (TYPE_MODE (type), result))
8131             result = width;
8132           break;
8133
8134         CASE_INT_FN (BUILT_IN_CLRSB):
8135           if (width > HOST_BITS_PER_WIDE_INT
8136               && (hi & ((unsigned HOST_WIDE_INT) 1
8137                         << (width - HOST_BITS_PER_WIDE_INT - 1))) != 0)
8138             {
8139               hi = ~hi & ~((unsigned HOST_WIDE_INT) (-1)
8140                            << (width - HOST_BITS_PER_WIDE_INT - 1));
8141               lo = ~lo;
8142             }
8143           else if (width <= HOST_BITS_PER_WIDE_INT
8144                    && (lo & ((unsigned HOST_WIDE_INT) 1 << (width - 1))) != 0)
8145             lo = ~lo & ~((unsigned HOST_WIDE_INT) (-1) << (width - 1));
8146           if (hi != 0)
8147             result = width - floor_log2 (hi) - 2 - HOST_BITS_PER_WIDE_INT;
8148           else if (lo != 0)
8149             result = width - floor_log2 (lo) - 2;
8150           else
8151             result = width - 1;
8152           break;
8153
8154         CASE_INT_FN (BUILT_IN_POPCOUNT):
8155           result = 0;
8156           while (lo)
8157             result++, lo &= lo - 1;
8158           while (hi)
8159             result++, hi &= (unsigned HOST_WIDE_INT) hi - 1;
8160           break;
8161
8162         CASE_INT_FN (BUILT_IN_PARITY):
8163           result = 0;
8164           while (lo)
8165             result++, lo &= lo - 1;
8166           while (hi)
8167             result++, hi &= (unsigned HOST_WIDE_INT) hi - 1;
8168           result &= 1;
8169           break;
8170
8171         default:
8172           gcc_unreachable ();
8173         }
8174
8175       return build_int_cst (TREE_TYPE (TREE_TYPE (fndecl)), result);
8176     }
8177
8178   return NULL_TREE;
8179 }
8180
8181 /* Fold function call to builtin_bswap and the short, long and long long
8182    variants.  Return NULL_TREE if no simplification can be made.  */
8183 static tree
8184 fold_builtin_bswap (tree fndecl, tree arg)
8185 {
8186   if (! validate_arg (arg, INTEGER_TYPE))
8187     return NULL_TREE;
8188
8189   /* Optimize constant value.  */
8190   if (TREE_CODE (arg) == INTEGER_CST && !TREE_OVERFLOW (arg))
8191     {
8192       HOST_WIDE_INT hi, width, r_hi = 0;
8193       unsigned HOST_WIDE_INT lo, r_lo = 0;
8194       tree type = TREE_TYPE (TREE_TYPE (fndecl));
8195
8196       width = TYPE_PRECISION (type);
8197       lo = TREE_INT_CST_LOW (arg);
8198       hi = TREE_INT_CST_HIGH (arg);
8199
8200       switch (DECL_FUNCTION_CODE (fndecl))
8201         {
8202           case BUILT_IN_BSWAP16:
8203           case BUILT_IN_BSWAP32:
8204           case BUILT_IN_BSWAP64:
8205             {
8206               int s;
8207
8208               for (s = 0; s < width; s += 8)
8209                 {
8210                   int d = width - s - 8;
8211                   unsigned HOST_WIDE_INT byte;
8212
8213                   if (s < HOST_BITS_PER_WIDE_INT)
8214                     byte = (lo >> s) & 0xff;
8215                   else
8216                     byte = (hi >> (s - HOST_BITS_PER_WIDE_INT)) & 0xff;
8217
8218                   if (d < HOST_BITS_PER_WIDE_INT)
8219                     r_lo |= byte << d;
8220                   else
8221                     r_hi |= byte << (d - HOST_BITS_PER_WIDE_INT);
8222                 }
8223             }
8224
8225             break;
8226
8227         default:
8228           gcc_unreachable ();
8229         }
8230
8231       if (width < HOST_BITS_PER_WIDE_INT)
8232         return build_int_cst (type, r_lo);
8233       else
8234         return build_int_cst_wide (type, r_lo, r_hi);
8235     }
8236
8237   return NULL_TREE;
8238 }
8239
8240 /* A subroutine of fold_builtin to fold the various logarithmic
8241    functions.  Return NULL_TREE if no simplification can me made.
8242    FUNC is the corresponding MPFR logarithm function.  */
8243
8244 static tree
8245 fold_builtin_logarithm (location_t loc, tree fndecl, tree arg,
8246                         int (*func)(mpfr_ptr, mpfr_srcptr, mp_rnd_t))
8247 {
8248   if (validate_arg (arg, REAL_TYPE))
8249     {
8250       tree type = TREE_TYPE (TREE_TYPE (fndecl));
8251       tree res;
8252       const enum built_in_function fcode = builtin_mathfn_code (arg);
8253
8254       /* Calculate the result when the argument is a constant.  */
8255       if ((res = do_mpfr_arg1 (arg, type, func, &dconst0, NULL, false)))
8256         return res;
8257
8258       /* Special case, optimize logN(expN(x)) = x.  */
8259       if (flag_unsafe_math_optimizations
8260           && ((func == mpfr_log
8261                && (fcode == BUILT_IN_EXP
8262                    || fcode == BUILT_IN_EXPF
8263                    || fcode == BUILT_IN_EXPL))
8264               || (func == mpfr_log2
8265                   && (fcode == BUILT_IN_EXP2
8266                       || fcode == BUILT_IN_EXP2F
8267                       || fcode == BUILT_IN_EXP2L))
8268               || (func == mpfr_log10 && (BUILTIN_EXP10_P (fcode)))))
8269         return fold_convert_loc (loc, type, CALL_EXPR_ARG (arg, 0));
8270
8271       /* Optimize logN(func()) for various exponential functions.  We
8272          want to determine the value "x" and the power "exponent" in
8273          order to transform logN(x**exponent) into exponent*logN(x).  */
8274       if (flag_unsafe_math_optimizations)
8275         {
8276           tree exponent = 0, x = 0;
8277
8278           switch (fcode)
8279           {
8280           CASE_FLT_FN (BUILT_IN_EXP):
8281             /* Prepare to do logN(exp(exponent) -> exponent*logN(e).  */
8282             x = build_real (type, real_value_truncate (TYPE_MODE (type),
8283                                                        dconst_e ()));
8284             exponent = CALL_EXPR_ARG (arg, 0);
8285             break;
8286           CASE_FLT_FN (BUILT_IN_EXP2):
8287             /* Prepare to do logN(exp2(exponent) -> exponent*logN(2).  */
8288             x = build_real (type, dconst2);
8289             exponent = CALL_EXPR_ARG (arg, 0);
8290             break;
8291           CASE_FLT_FN (BUILT_IN_EXP10):
8292           CASE_FLT_FN (BUILT_IN_POW10):
8293             /* Prepare to do logN(exp10(exponent) -> exponent*logN(10).  */
8294             {
8295               REAL_VALUE_TYPE dconst10;
8296               real_from_integer (&dconst10, VOIDmode, 10, 0, 0);
8297               x = build_real (type, dconst10);
8298             }
8299             exponent = CALL_EXPR_ARG (arg, 0);
8300             break;
8301           CASE_FLT_FN (BUILT_IN_SQRT):
8302             /* Prepare to do logN(sqrt(x) -> 0.5*logN(x).  */
8303             x = CALL_EXPR_ARG (arg, 0);
8304             exponent = build_real (type, dconsthalf);
8305             break;
8306           CASE_FLT_FN (BUILT_IN_CBRT):
8307             /* Prepare to do logN(cbrt(x) -> (1/3)*logN(x).  */
8308             x = CALL_EXPR_ARG (arg, 0);
8309             exponent = build_real (type, real_value_truncate (TYPE_MODE (type),
8310                                                               dconst_third ()));
8311             break;
8312           CASE_FLT_FN (BUILT_IN_POW):
8313             /* Prepare to do logN(pow(x,exponent) -> exponent*logN(x).  */
8314             x = CALL_EXPR_ARG (arg, 0);
8315             exponent = CALL_EXPR_ARG (arg, 1);
8316             break;
8317           default:
8318             break;
8319           }
8320
8321           /* Now perform the optimization.  */
8322           if (x && exponent)
8323             {
8324               tree logfn = build_call_expr_loc (loc, fndecl, 1, x);
8325               return fold_build2_loc (loc, MULT_EXPR, type, exponent, logfn);
8326             }
8327         }
8328     }
8329
8330   return NULL_TREE;
8331 }
8332
8333 /* Fold a builtin function call to hypot, hypotf, or hypotl.  Return
8334    NULL_TREE if no simplification can be made.  */
8335
8336 static tree
8337 fold_builtin_hypot (location_t loc, tree fndecl,
8338                     tree arg0, tree arg1, tree type)
8339 {
8340   tree res, narg0, narg1;
8341
8342   if (!validate_arg (arg0, REAL_TYPE)
8343       || !validate_arg (arg1, REAL_TYPE))
8344     return NULL_TREE;
8345
8346   /* Calculate the result when the argument is a constant.  */
8347   if ((res = do_mpfr_arg2 (arg0, arg1, type, mpfr_hypot)))
8348     return res;
8349
8350   /* If either argument to hypot has a negate or abs, strip that off.
8351      E.g. hypot(-x,fabs(y)) -> hypot(x,y).  */
8352   narg0 = fold_strip_sign_ops (arg0);
8353   narg1 = fold_strip_sign_ops (arg1);
8354   if (narg0 || narg1)
8355     {
8356       return build_call_expr_loc (loc, fndecl, 2, narg0 ? narg0 : arg0,
8357                               narg1 ? narg1 : arg1);
8358     }
8359
8360   /* If either argument is zero, hypot is fabs of the other.  */
8361   if (real_zerop (arg0))
8362     return fold_build1_loc (loc, ABS_EXPR, type, arg1);
8363   else if (real_zerop (arg1))
8364     return fold_build1_loc (loc, ABS_EXPR, type, arg0);
8365
8366   /* hypot(x,x) -> fabs(x)*sqrt(2).  */
8367   if (flag_unsafe_math_optimizations
8368       && operand_equal_p (arg0, arg1, OEP_PURE_SAME))
8369     {
8370       const REAL_VALUE_TYPE sqrt2_trunc
8371         = real_value_truncate (TYPE_MODE (type), dconst_sqrt2 ());
8372       return fold_build2_loc (loc, MULT_EXPR, type,
8373                           fold_build1_loc (loc, ABS_EXPR, type, arg0),
8374                           build_real (type, sqrt2_trunc));
8375     }
8376
8377   return NULL_TREE;
8378 }
8379
8380
8381 /* Fold a builtin function call to pow, powf, or powl.  Return
8382    NULL_TREE if no simplification can be made.  */
8383 static tree
8384 fold_builtin_pow (location_t loc, tree fndecl, tree arg0, tree arg1, tree type)
8385 {
8386   tree res;
8387
8388   if (!validate_arg (arg0, REAL_TYPE)
8389        || !validate_arg (arg1, REAL_TYPE))
8390     return NULL_TREE;
8391
8392   /* Calculate the result when the argument is a constant.  */
8393   if ((res = do_mpfr_arg2 (arg0, arg1, type, mpfr_pow)))
8394     return res;
8395
8396   /* Optimize pow(1.0,y) = 1.0.  */
8397   if (real_onep (arg0))
8398     return omit_one_operand_loc (loc, type, build_real (type, dconst1), arg1);
8399
8400   if (TREE_CODE (arg1) == REAL_CST
8401       && !TREE_OVERFLOW (arg1))
8402     {
8403       REAL_VALUE_TYPE cint;
8404       REAL_VALUE_TYPE c;
8405       HOST_WIDE_INT n;
8406
8407       c = TREE_REAL_CST (arg1);
8408
8409       /* Optimize pow(x,0.0) = 1.0.  */
8410       if (REAL_VALUES_EQUAL (c, dconst0))
8411         return omit_one_operand_loc (loc, type, build_real (type, dconst1),
8412                                  arg0);
8413
8414       /* Optimize pow(x,1.0) = x.  */
8415       if (REAL_VALUES_EQUAL (c, dconst1))
8416         return arg0;
8417
8418       /* Optimize pow(x,-1.0) = 1.0/x.  */
8419       if (REAL_VALUES_EQUAL (c, dconstm1))
8420         return fold_build2_loc (loc, RDIV_EXPR, type,
8421                             build_real (type, dconst1), arg0);
8422
8423       /* Optimize pow(x,0.5) = sqrt(x).  */
8424       if (flag_unsafe_math_optimizations
8425           && REAL_VALUES_EQUAL (c, dconsthalf))
8426         {
8427           tree sqrtfn = mathfn_built_in (type, BUILT_IN_SQRT);
8428
8429           if (sqrtfn != NULL_TREE)
8430             return build_call_expr_loc (loc, sqrtfn, 1, arg0);
8431         }
8432
8433       /* Optimize pow(x,1.0/3.0) = cbrt(x).  */
8434       if (flag_unsafe_math_optimizations)
8435         {
8436           const REAL_VALUE_TYPE dconstroot
8437             = real_value_truncate (TYPE_MODE (type), dconst_third ());
8438
8439           if (REAL_VALUES_EQUAL (c, dconstroot))
8440             {
8441               tree cbrtfn = mathfn_built_in (type, BUILT_IN_CBRT);
8442               if (cbrtfn != NULL_TREE)
8443                 return build_call_expr_loc (loc, cbrtfn, 1, arg0);
8444             }
8445         }
8446
8447       /* Check for an integer exponent.  */
8448       n = real_to_integer (&c);
8449       real_from_integer (&cint, VOIDmode, n, n < 0 ? -1 : 0, 0);
8450       if (real_identical (&c, &cint))
8451         {
8452           /* Attempt to evaluate pow at compile-time, unless this should
8453              raise an exception.  */
8454           if (TREE_CODE (arg0) == REAL_CST
8455               && !TREE_OVERFLOW (arg0)
8456               && (n > 0
8457                   || (!flag_trapping_math && !flag_errno_math)
8458                   || !REAL_VALUES_EQUAL (TREE_REAL_CST (arg0), dconst0)))
8459             {
8460               REAL_VALUE_TYPE x;
8461               bool inexact;
8462
8463               x = TREE_REAL_CST (arg0);
8464               inexact = real_powi (&x, TYPE_MODE (type), &x, n);
8465               if (flag_unsafe_math_optimizations || !inexact)
8466                 return build_real (type, x);
8467             }
8468
8469           /* Strip sign ops from even integer powers.  */
8470           if ((n & 1) == 0 && flag_unsafe_math_optimizations)
8471             {
8472               tree narg0 = fold_strip_sign_ops (arg0);
8473               if (narg0)
8474                 return build_call_expr_loc (loc, fndecl, 2, narg0, arg1);
8475             }
8476         }
8477     }
8478
8479   if (flag_unsafe_math_optimizations)
8480     {
8481       const enum built_in_function fcode = builtin_mathfn_code (arg0);
8482
8483       /* Optimize pow(expN(x),y) = expN(x*y).  */
8484       if (BUILTIN_EXPONENT_P (fcode))
8485         {
8486           tree expfn = TREE_OPERAND (CALL_EXPR_FN (arg0), 0);
8487           tree arg = CALL_EXPR_ARG (arg0, 0);
8488           arg = fold_build2_loc (loc, MULT_EXPR, type, arg, arg1);
8489           return build_call_expr_loc (loc, expfn, 1, arg);
8490         }
8491
8492       /* Optimize pow(sqrt(x),y) = pow(x,y*0.5).  */
8493       if (BUILTIN_SQRT_P (fcode))
8494         {
8495           tree narg0 = CALL_EXPR_ARG (arg0, 0);
8496           tree narg1 = fold_build2_loc (loc, MULT_EXPR, type, arg1,
8497                                     build_real (type, dconsthalf));
8498           return build_call_expr_loc (loc, fndecl, 2, narg0, narg1);
8499         }
8500
8501       /* Optimize pow(cbrt(x),y) = pow(x,y/3) iff x is nonnegative.  */
8502       if (BUILTIN_CBRT_P (fcode))
8503         {
8504           tree arg = CALL_EXPR_ARG (arg0, 0);
8505           if (tree_expr_nonnegative_p (arg))
8506             {
8507               const REAL_VALUE_TYPE dconstroot
8508                 = real_value_truncate (TYPE_MODE (type), dconst_third ());
8509               tree narg1 = fold_build2_loc (loc, MULT_EXPR, type, arg1,
8510                                         build_real (type, dconstroot));
8511               return build_call_expr_loc (loc, fndecl, 2, arg, narg1);
8512             }
8513         }
8514
8515       /* Optimize pow(pow(x,y),z) = pow(x,y*z) iff x is nonnegative.  */
8516       if (fcode == BUILT_IN_POW
8517           || fcode == BUILT_IN_POWF
8518           || fcode == BUILT_IN_POWL)
8519         {
8520           tree arg00 = CALL_EXPR_ARG (arg0, 0);
8521           if (tree_expr_nonnegative_p (arg00))
8522             {
8523               tree arg01 = CALL_EXPR_ARG (arg0, 1);
8524               tree narg1 = fold_build2_loc (loc, MULT_EXPR, type, arg01, arg1);
8525               return build_call_expr_loc (loc, fndecl, 2, arg00, narg1);
8526             }
8527         }
8528     }
8529
8530   return NULL_TREE;
8531 }
8532
8533 /* Fold a builtin function call to powi, powif, or powil with argument ARG.
8534    Return NULL_TREE if no simplification can be made.  */
8535 static tree
8536 fold_builtin_powi (location_t loc, tree fndecl ATTRIBUTE_UNUSED,
8537                    tree arg0, tree arg1, tree type)
8538 {
8539   if (!validate_arg (arg0, REAL_TYPE)
8540       || !validate_arg (arg1, INTEGER_TYPE))
8541     return NULL_TREE;
8542
8543   /* Optimize pow(1.0,y) = 1.0.  */
8544   if (real_onep (arg0))
8545     return omit_one_operand_loc (loc, type, build_real (type, dconst1), arg1);
8546
8547   if (host_integerp (arg1, 0))
8548     {
8549       HOST_WIDE_INT c = TREE_INT_CST_LOW (arg1);
8550
8551       /* Evaluate powi at compile-time.  */
8552       if (TREE_CODE (arg0) == REAL_CST
8553           && !TREE_OVERFLOW (arg0))
8554         {
8555           REAL_VALUE_TYPE x;
8556           x = TREE_REAL_CST (arg0);
8557           real_powi (&x, TYPE_MODE (type), &x, c);
8558           return build_real (type, x);
8559         }
8560
8561       /* Optimize pow(x,0) = 1.0.  */
8562       if (c == 0)
8563         return omit_one_operand_loc (loc, type, build_real (type, dconst1),
8564                                  arg0);
8565
8566       /* Optimize pow(x,1) = x.  */
8567       if (c == 1)
8568         return arg0;
8569
8570       /* Optimize pow(x,-1) = 1.0/x.  */
8571       if (c == -1)
8572         return fold_build2_loc (loc, RDIV_EXPR, type,
8573                            build_real (type, dconst1), arg0);
8574     }
8575
8576   return NULL_TREE;
8577 }
8578
8579 /* A subroutine of fold_builtin to fold the various exponent
8580    functions.  Return NULL_TREE if no simplification can be made.
8581    FUNC is the corresponding MPFR exponent function.  */
8582
8583 static tree
8584 fold_builtin_exponent (location_t loc, tree fndecl, tree arg,
8585                        int (*func)(mpfr_ptr, mpfr_srcptr, mp_rnd_t))
8586 {
8587   if (validate_arg (arg, REAL_TYPE))
8588     {
8589       tree type = TREE_TYPE (TREE_TYPE (fndecl));
8590       tree res;
8591
8592       /* Calculate the result when the argument is a constant.  */
8593       if ((res = do_mpfr_arg1 (arg, type, func, NULL, NULL, 0)))
8594         return res;
8595
8596       /* Optimize expN(logN(x)) = x.  */
8597       if (flag_unsafe_math_optimizations)
8598         {
8599           const enum built_in_function fcode = builtin_mathfn_code (arg);
8600
8601           if ((func == mpfr_exp
8602                && (fcode == BUILT_IN_LOG
8603                    || fcode == BUILT_IN_LOGF
8604                    || fcode == BUILT_IN_LOGL))
8605               || (func == mpfr_exp2
8606                   && (fcode == BUILT_IN_LOG2
8607                       || fcode == BUILT_IN_LOG2F
8608                       || fcode == BUILT_IN_LOG2L))
8609               || (func == mpfr_exp10
8610                   && (fcode == BUILT_IN_LOG10
8611                       || fcode == BUILT_IN_LOG10F
8612                       || fcode == BUILT_IN_LOG10L)))
8613             return fold_convert_loc (loc, type, CALL_EXPR_ARG (arg, 0));
8614         }
8615     }
8616
8617   return NULL_TREE;
8618 }
8619
8620 /* Return true if VAR is a VAR_DECL or a component thereof.  */
8621
8622 static bool
8623 var_decl_component_p (tree var)
8624 {
8625   tree inner = var;
8626   while (handled_component_p (inner))
8627     inner = TREE_OPERAND (inner, 0);
8628   return SSA_VAR_P (inner);
8629 }
8630
8631 /* Fold function call to builtin memset.  Return
8632    NULL_TREE if no simplification can be made.  */
8633
8634 static tree
8635 fold_builtin_memset (location_t loc, tree dest, tree c, tree len,
8636                      tree type, bool ignore)
8637 {
8638   tree var, ret, etype;
8639   unsigned HOST_WIDE_INT length, cval;
8640
8641   if (! validate_arg (dest, POINTER_TYPE)
8642       || ! validate_arg (c, INTEGER_TYPE)
8643       || ! validate_arg (len, INTEGER_TYPE))
8644     return NULL_TREE;
8645
8646   if (! host_integerp (len, 1))
8647     return NULL_TREE;
8648
8649   /* If the LEN parameter is zero, return DEST.  */
8650   if (integer_zerop (len))
8651     return omit_one_operand_loc (loc, type, dest, c);
8652
8653   if (TREE_CODE (c) != INTEGER_CST || TREE_SIDE_EFFECTS (dest))
8654     return NULL_TREE;
8655
8656   var = dest;
8657   STRIP_NOPS (var);
8658   if (TREE_CODE (var) != ADDR_EXPR)
8659     return NULL_TREE;
8660
8661   var = TREE_OPERAND (var, 0);
8662   if (TREE_THIS_VOLATILE (var))
8663     return NULL_TREE;
8664
8665   etype = TREE_TYPE (var);
8666   if (TREE_CODE (etype) == ARRAY_TYPE)
8667     etype = TREE_TYPE (etype);
8668
8669   if (!INTEGRAL_TYPE_P (etype)
8670       && !POINTER_TYPE_P (etype))
8671     return NULL_TREE;
8672
8673   if (! var_decl_component_p (var))
8674     return NULL_TREE;
8675
8676   length = tree_low_cst (len, 1);
8677   if (GET_MODE_SIZE (TYPE_MODE (etype)) != length
8678       || get_pointer_alignment (dest) / BITS_PER_UNIT < length)
8679     return NULL_TREE;
8680
8681   if (length > HOST_BITS_PER_WIDE_INT / BITS_PER_UNIT)
8682     return NULL_TREE;
8683
8684   if (integer_zerop (c))
8685     cval = 0;
8686   else
8687     {
8688       if (CHAR_BIT != 8 || BITS_PER_UNIT != 8 || HOST_BITS_PER_WIDE_INT > 64)
8689         return NULL_TREE;
8690
8691       cval = TREE_INT_CST_LOW (c);
8692       cval &= 0xff;
8693       cval |= cval << 8;
8694       cval |= cval << 16;
8695       cval |= (cval << 31) << 1;
8696     }
8697
8698   ret = build_int_cst_type (etype, cval);
8699   var = build_fold_indirect_ref_loc (loc,
8700                                  fold_convert_loc (loc,
8701                                                    build_pointer_type (etype),
8702                                                    dest));
8703   ret = build2 (MODIFY_EXPR, etype, var, ret);
8704   if (ignore)
8705     return ret;
8706
8707   return omit_one_operand_loc (loc, type, dest, ret);
8708 }
8709
8710 /* Fold function call to builtin memset.  Return
8711    NULL_TREE if no simplification can be made.  */
8712
8713 static tree
8714 fold_builtin_bzero (location_t loc, tree dest, tree size, bool ignore)
8715 {
8716   if (! validate_arg (dest, POINTER_TYPE)
8717       || ! validate_arg (size, INTEGER_TYPE))
8718     return NULL_TREE;
8719
8720   if (!ignore)
8721     return NULL_TREE;
8722
8723   /* New argument list transforming bzero(ptr x, int y) to
8724      memset(ptr x, int 0, size_t y).   This is done this way
8725      so that if it isn't expanded inline, we fallback to
8726      calling bzero instead of memset.  */
8727
8728   return fold_builtin_memset (loc, dest, integer_zero_node,
8729                               fold_convert_loc (loc, size_type_node, size),
8730                               void_type_node, ignore);
8731 }
8732
8733 /* Fold function call to builtin mem{{,p}cpy,move}.  Return
8734    NULL_TREE if no simplification can be made.
8735    If ENDP is 0, return DEST (like memcpy).
8736    If ENDP is 1, return DEST+LEN (like mempcpy).
8737    If ENDP is 2, return DEST+LEN-1 (like stpcpy).
8738    If ENDP is 3, return DEST, additionally *SRC and *DEST may overlap
8739    (memmove).   */
8740
8741 static tree
8742 fold_builtin_memory_op (location_t loc, tree dest, tree src,
8743                         tree len, tree type, bool ignore, int endp)
8744 {
8745   tree destvar, srcvar, expr;
8746
8747   if (! validate_arg (dest, POINTER_TYPE)
8748       || ! validate_arg (src, POINTER_TYPE)
8749       || ! validate_arg (len, INTEGER_TYPE))
8750     return NULL_TREE;
8751
8752   /* If the LEN parameter is zero, return DEST.  */
8753   if (integer_zerop (len))
8754     return omit_one_operand_loc (loc, type, dest, src);
8755
8756   /* If SRC and DEST are the same (and not volatile), return
8757      DEST{,+LEN,+LEN-1}.  */
8758   if (operand_equal_p (src, dest, 0))
8759     expr = len;
8760   else
8761     {
8762       tree srctype, desttype;
8763       unsigned int src_align, dest_align;
8764       tree off0;
8765
8766       if (endp == 3)
8767         {
8768           src_align = get_pointer_alignment (src);
8769           dest_align = get_pointer_alignment (dest);
8770
8771           /* Both DEST and SRC must be pointer types.
8772              ??? This is what old code did.  Is the testing for pointer types
8773              really mandatory?
8774
8775              If either SRC is readonly or length is 1, we can use memcpy.  */
8776           if (!dest_align || !src_align)
8777             return NULL_TREE;
8778           if (readonly_data_expr (src)
8779               || (host_integerp (len, 1)
8780                   && (MIN (src_align, dest_align) / BITS_PER_UNIT
8781                       >= (unsigned HOST_WIDE_INT) tree_low_cst (len, 1))))
8782             {
8783               tree fn = builtin_decl_implicit (BUILT_IN_MEMCPY);
8784               if (!fn)
8785                 return NULL_TREE;
8786               return build_call_expr_loc (loc, fn, 3, dest, src, len);
8787             }
8788
8789           /* If *src and *dest can't overlap, optimize into memcpy as well.  */
8790           if (TREE_CODE (src) == ADDR_EXPR
8791               && TREE_CODE (dest) == ADDR_EXPR)
8792             {
8793               tree src_base, dest_base, fn;
8794               HOST_WIDE_INT src_offset = 0, dest_offset = 0;
8795               HOST_WIDE_INT size = -1;
8796               HOST_WIDE_INT maxsize = -1;
8797
8798               srcvar = TREE_OPERAND (src, 0);
8799               src_base = get_ref_base_and_extent (srcvar, &src_offset,
8800                                                   &size, &maxsize);
8801               destvar = TREE_OPERAND (dest, 0);
8802               dest_base = get_ref_base_and_extent (destvar, &dest_offset,
8803                                                    &size, &maxsize);
8804               if (host_integerp (len, 1))
8805                 maxsize = tree_low_cst (len, 1);
8806               else
8807                 maxsize = -1;
8808               src_offset /= BITS_PER_UNIT;
8809               dest_offset /= BITS_PER_UNIT;
8810               if (SSA_VAR_P (src_base)
8811                   && SSA_VAR_P (dest_base))
8812                 {
8813                   if (operand_equal_p (src_base, dest_base, 0)
8814                       && ranges_overlap_p (src_offset, maxsize,
8815                                            dest_offset, maxsize))
8816                     return NULL_TREE;
8817                 }
8818               else if (TREE_CODE (src_base) == MEM_REF
8819                        && TREE_CODE (dest_base) == MEM_REF)
8820                 {
8821                   double_int off;
8822                   if (! operand_equal_p (TREE_OPERAND (src_base, 0),
8823                                          TREE_OPERAND (dest_base, 0), 0))
8824                     return NULL_TREE;
8825                   off = mem_ref_offset (src_base) +
8826                                         double_int::from_shwi (src_offset);
8827                   if (!off.fits_shwi ())
8828                     return NULL_TREE;
8829                   src_offset = off.low;
8830                   off = mem_ref_offset (dest_base) +
8831                                         double_int::from_shwi (dest_offset);
8832                   if (!off.fits_shwi ())
8833                     return NULL_TREE;
8834                   dest_offset = off.low;
8835                   if (ranges_overlap_p (src_offset, maxsize,
8836                                         dest_offset, maxsize))
8837                     return NULL_TREE;
8838                 }
8839               else
8840                 return NULL_TREE;
8841
8842               fn = builtin_decl_implicit (BUILT_IN_MEMCPY);
8843               if (!fn)
8844                 return NULL_TREE;
8845               return build_call_expr_loc (loc, fn, 3, dest, src, len);
8846             }
8847
8848           /* If the destination and source do not alias optimize into
8849              memcpy as well.  */
8850           if ((is_gimple_min_invariant (dest)
8851                || TREE_CODE (dest) == SSA_NAME)
8852               && (is_gimple_min_invariant (src)
8853                   || TREE_CODE (src) == SSA_NAME))
8854             {
8855               ao_ref destr, srcr;
8856               ao_ref_init_from_ptr_and_size (&destr, dest, len);
8857               ao_ref_init_from_ptr_and_size (&srcr, src, len);
8858               if (!refs_may_alias_p_1 (&destr, &srcr, false))
8859                 {
8860                   tree fn;
8861                   fn = builtin_decl_implicit (BUILT_IN_MEMCPY);
8862                   if (!fn)
8863                     return NULL_TREE;
8864                   return build_call_expr_loc (loc, fn, 3, dest, src, len);
8865                 }
8866             }
8867
8868           return NULL_TREE;
8869         }
8870
8871       if (!host_integerp (len, 0))
8872         return NULL_TREE;
8873       /* FIXME:
8874          This logic lose for arguments like (type *)malloc (sizeof (type)),
8875          since we strip the casts of up to VOID return value from malloc.
8876          Perhaps we ought to inherit type from non-VOID argument here?  */
8877       STRIP_NOPS (src);
8878       STRIP_NOPS (dest);
8879       if (!POINTER_TYPE_P (TREE_TYPE (src))
8880           || !POINTER_TYPE_P (TREE_TYPE (dest)))
8881         return NULL_TREE;
8882       /* As we fold (void *)(p + CST) to (void *)p + CST undo this here.  */
8883       if (TREE_CODE (src) == POINTER_PLUS_EXPR)
8884         {
8885           tree tem = TREE_OPERAND (src, 0);
8886           STRIP_NOPS (tem);
8887           if (tem != TREE_OPERAND (src, 0))
8888             src = build1 (NOP_EXPR, TREE_TYPE (tem), src);
8889         }
8890       if (TREE_CODE (dest) == POINTER_PLUS_EXPR)
8891         {
8892           tree tem = TREE_OPERAND (dest, 0);
8893           STRIP_NOPS (tem);
8894           if (tem != TREE_OPERAND (dest, 0))
8895             dest = build1 (NOP_EXPR, TREE_TYPE (tem), dest);
8896         }
8897       srctype = TREE_TYPE (TREE_TYPE (src));
8898       if (TREE_CODE (srctype) == ARRAY_TYPE
8899           && !tree_int_cst_equal (TYPE_SIZE_UNIT (srctype), len))
8900         {
8901           srctype = TREE_TYPE (srctype);
8902           STRIP_NOPS (src);
8903           src = build1 (NOP_EXPR, build_pointer_type (srctype), src);
8904         }
8905       desttype = TREE_TYPE (TREE_TYPE (dest));
8906       if (TREE_CODE (desttype) == ARRAY_TYPE
8907           && !tree_int_cst_equal (TYPE_SIZE_UNIT (desttype), len))
8908         {
8909           desttype = TREE_TYPE (desttype);
8910           STRIP_NOPS (dest);
8911           dest = build1 (NOP_EXPR, build_pointer_type (desttype), dest);
8912         }
8913       if (TREE_ADDRESSABLE (srctype)
8914           || TREE_ADDRESSABLE (desttype))
8915         return NULL_TREE;
8916
8917       src_align = get_pointer_alignment (src);
8918       dest_align = get_pointer_alignment (dest);
8919       if (dest_align < TYPE_ALIGN (desttype)
8920           || src_align < TYPE_ALIGN (srctype))
8921         return NULL_TREE;
8922
8923       if (!ignore)
8924         dest = builtin_save_expr (dest);
8925
8926       /* Build accesses at offset zero with a ref-all character type.  */
8927       off0 = build_int_cst (build_pointer_type_for_mode (char_type_node,
8928                                                          ptr_mode, true), 0);
8929
8930       destvar = dest;
8931       STRIP_NOPS (destvar);
8932       if (TREE_CODE (destvar) == ADDR_EXPR
8933           && var_decl_component_p (TREE_OPERAND (destvar, 0))
8934           && tree_int_cst_equal (TYPE_SIZE_UNIT (desttype), len))
8935         destvar = fold_build2 (MEM_REF, desttype, destvar, off0);
8936       else
8937         destvar = NULL_TREE;
8938
8939       srcvar = src;
8940       STRIP_NOPS (srcvar);
8941       if (TREE_CODE (srcvar) == ADDR_EXPR
8942           && var_decl_component_p (TREE_OPERAND (srcvar, 0))
8943           && tree_int_cst_equal (TYPE_SIZE_UNIT (srctype), len))
8944         {
8945           if (!destvar
8946               || src_align >= TYPE_ALIGN (desttype))
8947             srcvar = fold_build2 (MEM_REF, destvar ? desttype : srctype,
8948                                   srcvar, off0);
8949           else if (!STRICT_ALIGNMENT)
8950             {
8951               srctype = build_aligned_type (TYPE_MAIN_VARIANT (desttype),
8952                                             src_align);
8953               srcvar = fold_build2 (MEM_REF, srctype, srcvar, off0);
8954             }
8955           else
8956             srcvar = NULL_TREE;
8957         }
8958       else
8959         srcvar = NULL_TREE;
8960
8961       if (srcvar == NULL_TREE && destvar == NULL_TREE)
8962         return NULL_TREE;
8963
8964       if (srcvar == NULL_TREE)
8965         {
8966           STRIP_NOPS (src);
8967           if (src_align >= TYPE_ALIGN (desttype))
8968             srcvar = fold_build2 (MEM_REF, desttype, src, off0);
8969           else
8970             {
8971               if (STRICT_ALIGNMENT)
8972                 return NULL_TREE;
8973               srctype = build_aligned_type (TYPE_MAIN_VARIANT (desttype),
8974                                             src_align);
8975               srcvar = fold_build2 (MEM_REF, srctype, src, off0);
8976             }
8977         }
8978       else if (destvar == NULL_TREE)
8979         {
8980           STRIP_NOPS (dest);
8981           if (dest_align >= TYPE_ALIGN (srctype))
8982             destvar = fold_build2 (MEM_REF, srctype, dest, off0);
8983           else
8984             {
8985               if (STRICT_ALIGNMENT)
8986                 return NULL_TREE;
8987               desttype = build_aligned_type (TYPE_MAIN_VARIANT (srctype),
8988                                              dest_align);
8989               destvar = fold_build2 (MEM_REF, desttype, dest, off0);
8990             }
8991         }
8992
8993       expr = build2 (MODIFY_EXPR, TREE_TYPE (destvar), destvar, srcvar);
8994     }
8995
8996   if (ignore)
8997     return expr;
8998
8999   if (endp == 0 || endp == 3)
9000     return omit_one_operand_loc (loc, type, dest, expr);
9001
9002   if (expr == len)
9003     expr = NULL_TREE;
9004
9005   if (endp == 2)
9006     len = fold_build2_loc (loc, MINUS_EXPR, TREE_TYPE (len), len,
9007                        ssize_int (1));
9008
9009   dest = fold_build_pointer_plus_loc (loc, dest, len);
9010   dest = fold_convert_loc (loc, type, dest);
9011   if (expr)
9012     dest = omit_one_operand_loc (loc, type, dest, expr);
9013   return dest;
9014 }
9015
9016 /* Fold function call to builtin strcpy with arguments DEST and SRC.
9017    If LEN is not NULL, it represents the length of the string to be
9018    copied.  Return NULL_TREE if no simplification can be made.  */
9019
9020 tree
9021 fold_builtin_strcpy (location_t loc, tree fndecl, tree dest, tree src, tree len)
9022 {
9023   tree fn;
9024
9025   if (!validate_arg (dest, POINTER_TYPE)
9026       || !validate_arg (src, POINTER_TYPE))
9027     return NULL_TREE;
9028
9029   /* If SRC and DEST are the same (and not volatile), return DEST.  */
9030   if (operand_equal_p (src, dest, 0))
9031     return fold_convert_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)), dest);
9032
9033   if (optimize_function_for_size_p (cfun))
9034     return NULL_TREE;
9035
9036   fn = builtin_decl_implicit (BUILT_IN_MEMCPY);
9037   if (!fn)
9038     return NULL_TREE;
9039
9040   if (!len)
9041     {
9042       len = c_strlen (src, 1);
9043       if (! len || TREE_SIDE_EFFECTS (len))
9044         return NULL_TREE;
9045     }
9046
9047   len = fold_convert_loc (loc, size_type_node, len);
9048   len = size_binop_loc (loc, PLUS_EXPR, len, build_int_cst (size_type_node, 1));
9049   return fold_convert_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)),
9050                            build_call_expr_loc (loc, fn, 3, dest, src, len));
9051 }
9052
9053 /* Fold function call to builtin stpcpy with arguments DEST and SRC.
9054    Return NULL_TREE if no simplification can be made.  */
9055
9056 static tree
9057 fold_builtin_stpcpy (location_t loc, tree fndecl, tree dest, tree src)
9058 {
9059   tree fn, len, lenp1, call, type;
9060
9061   if (!validate_arg (dest, POINTER_TYPE)
9062       || !validate_arg (src, POINTER_TYPE))
9063     return NULL_TREE;
9064
9065   len = c_strlen (src, 1);
9066   if (!len
9067       || TREE_CODE (len) != INTEGER_CST)
9068     return NULL_TREE;
9069
9070   if (optimize_function_for_size_p (cfun)
9071       /* If length is zero it's small enough.  */
9072       && !integer_zerop (len))
9073     return NULL_TREE;
9074
9075   fn = builtin_decl_implicit (BUILT_IN_MEMCPY);
9076   if (!fn)
9077     return NULL_TREE;
9078
9079   lenp1 = size_binop_loc (loc, PLUS_EXPR,
9080                           fold_convert_loc (loc, size_type_node, len),
9081                           build_int_cst (size_type_node, 1));
9082   /* We use dest twice in building our expression.  Save it from
9083      multiple expansions.  */
9084   dest = builtin_save_expr (dest);
9085   call = build_call_expr_loc (loc, fn, 3, dest, src, lenp1);
9086
9087   type = TREE_TYPE (TREE_TYPE (fndecl));
9088   dest = fold_build_pointer_plus_loc (loc, dest, len);
9089   dest = fold_convert_loc (loc, type, dest);
9090   dest = omit_one_operand_loc (loc, type, dest, call);
9091   return dest;
9092 }
9093
9094 /* Fold function call to builtin strncpy with arguments DEST, SRC, and LEN.
9095    If SLEN is not NULL, it represents the length of the source string.
9096    Return NULL_TREE if no simplification can be made.  */
9097
9098 tree
9099 fold_builtin_strncpy (location_t loc, tree fndecl, tree dest,
9100                       tree src, tree len, tree slen)
9101 {
9102   tree fn;
9103
9104   if (!validate_arg (dest, POINTER_TYPE)
9105       || !validate_arg (src, POINTER_TYPE)
9106       || !validate_arg (len, INTEGER_TYPE))
9107     return NULL_TREE;
9108
9109   /* If the LEN parameter is zero, return DEST.  */
9110   if (integer_zerop (len))
9111     return omit_one_operand_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)), dest, src);
9112
9113   /* We can't compare slen with len as constants below if len is not a
9114      constant.  */
9115   if (len == 0 || TREE_CODE (len) != INTEGER_CST)
9116     return NULL_TREE;
9117
9118   if (!slen)
9119     slen = c_strlen (src, 1);
9120
9121   /* Now, we must be passed a constant src ptr parameter.  */
9122   if (slen == 0 || TREE_CODE (slen) != INTEGER_CST)
9123     return NULL_TREE;
9124
9125   slen = size_binop_loc (loc, PLUS_EXPR, slen, ssize_int (1));
9126
9127   /* We do not support simplification of this case, though we do
9128      support it when expanding trees into RTL.  */
9129   /* FIXME: generate a call to __builtin_memset.  */
9130   if (tree_int_cst_lt (slen, len))
9131     return NULL_TREE;
9132
9133   /* OK transform into builtin memcpy.  */
9134   fn = builtin_decl_implicit (BUILT_IN_MEMCPY);
9135   if (!fn)
9136     return NULL_TREE;
9137
9138   len = fold_convert_loc (loc, size_type_node, len);
9139   return fold_convert_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)),
9140                            build_call_expr_loc (loc, fn, 3, dest, src, len));
9141 }
9142
9143 /* Fold function call to builtin memchr.  ARG1, ARG2 and LEN are the
9144    arguments to the call, and TYPE is its return type.
9145    Return NULL_TREE if no simplification can be made.  */
9146
9147 static tree
9148 fold_builtin_memchr (location_t loc, tree arg1, tree arg2, tree len, tree type)
9149 {
9150   if (!validate_arg (arg1, POINTER_TYPE)
9151       || !validate_arg (arg2, INTEGER_TYPE)
9152       || !validate_arg (len, INTEGER_TYPE))
9153     return NULL_TREE;
9154   else
9155     {
9156       const char *p1;
9157
9158       if (TREE_CODE (arg2) != INTEGER_CST
9159           || !host_integerp (len, 1))
9160         return NULL_TREE;
9161
9162       p1 = c_getstr (arg1);
9163       if (p1 && compare_tree_int (len, strlen (p1) + 1) <= 0)
9164         {
9165           char c;
9166           const char *r;
9167           tree tem;
9168
9169           if (target_char_cast (arg2, &c))
9170             return NULL_TREE;
9171
9172           r = (const char *) memchr (p1, c, tree_low_cst (len, 1));
9173
9174           if (r == NULL)
9175             return build_int_cst (TREE_TYPE (arg1), 0);
9176
9177           tem = fold_build_pointer_plus_hwi_loc (loc, arg1, r - p1);
9178           return fold_convert_loc (loc, type, tem);
9179         }
9180       return NULL_TREE;
9181     }
9182 }
9183
9184 /* Fold function call to builtin memcmp with arguments ARG1 and ARG2.
9185    Return NULL_TREE if no simplification can be made.  */
9186
9187 static tree
9188 fold_builtin_memcmp (location_t loc, tree arg1, tree arg2, tree len)
9189 {
9190   const char *p1, *p2;
9191
9192   if (!validate_arg (arg1, POINTER_TYPE)
9193       || !validate_arg (arg2, POINTER_TYPE)
9194       || !validate_arg (len, INTEGER_TYPE))
9195     return NULL_TREE;
9196
9197   /* If the LEN parameter is zero, return zero.  */
9198   if (integer_zerop (len))
9199     return omit_two_operands_loc (loc, integer_type_node, integer_zero_node,
9200                               arg1, arg2);
9201
9202   /* If ARG1 and ARG2 are the same (and not volatile), return zero.  */
9203   if (operand_equal_p (arg1, arg2, 0))
9204     return omit_one_operand_loc (loc, integer_type_node, integer_zero_node, len);
9205
9206   p1 = c_getstr (arg1);
9207   p2 = c_getstr (arg2);
9208
9209   /* If all arguments are constant, and the value of len is not greater
9210      than the lengths of arg1 and arg2, evaluate at compile-time.  */
9211   if (host_integerp (len, 1) && p1 && p2
9212       && compare_tree_int (len, strlen (p1) + 1) <= 0
9213       && compare_tree_int (len, strlen (p2) + 1) <= 0)
9214     {
9215       const int r = memcmp (p1, p2, tree_low_cst (len, 1));
9216
9217       if (r > 0)
9218         return integer_one_node;
9219       else if (r < 0)
9220         return integer_minus_one_node;
9221       else
9222         return integer_zero_node;
9223     }
9224
9225   /* If len parameter is one, return an expression corresponding to
9226      (*(const unsigned char*)arg1 - (const unsigned char*)arg2).  */
9227   if (host_integerp (len, 1) && tree_low_cst (len, 1) == 1)
9228     {
9229       tree cst_uchar_node = build_type_variant (unsigned_char_type_node, 1, 0);
9230       tree cst_uchar_ptr_node
9231         = build_pointer_type_for_mode (cst_uchar_node, ptr_mode, true);
9232
9233       tree ind1
9234         = fold_convert_loc (loc, integer_type_node,
9235                             build1 (INDIRECT_REF, cst_uchar_node,
9236                                     fold_convert_loc (loc,
9237                                                       cst_uchar_ptr_node,
9238                                                       arg1)));
9239       tree ind2
9240         = fold_convert_loc (loc, integer_type_node,
9241                             build1 (INDIRECT_REF, cst_uchar_node,
9242                                     fold_convert_loc (loc,
9243                                                       cst_uchar_ptr_node,
9244                                                       arg2)));
9245       return fold_build2_loc (loc, MINUS_EXPR, integer_type_node, ind1, ind2);
9246     }
9247
9248   return NULL_TREE;
9249 }
9250
9251 /* Fold function call to builtin strcmp with arguments ARG1 and ARG2.
9252    Return NULL_TREE if no simplification can be made.  */
9253
9254 static tree
9255 fold_builtin_strcmp (location_t loc, tree arg1, tree arg2)
9256 {
9257   const char *p1, *p2;
9258
9259   if (!validate_arg (arg1, POINTER_TYPE)
9260       || !validate_arg (arg2, POINTER_TYPE))
9261     return NULL_TREE;
9262
9263   /* If ARG1 and ARG2 are the same (and not volatile), return zero.  */
9264   if (operand_equal_p (arg1, arg2, 0))
9265     return integer_zero_node;
9266
9267   p1 = c_getstr (arg1);
9268   p2 = c_getstr (arg2);
9269
9270   if (p1 && p2)
9271     {
9272       const int i = strcmp (p1, p2);
9273       if (i < 0)
9274         return integer_minus_one_node;
9275       else if (i > 0)
9276         return integer_one_node;
9277       else
9278         return integer_zero_node;
9279     }
9280
9281   /* If the second arg is "", return *(const unsigned char*)arg1.  */
9282   if (p2 && *p2 == '\0')
9283     {
9284       tree cst_uchar_node = build_type_variant (unsigned_char_type_node, 1, 0);
9285       tree cst_uchar_ptr_node
9286         = build_pointer_type_for_mode (cst_uchar_node, ptr_mode, true);
9287
9288       return fold_convert_loc (loc, integer_type_node,
9289                                build1 (INDIRECT_REF, cst_uchar_node,
9290                                        fold_convert_loc (loc,
9291                                                          cst_uchar_ptr_node,
9292                                                          arg1)));
9293     }
9294
9295   /* If the first arg is "", return -*(const unsigned char*)arg2.  */
9296   if (p1 && *p1 == '\0')
9297     {
9298       tree cst_uchar_node = build_type_variant (unsigned_char_type_node, 1, 0);
9299       tree cst_uchar_ptr_node
9300         = build_pointer_type_for_mode (cst_uchar_node, ptr_mode, true);
9301
9302       tree temp
9303         = fold_convert_loc (loc, integer_type_node,
9304                             build1 (INDIRECT_REF, cst_uchar_node,
9305                                     fold_convert_loc (loc,
9306                                                       cst_uchar_ptr_node,
9307                                                       arg2)));
9308       return fold_build1_loc (loc, NEGATE_EXPR, integer_type_node, temp);
9309     }
9310
9311   return NULL_TREE;
9312 }
9313
9314 /* Fold function call to builtin strncmp with arguments ARG1, ARG2, and LEN.
9315    Return NULL_TREE if no simplification can be made.  */
9316
9317 static tree
9318 fold_builtin_strncmp (location_t loc, tree arg1, tree arg2, tree len)
9319 {
9320   const char *p1, *p2;
9321
9322   if (!validate_arg (arg1, POINTER_TYPE)
9323       || !validate_arg (arg2, POINTER_TYPE)
9324       || !validate_arg (len, INTEGER_TYPE))
9325     return NULL_TREE;
9326
9327   /* If the LEN parameter is zero, return zero.  */
9328   if (integer_zerop (len))
9329     return omit_two_operands_loc (loc, integer_type_node, integer_zero_node,
9330                               arg1, arg2);
9331
9332   /* If ARG1 and ARG2 are the same (and not volatile), return zero.  */
9333   if (operand_equal_p (arg1, arg2, 0))
9334     return omit_one_operand_loc (loc, integer_type_node, integer_zero_node, len);
9335
9336   p1 = c_getstr (arg1);
9337   p2 = c_getstr (arg2);
9338
9339   if (host_integerp (len, 1) && p1 && p2)
9340     {
9341       const int i = strncmp (p1, p2, tree_low_cst (len, 1));
9342       if (i > 0)
9343         return integer_one_node;
9344       else if (i < 0)
9345         return integer_minus_one_node;
9346       else
9347         return integer_zero_node;
9348     }
9349
9350   /* If the second arg is "", and the length is greater than zero,
9351      return *(const unsigned char*)arg1.  */
9352   if (p2 && *p2 == '\0'
9353       && TREE_CODE (len) == INTEGER_CST
9354       && tree_int_cst_sgn (len) == 1)
9355     {
9356       tree cst_uchar_node = build_type_variant (unsigned_char_type_node, 1, 0);
9357       tree cst_uchar_ptr_node
9358         = build_pointer_type_for_mode (cst_uchar_node, ptr_mode, true);
9359
9360       return fold_convert_loc (loc, integer_type_node,
9361                                build1 (INDIRECT_REF, cst_uchar_node,
9362                                        fold_convert_loc (loc,
9363                                                          cst_uchar_ptr_node,
9364                                                          arg1)));
9365     }
9366
9367   /* If the first arg is "", and the length is greater than zero,
9368      return -*(const unsigned char*)arg2.  */
9369   if (p1 && *p1 == '\0'
9370       && TREE_CODE (len) == INTEGER_CST
9371       && tree_int_cst_sgn (len) == 1)
9372     {
9373       tree cst_uchar_node = build_type_variant (unsigned_char_type_node, 1, 0);
9374       tree cst_uchar_ptr_node
9375         = build_pointer_type_for_mode (cst_uchar_node, ptr_mode, true);
9376
9377       tree temp = fold_convert_loc (loc, integer_type_node,
9378                                     build1 (INDIRECT_REF, cst_uchar_node,
9379                                             fold_convert_loc (loc,
9380                                                               cst_uchar_ptr_node,
9381                                                               arg2)));
9382       return fold_build1_loc (loc, NEGATE_EXPR, integer_type_node, temp);
9383     }
9384
9385   /* If len parameter is one, return an expression corresponding to
9386      (*(const unsigned char*)arg1 - (const unsigned char*)arg2).  */
9387   if (host_integerp (len, 1) && tree_low_cst (len, 1) == 1)
9388     {
9389       tree cst_uchar_node = build_type_variant (unsigned_char_type_node, 1, 0);
9390       tree cst_uchar_ptr_node
9391         = build_pointer_type_for_mode (cst_uchar_node, ptr_mode, true);
9392
9393       tree ind1 = fold_convert_loc (loc, integer_type_node,
9394                                     build1 (INDIRECT_REF, cst_uchar_node,
9395                                             fold_convert_loc (loc,
9396                                                               cst_uchar_ptr_node,
9397                                                               arg1)));
9398       tree ind2 = fold_convert_loc (loc, integer_type_node,
9399                                     build1 (INDIRECT_REF, cst_uchar_node,
9400                                             fold_convert_loc (loc,
9401                                                               cst_uchar_ptr_node,
9402                                                               arg2)));
9403       return fold_build2_loc (loc, MINUS_EXPR, integer_type_node, ind1, ind2);
9404     }
9405
9406   return NULL_TREE;
9407 }
9408
9409 /* Fold function call to builtin signbit, signbitf or signbitl with argument
9410    ARG.  Return NULL_TREE if no simplification can be made.  */
9411
9412 static tree
9413 fold_builtin_signbit (location_t loc, tree arg, tree type)
9414 {
9415   if (!validate_arg (arg, REAL_TYPE))
9416     return NULL_TREE;
9417
9418   /* If ARG is a compile-time constant, determine the result.  */
9419   if (TREE_CODE (arg) == REAL_CST
9420       && !TREE_OVERFLOW (arg))
9421     {
9422       REAL_VALUE_TYPE c;
9423
9424       c = TREE_REAL_CST (arg);
9425       return (REAL_VALUE_NEGATIVE (c)
9426               ? build_one_cst (type)
9427               : build_zero_cst (type));
9428     }
9429
9430   /* If ARG is non-negative, the result is always zero.  */
9431   if (tree_expr_nonnegative_p (arg))
9432     return omit_one_operand_loc (loc, type, integer_zero_node, arg);
9433
9434   /* If ARG's format doesn't have signed zeros, return "arg < 0.0".  */
9435   if (!HONOR_SIGNED_ZEROS (TYPE_MODE (TREE_TYPE (arg))))
9436     return fold_convert (type,
9437                          fold_build2_loc (loc, LT_EXPR, boolean_type_node, arg,
9438                         build_real (TREE_TYPE (arg), dconst0)));
9439
9440   return NULL_TREE;
9441 }
9442
9443 /* Fold function call to builtin copysign, copysignf or copysignl with
9444    arguments ARG1 and ARG2.  Return NULL_TREE if no simplification can
9445    be made.  */
9446
9447 static tree
9448 fold_builtin_copysign (location_t loc, tree fndecl,
9449                        tree arg1, tree arg2, tree type)
9450 {
9451   tree tem;
9452
9453   if (!validate_arg (arg1, REAL_TYPE)
9454       || !validate_arg (arg2, REAL_TYPE))
9455     return NULL_TREE;
9456
9457   /* copysign(X,X) is X.  */
9458   if (operand_equal_p (arg1, arg2, 0))
9459     return fold_convert_loc (loc, type, arg1);
9460
9461   /* If ARG1 and ARG2 are compile-time constants, determine the result.  */
9462   if (TREE_CODE (arg1) == REAL_CST
9463       && TREE_CODE (arg2) == REAL_CST
9464       && !TREE_OVERFLOW (arg1)
9465       && !TREE_OVERFLOW (arg2))
9466     {
9467       REAL_VALUE_TYPE c1, c2;
9468
9469       c1 = TREE_REAL_CST (arg1);
9470       c2 = TREE_REAL_CST (arg2);
9471       /* c1.sign := c2.sign.  */
9472       real_copysign (&c1, &c2);
9473       return build_real (type, c1);
9474     }
9475
9476   /* copysign(X, Y) is fabs(X) when Y is always non-negative.
9477      Remember to evaluate Y for side-effects.  */
9478   if (tree_expr_nonnegative_p (arg2))
9479     return omit_one_operand_loc (loc, type,
9480                              fold_build1_loc (loc, ABS_EXPR, type, arg1),
9481                              arg2);
9482
9483   /* Strip sign changing operations for the first argument.  */
9484   tem = fold_strip_sign_ops (arg1);
9485   if (tem)
9486     return build_call_expr_loc (loc, fndecl, 2, tem, arg2);
9487
9488   return NULL_TREE;
9489 }
9490
9491 /* Fold a call to builtin isascii with argument ARG.  */
9492
9493 static tree
9494 fold_builtin_isascii (location_t loc, tree arg)
9495 {
9496   if (!validate_arg (arg, INTEGER_TYPE))
9497     return NULL_TREE;
9498   else
9499     {
9500       /* Transform isascii(c) -> ((c & ~0x7f) == 0).  */
9501       arg = fold_build2 (BIT_AND_EXPR, integer_type_node, arg,
9502                          build_int_cst (integer_type_node,
9503                                         ~ (unsigned HOST_WIDE_INT) 0x7f));
9504       return fold_build2_loc (loc, EQ_EXPR, integer_type_node,
9505                               arg, integer_zero_node);
9506     }
9507 }
9508
9509 /* Fold a call to builtin toascii with argument ARG.  */
9510
9511 static tree
9512 fold_builtin_toascii (location_t loc, tree arg)
9513 {
9514   if (!validate_arg (arg, INTEGER_TYPE))
9515     return NULL_TREE;
9516
9517   /* Transform toascii(c) -> (c & 0x7f).  */
9518   return fold_build2_loc (loc, BIT_AND_EXPR, integer_type_node, arg,
9519                           build_int_cst (integer_type_node, 0x7f));
9520 }
9521
9522 /* Fold a call to builtin isdigit with argument ARG.  */
9523
9524 static tree
9525 fold_builtin_isdigit (location_t loc, tree arg)
9526 {
9527   if (!validate_arg (arg, INTEGER_TYPE))
9528     return NULL_TREE;
9529   else
9530     {
9531       /* Transform isdigit(c) -> (unsigned)(c) - '0' <= 9.  */
9532       /* According to the C standard, isdigit is unaffected by locale.
9533          However, it definitely is affected by the target character set.  */
9534       unsigned HOST_WIDE_INT target_digit0
9535         = lang_hooks.to_target_charset ('0');
9536
9537       if (target_digit0 == 0)
9538         return NULL_TREE;
9539
9540       arg = fold_convert_loc (loc, unsigned_type_node, arg);
9541       arg = fold_build2 (MINUS_EXPR, unsigned_type_node, arg,
9542                          build_int_cst (unsigned_type_node, target_digit0));
9543       return fold_build2_loc (loc, LE_EXPR, integer_type_node, arg,
9544                           build_int_cst (unsigned_type_node, 9));
9545     }
9546 }
9547
9548 /* Fold a call to fabs, fabsf or fabsl with argument ARG.  */
9549
9550 static tree
9551 fold_builtin_fabs (location_t loc, tree arg, tree type)
9552 {
9553   if (!validate_arg (arg, REAL_TYPE))
9554     return NULL_TREE;
9555
9556   arg = fold_convert_loc (loc, type, arg);
9557   if (TREE_CODE (arg) == REAL_CST)
9558     return fold_abs_const (arg, type);
9559   return fold_build1_loc (loc, ABS_EXPR, type, arg);
9560 }
9561
9562 /* Fold a call to abs, labs, llabs or imaxabs with argument ARG.  */
9563
9564 static tree
9565 fold_builtin_abs (location_t loc, tree arg, tree type)
9566 {
9567   if (!validate_arg (arg, INTEGER_TYPE))
9568     return NULL_TREE;
9569
9570   arg = fold_convert_loc (loc, type, arg);
9571   if (TREE_CODE (arg) == INTEGER_CST)
9572     return fold_abs_const (arg, type);
9573   return fold_build1_loc (loc, ABS_EXPR, type, arg);
9574 }
9575
9576 /* Fold a fma operation with arguments ARG[012].  */
9577
9578 tree
9579 fold_fma (location_t loc ATTRIBUTE_UNUSED,
9580           tree type, tree arg0, tree arg1, tree arg2)
9581 {
9582   if (TREE_CODE (arg0) == REAL_CST
9583       && TREE_CODE (arg1) == REAL_CST
9584       && TREE_CODE (arg2) == REAL_CST)
9585     return do_mpfr_arg3 (arg0, arg1, arg2, type, mpfr_fma);
9586
9587   return NULL_TREE;
9588 }
9589
9590 /* Fold a call to fma, fmaf, or fmal with arguments ARG[012].  */
9591
9592 static tree
9593 fold_builtin_fma (location_t loc, tree arg0, tree arg1, tree arg2, tree type)
9594 {
9595   if (validate_arg (arg0, REAL_TYPE)
9596       && validate_arg(arg1, REAL_TYPE)
9597       && validate_arg(arg2, REAL_TYPE))
9598     {
9599       tree tem = fold_fma (loc, type, arg0, arg1, arg2);
9600       if (tem)
9601         return tem;
9602
9603       /* ??? Only expand to FMA_EXPR if it's directly supported.  */
9604       if (optab_handler (fma_optab, TYPE_MODE (type)) != CODE_FOR_nothing)
9605         return fold_build3_loc (loc, FMA_EXPR, type, arg0, arg1, arg2);
9606     }
9607   return NULL_TREE;
9608 }
9609
9610 /* Fold a call to builtin fmin or fmax.  */
9611
9612 static tree
9613 fold_builtin_fmin_fmax (location_t loc, tree arg0, tree arg1,
9614                         tree type, bool max)
9615 {
9616   if (validate_arg (arg0, REAL_TYPE) && validate_arg (arg1, REAL_TYPE))
9617     {
9618       /* Calculate the result when the argument is a constant.  */
9619       tree res = do_mpfr_arg2 (arg0, arg1, type, (max ? mpfr_max : mpfr_min));
9620
9621       if (res)
9622         return res;
9623
9624       /* If either argument is NaN, return the other one.  Avoid the
9625          transformation if we get (and honor) a signalling NaN.  Using
9626          omit_one_operand() ensures we create a non-lvalue.  */
9627       if (TREE_CODE (arg0) == REAL_CST
9628           && real_isnan (&TREE_REAL_CST (arg0))
9629           && (! HONOR_SNANS (TYPE_MODE (TREE_TYPE (arg0)))
9630               || ! TREE_REAL_CST (arg0).signalling))
9631         return omit_one_operand_loc (loc, type, arg1, arg0);
9632       if (TREE_CODE (arg1) == REAL_CST
9633           && real_isnan (&TREE_REAL_CST (arg1))
9634           && (! HONOR_SNANS (TYPE_MODE (TREE_TYPE (arg1)))
9635               || ! TREE_REAL_CST (arg1).signalling))
9636         return omit_one_operand_loc (loc, type, arg0, arg1);
9637
9638       /* Transform fmin/fmax(x,x) -> x.  */
9639       if (operand_equal_p (arg0, arg1, OEP_PURE_SAME))
9640         return omit_one_operand_loc (loc, type, arg0, arg1);
9641
9642       /* Convert fmin/fmax to MIN_EXPR/MAX_EXPR.  C99 requires these
9643          functions to return the numeric arg if the other one is NaN.
9644          These tree codes don't honor that, so only transform if
9645          -ffinite-math-only is set.  C99 doesn't require -0.0 to be
9646          handled, so we don't have to worry about it either.  */
9647       if (flag_finite_math_only)
9648         return fold_build2_loc (loc, (max ? MAX_EXPR : MIN_EXPR), type,
9649                             fold_convert_loc (loc, type, arg0),
9650                             fold_convert_loc (loc, type, arg1));
9651     }
9652   return NULL_TREE;
9653 }
9654
9655 /* Fold a call to builtin carg(a+bi) -> atan2(b,a).  */
9656
9657 static tree
9658 fold_builtin_carg (location_t loc, tree arg, tree type)
9659 {
9660   if (validate_arg (arg, COMPLEX_TYPE)
9661       && TREE_CODE (TREE_TYPE (TREE_TYPE (arg))) == REAL_TYPE)
9662     {
9663       tree atan2_fn = mathfn_built_in (type, BUILT_IN_ATAN2);
9664
9665       if (atan2_fn)
9666         {
9667           tree new_arg = builtin_save_expr (arg);
9668           tree r_arg = fold_build1_loc (loc, REALPART_EXPR, type, new_arg);
9669           tree i_arg = fold_build1_loc (loc, IMAGPART_EXPR, type, new_arg);
9670           return build_call_expr_loc (loc, atan2_fn, 2, i_arg, r_arg);
9671         }
9672     }
9673
9674   return NULL_TREE;
9675 }
9676
9677 /* Fold a call to builtin logb/ilogb.  */
9678
9679 static tree
9680 fold_builtin_logb (location_t loc, tree arg, tree rettype)
9681 {
9682   if (! validate_arg (arg, REAL_TYPE))
9683     return NULL_TREE;
9684
9685   STRIP_NOPS (arg);
9686
9687   if (TREE_CODE (arg) == REAL_CST && ! TREE_OVERFLOW (arg))
9688     {
9689       const REAL_VALUE_TYPE *const value = TREE_REAL_CST_PTR (arg);
9690
9691       switch (value->cl)
9692       {
9693       case rvc_nan:
9694       case rvc_inf:
9695         /* If arg is Inf or NaN and we're logb, return it.  */
9696         if (TREE_CODE (rettype) == REAL_TYPE)
9697           {
9698             /* For logb(-Inf) we have to return +Inf.  */
9699             if (real_isinf (value) && real_isneg (value))
9700               {
9701                 REAL_VALUE_TYPE tem;
9702                 real_inf (&tem);
9703                 return build_real (rettype, tem);
9704               }
9705             return fold_convert_loc (loc, rettype, arg);
9706           }
9707         /* Fall through... */
9708       case rvc_zero:
9709         /* Zero may set errno and/or raise an exception for logb, also
9710            for ilogb we don't know FP_ILOGB0.  */
9711         return NULL_TREE;
9712       case rvc_normal:
9713         /* For normal numbers, proceed iff radix == 2.  In GCC,
9714            normalized significands are in the range [0.5, 1.0).  We
9715            want the exponent as if they were [1.0, 2.0) so get the
9716            exponent and subtract 1.  */
9717         if (REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (arg)))->b == 2)
9718           return fold_convert_loc (loc, rettype,
9719                                    build_int_cst (integer_type_node,
9720                                                   REAL_EXP (value)-1));
9721         break;
9722       }
9723     }
9724
9725   return NULL_TREE;
9726 }
9727
9728 /* Fold a call to builtin significand, if radix == 2.  */
9729
9730 static tree
9731 fold_builtin_significand (location_t loc, tree arg, tree rettype)
9732 {
9733   if (! validate_arg (arg, REAL_TYPE))
9734     return NULL_TREE;
9735
9736   STRIP_NOPS (arg);
9737
9738   if (TREE_CODE (arg) == REAL_CST && ! TREE_OVERFLOW (arg))
9739     {
9740       const REAL_VALUE_TYPE *const value = TREE_REAL_CST_PTR (arg);
9741
9742       switch (value->cl)
9743       {
9744       case rvc_zero:
9745       case rvc_nan:
9746       case rvc_inf:
9747         /* If arg is +-0, +-Inf or +-NaN, then return it.  */
9748         return fold_convert_loc (loc, rettype, arg);
9749       case rvc_normal:
9750         /* For normal numbers, proceed iff radix == 2.  */
9751         if (REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (arg)))->b == 2)
9752           {
9753             REAL_VALUE_TYPE result = *value;
9754             /* In GCC, normalized significands are in the range [0.5,
9755                1.0).  We want them to be [1.0, 2.0) so set the
9756                exponent to 1.  */
9757             SET_REAL_EXP (&result, 1);
9758             return build_real (rettype, result);
9759           }
9760         break;
9761       }
9762     }
9763
9764   return NULL_TREE;
9765 }
9766
9767 /* Fold a call to builtin frexp, we can assume the base is 2.  */
9768
9769 static tree
9770 fold_builtin_frexp (location_t loc, tree arg0, tree arg1, tree rettype)
9771 {
9772   if (! validate_arg (arg0, REAL_TYPE) || ! validate_arg (arg1, POINTER_TYPE))
9773     return NULL_TREE;
9774
9775   STRIP_NOPS (arg0);
9776
9777   if (!(TREE_CODE (arg0) == REAL_CST && ! TREE_OVERFLOW (arg0)))
9778     return NULL_TREE;
9779
9780   arg1 = build_fold_indirect_ref_loc (loc, arg1);
9781
9782   /* Proceed if a valid pointer type was passed in.  */
9783   if (TYPE_MAIN_VARIANT (TREE_TYPE (arg1)) == integer_type_node)
9784     {
9785       const REAL_VALUE_TYPE *const value = TREE_REAL_CST_PTR (arg0);
9786       tree frac, exp;
9787
9788       switch (value->cl)
9789       {
9790       case rvc_zero:
9791         /* For +-0, return (*exp = 0, +-0).  */
9792         exp = integer_zero_node;
9793         frac = arg0;
9794         break;
9795       case rvc_nan:
9796       case rvc_inf:
9797         /* For +-NaN or +-Inf, *exp is unspecified, return arg0.  */
9798         return omit_one_operand_loc (loc, rettype, arg0, arg1);
9799       case rvc_normal:
9800         {
9801           /* Since the frexp function always expects base 2, and in
9802              GCC normalized significands are already in the range
9803              [0.5, 1.0), we have exactly what frexp wants.  */
9804           REAL_VALUE_TYPE frac_rvt = *value;
9805           SET_REAL_EXP (&frac_rvt, 0);
9806           frac = build_real (rettype, frac_rvt);
9807           exp = build_int_cst (integer_type_node, REAL_EXP (value));
9808         }
9809         break;
9810       default:
9811         gcc_unreachable ();
9812       }
9813
9814       /* Create the COMPOUND_EXPR (*arg1 = trunc, frac). */
9815       arg1 = fold_build2_loc (loc, MODIFY_EXPR, rettype, arg1, exp);
9816       TREE_SIDE_EFFECTS (arg1) = 1;
9817       return fold_build2_loc (loc, COMPOUND_EXPR, rettype, arg1, frac);
9818     }
9819
9820   return NULL_TREE;
9821 }
9822
9823 /* Fold a call to builtin ldexp or scalbn/scalbln.  If LDEXP is true
9824    then we can assume the base is two.  If it's false, then we have to
9825    check the mode of the TYPE parameter in certain cases.  */
9826
9827 static tree
9828 fold_builtin_load_exponent (location_t loc, tree arg0, tree arg1,
9829                             tree type, bool ldexp)
9830 {
9831   if (validate_arg (arg0, REAL_TYPE) && validate_arg (arg1, INTEGER_TYPE))
9832     {
9833       STRIP_NOPS (arg0);
9834       STRIP_NOPS (arg1);
9835
9836       /* If arg0 is 0, Inf or NaN, or if arg1 is 0, then return arg0.  */
9837       if (real_zerop (arg0) || integer_zerop (arg1)
9838           || (TREE_CODE (arg0) == REAL_CST
9839               && !real_isfinite (&TREE_REAL_CST (arg0))))
9840         return omit_one_operand_loc (loc, type, arg0, arg1);
9841
9842       /* If both arguments are constant, then try to evaluate it.  */
9843       if ((ldexp || REAL_MODE_FORMAT (TYPE_MODE (type))->b == 2)
9844           && TREE_CODE (arg0) == REAL_CST && !TREE_OVERFLOW (arg0)
9845           && host_integerp (arg1, 0))
9846         {
9847           /* Bound the maximum adjustment to twice the range of the
9848              mode's valid exponents.  Use abs to ensure the range is
9849              positive as a sanity check.  */
9850           const long max_exp_adj = 2 *
9851             labs (REAL_MODE_FORMAT (TYPE_MODE (type))->emax
9852                  - REAL_MODE_FORMAT (TYPE_MODE (type))->emin);
9853
9854           /* Get the user-requested adjustment.  */
9855           const HOST_WIDE_INT req_exp_adj = tree_low_cst (arg1, 0);
9856
9857           /* The requested adjustment must be inside this range.  This
9858              is a preliminary cap to avoid things like overflow, we
9859              may still fail to compute the result for other reasons.  */
9860           if (-max_exp_adj < req_exp_adj && req_exp_adj < max_exp_adj)
9861             {
9862               REAL_VALUE_TYPE initial_result;
9863
9864               real_ldexp (&initial_result, &TREE_REAL_CST (arg0), req_exp_adj);
9865
9866               /* Ensure we didn't overflow.  */
9867               if (! real_isinf (&initial_result))
9868                 {
9869                   const REAL_VALUE_TYPE trunc_result
9870                     = real_value_truncate (TYPE_MODE (type), initial_result);
9871
9872                   /* Only proceed if the target mode can hold the
9873                      resulting value.  */
9874                   if (REAL_VALUES_EQUAL (initial_result, trunc_result))
9875                     return build_real (type, trunc_result);
9876                 }
9877             }
9878         }
9879     }
9880
9881   return NULL_TREE;
9882 }
9883
9884 /* Fold a call to builtin modf.  */
9885
9886 static tree
9887 fold_builtin_modf (location_t loc, tree arg0, tree arg1, tree rettype)
9888 {
9889   if (! validate_arg (arg0, REAL_TYPE) || ! validate_arg (arg1, POINTER_TYPE))
9890     return NULL_TREE;
9891
9892   STRIP_NOPS (arg0);
9893
9894   if (!(TREE_CODE (arg0) == REAL_CST && ! TREE_OVERFLOW (arg0)))
9895     return NULL_TREE;
9896
9897   arg1 = build_fold_indirect_ref_loc (loc, arg1);
9898
9899   /* Proceed if a valid pointer type was passed in.  */
9900   if (TYPE_MAIN_VARIANT (TREE_TYPE (arg1)) == TYPE_MAIN_VARIANT (rettype))
9901     {
9902       const REAL_VALUE_TYPE *const value = TREE_REAL_CST_PTR (arg0);
9903       REAL_VALUE_TYPE trunc, frac;
9904
9905       switch (value->cl)
9906       {
9907       case rvc_nan:
9908       case rvc_zero:
9909         /* For +-NaN or +-0, return (*arg1 = arg0, arg0).  */
9910         trunc = frac = *value;
9911         break;
9912       case rvc_inf:
9913         /* For +-Inf, return (*arg1 = arg0, +-0).  */
9914         frac = dconst0;
9915         frac.sign = value->sign;
9916         trunc = *value;
9917         break;
9918       case rvc_normal:
9919         /* Return (*arg1 = trunc(arg0), arg0-trunc(arg0)).  */
9920         real_trunc (&trunc, VOIDmode, value);
9921         real_arithmetic (&frac, MINUS_EXPR, value, &trunc);
9922         /* If the original number was negative and already
9923            integral, then the fractional part is -0.0.  */
9924         if (value->sign && frac.cl == rvc_zero)
9925           frac.sign = value->sign;
9926         break;
9927       }
9928
9929       /* Create the COMPOUND_EXPR (*arg1 = trunc, frac). */
9930       arg1 = fold_build2_loc (loc, MODIFY_EXPR, rettype, arg1,
9931                           build_real (rettype, trunc));
9932       TREE_SIDE_EFFECTS (arg1) = 1;
9933       return fold_build2_loc (loc, COMPOUND_EXPR, rettype, arg1,
9934                           build_real (rettype, frac));
9935     }
9936
9937   return NULL_TREE;
9938 }
9939
9940 /* Given a location LOC, an interclass builtin function decl FNDECL
9941    and its single argument ARG, return an folded expression computing
9942    the same, or NULL_TREE if we either couldn't or didn't want to fold
9943    (the latter happen if there's an RTL instruction available).  */
9944
9945 static tree
9946 fold_builtin_interclass_mathfn (location_t loc, tree fndecl, tree arg)
9947 {
9948   enum machine_mode mode;
9949
9950   if (!validate_arg (arg, REAL_TYPE))
9951     return NULL_TREE;
9952
9953   if (interclass_mathfn_icode (arg, fndecl) != CODE_FOR_nothing)
9954     return NULL_TREE;
9955
9956   mode = TYPE_MODE (TREE_TYPE (arg));
9957
9958   /* If there is no optab, try generic code.  */
9959   switch (DECL_FUNCTION_CODE (fndecl))
9960     {
9961       tree result;
9962
9963     CASE_FLT_FN (BUILT_IN_ISINF):
9964       {
9965         /* isinf(x) -> isgreater(fabs(x),DBL_MAX).  */
9966         tree const isgr_fn = builtin_decl_explicit (BUILT_IN_ISGREATER);
9967         tree const type = TREE_TYPE (arg);
9968         REAL_VALUE_TYPE r;
9969         char buf[128];
9970
9971         get_max_float (REAL_MODE_FORMAT (mode), buf, sizeof (buf));
9972         real_from_string (&r, buf);
9973         result = build_call_expr (isgr_fn, 2,
9974                                   fold_build1_loc (loc, ABS_EXPR, type, arg),
9975                                   build_real (type, r));
9976         return result;
9977       }
9978     CASE_FLT_FN (BUILT_IN_FINITE):
9979     case BUILT_IN_ISFINITE:
9980       {
9981         /* isfinite(x) -> islessequal(fabs(x),DBL_MAX).  */
9982         tree const isle_fn = builtin_decl_explicit (BUILT_IN_ISLESSEQUAL);
9983         tree const type = TREE_TYPE (arg);
9984         REAL_VALUE_TYPE r;
9985         char buf[128];
9986
9987         get_max_float (REAL_MODE_FORMAT (mode), buf, sizeof (buf));
9988         real_from_string (&r, buf);
9989         result = build_call_expr (isle_fn, 2,
9990                                   fold_build1_loc (loc, ABS_EXPR, type, arg),
9991                                   build_real (type, r));
9992         /*result = fold_build2_loc (loc, UNGT_EXPR,
9993                                   TREE_TYPE (TREE_TYPE (fndecl)),
9994                                   fold_build1_loc (loc, ABS_EXPR, type, arg),
9995                                   build_real (type, r));
9996         result = fold_build1_loc (loc, TRUTH_NOT_EXPR,
9997                                   TREE_TYPE (TREE_TYPE (fndecl)),
9998                                   result);*/
9999         return result;
10000       }
10001     case BUILT_IN_ISNORMAL:
10002       {
10003         /* isnormal(x) -> isgreaterequal(fabs(x),DBL_MIN) &
10004            islessequal(fabs(x),DBL_MAX).  */
10005         tree const isle_fn = builtin_decl_explicit (BUILT_IN_ISLESSEQUAL);
10006         tree const isge_fn = builtin_decl_explicit (BUILT_IN_ISGREATEREQUAL);
10007         tree const type = TREE_TYPE (arg);
10008         REAL_VALUE_TYPE rmax, rmin;
10009         char buf[128];
10010
10011         get_max_float (REAL_MODE_FORMAT (mode), buf, sizeof (buf));
10012         real_from_string (&rmax, buf);
10013         sprintf (buf, "0x1p%d", REAL_MODE_FORMAT (mode)->emin - 1);
10014         real_from_string (&rmin, buf);
10015         arg = builtin_save_expr (fold_build1_loc (loc, ABS_EXPR, type, arg));
10016         result = build_call_expr (isle_fn, 2, arg,
10017                                   build_real (type, rmax));
10018         result = fold_build2 (BIT_AND_EXPR, integer_type_node, result,
10019                               build_call_expr (isge_fn, 2, arg,
10020                                                build_real (type, rmin)));
10021         return result;
10022       }
10023     default:
10024       break;
10025     }
10026
10027   return NULL_TREE;
10028 }
10029
10030 /* Fold a call to __builtin_isnan(), __builtin_isinf, __builtin_finite.
10031    ARG is the argument for the call.  */
10032
10033 static tree
10034 fold_builtin_classify (location_t loc, tree fndecl, tree arg, int builtin_index)
10035 {
10036   tree type = TREE_TYPE (TREE_TYPE (fndecl));
10037   REAL_VALUE_TYPE r;
10038
10039   if (!validate_arg (arg, REAL_TYPE))
10040     return NULL_TREE;
10041
10042   switch (builtin_index)
10043     {
10044     case BUILT_IN_ISINF:
10045       if (!HONOR_INFINITIES (TYPE_MODE (TREE_TYPE (arg))))
10046         return omit_one_operand_loc (loc, type, integer_zero_node, arg);
10047
10048       if (TREE_CODE (arg) == REAL_CST)
10049         {
10050           r = TREE_REAL_CST (arg);
10051           if (real_isinf (&r))
10052             return real_compare (GT_EXPR, &r, &dconst0)
10053                    ? integer_one_node : integer_minus_one_node;
10054           else
10055             return integer_zero_node;
10056         }
10057
10058       return NULL_TREE;
10059
10060     case BUILT_IN_ISINF_SIGN:
10061       {
10062         /* isinf_sign(x) -> isinf(x) ? (signbit(x) ? -1 : 1) : 0 */
10063         /* In a boolean context, GCC will fold the inner COND_EXPR to
10064            1.  So e.g. "if (isinf_sign(x))" would be folded to just
10065            "if (isinf(x) ? 1 : 0)" which becomes "if (isinf(x))". */
10066         tree signbit_fn = mathfn_built_in_1 (TREE_TYPE (arg), BUILT_IN_SIGNBIT, 0);
10067         tree isinf_fn = builtin_decl_explicit (BUILT_IN_ISINF);
10068         tree tmp = NULL_TREE;
10069
10070         arg = builtin_save_expr (arg);
10071
10072         if (signbit_fn && isinf_fn)
10073           {
10074             tree signbit_call = build_call_expr_loc (loc, signbit_fn, 1, arg);
10075             tree isinf_call = build_call_expr_loc (loc, isinf_fn, 1, arg);
10076
10077             signbit_call = fold_build2_loc (loc, NE_EXPR, integer_type_node,
10078                                         signbit_call, integer_zero_node);
10079             isinf_call = fold_build2_loc (loc, NE_EXPR, integer_type_node,
10080                                       isinf_call, integer_zero_node);
10081
10082             tmp = fold_build3_loc (loc, COND_EXPR, integer_type_node, signbit_call,
10083                                integer_minus_one_node, integer_one_node);
10084             tmp = fold_build3_loc (loc, COND_EXPR, integer_type_node,
10085                                isinf_call, tmp,
10086                                integer_zero_node);
10087           }
10088
10089         return tmp;
10090       }
10091
10092     case BUILT_IN_ISFINITE:
10093       if (!HONOR_NANS (TYPE_MODE (TREE_TYPE (arg)))
10094           && !HONOR_INFINITIES (TYPE_MODE (TREE_TYPE (arg))))
10095         return omit_one_operand_loc (loc, type, integer_one_node, arg);
10096
10097       if (TREE_CODE (arg) == REAL_CST)
10098         {
10099           r = TREE_REAL_CST (arg);
10100           return real_isfinite (&r) ? integer_one_node : integer_zero_node;
10101         }
10102
10103       return NULL_TREE;
10104
10105     case BUILT_IN_ISNAN:
10106       if (!HONOR_NANS (TYPE_MODE (TREE_TYPE (arg))))
10107         return omit_one_operand_loc (loc, type, integer_zero_node, arg);
10108
10109       if (TREE_CODE (arg) == REAL_CST)
10110         {
10111           r = TREE_REAL_CST (arg);
10112           return real_isnan (&r) ? integer_one_node : integer_zero_node;
10113         }
10114
10115       arg = builtin_save_expr (arg);
10116       return fold_build2_loc (loc, UNORDERED_EXPR, type, arg, arg);
10117
10118     default:
10119       gcc_unreachable ();
10120     }
10121 }
10122
10123 /* Fold a call to __builtin_fpclassify(int, int, int, int, int, ...).
10124    This builtin will generate code to return the appropriate floating
10125    point classification depending on the value of the floating point
10126    number passed in.  The possible return values must be supplied as
10127    int arguments to the call in the following order: FP_NAN, FP_INFINITE,
10128    FP_NORMAL, FP_SUBNORMAL and FP_ZERO.  The ellipses is for exactly
10129    one floating point argument which is "type generic".  */
10130
10131 static tree
10132 fold_builtin_fpclassify (location_t loc, tree exp)
10133 {
10134   tree fp_nan, fp_infinite, fp_normal, fp_subnormal, fp_zero,
10135     arg, type, res, tmp;
10136   enum machine_mode mode;
10137   REAL_VALUE_TYPE r;
10138   char buf[128];
10139
10140   /* Verify the required arguments in the original call.  */
10141   if (!validate_arglist (exp, INTEGER_TYPE, INTEGER_TYPE,
10142                          INTEGER_TYPE, INTEGER_TYPE,
10143                          INTEGER_TYPE, REAL_TYPE, VOID_TYPE))
10144     return NULL_TREE;
10145
10146   fp_nan = CALL_EXPR_ARG (exp, 0);
10147   fp_infinite = CALL_EXPR_ARG (exp, 1);
10148   fp_normal = CALL_EXPR_ARG (exp, 2);
10149   fp_subnormal = CALL_EXPR_ARG (exp, 3);
10150   fp_zero = CALL_EXPR_ARG (exp, 4);
10151   arg = CALL_EXPR_ARG (exp, 5);
10152   type = TREE_TYPE (arg);
10153   mode = TYPE_MODE (type);
10154   arg = builtin_save_expr (fold_build1_loc (loc, ABS_EXPR, type, arg));
10155
10156   /* fpclassify(x) ->
10157        isnan(x) ? FP_NAN :
10158          (fabs(x) == Inf ? FP_INFINITE :
10159            (fabs(x) >= DBL_MIN ? FP_NORMAL :
10160              (x == 0 ? FP_ZERO : FP_SUBNORMAL))).  */
10161
10162   tmp = fold_build2_loc (loc, EQ_EXPR, integer_type_node, arg,
10163                      build_real (type, dconst0));
10164   res = fold_build3_loc (loc, COND_EXPR, integer_type_node,
10165                      tmp, fp_zero, fp_subnormal);
10166
10167   sprintf (buf, "0x1p%d", REAL_MODE_FORMAT (mode)->emin - 1);
10168   real_from_string (&r, buf);
10169   tmp = fold_build2_loc (loc, GE_EXPR, integer_type_node,
10170                      arg, build_real (type, r));
10171   res = fold_build3_loc (loc, COND_EXPR, integer_type_node, tmp, fp_normal, res);
10172
10173   if (HONOR_INFINITIES (mode))
10174     {
10175       real_inf (&r);
10176       tmp = fold_build2_loc (loc, EQ_EXPR, integer_type_node, arg,
10177                          build_real (type, r));
10178       res = fold_build3_loc (loc, COND_EXPR, integer_type_node, tmp,
10179                          fp_infinite, res);
10180     }
10181
10182   if (HONOR_NANS (mode))
10183     {
10184       tmp = fold_build2_loc (loc, ORDERED_EXPR, integer_type_node, arg, arg);
10185       res = fold_build3_loc (loc, COND_EXPR, integer_type_node, tmp, res, fp_nan);
10186     }
10187
10188   return res;
10189 }
10190
10191 /* Fold a call to an unordered comparison function such as
10192    __builtin_isgreater().  FNDECL is the FUNCTION_DECL for the function
10193    being called and ARG0 and ARG1 are the arguments for the call.
10194    UNORDERED_CODE and ORDERED_CODE are comparison codes that give
10195    the opposite of the desired result.  UNORDERED_CODE is used
10196    for modes that can hold NaNs and ORDERED_CODE is used for
10197    the rest.  */
10198
10199 static tree
10200 fold_builtin_unordered_cmp (location_t loc, tree fndecl, tree arg0, tree arg1,
10201                             enum tree_code unordered_code,
10202                             enum tree_code ordered_code)
10203 {
10204   tree type = TREE_TYPE (TREE_TYPE (fndecl));
10205   enum tree_code code;
10206   tree type0, type1;
10207   enum tree_code code0, code1;
10208   tree cmp_type = NULL_TREE;
10209
10210   type0 = TREE_TYPE (arg0);
10211   type1 = TREE_TYPE (arg1);
10212
10213   code0 = TREE_CODE (type0);
10214   code1 = TREE_CODE (type1);
10215
10216   if (code0 == REAL_TYPE && code1 == REAL_TYPE)
10217     /* Choose the wider of two real types.  */
10218     cmp_type = TYPE_PRECISION (type0) >= TYPE_PRECISION (type1)
10219       ? type0 : type1;
10220   else if (code0 == REAL_TYPE && code1 == INTEGER_TYPE)
10221     cmp_type = type0;
10222   else if (code0 == INTEGER_TYPE && code1 == REAL_TYPE)
10223     cmp_type = type1;
10224
10225   arg0 = fold_convert_loc (loc, cmp_type, arg0);
10226   arg1 = fold_convert_loc (loc, cmp_type, arg1);
10227
10228   if (unordered_code == UNORDERED_EXPR)
10229     {
10230       if (!HONOR_NANS (TYPE_MODE (TREE_TYPE (arg0))))
10231         return omit_two_operands_loc (loc, type, integer_zero_node, arg0, arg1);
10232       return fold_build2_loc (loc, UNORDERED_EXPR, type, arg0, arg1);
10233     }
10234
10235   code = HONOR_NANS (TYPE_MODE (TREE_TYPE (arg0))) ? unordered_code
10236                                                    : ordered_code;
10237   return fold_build1_loc (loc, TRUTH_NOT_EXPR, type,
10238                       fold_build2_loc (loc, code, type, arg0, arg1));
10239 }
10240
10241 /* Fold a call to built-in function FNDECL with 0 arguments.
10242    IGNORE is true if the result of the function call is ignored.  This
10243    function returns NULL_TREE if no simplification was possible.  */
10244
10245 static tree
10246 fold_builtin_0 (location_t loc, tree fndecl, bool ignore ATTRIBUTE_UNUSED)
10247 {
10248   tree type = TREE_TYPE (TREE_TYPE (fndecl));
10249   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
10250   switch (fcode)
10251     {
10252     CASE_FLT_FN (BUILT_IN_INF):
10253     case BUILT_IN_INFD32:
10254     case BUILT_IN_INFD64:
10255     case BUILT_IN_INFD128:
10256       return fold_builtin_inf (loc, type, true);
10257
10258     CASE_FLT_FN (BUILT_IN_HUGE_VAL):
10259       return fold_builtin_inf (loc, type, false);
10260
10261     case BUILT_IN_CLASSIFY_TYPE:
10262       return fold_builtin_classify_type (NULL_TREE);
10263
10264     default:
10265       break;
10266     }
10267   return NULL_TREE;
10268 }
10269
10270 /* Fold a call to built-in function FNDECL with 1 argument, ARG0.
10271    IGNORE is true if the result of the function call is ignored.  This
10272    function returns NULL_TREE if no simplification was possible.  */
10273
10274 static tree
10275 fold_builtin_1 (location_t loc, tree fndecl, tree arg0, bool ignore)
10276 {
10277   tree type = TREE_TYPE (TREE_TYPE (fndecl));
10278   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
10279   switch (fcode)
10280     {
10281     case BUILT_IN_CONSTANT_P:
10282       {
10283         tree val = fold_builtin_constant_p (arg0);
10284
10285         /* Gimplification will pull the CALL_EXPR for the builtin out of
10286            an if condition.  When not optimizing, we'll not CSE it back.
10287            To avoid link error types of regressions, return false now.  */
10288         if (!val && !optimize)
10289           val = integer_zero_node;
10290
10291         return val;
10292       }
10293
10294     case BUILT_IN_CLASSIFY_TYPE:
10295       return fold_builtin_classify_type (arg0);
10296
10297     case BUILT_IN_STRLEN:
10298       return fold_builtin_strlen (loc, type, arg0);
10299
10300     CASE_FLT_FN (BUILT_IN_FABS):
10301       return fold_builtin_fabs (loc, arg0, type);
10302
10303     case BUILT_IN_ABS:
10304     case BUILT_IN_LABS:
10305     case BUILT_IN_LLABS:
10306     case BUILT_IN_IMAXABS:
10307       return fold_builtin_abs (loc, arg0, type);
10308
10309     CASE_FLT_FN (BUILT_IN_CONJ):
10310       if (validate_arg (arg0, COMPLEX_TYPE)
10311         && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
10312         return fold_build1_loc (loc, CONJ_EXPR, type, arg0);
10313     break;
10314
10315     CASE_FLT_FN (BUILT_IN_CREAL):
10316       if (validate_arg (arg0, COMPLEX_TYPE)
10317         && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
10318         return non_lvalue_loc (loc, fold_build1_loc (loc, REALPART_EXPR, type, arg0));;
10319     break;
10320
10321     CASE_FLT_FN (BUILT_IN_CIMAG):
10322       if (validate_arg (arg0, COMPLEX_TYPE)
10323           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
10324         return non_lvalue_loc (loc, fold_build1_loc (loc, IMAGPART_EXPR, type, arg0));
10325     break;
10326
10327     CASE_FLT_FN (BUILT_IN_CCOS):
10328       return fold_builtin_ccos(loc, arg0, type, fndecl, /*hyper=*/ false);
10329
10330     CASE_FLT_FN (BUILT_IN_CCOSH):
10331       return fold_builtin_ccos(loc, arg0, type, fndecl, /*hyper=*/ true);
10332
10333     CASE_FLT_FN (BUILT_IN_CPROJ):
10334       return fold_builtin_cproj(loc, arg0, type);
10335
10336     CASE_FLT_FN (BUILT_IN_CSIN):
10337       if (validate_arg (arg0, COMPLEX_TYPE)
10338           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
10339         return do_mpc_arg1 (arg0, type, mpc_sin);
10340     break;
10341
10342     CASE_FLT_FN (BUILT_IN_CSINH):
10343       if (validate_arg (arg0, COMPLEX_TYPE)
10344           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
10345         return do_mpc_arg1 (arg0, type, mpc_sinh);
10346     break;
10347
10348     CASE_FLT_FN (BUILT_IN_CTAN):
10349       if (validate_arg (arg0, COMPLEX_TYPE)
10350           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
10351         return do_mpc_arg1 (arg0, type, mpc_tan);
10352     break;
10353
10354     CASE_FLT_FN (BUILT_IN_CTANH):
10355       if (validate_arg (arg0, COMPLEX_TYPE)
10356           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
10357         return do_mpc_arg1 (arg0, type, mpc_tanh);
10358     break;
10359
10360     CASE_FLT_FN (BUILT_IN_CLOG):
10361       if (validate_arg (arg0, COMPLEX_TYPE)
10362           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
10363         return do_mpc_arg1 (arg0, type, mpc_log);
10364     break;
10365
10366     CASE_FLT_FN (BUILT_IN_CSQRT):
10367       if (validate_arg (arg0, COMPLEX_TYPE)
10368           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
10369         return do_mpc_arg1 (arg0, type, mpc_sqrt);
10370     break;
10371
10372     CASE_FLT_FN (BUILT_IN_CASIN):
10373       if (validate_arg (arg0, COMPLEX_TYPE)
10374           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
10375         return do_mpc_arg1 (arg0, type, mpc_asin);
10376     break;
10377
10378     CASE_FLT_FN (BUILT_IN_CACOS):
10379       if (validate_arg (arg0, COMPLEX_TYPE)
10380           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
10381         return do_mpc_arg1 (arg0, type, mpc_acos);
10382     break;
10383
10384     CASE_FLT_FN (BUILT_IN_CATAN):
10385       if (validate_arg (arg0, COMPLEX_TYPE)
10386           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
10387         return do_mpc_arg1 (arg0, type, mpc_atan);
10388     break;
10389
10390     CASE_FLT_FN (BUILT_IN_CASINH):
10391       if (validate_arg (arg0, COMPLEX_TYPE)
10392           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
10393         return do_mpc_arg1 (arg0, type, mpc_asinh);
10394     break;
10395
10396     CASE_FLT_FN (BUILT_IN_CACOSH):
10397       if (validate_arg (arg0, COMPLEX_TYPE)
10398           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
10399         return do_mpc_arg1 (arg0, type, mpc_acosh);
10400     break;
10401
10402     CASE_FLT_FN (BUILT_IN_CATANH):
10403       if (validate_arg (arg0, COMPLEX_TYPE)
10404           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
10405         return do_mpc_arg1 (arg0, type, mpc_atanh);
10406     break;
10407
10408     CASE_FLT_FN (BUILT_IN_CABS):
10409       return fold_builtin_cabs (loc, arg0, type, fndecl);
10410
10411     CASE_FLT_FN (BUILT_IN_CARG):
10412       return fold_builtin_carg (loc, arg0, type);
10413
10414     CASE_FLT_FN (BUILT_IN_SQRT):
10415       return fold_builtin_sqrt (loc, arg0, type);
10416
10417     CASE_FLT_FN (BUILT_IN_CBRT):
10418       return fold_builtin_cbrt (loc, arg0, type);
10419
10420     CASE_FLT_FN (BUILT_IN_ASIN):
10421       if (validate_arg (arg0, REAL_TYPE))
10422         return do_mpfr_arg1 (arg0, type, mpfr_asin,
10423                              &dconstm1, &dconst1, true);
10424     break;
10425
10426     CASE_FLT_FN (BUILT_IN_ACOS):
10427       if (validate_arg (arg0, REAL_TYPE))
10428         return do_mpfr_arg1 (arg0, type, mpfr_acos,
10429                              &dconstm1, &dconst1, true);
10430     break;
10431
10432     CASE_FLT_FN (BUILT_IN_ATAN):
10433       if (validate_arg (arg0, REAL_TYPE))
10434         return do_mpfr_arg1 (arg0, type, mpfr_atan, NULL, NULL, 0);
10435     break;
10436
10437     CASE_FLT_FN (BUILT_IN_ASINH):
10438       if (validate_arg (arg0, REAL_TYPE))
10439         return do_mpfr_arg1 (arg0, type, mpfr_asinh, NULL, NULL, 0);
10440     break;
10441
10442     CASE_FLT_FN (BUILT_IN_ACOSH):
10443       if (validate_arg (arg0, REAL_TYPE))
10444         return do_mpfr_arg1 (arg0, type, mpfr_acosh,
10445                              &dconst1, NULL, true);
10446     break;
10447
10448     CASE_FLT_FN (BUILT_IN_ATANH):
10449       if (validate_arg (arg0, REAL_TYPE))
10450         return do_mpfr_arg1 (arg0, type, mpfr_atanh,
10451                              &dconstm1, &dconst1, false);
10452     break;
10453
10454     CASE_FLT_FN (BUILT_IN_SIN):
10455       if (validate_arg (arg0, REAL_TYPE))
10456         return do_mpfr_arg1 (arg0, type, mpfr_sin, NULL, NULL, 0);
10457     break;
10458
10459     CASE_FLT_FN (BUILT_IN_COS):
10460       return fold_builtin_cos (loc, arg0, type, fndecl);
10461
10462     CASE_FLT_FN (BUILT_IN_TAN):
10463       return fold_builtin_tan (arg0, type);
10464
10465     CASE_FLT_FN (BUILT_IN_CEXP):
10466       return fold_builtin_cexp (loc, arg0, type);
10467
10468     CASE_FLT_FN (BUILT_IN_CEXPI):
10469       if (validate_arg (arg0, REAL_TYPE))
10470         return do_mpfr_sincos (arg0, NULL_TREE, NULL_TREE);
10471     break;
10472
10473     CASE_FLT_FN (BUILT_IN_SINH):
10474       if (validate_arg (arg0, REAL_TYPE))
10475         return do_mpfr_arg1 (arg0, type, mpfr_sinh, NULL, NULL, 0);
10476     break;
10477
10478     CASE_FLT_FN (BUILT_IN_COSH):
10479       return fold_builtin_cosh (loc, arg0, type, fndecl);
10480
10481     CASE_FLT_FN (BUILT_IN_TANH):
10482       if (validate_arg (arg0, REAL_TYPE))
10483         return do_mpfr_arg1 (arg0, type, mpfr_tanh, NULL, NULL, 0);
10484     break;
10485
10486     CASE_FLT_FN (BUILT_IN_ERF):
10487       if (validate_arg (arg0, REAL_TYPE))
10488         return do_mpfr_arg1 (arg0, type, mpfr_erf, NULL, NULL, 0);
10489     break;
10490
10491     CASE_FLT_FN (BUILT_IN_ERFC):
10492       if (validate_arg (arg0, REAL_TYPE))
10493         return do_mpfr_arg1 (arg0, type, mpfr_erfc, NULL, NULL, 0);
10494     break;
10495
10496     CASE_FLT_FN (BUILT_IN_TGAMMA):
10497       if (validate_arg (arg0, REAL_TYPE))
10498         return do_mpfr_arg1 (arg0, type, mpfr_gamma, NULL, NULL, 0);
10499     break;
10500
10501     CASE_FLT_FN (BUILT_IN_EXP):
10502       return fold_builtin_exponent (loc, fndecl, arg0, mpfr_exp);
10503
10504     CASE_FLT_FN (BUILT_IN_EXP2):
10505       return fold_builtin_exponent (loc, fndecl, arg0, mpfr_exp2);
10506
10507     CASE_FLT_FN (BUILT_IN_EXP10):
10508     CASE_FLT_FN (BUILT_IN_POW10):
10509       return fold_builtin_exponent (loc, fndecl, arg0, mpfr_exp10);
10510
10511     CASE_FLT_FN (BUILT_IN_EXPM1):
10512       if (validate_arg (arg0, REAL_TYPE))
10513         return do_mpfr_arg1 (arg0, type, mpfr_expm1, NULL, NULL, 0);
10514     break;
10515
10516     CASE_FLT_FN (BUILT_IN_LOG):
10517     return fold_builtin_logarithm (loc, fndecl, arg0, mpfr_log);
10518
10519     CASE_FLT_FN (BUILT_IN_LOG2):
10520       return fold_builtin_logarithm (loc, fndecl, arg0, mpfr_log2);
10521
10522     CASE_FLT_FN (BUILT_IN_LOG10):
10523       return fold_builtin_logarithm (loc, fndecl, arg0, mpfr_log10);
10524
10525     CASE_FLT_FN (BUILT_IN_LOG1P):
10526       if (validate_arg (arg0, REAL_TYPE))
10527         return do_mpfr_arg1 (arg0, type, mpfr_log1p,
10528                              &dconstm1, NULL, false);
10529     break;
10530
10531     CASE_FLT_FN (BUILT_IN_J0):
10532       if (validate_arg (arg0, REAL_TYPE))
10533         return do_mpfr_arg1 (arg0, type, mpfr_j0,
10534                              NULL, NULL, 0);
10535     break;
10536
10537     CASE_FLT_FN (BUILT_IN_J1):
10538       if (validate_arg (arg0, REAL_TYPE))
10539         return do_mpfr_arg1 (arg0, type, mpfr_j1,
10540                              NULL, NULL, 0);
10541     break;
10542
10543     CASE_FLT_FN (BUILT_IN_Y0):
10544       if (validate_arg (arg0, REAL_TYPE))
10545         return do_mpfr_arg1 (arg0, type, mpfr_y0,
10546                              &dconst0, NULL, false);
10547     break;
10548
10549     CASE_FLT_FN (BUILT_IN_Y1):
10550       if (validate_arg (arg0, REAL_TYPE))
10551         return do_mpfr_arg1 (arg0, type, mpfr_y1,
10552                              &dconst0, NULL, false);
10553     break;
10554
10555     CASE_FLT_FN (BUILT_IN_NAN):
10556     case BUILT_IN_NAND32:
10557     case BUILT_IN_NAND64:
10558     case BUILT_IN_NAND128:
10559       return fold_builtin_nan (arg0, type, true);
10560
10561     CASE_FLT_FN (BUILT_IN_NANS):
10562       return fold_builtin_nan (arg0, type, false);
10563
10564     CASE_FLT_FN (BUILT_IN_FLOOR):
10565       return fold_builtin_floor (loc, fndecl, arg0);
10566
10567     CASE_FLT_FN (BUILT_IN_CEIL):
10568       return fold_builtin_ceil (loc, fndecl, arg0);
10569
10570     CASE_FLT_FN (BUILT_IN_TRUNC):
10571       return fold_builtin_trunc (loc, fndecl, arg0);
10572
10573     CASE_FLT_FN (BUILT_IN_ROUND):
10574       return fold_builtin_round (loc, fndecl, arg0);
10575
10576     CASE_FLT_FN (BUILT_IN_NEARBYINT):
10577     CASE_FLT_FN (BUILT_IN_RINT):
10578       return fold_trunc_transparent_mathfn (loc, fndecl, arg0);
10579
10580     CASE_FLT_FN (BUILT_IN_ICEIL):
10581     CASE_FLT_FN (BUILT_IN_LCEIL):
10582     CASE_FLT_FN (BUILT_IN_LLCEIL):
10583     CASE_FLT_FN (BUILT_IN_LFLOOR):
10584     CASE_FLT_FN (BUILT_IN_IFLOOR):
10585     CASE_FLT_FN (BUILT_IN_LLFLOOR):
10586     CASE_FLT_FN (BUILT_IN_IROUND):
10587     CASE_FLT_FN (BUILT_IN_LROUND):
10588     CASE_FLT_FN (BUILT_IN_LLROUND):
10589       return fold_builtin_int_roundingfn (loc, fndecl, arg0);
10590
10591     CASE_FLT_FN (BUILT_IN_IRINT):
10592     CASE_FLT_FN (BUILT_IN_LRINT):
10593     CASE_FLT_FN (BUILT_IN_LLRINT):
10594       return fold_fixed_mathfn (loc, fndecl, arg0);
10595
10596     case BUILT_IN_BSWAP16:
10597     case BUILT_IN_BSWAP32:
10598     case BUILT_IN_BSWAP64:
10599       return fold_builtin_bswap (fndecl, arg0);
10600
10601     CASE_INT_FN (BUILT_IN_FFS):
10602     CASE_INT_FN (BUILT_IN_CLZ):
10603     CASE_INT_FN (BUILT_IN_CTZ):
10604     CASE_INT_FN (BUILT_IN_CLRSB):
10605     CASE_INT_FN (BUILT_IN_POPCOUNT):
10606     CASE_INT_FN (BUILT_IN_PARITY):
10607       return fold_builtin_bitop (fndecl, arg0);
10608
10609     CASE_FLT_FN (BUILT_IN_SIGNBIT):
10610       return fold_builtin_signbit (loc, arg0, type);
10611
10612     CASE_FLT_FN (BUILT_IN_SIGNIFICAND):
10613       return fold_builtin_significand (loc, arg0, type);
10614
10615     CASE_FLT_FN (BUILT_IN_ILOGB):
10616     CASE_FLT_FN (BUILT_IN_LOGB):
10617       return fold_builtin_logb (loc, arg0, type);
10618
10619     case BUILT_IN_ISASCII:
10620       return fold_builtin_isascii (loc, arg0);
10621
10622     case BUILT_IN_TOASCII:
10623       return fold_builtin_toascii (loc, arg0);
10624
10625     case BUILT_IN_ISDIGIT:
10626       return fold_builtin_isdigit (loc, arg0);
10627
10628     CASE_FLT_FN (BUILT_IN_FINITE):
10629     case BUILT_IN_FINITED32:
10630     case BUILT_IN_FINITED64:
10631     case BUILT_IN_FINITED128:
10632     case BUILT_IN_ISFINITE:
10633       {
10634         tree ret = fold_builtin_classify (loc, fndecl, arg0, BUILT_IN_ISFINITE);
10635         if (ret)
10636           return ret;
10637         return fold_builtin_interclass_mathfn (loc, fndecl, arg0);
10638       }
10639
10640     CASE_FLT_FN (BUILT_IN_ISINF):
10641     case BUILT_IN_ISINFD32:
10642     case BUILT_IN_ISINFD64:
10643     case BUILT_IN_ISINFD128:
10644       {
10645         tree ret = fold_builtin_classify (loc, fndecl, arg0, BUILT_IN_ISINF);
10646         if (ret)
10647           return ret;
10648         return fold_builtin_interclass_mathfn (loc, fndecl, arg0);
10649       }
10650
10651     case BUILT_IN_ISNORMAL:
10652       return fold_builtin_interclass_mathfn (loc, fndecl, arg0);
10653
10654     case BUILT_IN_ISINF_SIGN:
10655       return fold_builtin_classify (loc, fndecl, arg0, BUILT_IN_ISINF_SIGN);
10656
10657     CASE_FLT_FN (BUILT_IN_ISNAN):
10658     case BUILT_IN_ISNAND32:
10659     case BUILT_IN_ISNAND64:
10660     case BUILT_IN_ISNAND128:
10661       return fold_builtin_classify (loc, fndecl, arg0, BUILT_IN_ISNAN);
10662
10663     case BUILT_IN_PRINTF:
10664     case BUILT_IN_PRINTF_UNLOCKED:
10665     case BUILT_IN_VPRINTF:
10666       return fold_builtin_printf (loc, fndecl, arg0, NULL_TREE, ignore, fcode);
10667
10668     case BUILT_IN_FREE:
10669       if (integer_zerop (arg0))
10670         return build_empty_stmt (loc);
10671       break;
10672
10673     default:
10674       break;
10675     }
10676
10677   return NULL_TREE;
10678
10679 }
10680
10681 /* Fold a call to built-in function FNDECL with 2 arguments, ARG0 and ARG1.
10682    IGNORE is true if the result of the function call is ignored.  This
10683    function returns NULL_TREE if no simplification was possible.  */
10684
10685 static tree
10686 fold_builtin_2 (location_t loc, tree fndecl, tree arg0, tree arg1, bool ignore)
10687 {
10688   tree type = TREE_TYPE (TREE_TYPE (fndecl));
10689   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
10690
10691   switch (fcode)
10692     {
10693     CASE_FLT_FN (BUILT_IN_JN):
10694       if (validate_arg (arg0, INTEGER_TYPE)
10695           && validate_arg (arg1, REAL_TYPE))
10696         return do_mpfr_bessel_n (arg0, arg1, type, mpfr_jn, NULL, 0);
10697     break;
10698
10699     CASE_FLT_FN (BUILT_IN_YN):
10700       if (validate_arg (arg0, INTEGER_TYPE)
10701           && validate_arg (arg1, REAL_TYPE))
10702         return do_mpfr_bessel_n (arg0, arg1, type, mpfr_yn,
10703                                  &dconst0, false);
10704     break;
10705
10706     CASE_FLT_FN (BUILT_IN_DREM):
10707     CASE_FLT_FN (BUILT_IN_REMAINDER):
10708       if (validate_arg (arg0, REAL_TYPE)
10709           && validate_arg(arg1, REAL_TYPE))
10710         return do_mpfr_arg2 (arg0, arg1, type, mpfr_remainder);
10711     break;
10712
10713     CASE_FLT_FN_REENT (BUILT_IN_GAMMA): /* GAMMA_R */
10714     CASE_FLT_FN_REENT (BUILT_IN_LGAMMA): /* LGAMMA_R */
10715       if (validate_arg (arg0, REAL_TYPE)
10716           && validate_arg(arg1, POINTER_TYPE))
10717         return do_mpfr_lgamma_r (arg0, arg1, type);
10718     break;
10719
10720     CASE_FLT_FN (BUILT_IN_ATAN2):
10721       if (validate_arg (arg0, REAL_TYPE)
10722           && validate_arg(arg1, REAL_TYPE))
10723         return do_mpfr_arg2 (arg0, arg1, type, mpfr_atan2);
10724     break;
10725
10726     CASE_FLT_FN (BUILT_IN_FDIM):
10727       if (validate_arg (arg0, REAL_TYPE)
10728           && validate_arg(arg1, REAL_TYPE))
10729         return do_mpfr_arg2 (arg0, arg1, type, mpfr_dim);
10730     break;
10731
10732     CASE_FLT_FN (BUILT_IN_HYPOT):
10733       return fold_builtin_hypot (loc, fndecl, arg0, arg1, type);
10734
10735     CASE_FLT_FN (BUILT_IN_CPOW):
10736       if (validate_arg (arg0, COMPLEX_TYPE)
10737           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE
10738           && validate_arg (arg1, COMPLEX_TYPE)
10739           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg1))) == REAL_TYPE)
10740         return do_mpc_arg2 (arg0, arg1, type, /*do_nonfinite=*/ 0, mpc_pow);
10741     break;
10742
10743     CASE_FLT_FN (BUILT_IN_LDEXP):
10744       return fold_builtin_load_exponent (loc, arg0, arg1, type, /*ldexp=*/true);
10745     CASE_FLT_FN (BUILT_IN_SCALBN):
10746     CASE_FLT_FN (BUILT_IN_SCALBLN):
10747       return fold_builtin_load_exponent (loc, arg0, arg1,
10748                                          type, /*ldexp=*/false);
10749
10750     CASE_FLT_FN (BUILT_IN_FREXP):
10751       return fold_builtin_frexp (loc, arg0, arg1, type);
10752
10753     CASE_FLT_FN (BUILT_IN_MODF):
10754       return fold_builtin_modf (loc, arg0, arg1, type);
10755
10756     case BUILT_IN_BZERO:
10757       return fold_builtin_bzero (loc, arg0, arg1, ignore);
10758
10759     case BUILT_IN_FPUTS:
10760       return fold_builtin_fputs (loc, arg0, arg1, ignore, false, NULL_TREE);
10761
10762     case BUILT_IN_FPUTS_UNLOCKED:
10763       return fold_builtin_fputs (loc, arg0, arg1, ignore, true, NULL_TREE);
10764
10765     case BUILT_IN_STRSTR:
10766       return fold_builtin_strstr (loc, arg0, arg1, type);
10767
10768     case BUILT_IN_STRCAT:
10769       return fold_builtin_strcat (loc, arg0, arg1);
10770
10771     case BUILT_IN_STRSPN:
10772       return fold_builtin_strspn (loc, arg0, arg1);
10773
10774     case BUILT_IN_STRCSPN:
10775       return fold_builtin_strcspn (loc, arg0, arg1);
10776
10777     case BUILT_IN_STRCHR:
10778     case BUILT_IN_INDEX:
10779       return fold_builtin_strchr (loc, arg0, arg1, type);
10780
10781     case BUILT_IN_STRRCHR:
10782     case BUILT_IN_RINDEX:
10783       return fold_builtin_strrchr (loc, arg0, arg1, type);
10784
10785     case BUILT_IN_STRCPY:
10786       return fold_builtin_strcpy (loc, fndecl, arg0, arg1, NULL_TREE);
10787
10788     case BUILT_IN_STPCPY:
10789       if (ignore)
10790         {
10791           tree fn = builtin_decl_implicit (BUILT_IN_STRCPY);
10792           if (!fn)
10793             break;
10794
10795           return build_call_expr_loc (loc, fn, 2, arg0, arg1);
10796         }
10797       else
10798         return fold_builtin_stpcpy (loc, fndecl, arg0, arg1);
10799       break;
10800
10801     case BUILT_IN_STRCMP:
10802       return fold_builtin_strcmp (loc, arg0, arg1);
10803
10804     case BUILT_IN_STRPBRK:
10805       return fold_builtin_strpbrk (loc, arg0, arg1, type);
10806
10807     case BUILT_IN_EXPECT:
10808       return fold_builtin_expect (loc, arg0, arg1);
10809
10810     CASE_FLT_FN (BUILT_IN_POW):
10811       return fold_builtin_pow (loc, fndecl, arg0, arg1, type);
10812
10813     CASE_FLT_FN (BUILT_IN_POWI):
10814       return fold_builtin_powi (loc, fndecl, arg0, arg1, type);
10815
10816     CASE_FLT_FN (BUILT_IN_COPYSIGN):
10817       return fold_builtin_copysign (loc, fndecl, arg0, arg1, type);
10818
10819     CASE_FLT_FN (BUILT_IN_FMIN):
10820       return fold_builtin_fmin_fmax (loc, arg0, arg1, type, /*max=*/false);
10821
10822     CASE_FLT_FN (BUILT_IN_FMAX):
10823       return fold_builtin_fmin_fmax (loc, arg0, arg1, type, /*max=*/true);
10824
10825     case BUILT_IN_ISGREATER:
10826       return fold_builtin_unordered_cmp (loc, fndecl,
10827                                          arg0, arg1, UNLE_EXPR, LE_EXPR);
10828     case BUILT_IN_ISGREATEREQUAL:
10829       return fold_builtin_unordered_cmp (loc, fndecl,
10830                                          arg0, arg1, UNLT_EXPR, LT_EXPR);
10831     case BUILT_IN_ISLESS:
10832       return fold_builtin_unordered_cmp (loc, fndecl,
10833                                          arg0, arg1, UNGE_EXPR, GE_EXPR);
10834     case BUILT_IN_ISLESSEQUAL:
10835       return fold_builtin_unordered_cmp (loc, fndecl,
10836                                          arg0, arg1, UNGT_EXPR, GT_EXPR);
10837     case BUILT_IN_ISLESSGREATER:
10838       return fold_builtin_unordered_cmp (loc, fndecl,
10839                                          arg0, arg1, UNEQ_EXPR, EQ_EXPR);
10840     case BUILT_IN_ISUNORDERED:
10841       return fold_builtin_unordered_cmp (loc, fndecl,
10842                                          arg0, arg1, UNORDERED_EXPR,
10843                                          NOP_EXPR);
10844
10845       /* We do the folding for va_start in the expander.  */
10846     case BUILT_IN_VA_START:
10847       break;
10848
10849     case BUILT_IN_SPRINTF:
10850       return fold_builtin_sprintf (loc, arg0, arg1, NULL_TREE, ignore);
10851
10852     case BUILT_IN_OBJECT_SIZE:
10853       return fold_builtin_object_size (arg0, arg1);
10854
10855     case BUILT_IN_PRINTF:
10856     case BUILT_IN_PRINTF_UNLOCKED:
10857     case BUILT_IN_VPRINTF:
10858       return fold_builtin_printf (loc, fndecl, arg0, arg1, ignore, fcode);
10859
10860     case BUILT_IN_PRINTF_CHK:
10861     case BUILT_IN_VPRINTF_CHK:
10862       if (!validate_arg (arg0, INTEGER_TYPE)
10863           || TREE_SIDE_EFFECTS (arg0))
10864         return NULL_TREE;
10865       else
10866         return fold_builtin_printf (loc, fndecl,
10867                                     arg1, NULL_TREE, ignore, fcode);
10868     break;
10869
10870     case BUILT_IN_FPRINTF:
10871     case BUILT_IN_FPRINTF_UNLOCKED:
10872     case BUILT_IN_VFPRINTF:
10873       return fold_builtin_fprintf (loc, fndecl, arg0, arg1, NULL_TREE,
10874                                    ignore, fcode);
10875
10876     case BUILT_IN_ATOMIC_ALWAYS_LOCK_FREE:
10877       return fold_builtin_atomic_always_lock_free (arg0, arg1);
10878
10879     case BUILT_IN_ATOMIC_IS_LOCK_FREE:
10880       return fold_builtin_atomic_is_lock_free (arg0, arg1);
10881
10882     default:
10883       break;
10884     }
10885   return NULL_TREE;
10886 }
10887
10888 /* Fold a call to built-in function FNDECL with 3 arguments, ARG0, ARG1,
10889    and ARG2.  IGNORE is true if the result of the function call is ignored.
10890    This function returns NULL_TREE if no simplification was possible.  */
10891
10892 static tree
10893 fold_builtin_3 (location_t loc, tree fndecl,
10894                 tree arg0, tree arg1, tree arg2, bool ignore)
10895 {
10896   tree type = TREE_TYPE (TREE_TYPE (fndecl));
10897   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
10898   switch (fcode)
10899     {
10900
10901     CASE_FLT_FN (BUILT_IN_SINCOS):
10902       return fold_builtin_sincos (loc, arg0, arg1, arg2);
10903
10904     CASE_FLT_FN (BUILT_IN_FMA):
10905       return fold_builtin_fma (loc, arg0, arg1, arg2, type);
10906     break;
10907
10908     CASE_FLT_FN (BUILT_IN_REMQUO):
10909       if (validate_arg (arg0, REAL_TYPE)
10910           && validate_arg(arg1, REAL_TYPE)
10911           && validate_arg(arg2, POINTER_TYPE))
10912         return do_mpfr_remquo (arg0, arg1, arg2);
10913     break;
10914
10915     case BUILT_IN_MEMSET:
10916       return fold_builtin_memset (loc, arg0, arg1, arg2, type, ignore);
10917
10918     case BUILT_IN_BCOPY:
10919       return fold_builtin_memory_op (loc, arg1, arg0, arg2,
10920                                      void_type_node, true, /*endp=*/3);
10921
10922     case BUILT_IN_MEMCPY:
10923       return fold_builtin_memory_op (loc, arg0, arg1, arg2,
10924                                      type, ignore, /*endp=*/0);
10925
10926     case BUILT_IN_MEMPCPY:
10927       return fold_builtin_memory_op (loc, arg0, arg1, arg2,
10928                                      type, ignore, /*endp=*/1);
10929
10930     case BUILT_IN_MEMMOVE:
10931       return fold_builtin_memory_op (loc, arg0, arg1, arg2,
10932                                      type, ignore, /*endp=*/3);
10933
10934     case BUILT_IN_STRNCAT:
10935       return fold_builtin_strncat (loc, arg0, arg1, arg2);
10936
10937     case BUILT_IN_STRNCPY:
10938       return fold_builtin_strncpy (loc, fndecl, arg0, arg1, arg2, NULL_TREE);
10939
10940     case BUILT_IN_STRNCMP:
10941       return fold_builtin_strncmp (loc, arg0, arg1, arg2);
10942
10943     case BUILT_IN_MEMCHR:
10944       return fold_builtin_memchr (loc, arg0, arg1, arg2, type);
10945
10946     case BUILT_IN_BCMP:
10947     case BUILT_IN_MEMCMP:
10948       return fold_builtin_memcmp (loc, arg0, arg1, arg2);;
10949
10950     case BUILT_IN_SPRINTF:
10951       return fold_builtin_sprintf (loc, arg0, arg1, arg2, ignore);
10952
10953     case BUILT_IN_SNPRINTF:
10954       return fold_builtin_snprintf (loc, arg0, arg1, arg2, NULL_TREE, ignore);
10955
10956     case BUILT_IN_STRCPY_CHK:
10957     case BUILT_IN_STPCPY_CHK:
10958       return fold_builtin_stxcpy_chk (loc, fndecl, arg0, arg1, arg2, NULL_TREE,
10959                                       ignore, fcode);
10960
10961     case BUILT_IN_STRCAT_CHK:
10962       return fold_builtin_strcat_chk (loc, fndecl, arg0, arg1, arg2);
10963
10964     case BUILT_IN_PRINTF_CHK:
10965     case BUILT_IN_VPRINTF_CHK:
10966       if (!validate_arg (arg0, INTEGER_TYPE)
10967           || TREE_SIDE_EFFECTS (arg0))
10968         return NULL_TREE;
10969       else
10970         return fold_builtin_printf (loc, fndecl, arg1, arg2, ignore, fcode);
10971     break;
10972
10973     case BUILT_IN_FPRINTF:
10974     case BUILT_IN_FPRINTF_UNLOCKED:
10975     case BUILT_IN_VFPRINTF:
10976       return fold_builtin_fprintf (loc, fndecl, arg0, arg1, arg2,
10977                                    ignore, fcode);
10978
10979     case BUILT_IN_FPRINTF_CHK:
10980     case BUILT_IN_VFPRINTF_CHK:
10981       if (!validate_arg (arg1, INTEGER_TYPE)
10982           || TREE_SIDE_EFFECTS (arg1))
10983         return NULL_TREE;
10984       else
10985         return fold_builtin_fprintf (loc, fndecl, arg0, arg2, NULL_TREE,
10986                                      ignore, fcode);
10987
10988     default:
10989       break;
10990     }
10991   return NULL_TREE;
10992 }
10993
10994 /* Fold a call to built-in function FNDECL with 4 arguments, ARG0, ARG1,
10995    ARG2, and ARG3.  IGNORE is true if the result of the function call is
10996    ignored.  This function returns NULL_TREE if no simplification was
10997    possible.  */
10998
10999 static tree
11000 fold_builtin_4 (location_t loc, tree fndecl,
11001                 tree arg0, tree arg1, tree arg2, tree arg3, bool ignore)
11002 {
11003   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
11004
11005   switch (fcode)
11006     {
11007     case BUILT_IN_MEMCPY_CHK:
11008     case BUILT_IN_MEMPCPY_CHK:
11009     case BUILT_IN_MEMMOVE_CHK:
11010     case BUILT_IN_MEMSET_CHK:
11011       return fold_builtin_memory_chk (loc, fndecl, arg0, arg1, arg2, arg3,
11012                                       NULL_TREE, ignore,
11013                                       DECL_FUNCTION_CODE (fndecl));
11014
11015     case BUILT_IN_STRNCPY_CHK:
11016     case BUILT_IN_STPNCPY_CHK:
11017       return fold_builtin_stxncpy_chk (loc, arg0, arg1, arg2, arg3, NULL_TREE,
11018                                        ignore, fcode);
11019
11020     case BUILT_IN_STRNCAT_CHK:
11021       return fold_builtin_strncat_chk (loc, fndecl, arg0, arg1, arg2, arg3);
11022
11023     case BUILT_IN_SNPRINTF:
11024       return fold_builtin_snprintf (loc, arg0, arg1, arg2, arg3, ignore);
11025
11026     case BUILT_IN_FPRINTF_CHK:
11027     case BUILT_IN_VFPRINTF_CHK:
11028       if (!validate_arg (arg1, INTEGER_TYPE)
11029           || TREE_SIDE_EFFECTS (arg1))
11030         return NULL_TREE;
11031       else
11032         return fold_builtin_fprintf (loc, fndecl, arg0, arg2, arg3,
11033                                      ignore, fcode);
11034     break;
11035
11036     default:
11037       break;
11038     }
11039   return NULL_TREE;
11040 }
11041
11042 /* Fold a call to built-in function FNDECL.  ARGS is an array of NARGS
11043     arguments, where NARGS <= 4.  IGNORE is true if the result of the
11044     function call is ignored.  This function returns NULL_TREE if no
11045     simplification was possible.  Note that this only folds builtins with
11046     fixed argument patterns.  Foldings that do varargs-to-varargs
11047     transformations, or that match calls with more than 4 arguments,
11048     need to be handled with fold_builtin_varargs instead.  */
11049
11050 #define MAX_ARGS_TO_FOLD_BUILTIN 4
11051
11052 static tree
11053 fold_builtin_n (location_t loc, tree fndecl, tree *args, int nargs, bool ignore)
11054 {
11055   tree ret = NULL_TREE;
11056
11057   switch (nargs)
11058     {
11059     case 0:
11060       ret = fold_builtin_0 (loc, fndecl, ignore);
11061       break;
11062     case 1:
11063       ret = fold_builtin_1 (loc, fndecl, args[0], ignore);
11064       break;
11065     case 2:
11066       ret = fold_builtin_2 (loc, fndecl, args[0], args[1], ignore);
11067       break;
11068     case 3:
11069       ret = fold_builtin_3 (loc, fndecl, args[0], args[1], args[2], ignore);
11070       break;
11071     case 4:
11072       ret = fold_builtin_4 (loc, fndecl, args[0], args[1], args[2], args[3],
11073                             ignore);
11074       break;
11075     default:
11076       break;
11077     }
11078   if (ret)
11079     {
11080       ret = build1 (NOP_EXPR, TREE_TYPE (ret), ret);
11081       SET_EXPR_LOCATION (ret, loc);
11082       TREE_NO_WARNING (ret) = 1;
11083       return ret;
11084     }
11085   return NULL_TREE;
11086 }
11087
11088 /* Builtins with folding operations that operate on "..." arguments
11089    need special handling; we need to store the arguments in a convenient
11090    data structure before attempting any folding.  Fortunately there are
11091    only a few builtins that fall into this category.  FNDECL is the
11092    function, EXP is the CALL_EXPR for the call, and IGNORE is true if the
11093    result of the function call is ignored.  */
11094
11095 static tree
11096 fold_builtin_varargs (location_t loc, tree fndecl, tree exp,
11097                       bool ignore ATTRIBUTE_UNUSED)
11098 {
11099   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
11100   tree ret = NULL_TREE;
11101
11102   switch (fcode)
11103     {
11104     case BUILT_IN_SPRINTF_CHK:
11105     case BUILT_IN_VSPRINTF_CHK:
11106       ret = fold_builtin_sprintf_chk (loc, exp, fcode);
11107       break;
11108
11109     case BUILT_IN_SNPRINTF_CHK:
11110     case BUILT_IN_VSNPRINTF_CHK:
11111       ret = fold_builtin_snprintf_chk (loc, exp, NULL_TREE, fcode);
11112       break;
11113
11114     case BUILT_IN_FPCLASSIFY:
11115       ret = fold_builtin_fpclassify (loc, exp);
11116       break;
11117
11118     default:
11119       break;
11120     }
11121   if (ret)
11122     {
11123       ret = build1 (NOP_EXPR, TREE_TYPE (ret), ret);
11124       SET_EXPR_LOCATION (ret, loc);
11125       TREE_NO_WARNING (ret) = 1;
11126       return ret;
11127     }
11128   return NULL_TREE;
11129 }
11130
11131 /* Return true if FNDECL shouldn't be folded right now.
11132    If a built-in function has an inline attribute always_inline
11133    wrapper, defer folding it after always_inline functions have
11134    been inlined, otherwise e.g. -D_FORTIFY_SOURCE checking
11135    might not be performed.  */
11136
11137 bool
11138 avoid_folding_inline_builtin (tree fndecl)
11139 {
11140   return (DECL_DECLARED_INLINE_P (fndecl)
11141           && DECL_DISREGARD_INLINE_LIMITS (fndecl)
11142           && cfun
11143           && !cfun->always_inline_functions_inlined
11144           && lookup_attribute ("always_inline", DECL_ATTRIBUTES (fndecl)));
11145 }
11146
11147 /* A wrapper function for builtin folding that prevents warnings for
11148    "statement without effect" and the like, caused by removing the
11149    call node earlier than the warning is generated.  */
11150
11151 tree
11152 fold_call_expr (location_t loc, tree exp, bool ignore)
11153 {
11154   tree ret = NULL_TREE;
11155   tree fndecl = get_callee_fndecl (exp);
11156   if (fndecl
11157       && TREE_CODE (fndecl) == FUNCTION_DECL
11158       && DECL_BUILT_IN (fndecl)
11159       /* If CALL_EXPR_VA_ARG_PACK is set, the arguments aren't finalized
11160          yet.  Defer folding until we see all the arguments
11161          (after inlining).  */
11162       && !CALL_EXPR_VA_ARG_PACK (exp))
11163     {
11164       int nargs = call_expr_nargs (exp);
11165
11166       /* Before gimplification CALL_EXPR_VA_ARG_PACK is not set, but
11167          instead last argument is __builtin_va_arg_pack ().  Defer folding
11168          even in that case, until arguments are finalized.  */
11169       if (nargs && TREE_CODE (CALL_EXPR_ARG (exp, nargs - 1)) == CALL_EXPR)
11170         {
11171           tree fndecl2 = get_callee_fndecl (CALL_EXPR_ARG (exp, nargs - 1));
11172           if (fndecl2
11173               && TREE_CODE (fndecl2) == FUNCTION_DECL
11174               && DECL_BUILT_IN_CLASS (fndecl2) == BUILT_IN_NORMAL
11175               && DECL_FUNCTION_CODE (fndecl2) == BUILT_IN_VA_ARG_PACK)
11176             return NULL_TREE;
11177         }
11178
11179       if (avoid_folding_inline_builtin (fndecl))
11180         return NULL_TREE;
11181
11182       if (DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_MD)
11183         return targetm.fold_builtin (fndecl, call_expr_nargs (exp),
11184                                      CALL_EXPR_ARGP (exp), ignore);
11185       else
11186         {
11187           if (nargs <= MAX_ARGS_TO_FOLD_BUILTIN)
11188             {
11189               tree *args = CALL_EXPR_ARGP (exp);
11190               ret = fold_builtin_n (loc, fndecl, args, nargs, ignore);
11191             }
11192           if (!ret)
11193             ret = fold_builtin_varargs (loc, fndecl, exp, ignore);
11194           if (ret)
11195             return ret;
11196         }
11197     }
11198   return NULL_TREE;
11199 }
11200
11201 /* Conveniently construct a function call expression.  FNDECL names the
11202    function to be called and N arguments are passed in the array
11203    ARGARRAY.  */
11204
11205 tree
11206 build_call_expr_loc_array (location_t loc, tree fndecl, int n, tree *argarray)
11207 {
11208   tree fntype = TREE_TYPE (fndecl);
11209   tree fn = build1 (ADDR_EXPR, build_pointer_type (fntype), fndecl);
11210  
11211   return fold_builtin_call_array (loc, TREE_TYPE (fntype), fn, n, argarray);
11212 }
11213
11214 /* Conveniently construct a function call expression.  FNDECL names the
11215    function to be called and the arguments are passed in the vector
11216    VEC.  */
11217
11218 tree
11219 build_call_expr_loc_vec (location_t loc, tree fndecl, vec<tree, va_gc> *vec)
11220 {
11221   return build_call_expr_loc_array (loc, fndecl, vec_safe_length (vec),
11222                                     vec_safe_address (vec));
11223 }
11224
11225
11226 /* Conveniently construct a function call expression.  FNDECL names the
11227    function to be called, N is the number of arguments, and the "..."
11228    parameters are the argument expressions.  */
11229
11230 tree
11231 build_call_expr_loc (location_t loc, tree fndecl, int n, ...)
11232 {
11233   va_list ap;
11234   tree *argarray = XALLOCAVEC (tree, n);
11235   int i;
11236
11237   va_start (ap, n);
11238   for (i = 0; i < n; i++)
11239     argarray[i] = va_arg (ap, tree);
11240   va_end (ap);
11241   return build_call_expr_loc_array (loc, fndecl, n, argarray);
11242 }
11243
11244 /* Like build_call_expr_loc (UNKNOWN_LOCATION, ...).  Duplicated because
11245    varargs macros aren't supported by all bootstrap compilers.  */
11246
11247 tree
11248 build_call_expr (tree fndecl, int n, ...)
11249 {
11250   va_list ap;
11251   tree *argarray = XALLOCAVEC (tree, n);
11252   int i;
11253
11254   va_start (ap, n);
11255   for (i = 0; i < n; i++)
11256     argarray[i] = va_arg (ap, tree);
11257   va_end (ap);
11258   return build_call_expr_loc_array (UNKNOWN_LOCATION, fndecl, n, argarray);
11259 }
11260
11261 /* Construct a CALL_EXPR with type TYPE with FN as the function expression.
11262    N arguments are passed in the array ARGARRAY.  */
11263
11264 tree
11265 fold_builtin_call_array (location_t loc, tree type,
11266                          tree fn,
11267                          int n,
11268                          tree *argarray)
11269 {
11270   tree ret = NULL_TREE;
11271    tree exp;
11272
11273   if (TREE_CODE (fn) == ADDR_EXPR)
11274   {
11275     tree fndecl = TREE_OPERAND (fn, 0);
11276     if (TREE_CODE (fndecl) == FUNCTION_DECL
11277         && DECL_BUILT_IN (fndecl))
11278       {
11279         /* If last argument is __builtin_va_arg_pack (), arguments to this
11280            function are not finalized yet.  Defer folding until they are.  */
11281         if (n && TREE_CODE (argarray[n - 1]) == CALL_EXPR)
11282           {
11283             tree fndecl2 = get_callee_fndecl (argarray[n - 1]);
11284             if (fndecl2
11285                 && TREE_CODE (fndecl2) == FUNCTION_DECL
11286                 && DECL_BUILT_IN_CLASS (fndecl2) == BUILT_IN_NORMAL
11287                 && DECL_FUNCTION_CODE (fndecl2) == BUILT_IN_VA_ARG_PACK)
11288               return build_call_array_loc (loc, type, fn, n, argarray);
11289           }
11290         if (avoid_folding_inline_builtin (fndecl))
11291           return build_call_array_loc (loc, type, fn, n, argarray);
11292         if (DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_MD)
11293           {
11294             ret = targetm.fold_builtin (fndecl, n, argarray, false);
11295             if (ret)
11296               return ret;
11297
11298             return build_call_array_loc (loc, type, fn, n, argarray);
11299           }
11300         else if (n <= MAX_ARGS_TO_FOLD_BUILTIN)
11301           {
11302             /* First try the transformations that don't require consing up
11303                an exp.  */
11304             ret = fold_builtin_n (loc, fndecl, argarray, n, false);
11305             if (ret)
11306               return ret;
11307           }
11308
11309         /* If we got this far, we need to build an exp.  */
11310         exp = build_call_array_loc (loc, type, fn, n, argarray);
11311         ret = fold_builtin_varargs (loc, fndecl, exp, false);
11312         return ret ? ret : exp;
11313       }
11314   }
11315
11316   return build_call_array_loc (loc, type, fn, n, argarray);
11317 }
11318
11319 /* Construct a new CALL_EXPR to FNDECL using the tail of the argument
11320    list ARGS along with N new arguments in NEWARGS.  SKIP is the number
11321    of arguments in ARGS to be omitted.  OLDNARGS is the number of
11322    elements in ARGS.  */
11323
11324 static tree
11325 rewrite_call_expr_valist (location_t loc, int oldnargs, tree *args,
11326                           int skip, tree fndecl, int n, va_list newargs)
11327 {
11328   int nargs = oldnargs - skip + n;
11329   tree *buffer;
11330
11331   if (n > 0)
11332     {
11333       int i, j;
11334
11335       buffer = XALLOCAVEC (tree, nargs);
11336       for (i = 0; i < n; i++)
11337         buffer[i] = va_arg (newargs, tree);
11338       for (j = skip; j < oldnargs; j++, i++)
11339         buffer[i] = args[j];
11340     }
11341   else
11342     buffer = args + skip;
11343
11344   return build_call_expr_loc_array (loc, fndecl, nargs, buffer);
11345 }
11346
11347 /* Construct a new CALL_EXPR to FNDECL using the tail of the argument
11348    list ARGS along with N new arguments specified as the "..."
11349    parameters.  SKIP is the number of arguments in ARGS to be omitted.
11350    OLDNARGS is the number of elements in ARGS.  */
11351
11352 static tree
11353 rewrite_call_expr_array (location_t loc, int oldnargs, tree *args,
11354                          int skip, tree fndecl, int n, ...)
11355 {
11356   va_list ap;
11357   tree t;
11358
11359   va_start (ap, n);
11360   t = rewrite_call_expr_valist (loc, oldnargs, args, skip, fndecl, n, ap);
11361   va_end (ap);
11362
11363   return t;
11364 }
11365
11366 /* Construct a new CALL_EXPR using the tail of the argument list of EXP
11367    along with N new arguments specified as the "..." parameters.  SKIP
11368    is the number of arguments in EXP to be omitted.  This function is used
11369    to do varargs-to-varargs transformations.  */
11370
11371 static tree
11372 rewrite_call_expr (location_t loc, tree exp, int skip, tree fndecl, int n, ...)
11373 {
11374   va_list ap;
11375   tree t;
11376
11377   va_start (ap, n);
11378   t = rewrite_call_expr_valist (loc, call_expr_nargs (exp),
11379                                 CALL_EXPR_ARGP (exp), skip, fndecl, n, ap);
11380   va_end (ap);
11381
11382   return t;
11383 }
11384
11385 /* Validate a single argument ARG against a tree code CODE representing
11386    a type.  */
11387
11388 static bool
11389 validate_arg (const_tree arg, enum tree_code code)
11390 {
11391   if (!arg)
11392     return false;
11393   else if (code == POINTER_TYPE)
11394     return POINTER_TYPE_P (TREE_TYPE (arg));
11395   else if (code == INTEGER_TYPE)
11396     return INTEGRAL_TYPE_P (TREE_TYPE (arg));
11397   return code == TREE_CODE (TREE_TYPE (arg));
11398 }
11399
11400 /* This function validates the types of a function call argument list
11401    against a specified list of tree_codes.  If the last specifier is a 0,
11402    that represents an ellipses, otherwise the last specifier must be a
11403    VOID_TYPE.
11404
11405    This is the GIMPLE version of validate_arglist.  Eventually we want to
11406    completely convert builtins.c to work from GIMPLEs and the tree based
11407    validate_arglist will then be removed.  */
11408
11409 bool
11410 validate_gimple_arglist (const_gimple call, ...)
11411 {
11412   enum tree_code code;
11413   bool res = 0;
11414   va_list ap;
11415   const_tree arg;
11416   size_t i;
11417
11418   va_start (ap, call);
11419   i = 0;
11420
11421   do
11422     {
11423       code = (enum tree_code) va_arg (ap, int);
11424       switch (code)
11425         {
11426         case 0:
11427           /* This signifies an ellipses, any further arguments are all ok.  */
11428           res = true;
11429           goto end;
11430         case VOID_TYPE:
11431           /* This signifies an endlink, if no arguments remain, return
11432              true, otherwise return false.  */
11433           res = (i == gimple_call_num_args (call));
11434           goto end;
11435         default:
11436           /* If no parameters remain or the parameter's code does not
11437              match the specified code, return false.  Otherwise continue
11438              checking any remaining arguments.  */
11439           arg = gimple_call_arg (call, i++);
11440           if (!validate_arg (arg, code))
11441             goto end;
11442           break;
11443         }
11444     }
11445   while (1);
11446
11447   /* We need gotos here since we can only have one VA_CLOSE in a
11448      function.  */
11449  end: ;
11450   va_end (ap);
11451
11452   return res;
11453 }
11454
11455 /* This function validates the types of a function call argument list
11456    against a specified list of tree_codes.  If the last specifier is a 0,
11457    that represents an ellipses, otherwise the last specifier must be a
11458    VOID_TYPE.  */
11459
11460 bool
11461 validate_arglist (const_tree callexpr, ...)
11462 {
11463   enum tree_code code;
11464   bool res = 0;
11465   va_list ap;
11466   const_call_expr_arg_iterator iter;
11467   const_tree arg;
11468
11469   va_start (ap, callexpr);
11470   init_const_call_expr_arg_iterator (callexpr, &iter);
11471
11472   do
11473     {
11474       code = (enum tree_code) va_arg (ap, int);
11475       switch (code)
11476         {
11477         case 0:
11478           /* This signifies an ellipses, any further arguments are all ok.  */
11479           res = true;
11480           goto end;
11481         case VOID_TYPE:
11482           /* This signifies an endlink, if no arguments remain, return
11483              true, otherwise return false.  */
11484           res = !more_const_call_expr_args_p (&iter);
11485           goto end;
11486         default:
11487           /* If no parameters remain or the parameter's code does not
11488              match the specified code, return false.  Otherwise continue
11489              checking any remaining arguments.  */
11490           arg = next_const_call_expr_arg (&iter);
11491           if (!validate_arg (arg, code))
11492             goto end;
11493           break;
11494         }
11495     }
11496   while (1);
11497
11498   /* We need gotos here since we can only have one VA_CLOSE in a
11499      function.  */
11500  end: ;
11501   va_end (ap);
11502
11503   return res;
11504 }
11505
11506 /* Default target-specific builtin expander that does nothing.  */
11507
11508 rtx
11509 default_expand_builtin (tree exp ATTRIBUTE_UNUSED,
11510                         rtx target ATTRIBUTE_UNUSED,
11511                         rtx subtarget ATTRIBUTE_UNUSED,
11512                         enum machine_mode mode ATTRIBUTE_UNUSED,
11513                         int ignore ATTRIBUTE_UNUSED)
11514 {
11515   return NULL_RTX;
11516 }
11517
11518 /* Returns true is EXP represents data that would potentially reside
11519    in a readonly section.  */
11520
11521 static bool
11522 readonly_data_expr (tree exp)
11523 {
11524   STRIP_NOPS (exp);
11525
11526   if (TREE_CODE (exp) != ADDR_EXPR)
11527     return false;
11528
11529   exp = get_base_address (TREE_OPERAND (exp, 0));
11530   if (!exp)
11531     return false;
11532
11533   /* Make sure we call decl_readonly_section only for trees it
11534      can handle (since it returns true for everything it doesn't
11535      understand).  */
11536   if (TREE_CODE (exp) == STRING_CST
11537       || TREE_CODE (exp) == CONSTRUCTOR
11538       || (TREE_CODE (exp) == VAR_DECL && TREE_STATIC (exp)))
11539     return decl_readonly_section (exp, 0);
11540   else
11541     return false;
11542 }
11543
11544 /* Simplify a call to the strstr builtin.  S1 and S2 are the arguments
11545    to the call, and TYPE is its return type.
11546
11547    Return NULL_TREE if no simplification was possible, otherwise return the
11548    simplified form of the call as a tree.
11549
11550    The simplified form may be a constant or other expression which
11551    computes the same value, but in a more efficient manner (including
11552    calls to other builtin functions).
11553
11554    The call may contain arguments which need to be evaluated, but
11555    which are not useful to determine the result of the call.  In
11556    this case we return a chain of COMPOUND_EXPRs.  The LHS of each
11557    COMPOUND_EXPR will be an argument which must be evaluated.
11558    COMPOUND_EXPRs are chained through their RHS.  The RHS of the last
11559    COMPOUND_EXPR in the chain will contain the tree for the simplified
11560    form of the builtin function call.  */
11561
11562 static tree
11563 fold_builtin_strstr (location_t loc, tree s1, tree s2, tree type)
11564 {
11565   if (!validate_arg (s1, POINTER_TYPE)
11566       || !validate_arg (s2, POINTER_TYPE))
11567     return NULL_TREE;
11568   else
11569     {
11570       tree fn;
11571       const char *p1, *p2;
11572
11573       p2 = c_getstr (s2);
11574       if (p2 == NULL)
11575         return NULL_TREE;
11576
11577       p1 = c_getstr (s1);
11578       if (p1 != NULL)
11579         {
11580           const char *r = strstr (p1, p2);
11581           tree tem;
11582
11583           if (r == NULL)
11584             return build_int_cst (TREE_TYPE (s1), 0);
11585
11586           /* Return an offset into the constant string argument.  */
11587           tem = fold_build_pointer_plus_hwi_loc (loc, s1, r - p1);
11588           return fold_convert_loc (loc, type, tem);
11589         }
11590
11591       /* The argument is const char *, and the result is char *, so we need
11592          a type conversion here to avoid a warning.  */
11593       if (p2[0] == '\0')
11594         return fold_convert_loc (loc, type, s1);
11595
11596       if (p2[1] != '\0')
11597         return NULL_TREE;
11598
11599       fn = builtin_decl_implicit (BUILT_IN_STRCHR);
11600       if (!fn)
11601         return NULL_TREE;
11602
11603       /* New argument list transforming strstr(s1, s2) to
11604          strchr(s1, s2[0]).  */
11605       return build_call_expr_loc (loc, fn, 2, s1,
11606                                   build_int_cst (integer_type_node, p2[0]));
11607     }
11608 }
11609
11610 /* Simplify a call to the strchr builtin.  S1 and S2 are the arguments to
11611    the call, and TYPE is its return type.
11612
11613    Return NULL_TREE if no simplification was possible, otherwise return the
11614    simplified form of the call as a tree.
11615
11616    The simplified form may be a constant or other expression which
11617    computes the same value, but in a more efficient manner (including
11618    calls to other builtin functions).
11619
11620    The call may contain arguments which need to be evaluated, but
11621    which are not useful to determine the result of the call.  In
11622    this case we return a chain of COMPOUND_EXPRs.  The LHS of each
11623    COMPOUND_EXPR will be an argument which must be evaluated.
11624    COMPOUND_EXPRs are chained through their RHS.  The RHS of the last
11625    COMPOUND_EXPR in the chain will contain the tree for the simplified
11626    form of the builtin function call.  */
11627
11628 static tree
11629 fold_builtin_strchr (location_t loc, tree s1, tree s2, tree type)
11630 {
11631   if (!validate_arg (s1, POINTER_TYPE)
11632       || !validate_arg (s2, INTEGER_TYPE))
11633     return NULL_TREE;
11634   else
11635     {
11636       const char *p1;
11637
11638       if (TREE_CODE (s2) != INTEGER_CST)
11639         return NULL_TREE;
11640
11641       p1 = c_getstr (s1);
11642       if (p1 != NULL)
11643         {
11644           char c;
11645           const char *r;
11646           tree tem;
11647
11648           if (target_char_cast (s2, &c))
11649             return NULL_TREE;
11650
11651           r = strchr (p1, c);
11652
11653           if (r == NULL)
11654             return build_int_cst (TREE_TYPE (s1), 0);
11655
11656           /* Return an offset into the constant string argument.  */
11657           tem = fold_build_pointer_plus_hwi_loc (loc, s1, r - p1);
11658           return fold_convert_loc (loc, type, tem);
11659         }
11660       return NULL_TREE;
11661     }
11662 }
11663
11664 /* Simplify a call to the strrchr builtin.  S1 and S2 are the arguments to
11665    the call, and TYPE is its return type.
11666
11667    Return NULL_TREE if no simplification was possible, otherwise return the
11668    simplified form of the call as a tree.
11669
11670    The simplified form may be a constant or other expression which
11671    computes the same value, but in a more efficient manner (including
11672    calls to other builtin functions).
11673
11674    The call may contain arguments which need to be evaluated, but
11675    which are not useful to determine the result of the call.  In
11676    this case we return a chain of COMPOUND_EXPRs.  The LHS of each
11677    COMPOUND_EXPR will be an argument which must be evaluated.
11678    COMPOUND_EXPRs are chained through their RHS.  The RHS of the last
11679    COMPOUND_EXPR in the chain will contain the tree for the simplified
11680    form of the builtin function call.  */
11681
11682 static tree
11683 fold_builtin_strrchr (location_t loc, tree s1, tree s2, tree type)
11684 {
11685   if (!validate_arg (s1, POINTER_TYPE)
11686       || !validate_arg (s2, INTEGER_TYPE))
11687     return NULL_TREE;
11688   else
11689     {
11690       tree fn;
11691       const char *p1;
11692
11693       if (TREE_CODE (s2) != INTEGER_CST)
11694         return NULL_TREE;
11695
11696       p1 = c_getstr (s1);
11697       if (p1 != NULL)
11698         {
11699           char c;
11700           const char *r;
11701           tree tem;
11702
11703           if (target_char_cast (s2, &c))
11704             return NULL_TREE;
11705
11706           r = strrchr (p1, c);
11707
11708           if (r == NULL)
11709             return build_int_cst (TREE_TYPE (s1), 0);
11710
11711           /* Return an offset into the constant string argument.  */
11712           tem = fold_build_pointer_plus_hwi_loc (loc, s1, r - p1);
11713           return fold_convert_loc (loc, type, tem);
11714         }
11715
11716       if (! integer_zerop (s2))
11717         return NULL_TREE;
11718
11719       fn = builtin_decl_implicit (BUILT_IN_STRCHR);
11720       if (!fn)
11721         return NULL_TREE;
11722
11723       /* Transform strrchr(s1, '\0') to strchr(s1, '\0').  */
11724       return build_call_expr_loc (loc, fn, 2, s1, s2);
11725     }
11726 }
11727
11728 /* Simplify a call to the strpbrk builtin.  S1 and S2 are the arguments
11729    to the call, and TYPE is its return type.
11730
11731    Return NULL_TREE if no simplification was possible, otherwise return the
11732    simplified form of the call as a tree.
11733
11734    The simplified form may be a constant or other expression which
11735    computes the same value, but in a more efficient manner (including
11736    calls to other builtin functions).
11737
11738    The call may contain arguments which need to be evaluated, but
11739    which are not useful to determine the result of the call.  In
11740    this case we return a chain of COMPOUND_EXPRs.  The LHS of each
11741    COMPOUND_EXPR will be an argument which must be evaluated.
11742    COMPOUND_EXPRs are chained through their RHS.  The RHS of the last
11743    COMPOUND_EXPR in the chain will contain the tree for the simplified
11744    form of the builtin function call.  */
11745
11746 static tree
11747 fold_builtin_strpbrk (location_t loc, tree s1, tree s2, tree type)
11748 {
11749   if (!validate_arg (s1, POINTER_TYPE)
11750       || !validate_arg (s2, POINTER_TYPE))
11751     return NULL_TREE;
11752   else
11753     {
11754       tree fn;
11755       const char *p1, *p2;
11756
11757       p2 = c_getstr (s2);
11758       if (p2 == NULL)
11759         return NULL_TREE;
11760
11761       p1 = c_getstr (s1);
11762       if (p1 != NULL)
11763         {
11764           const char *r = strpbrk (p1, p2);
11765           tree tem;
11766
11767           if (r == NULL)
11768             return build_int_cst (TREE_TYPE (s1), 0);
11769
11770           /* Return an offset into the constant string argument.  */
11771           tem = fold_build_pointer_plus_hwi_loc (loc, s1, r - p1);
11772           return fold_convert_loc (loc, type, tem);
11773         }
11774
11775       if (p2[0] == '\0')
11776         /* strpbrk(x, "") == NULL.
11777            Evaluate and ignore s1 in case it had side-effects.  */
11778         return omit_one_operand_loc (loc, TREE_TYPE (s1), integer_zero_node, s1);
11779
11780       if (p2[1] != '\0')
11781         return NULL_TREE;  /* Really call strpbrk.  */
11782
11783       fn = builtin_decl_implicit (BUILT_IN_STRCHR);
11784       if (!fn)
11785         return NULL_TREE;
11786
11787       /* New argument list transforming strpbrk(s1, s2) to
11788          strchr(s1, s2[0]).  */
11789       return build_call_expr_loc (loc, fn, 2, s1,
11790                                   build_int_cst (integer_type_node, p2[0]));
11791     }
11792 }
11793
11794 /* Simplify a call to the strcat builtin.  DST and SRC are the arguments
11795    to the call.
11796
11797    Return NULL_TREE if no simplification was possible, otherwise return the
11798    simplified form of the call as a tree.
11799
11800    The simplified form may be a constant or other expression which
11801    computes the same value, but in a more efficient manner (including
11802    calls to other builtin functions).
11803
11804    The call may contain arguments which need to be evaluated, but
11805    which are not useful to determine the result of the call.  In
11806    this case we return a chain of COMPOUND_EXPRs.  The LHS of each
11807    COMPOUND_EXPR will be an argument which must be evaluated.
11808    COMPOUND_EXPRs are chained through their RHS.  The RHS of the last
11809    COMPOUND_EXPR in the chain will contain the tree for the simplified
11810    form of the builtin function call.  */
11811
11812 static tree
11813 fold_builtin_strcat (location_t loc ATTRIBUTE_UNUSED, tree dst, tree src)
11814 {
11815   if (!validate_arg (dst, POINTER_TYPE)
11816       || !validate_arg (src, POINTER_TYPE))
11817     return NULL_TREE;
11818   else
11819     {
11820       const char *p = c_getstr (src);
11821
11822       /* If the string length is zero, return the dst parameter.  */
11823       if (p && *p == '\0')
11824         return dst;
11825
11826       if (optimize_insn_for_speed_p ())
11827         {
11828           /* See if we can store by pieces into (dst + strlen(dst)).  */
11829           tree newdst, call;
11830           tree strlen_fn = builtin_decl_implicit (BUILT_IN_STRLEN);
11831           tree strcpy_fn = builtin_decl_implicit (BUILT_IN_STRCPY);
11832
11833           if (!strlen_fn || !strcpy_fn)
11834             return NULL_TREE;
11835
11836           /* If we don't have a movstr we don't want to emit an strcpy
11837              call.  We have to do that if the length of the source string
11838              isn't computable (in that case we can use memcpy probably
11839              later expanding to a sequence of mov instructions).  If we
11840              have movstr instructions we can emit strcpy calls.  */
11841           if (!HAVE_movstr)
11842             {
11843               tree len = c_strlen (src, 1);
11844               if (! len || TREE_SIDE_EFFECTS (len))
11845                 return NULL_TREE;
11846             }
11847
11848           /* Stabilize the argument list.  */
11849           dst = builtin_save_expr (dst);
11850
11851           /* Create strlen (dst).  */
11852           newdst = build_call_expr_loc (loc, strlen_fn, 1, dst);
11853           /* Create (dst p+ strlen (dst)).  */
11854
11855           newdst = fold_build_pointer_plus_loc (loc, dst, newdst);
11856           newdst = builtin_save_expr (newdst);
11857
11858           call = build_call_expr_loc (loc, strcpy_fn, 2, newdst, src);
11859           return build2 (COMPOUND_EXPR, TREE_TYPE (dst), call, dst);
11860         }
11861       return NULL_TREE;
11862     }
11863 }
11864
11865 /* Simplify a call to the strncat builtin.  DST, SRC, and LEN are the
11866    arguments to the call.
11867
11868    Return NULL_TREE if no simplification was possible, otherwise return the
11869    simplified form of the call as a tree.
11870
11871    The simplified form may be a constant or other expression which
11872    computes the same value, but in a more efficient manner (including
11873    calls to other builtin functions).
11874
11875    The call may contain arguments which need to be evaluated, but
11876    which are not useful to determine the result of the call.  In
11877    this case we return a chain of COMPOUND_EXPRs.  The LHS of each
11878    COMPOUND_EXPR will be an argument which must be evaluated.
11879    COMPOUND_EXPRs are chained through their RHS.  The RHS of the last
11880    COMPOUND_EXPR in the chain will contain the tree for the simplified
11881    form of the builtin function call.  */
11882
11883 static tree
11884 fold_builtin_strncat (location_t loc, tree dst, tree src, tree len)
11885 {
11886   if (!validate_arg (dst, POINTER_TYPE)
11887       || !validate_arg (src, POINTER_TYPE)
11888       || !validate_arg (len, INTEGER_TYPE))
11889     return NULL_TREE;
11890   else
11891     {
11892       const char *p = c_getstr (src);
11893
11894       /* If the requested length is zero, or the src parameter string
11895          length is zero, return the dst parameter.  */
11896       if (integer_zerop (len) || (p && *p == '\0'))
11897         return omit_two_operands_loc (loc, TREE_TYPE (dst), dst, src, len);
11898
11899       /* If the requested len is greater than or equal to the string
11900          length, call strcat.  */
11901       if (TREE_CODE (len) == INTEGER_CST && p
11902           && compare_tree_int (len, strlen (p)) >= 0)
11903         {
11904           tree fn = builtin_decl_implicit (BUILT_IN_STRCAT);
11905
11906           /* If the replacement _DECL isn't initialized, don't do the
11907              transformation.  */
11908           if (!fn)
11909             return NULL_TREE;
11910
11911           return build_call_expr_loc (loc, fn, 2, dst, src);
11912         }
11913       return NULL_TREE;
11914     }
11915 }
11916
11917 /* Simplify a call to the strspn builtin.  S1 and S2 are the arguments
11918    to the call.
11919
11920    Return NULL_TREE if no simplification was possible, otherwise return the
11921    simplified form of the call as a tree.
11922
11923    The simplified form may be a constant or other expression which
11924    computes the same value, but in a more efficient manner (including
11925    calls to other builtin functions).
11926
11927    The call may contain arguments which need to be evaluated, but
11928    which are not useful to determine the result of the call.  In
11929    this case we return a chain of COMPOUND_EXPRs.  The LHS of each
11930    COMPOUND_EXPR will be an argument which must be evaluated.
11931    COMPOUND_EXPRs are chained through their RHS.  The RHS of the last
11932    COMPOUND_EXPR in the chain will contain the tree for the simplified
11933    form of the builtin function call.  */
11934
11935 static tree
11936 fold_builtin_strspn (location_t loc, tree s1, tree s2)
11937 {
11938   if (!validate_arg (s1, POINTER_TYPE)
11939       || !validate_arg (s2, POINTER_TYPE))
11940     return NULL_TREE;
11941   else
11942     {
11943       const char *p1 = c_getstr (s1), *p2 = c_getstr (s2);
11944
11945       /* If both arguments are constants, evaluate at compile-time.  */
11946       if (p1 && p2)
11947         {
11948           const size_t r = strspn (p1, p2);
11949           return build_int_cst (size_type_node, r);
11950         }
11951
11952       /* If either argument is "", return NULL_TREE.  */
11953       if ((p1 && *p1 == '\0') || (p2 && *p2 == '\0'))
11954         /* Evaluate and ignore both arguments in case either one has
11955            side-effects.  */
11956         return omit_two_operands_loc (loc, size_type_node, size_zero_node,
11957                                   s1, s2);
11958       return NULL_TREE;
11959     }
11960 }
11961
11962 /* Simplify a call to the strcspn builtin.  S1 and S2 are the arguments
11963    to the call.
11964
11965    Return NULL_TREE if no simplification was possible, otherwise return the
11966    simplified form of the call as a tree.
11967
11968    The simplified form may be a constant or other expression which
11969    computes the same value, but in a more efficient manner (including
11970    calls to other builtin functions).
11971
11972    The call may contain arguments which need to be evaluated, but
11973    which are not useful to determine the result of the call.  In
11974    this case we return a chain of COMPOUND_EXPRs.  The LHS of each
11975    COMPOUND_EXPR will be an argument which must be evaluated.
11976    COMPOUND_EXPRs are chained through their RHS.  The RHS of the last
11977    COMPOUND_EXPR in the chain will contain the tree for the simplified
11978    form of the builtin function call.  */
11979
11980 static tree
11981 fold_builtin_strcspn (location_t loc, tree s1, tree s2)
11982 {
11983   if (!validate_arg (s1, POINTER_TYPE)
11984       || !validate_arg (s2, POINTER_TYPE))
11985     return NULL_TREE;
11986   else
11987     {
11988       const char *p1 = c_getstr (s1), *p2 = c_getstr (s2);
11989
11990       /* If both arguments are constants, evaluate at compile-time.  */
11991       if (p1 && p2)
11992         {
11993           const size_t r = strcspn (p1, p2);
11994           return build_int_cst (size_type_node, r);
11995         }
11996
11997       /* If the first argument is "", return NULL_TREE.  */
11998       if (p1 && *p1 == '\0')
11999         {
12000           /* Evaluate and ignore argument s2 in case it has
12001              side-effects.  */
12002           return omit_one_operand_loc (loc, size_type_node,
12003                                    size_zero_node, s2);
12004         }
12005
12006       /* If the second argument is "", return __builtin_strlen(s1).  */
12007       if (p2 && *p2 == '\0')
12008         {
12009           tree fn = builtin_decl_implicit (BUILT_IN_STRLEN);
12010
12011           /* If the replacement _DECL isn't initialized, don't do the
12012              transformation.  */
12013           if (!fn)
12014             return NULL_TREE;
12015
12016           return build_call_expr_loc (loc, fn, 1, s1);
12017         }
12018       return NULL_TREE;
12019     }
12020 }
12021
12022 /* Fold a call to the fputs builtin.  ARG0 and ARG1 are the arguments
12023    to the call.  IGNORE is true if the value returned
12024    by the builtin will be ignored.  UNLOCKED is true is true if this
12025    actually a call to fputs_unlocked.  If LEN in non-NULL, it represents
12026    the known length of the string.  Return NULL_TREE if no simplification
12027    was possible.  */
12028
12029 tree
12030 fold_builtin_fputs (location_t loc, tree arg0, tree arg1,
12031                     bool ignore, bool unlocked, tree len)
12032 {
12033   /* If we're using an unlocked function, assume the other unlocked
12034      functions exist explicitly.  */
12035   tree const fn_fputc = (unlocked
12036                          ? builtin_decl_explicit (BUILT_IN_FPUTC_UNLOCKED)
12037                          : builtin_decl_implicit (BUILT_IN_FPUTC));
12038   tree const fn_fwrite = (unlocked
12039                           ? builtin_decl_explicit (BUILT_IN_FWRITE_UNLOCKED)
12040                           : builtin_decl_implicit (BUILT_IN_FWRITE));
12041
12042   /* If the return value is used, don't do the transformation.  */
12043   if (!ignore)
12044     return NULL_TREE;
12045
12046   /* Verify the arguments in the original call.  */
12047   if (!validate_arg (arg0, POINTER_TYPE)
12048       || !validate_arg (arg1, POINTER_TYPE))
12049     return NULL_TREE;
12050
12051   if (! len)
12052     len = c_strlen (arg0, 0);
12053
12054   /* Get the length of the string passed to fputs.  If the length
12055      can't be determined, punt.  */
12056   if (!len
12057       || TREE_CODE (len) != INTEGER_CST)
12058     return NULL_TREE;
12059
12060   switch (compare_tree_int (len, 1))
12061     {
12062     case -1: /* length is 0, delete the call entirely .  */
12063       return omit_one_operand_loc (loc, integer_type_node,
12064                                integer_zero_node, arg1);;
12065
12066     case 0: /* length is 1, call fputc.  */
12067       {
12068         const char *p = c_getstr (arg0);
12069
12070         if (p != NULL)
12071           {
12072             if (fn_fputc)
12073               return build_call_expr_loc (loc, fn_fputc, 2,
12074                                           build_int_cst
12075                                             (integer_type_node, p[0]), arg1);
12076             else
12077               return NULL_TREE;
12078           }
12079       }
12080       /* FALLTHROUGH */
12081     case 1: /* length is greater than 1, call fwrite.  */
12082       {
12083         /* If optimizing for size keep fputs.  */
12084         if (optimize_function_for_size_p (cfun))
12085           return NULL_TREE;
12086         /* New argument list transforming fputs(string, stream) to
12087            fwrite(string, 1, len, stream).  */
12088         if (fn_fwrite)
12089           return build_call_expr_loc (loc, fn_fwrite, 4, arg0,
12090                                   size_one_node, len, arg1);
12091         else
12092           return NULL_TREE;
12093       }
12094     default:
12095       gcc_unreachable ();
12096     }
12097   return NULL_TREE;
12098 }
12099
12100 /* Fold the next_arg or va_start call EXP. Returns true if there was an error
12101    produced.  False otherwise.  This is done so that we don't output the error
12102    or warning twice or three times.  */
12103
12104 bool
12105 fold_builtin_next_arg (tree exp, bool va_start_p)
12106 {
12107   tree fntype = TREE_TYPE (current_function_decl);
12108   int nargs = call_expr_nargs (exp);
12109   tree arg;
12110   /* There is good chance the current input_location points inside the
12111      definition of the va_start macro (perhaps on the token for
12112      builtin) in a system header, so warnings will not be emitted.
12113      Use the location in real source code.  */
12114   source_location current_location =
12115     linemap_unwind_to_first_non_reserved_loc (line_table, input_location,
12116                                               NULL);
12117
12118   if (!stdarg_p (fntype))
12119     {
12120       error ("%<va_start%> used in function with fixed args");
12121       return true;
12122     }
12123
12124   if (va_start_p)
12125     {
12126       if (va_start_p && (nargs != 2))
12127         {
12128           error ("wrong number of arguments to function %<va_start%>");
12129           return true;
12130         }
12131       arg = CALL_EXPR_ARG (exp, 1);
12132     }
12133   /* We use __builtin_va_start (ap, 0, 0) or __builtin_next_arg (0, 0)
12134      when we checked the arguments and if needed issued a warning.  */
12135   else
12136     {
12137       if (nargs == 0)
12138         {
12139           /* Evidently an out of date version of <stdarg.h>; can't validate
12140              va_start's second argument, but can still work as intended.  */
12141           warning_at (current_location,
12142                       OPT_Wvarargs,
12143                    "%<__builtin_next_arg%> called without an argument");
12144           return true;
12145         }
12146       else if (nargs > 1)
12147         {
12148           error ("wrong number of arguments to function %<__builtin_next_arg%>");
12149           return true;
12150         }
12151       arg = CALL_EXPR_ARG (exp, 0);
12152     }
12153
12154   if (TREE_CODE (arg) == SSA_NAME)
12155     arg = SSA_NAME_VAR (arg);
12156
12157   /* We destructively modify the call to be __builtin_va_start (ap, 0)
12158      or __builtin_next_arg (0) the first time we see it, after checking
12159      the arguments and if needed issuing a warning.  */
12160   if (!integer_zerop (arg))
12161     {
12162       tree last_parm = tree_last (DECL_ARGUMENTS (current_function_decl));
12163
12164       /* Strip off all nops for the sake of the comparison.  This
12165          is not quite the same as STRIP_NOPS.  It does more.
12166          We must also strip off INDIRECT_EXPR for C++ reference
12167          parameters.  */
12168       while (CONVERT_EXPR_P (arg)
12169              || TREE_CODE (arg) == INDIRECT_REF)
12170         arg = TREE_OPERAND (arg, 0);
12171       if (arg != last_parm)
12172         {
12173           /* FIXME: Sometimes with the tree optimizers we can get the
12174              not the last argument even though the user used the last
12175              argument.  We just warn and set the arg to be the last
12176              argument so that we will get wrong-code because of
12177              it.  */
12178           warning_at (current_location,
12179                       OPT_Wvarargs,
12180                       "second parameter of %<va_start%> not last named argument");
12181         }
12182
12183       /* Undefined by C99 7.15.1.4p4 (va_start):
12184          "If the parameter parmN is declared with the register storage
12185          class, with a function or array type, or with a type that is
12186          not compatible with the type that results after application of
12187          the default argument promotions, the behavior is undefined."
12188       */
12189       else if (DECL_REGISTER (arg))
12190         {
12191           warning_at (current_location,
12192                       OPT_Wvarargs,
12193                       "undefined behaviour when second parameter of "
12194                       "%<va_start%> is declared with %<register%> storage");
12195         }
12196
12197       /* We want to verify the second parameter just once before the tree
12198          optimizers are run and then avoid keeping it in the tree,
12199          as otherwise we could warn even for correct code like:
12200          void foo (int i, ...)
12201          { va_list ap; i++; va_start (ap, i); va_end (ap); }  */
12202       if (va_start_p)
12203         CALL_EXPR_ARG (exp, 1) = integer_zero_node;
12204       else
12205         CALL_EXPR_ARG (exp, 0) = integer_zero_node;
12206     }
12207   return false;
12208 }
12209
12210
12211 /* Simplify a call to the sprintf builtin with arguments DEST, FMT, and ORIG.
12212    ORIG may be null if this is a 2-argument call.  We don't attempt to
12213    simplify calls with more than 3 arguments.
12214
12215    Return NULL_TREE if no simplification was possible, otherwise return the
12216    simplified form of the call as a tree.  If IGNORED is true, it means that
12217    the caller does not use the returned value of the function.  */
12218
12219 static tree
12220 fold_builtin_sprintf (location_t loc, tree dest, tree fmt,
12221                       tree orig, int ignored)
12222 {
12223   tree call, retval;
12224   const char *fmt_str = NULL;
12225
12226   /* Verify the required arguments in the original call.  We deal with two
12227      types of sprintf() calls: 'sprintf (str, fmt)' and
12228      'sprintf (dest, "%s", orig)'.  */
12229   if (!validate_arg (dest, POINTER_TYPE)
12230       || !validate_arg (fmt, POINTER_TYPE))
12231     return NULL_TREE;
12232   if (orig && !validate_arg (orig, POINTER_TYPE))
12233     return NULL_TREE;
12234
12235   /* Check whether the format is a literal string constant.  */
12236   fmt_str = c_getstr (fmt);
12237   if (fmt_str == NULL)
12238     return NULL_TREE;
12239
12240   call = NULL_TREE;
12241   retval = NULL_TREE;
12242
12243   if (!init_target_chars ())
12244     return NULL_TREE;
12245
12246   /* If the format doesn't contain % args or %%, use strcpy.  */
12247   if (strchr (fmt_str, target_percent) == NULL)
12248     {
12249       tree fn = builtin_decl_implicit (BUILT_IN_STRCPY);
12250
12251       if (!fn)
12252         return NULL_TREE;
12253
12254       /* Don't optimize sprintf (buf, "abc", ptr++).  */
12255       if (orig)
12256         return NULL_TREE;
12257
12258       /* Convert sprintf (str, fmt) into strcpy (str, fmt) when
12259          'format' is known to contain no % formats.  */
12260       call = build_call_expr_loc (loc, fn, 2, dest, fmt);
12261       if (!ignored)
12262         retval = build_int_cst (integer_type_node, strlen (fmt_str));
12263     }
12264
12265   /* If the format is "%s", use strcpy if the result isn't used.  */
12266   else if (fmt_str && strcmp (fmt_str, target_percent_s) == 0)
12267     {
12268       tree fn;
12269       fn = builtin_decl_implicit (BUILT_IN_STRCPY);
12270
12271       if (!fn)
12272         return NULL_TREE;
12273
12274       /* Don't crash on sprintf (str1, "%s").  */
12275       if (!orig)
12276         return NULL_TREE;
12277
12278       /* Convert sprintf (str1, "%s", str2) into strcpy (str1, str2).  */
12279       if (!ignored)
12280         {
12281           retval = c_strlen (orig, 1);
12282           if (!retval || TREE_CODE (retval) != INTEGER_CST)
12283             return NULL_TREE;
12284         }
12285       call = build_call_expr_loc (loc, fn, 2, dest, orig);
12286     }
12287
12288   if (call && retval)
12289     {
12290       retval = fold_convert_loc
12291         (loc, TREE_TYPE (TREE_TYPE (builtin_decl_implicit (BUILT_IN_SPRINTF))),
12292          retval);
12293       return build2 (COMPOUND_EXPR, TREE_TYPE (retval), call, retval);
12294     }
12295   else
12296     return call;
12297 }
12298
12299 /* Simplify a call to the snprintf builtin with arguments DEST, DESTSIZE,
12300    FMT, and ORIG.  ORIG may be null if this is a 3-argument call.  We don't
12301    attempt to simplify calls with more than 4 arguments.
12302
12303    Return NULL_TREE if no simplification was possible, otherwise return the
12304    simplified form of the call as a tree.  If IGNORED is true, it means that
12305    the caller does not use the returned value of the function.  */
12306
12307 static tree
12308 fold_builtin_snprintf (location_t loc, tree dest, tree destsize, tree fmt,
12309                        tree orig, int ignored)
12310 {
12311   tree call, retval;
12312   const char *fmt_str = NULL;
12313   unsigned HOST_WIDE_INT destlen;
12314
12315   /* Verify the required arguments in the original call.  We deal with two
12316      types of snprintf() calls: 'snprintf (str, cst, fmt)' and
12317      'snprintf (dest, cst, "%s", orig)'.  */
12318   if (!validate_arg (dest, POINTER_TYPE)
12319       || !validate_arg (destsize, INTEGER_TYPE)
12320       || !validate_arg (fmt, POINTER_TYPE))
12321     return NULL_TREE;
12322   if (orig && !validate_arg (orig, POINTER_TYPE))
12323     return NULL_TREE;
12324
12325   if (!host_integerp (destsize, 1))
12326     return NULL_TREE;
12327
12328   /* Check whether the format is a literal string constant.  */
12329   fmt_str = c_getstr (fmt);
12330   if (fmt_str == NULL)
12331     return NULL_TREE;
12332
12333   call = NULL_TREE;
12334   retval = NULL_TREE;
12335
12336   if (!init_target_chars ())
12337     return NULL_TREE;
12338
12339   destlen = tree_low_cst (destsize, 1);
12340
12341   /* If the format doesn't contain % args or %%, use strcpy.  */
12342   if (strchr (fmt_str, target_percent) == NULL)
12343     {
12344       tree fn = builtin_decl_implicit (BUILT_IN_STRCPY);
12345       size_t len = strlen (fmt_str);
12346
12347       /* Don't optimize snprintf (buf, 4, "abc", ptr++).  */
12348       if (orig)
12349         return NULL_TREE;
12350
12351       /* We could expand this as
12352          memcpy (str, fmt, cst - 1); str[cst - 1] = '\0';
12353          or to
12354          memcpy (str, fmt_with_nul_at_cstm1, cst);
12355          but in the former case that might increase code size
12356          and in the latter case grow .rodata section too much.
12357          So punt for now.  */
12358       if (len >= destlen)
12359         return NULL_TREE;
12360
12361       if (!fn)
12362         return NULL_TREE;
12363
12364       /* Convert snprintf (str, cst, fmt) into strcpy (str, fmt) when
12365          'format' is known to contain no % formats and
12366          strlen (fmt) < cst.  */
12367       call = build_call_expr_loc (loc, fn, 2, dest, fmt);
12368
12369       if (!ignored)
12370         retval = build_int_cst (integer_type_node, strlen (fmt_str));
12371     }
12372
12373   /* If the format is "%s", use strcpy if the result isn't used.  */
12374   else if (fmt_str && strcmp (fmt_str, target_percent_s) == 0)
12375     {
12376       tree fn = builtin_decl_implicit (BUILT_IN_STRCPY);
12377       unsigned HOST_WIDE_INT origlen;
12378
12379       /* Don't crash on snprintf (str1, cst, "%s").  */
12380       if (!orig)
12381         return NULL_TREE;
12382
12383       retval = c_strlen (orig, 1);
12384       if (!retval || !host_integerp (retval, 1))  
12385         return NULL_TREE;
12386
12387       origlen = tree_low_cst (retval, 1);
12388       /* We could expand this as
12389          memcpy (str1, str2, cst - 1); str1[cst - 1] = '\0';
12390          or to
12391          memcpy (str1, str2_with_nul_at_cstm1, cst);
12392          but in the former case that might increase code size
12393          and in the latter case grow .rodata section too much.
12394          So punt for now.  */
12395       if (origlen >= destlen)
12396         return NULL_TREE;
12397
12398       /* Convert snprintf (str1, cst, "%s", str2) into
12399          strcpy (str1, str2) if strlen (str2) < cst.  */
12400       if (!fn)
12401         return NULL_TREE;
12402
12403       call = build_call_expr_loc (loc, fn, 2, dest, orig);
12404
12405       if (ignored)
12406         retval = NULL_TREE;
12407     }
12408
12409   if (call && retval)
12410     {
12411       tree fn = builtin_decl_explicit (BUILT_IN_SNPRINTF);
12412       retval = fold_convert_loc (loc, TREE_TYPE (TREE_TYPE (fn)), retval);
12413       return build2 (COMPOUND_EXPR, TREE_TYPE (retval), call, retval);
12414     }
12415   else
12416     return call;
12417 }
12418
12419 /* Expand a call EXP to __builtin_object_size.  */
12420
12421 rtx
12422 expand_builtin_object_size (tree exp)
12423 {
12424   tree ost;
12425   int object_size_type;
12426   tree fndecl = get_callee_fndecl (exp);
12427
12428   if (!validate_arglist (exp, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
12429     {
12430       error ("%Kfirst argument of %D must be a pointer, second integer constant",
12431              exp, fndecl);
12432       expand_builtin_trap ();
12433       return const0_rtx;
12434     }
12435
12436   ost = CALL_EXPR_ARG (exp, 1);
12437   STRIP_NOPS (ost);
12438
12439   if (TREE_CODE (ost) != INTEGER_CST
12440       || tree_int_cst_sgn (ost) < 0
12441       || compare_tree_int (ost, 3) > 0)
12442     {
12443       error ("%Klast argument of %D is not integer constant between 0 and 3",
12444              exp, fndecl);
12445       expand_builtin_trap ();
12446       return const0_rtx;
12447     }
12448
12449   object_size_type = tree_low_cst (ost, 0);
12450
12451   return object_size_type < 2 ? constm1_rtx : const0_rtx;
12452 }
12453
12454 /* Expand EXP, a call to the __mem{cpy,pcpy,move,set}_chk builtin.
12455    FCODE is the BUILT_IN_* to use.
12456    Return NULL_RTX if we failed; the caller should emit a normal call,
12457    otherwise try to get the result in TARGET, if convenient (and in
12458    mode MODE if that's convenient).  */
12459
12460 static rtx
12461 expand_builtin_memory_chk (tree exp, rtx target, enum machine_mode mode,
12462                            enum built_in_function fcode)
12463 {
12464   tree dest, src, len, size;
12465
12466   if (!validate_arglist (exp,
12467                          POINTER_TYPE,
12468                          fcode == BUILT_IN_MEMSET_CHK
12469                          ? INTEGER_TYPE : POINTER_TYPE,
12470                          INTEGER_TYPE, INTEGER_TYPE, VOID_TYPE))
12471     return NULL_RTX;
12472
12473   dest = CALL_EXPR_ARG (exp, 0);
12474   src = CALL_EXPR_ARG (exp, 1);
12475   len = CALL_EXPR_ARG (exp, 2);
12476   size = CALL_EXPR_ARG (exp, 3);
12477
12478   if (! host_integerp (size, 1))
12479     return NULL_RTX;
12480
12481   if (host_integerp (len, 1) || integer_all_onesp (size))
12482     {
12483       tree fn;
12484
12485       if (! integer_all_onesp (size) && tree_int_cst_lt (size, len))
12486         {
12487           warning_at (tree_nonartificial_location (exp),
12488                       0, "%Kcall to %D will always overflow destination buffer",
12489                       exp, get_callee_fndecl (exp));
12490           return NULL_RTX;
12491         }
12492
12493       fn = NULL_TREE;
12494       /* If __builtin_mem{cpy,pcpy,move,set}_chk is used, assume
12495          mem{cpy,pcpy,move,set} is available.  */
12496       switch (fcode)
12497         {
12498         case BUILT_IN_MEMCPY_CHK:
12499           fn = builtin_decl_explicit (BUILT_IN_MEMCPY);
12500           break;
12501         case BUILT_IN_MEMPCPY_CHK:
12502           fn = builtin_decl_explicit (BUILT_IN_MEMPCPY);
12503           break;
12504         case BUILT_IN_MEMMOVE_CHK:
12505           fn = builtin_decl_explicit (BUILT_IN_MEMMOVE);
12506           break;
12507         case BUILT_IN_MEMSET_CHK:
12508           fn = builtin_decl_explicit (BUILT_IN_MEMSET);
12509           break;
12510         default:
12511           break;
12512         }
12513
12514       if (! fn)
12515         return NULL_RTX;
12516
12517       fn = build_call_nofold_loc (EXPR_LOCATION (exp), fn, 3, dest, src, len);
12518       gcc_assert (TREE_CODE (fn) == CALL_EXPR);
12519       CALL_EXPR_TAILCALL (fn) = CALL_EXPR_TAILCALL (exp);
12520       return expand_expr (fn, target, mode, EXPAND_NORMAL);
12521     }
12522   else if (fcode == BUILT_IN_MEMSET_CHK)
12523     return NULL_RTX;
12524   else
12525     {
12526       unsigned int dest_align = get_pointer_alignment (dest);
12527
12528       /* If DEST is not a pointer type, call the normal function.  */
12529       if (dest_align == 0)
12530         return NULL_RTX;
12531
12532       /* If SRC and DEST are the same (and not volatile), do nothing.  */
12533       if (operand_equal_p (src, dest, 0))
12534         {
12535           tree expr;
12536
12537           if (fcode != BUILT_IN_MEMPCPY_CHK)
12538             {
12539               /* Evaluate and ignore LEN in case it has side-effects.  */
12540               expand_expr (len, const0_rtx, VOIDmode, EXPAND_NORMAL);
12541               return expand_expr (dest, target, mode, EXPAND_NORMAL);
12542             }
12543
12544           expr = fold_build_pointer_plus (dest, len);
12545           return expand_expr (expr, target, mode, EXPAND_NORMAL);
12546         }
12547
12548       /* __memmove_chk special case.  */
12549       if (fcode == BUILT_IN_MEMMOVE_CHK)
12550         {
12551           unsigned int src_align = get_pointer_alignment (src);
12552
12553           if (src_align == 0)
12554             return NULL_RTX;
12555
12556           /* If src is categorized for a readonly section we can use
12557              normal __memcpy_chk.  */
12558           if (readonly_data_expr (src))
12559             {
12560               tree fn = builtin_decl_explicit (BUILT_IN_MEMCPY_CHK);
12561               if (!fn)
12562                 return NULL_RTX;
12563               fn = build_call_nofold_loc (EXPR_LOCATION (exp), fn, 4,
12564                                           dest, src, len, size);
12565               gcc_assert (TREE_CODE (fn) == CALL_EXPR);
12566               CALL_EXPR_TAILCALL (fn) = CALL_EXPR_TAILCALL (exp);
12567               return expand_expr (fn, target, mode, EXPAND_NORMAL);
12568             }
12569         }
12570       return NULL_RTX;
12571     }
12572 }
12573
12574 /* Emit warning if a buffer overflow is detected at compile time.  */
12575
12576 static void
12577 maybe_emit_chk_warning (tree exp, enum built_in_function fcode)
12578 {
12579   int is_strlen = 0;
12580   tree len, size;
12581   location_t loc = tree_nonartificial_location (exp);
12582
12583   switch (fcode)
12584     {
12585     case BUILT_IN_STRCPY_CHK:
12586     case BUILT_IN_STPCPY_CHK:
12587     /* For __strcat_chk the warning will be emitted only if overflowing
12588        by at least strlen (dest) + 1 bytes.  */
12589     case BUILT_IN_STRCAT_CHK:
12590       len = CALL_EXPR_ARG (exp, 1);
12591       size = CALL_EXPR_ARG (exp, 2);
12592       is_strlen = 1;
12593       break;
12594     case BUILT_IN_STRNCAT_CHK:
12595     case BUILT_IN_STRNCPY_CHK:
12596     case BUILT_IN_STPNCPY_CHK:
12597       len = CALL_EXPR_ARG (exp, 2);
12598       size = CALL_EXPR_ARG (exp, 3);
12599       break;
12600     case BUILT_IN_SNPRINTF_CHK:
12601     case BUILT_IN_VSNPRINTF_CHK:
12602       len = CALL_EXPR_ARG (exp, 1);
12603       size = CALL_EXPR_ARG (exp, 3);
12604       break;
12605     default:
12606       gcc_unreachable ();
12607     }
12608
12609   if (!len || !size)
12610     return;
12611
12612   if (! host_integerp (size, 1) || integer_all_onesp (size))
12613     return;
12614
12615   if (is_strlen)
12616     {
12617       len = c_strlen (len, 1);
12618       if (! len || ! host_integerp (len, 1) || tree_int_cst_lt (len, size))
12619         return;
12620     }
12621   else if (fcode == BUILT_IN_STRNCAT_CHK)
12622     {
12623       tree src = CALL_EXPR_ARG (exp, 1);
12624       if (! src || ! host_integerp (len, 1) || tree_int_cst_lt (len, size))
12625         return;
12626       src = c_strlen (src, 1);
12627       if (! src || ! host_integerp (src, 1))
12628         {
12629           warning_at (loc, 0, "%Kcall to %D might overflow destination buffer",
12630                       exp, get_callee_fndecl (exp));
12631           return;
12632         }
12633       else if (tree_int_cst_lt (src, size))
12634         return;
12635     }
12636   else if (! host_integerp (len, 1) || ! tree_int_cst_lt (size, len))
12637     return;
12638
12639   warning_at (loc, 0, "%Kcall to %D will always overflow destination buffer",
12640               exp, get_callee_fndecl (exp));
12641 }
12642
12643 /* Emit warning if a buffer overflow is detected at compile time
12644    in __sprintf_chk/__vsprintf_chk calls.  */
12645
12646 static void
12647 maybe_emit_sprintf_chk_warning (tree exp, enum built_in_function fcode)
12648 {
12649   tree size, len, fmt;
12650   const char *fmt_str;
12651   int nargs = call_expr_nargs (exp);
12652
12653   /* Verify the required arguments in the original call.  */
12654
12655   if (nargs < 4)
12656     return;
12657   size = CALL_EXPR_ARG (exp, 2);
12658   fmt = CALL_EXPR_ARG (exp, 3);
12659
12660   if (! host_integerp (size, 1) || integer_all_onesp (size))
12661     return;
12662
12663   /* Check whether the format is a literal string constant.  */
12664   fmt_str = c_getstr (fmt);
12665   if (fmt_str == NULL)
12666     return;
12667
12668   if (!init_target_chars ())
12669     return;
12670
12671   /* If the format doesn't contain % args or %%, we know its size.  */
12672   if (strchr (fmt_str, target_percent) == 0)
12673     len = build_int_cstu (size_type_node, strlen (fmt_str));
12674   /* If the format is "%s" and first ... argument is a string literal,
12675      we know it too.  */
12676   else if (fcode == BUILT_IN_SPRINTF_CHK
12677            && strcmp (fmt_str, target_percent_s) == 0)
12678     {
12679       tree arg;
12680
12681       if (nargs < 5)
12682         return;
12683       arg = CALL_EXPR_ARG (exp, 4);
12684       if (! POINTER_TYPE_P (TREE_TYPE (arg)))
12685         return;
12686
12687       len = c_strlen (arg, 1);
12688       if (!len || ! host_integerp (len, 1))
12689         return;
12690     }
12691   else
12692     return;
12693
12694   if (! tree_int_cst_lt (len, size))
12695     warning_at (tree_nonartificial_location (exp),
12696                 0, "%Kcall to %D will always overflow destination buffer",
12697                 exp, get_callee_fndecl (exp));
12698 }
12699
12700 /* Emit warning if a free is called with address of a variable.  */
12701
12702 static void
12703 maybe_emit_free_warning (tree exp)
12704 {
12705   tree arg = CALL_EXPR_ARG (exp, 0);
12706
12707   STRIP_NOPS (arg);
12708   if (TREE_CODE (arg) != ADDR_EXPR)
12709     return;
12710
12711   arg = get_base_address (TREE_OPERAND (arg, 0));
12712   if (arg == NULL || INDIRECT_REF_P (arg) || TREE_CODE (arg) == MEM_REF)
12713     return;
12714
12715   if (SSA_VAR_P (arg))
12716     warning_at (tree_nonartificial_location (exp), OPT_Wfree_nonheap_object,
12717                 "%Kattempt to free a non-heap object %qD", exp, arg);
12718   else
12719     warning_at (tree_nonartificial_location (exp), OPT_Wfree_nonheap_object,
12720                 "%Kattempt to free a non-heap object", exp);
12721 }
12722
12723 /* Fold a call to __builtin_object_size with arguments PTR and OST,
12724    if possible.  */
12725
12726 tree
12727 fold_builtin_object_size (tree ptr, tree ost)
12728 {
12729   unsigned HOST_WIDE_INT bytes;
12730   int object_size_type;
12731
12732   if (!validate_arg (ptr, POINTER_TYPE)
12733       || !validate_arg (ost, INTEGER_TYPE))
12734     return NULL_TREE;
12735
12736   STRIP_NOPS (ost);
12737
12738   if (TREE_CODE (ost) != INTEGER_CST
12739       || tree_int_cst_sgn (ost) < 0
12740       || compare_tree_int (ost, 3) > 0)
12741     return NULL_TREE;
12742
12743   object_size_type = tree_low_cst (ost, 0);
12744
12745   /* __builtin_object_size doesn't evaluate side-effects in its arguments;
12746      if there are any side-effects, it returns (size_t) -1 for types 0 and 1
12747      and (size_t) 0 for types 2 and 3.  */
12748   if (TREE_SIDE_EFFECTS (ptr))
12749     return build_int_cst_type (size_type_node, object_size_type < 2 ? -1 : 0);
12750
12751   if (TREE_CODE (ptr) == ADDR_EXPR)
12752     {
12753       bytes = compute_builtin_object_size (ptr, object_size_type);
12754       if (double_int_fits_to_tree_p (size_type_node,
12755                                      double_int::from_uhwi (bytes)))
12756         return build_int_cstu (size_type_node, bytes);
12757     }
12758   else if (TREE_CODE (ptr) == SSA_NAME)
12759     {
12760       /* If object size is not known yet, delay folding until
12761        later.  Maybe subsequent passes will help determining
12762        it.  */
12763       bytes = compute_builtin_object_size (ptr, object_size_type);
12764       if (bytes != (unsigned HOST_WIDE_INT) (object_size_type < 2 ? -1 : 0)
12765           && double_int_fits_to_tree_p (size_type_node,
12766                                         double_int::from_uhwi (bytes)))
12767         return build_int_cstu (size_type_node, bytes);
12768     }
12769
12770   return NULL_TREE;
12771 }
12772
12773 /* Fold a call to the __mem{cpy,pcpy,move,set}_chk builtin.
12774    DEST, SRC, LEN, and SIZE are the arguments to the call.
12775    IGNORE is true, if return value can be ignored.  FCODE is the BUILT_IN_*
12776    code of the builtin.  If MAXLEN is not NULL, it is maximum length
12777    passed as third argument.  */
12778
12779 tree
12780 fold_builtin_memory_chk (location_t loc, tree fndecl,
12781                          tree dest, tree src, tree len, tree size,
12782                          tree maxlen, bool ignore,
12783                          enum built_in_function fcode)
12784 {
12785   tree fn;
12786
12787   if (!validate_arg (dest, POINTER_TYPE)
12788       || !validate_arg (src,
12789                         (fcode == BUILT_IN_MEMSET_CHK
12790                          ? INTEGER_TYPE : POINTER_TYPE))
12791       || !validate_arg (len, INTEGER_TYPE)
12792       || !validate_arg (size, INTEGER_TYPE))
12793     return NULL_TREE;
12794
12795   /* If SRC and DEST are the same (and not volatile), return DEST
12796      (resp. DEST+LEN for __mempcpy_chk).  */
12797   if (fcode != BUILT_IN_MEMSET_CHK && operand_equal_p (src, dest, 0))
12798     {
12799       if (fcode != BUILT_IN_MEMPCPY_CHK)
12800         return omit_one_operand_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)),
12801                                  dest, len);
12802       else
12803         {
12804           tree temp = fold_build_pointer_plus_loc (loc, dest, len);
12805           return fold_convert_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)), temp);
12806         }
12807     }
12808
12809   if (! host_integerp (size, 1))
12810     return NULL_TREE;
12811
12812   if (! integer_all_onesp (size))
12813     {
12814       if (! host_integerp (len, 1))
12815         {
12816           /* If LEN is not constant, try MAXLEN too.
12817              For MAXLEN only allow optimizing into non-_ocs function
12818              if SIZE is >= MAXLEN, never convert to __ocs_fail ().  */
12819           if (maxlen == NULL_TREE || ! host_integerp (maxlen, 1))
12820             {
12821               if (fcode == BUILT_IN_MEMPCPY_CHK && ignore)
12822                 {
12823                   /* (void) __mempcpy_chk () can be optimized into
12824                      (void) __memcpy_chk ().  */
12825                   fn = builtin_decl_explicit (BUILT_IN_MEMCPY_CHK);
12826                   if (!fn)
12827                     return NULL_TREE;
12828
12829                   return build_call_expr_loc (loc, fn, 4, dest, src, len, size);
12830                 }
12831               return NULL_TREE;
12832             }
12833         }
12834       else
12835         maxlen = len;
12836
12837       if (tree_int_cst_lt (size, maxlen))
12838         return NULL_TREE;
12839     }
12840
12841   fn = NULL_TREE;
12842   /* If __builtin_mem{cpy,pcpy,move,set}_chk is used, assume
12843      mem{cpy,pcpy,move,set} is available.  */
12844   switch (fcode)
12845     {
12846     case BUILT_IN_MEMCPY_CHK:
12847       fn = builtin_decl_explicit (BUILT_IN_MEMCPY);
12848       break;
12849     case BUILT_IN_MEMPCPY_CHK:
12850       fn = builtin_decl_explicit (BUILT_IN_MEMPCPY);
12851       break;
12852     case BUILT_IN_MEMMOVE_CHK:
12853       fn = builtin_decl_explicit (BUILT_IN_MEMMOVE);
12854       break;
12855     case BUILT_IN_MEMSET_CHK:
12856       fn = builtin_decl_explicit (BUILT_IN_MEMSET);
12857       break;
12858     default:
12859       break;
12860     }
12861
12862   if (!fn)
12863     return NULL_TREE;
12864
12865   return build_call_expr_loc (loc, fn, 3, dest, src, len);
12866 }
12867
12868 /* Fold a call to the __st[rp]cpy_chk builtin.
12869    DEST, SRC, and SIZE are the arguments to the call.
12870    IGNORE is true if return value can be ignored.  FCODE is the BUILT_IN_*
12871    code of the builtin.  If MAXLEN is not NULL, it is maximum length of
12872    strings passed as second argument.  */
12873
12874 tree
12875 fold_builtin_stxcpy_chk (location_t loc, tree fndecl, tree dest,
12876                          tree src, tree size,
12877                          tree maxlen, bool ignore,
12878                          enum built_in_function fcode)
12879 {
12880   tree len, fn;
12881
12882   if (!validate_arg (dest, POINTER_TYPE)
12883       || !validate_arg (src, POINTER_TYPE)
12884       || !validate_arg (size, INTEGER_TYPE))
12885     return NULL_TREE;
12886
12887   /* If SRC and DEST are the same (and not volatile), return DEST.  */
12888   if (fcode == BUILT_IN_STRCPY_CHK && operand_equal_p (src, dest, 0))
12889     return fold_convert_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)), dest);
12890
12891   if (! host_integerp (size, 1))
12892     return NULL_TREE;
12893
12894   if (! integer_all_onesp (size))
12895     {
12896       len = c_strlen (src, 1);
12897       if (! len || ! host_integerp (len, 1))
12898         {
12899           /* If LEN is not constant, try MAXLEN too.
12900              For MAXLEN only allow optimizing into non-_ocs function
12901              if SIZE is >= MAXLEN, never convert to __ocs_fail ().  */
12902           if (maxlen == NULL_TREE || ! host_integerp (maxlen, 1))
12903             {
12904               if (fcode == BUILT_IN_STPCPY_CHK)
12905                 {
12906                   if (! ignore)
12907                     return NULL_TREE;
12908
12909                   /* If return value of __stpcpy_chk is ignored,
12910                      optimize into __strcpy_chk.  */
12911                   fn = builtin_decl_explicit (BUILT_IN_STRCPY_CHK);
12912                   if (!fn)
12913                     return NULL_TREE;
12914
12915                   return build_call_expr_loc (loc, fn, 3, dest, src, size);
12916                 }
12917
12918               if (! len || TREE_SIDE_EFFECTS (len))
12919                 return NULL_TREE;
12920
12921               /* If c_strlen returned something, but not a constant,
12922                  transform __strcpy_chk into __memcpy_chk.  */
12923               fn = builtin_decl_explicit (BUILT_IN_MEMCPY_CHK);
12924               if (!fn)
12925                 return NULL_TREE;
12926
12927               len = fold_convert_loc (loc, size_type_node, len);
12928               len = size_binop_loc (loc, PLUS_EXPR, len,
12929                                     build_int_cst (size_type_node, 1));
12930               return fold_convert_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)),
12931                                        build_call_expr_loc (loc, fn, 4,
12932                                                         dest, src, len, size));
12933             }
12934         }
12935       else
12936         maxlen = len;
12937
12938       if (! tree_int_cst_lt (maxlen, size))
12939         return NULL_TREE;
12940     }
12941
12942   /* If __builtin_st{r,p}cpy_chk is used, assume st{r,p}cpy is available.  */
12943   fn = builtin_decl_explicit (fcode == BUILT_IN_STPCPY_CHK
12944                               ? BUILT_IN_STPCPY : BUILT_IN_STRCPY);
12945   if (!fn)
12946     return NULL_TREE;
12947
12948   return build_call_expr_loc (loc, fn, 2, dest, src);
12949 }
12950
12951 /* Fold a call to the __st{r,p}ncpy_chk builtin.  DEST, SRC, LEN, and SIZE
12952    are the arguments to the call.  If MAXLEN is not NULL, it is maximum
12953    length passed as third argument. IGNORE is true if return value can be
12954    ignored. FCODE is the BUILT_IN_* code of the builtin. */
12955
12956 tree
12957 fold_builtin_stxncpy_chk (location_t loc, tree dest, tree src,
12958                           tree len, tree size, tree maxlen, bool ignore,
12959                           enum built_in_function fcode)
12960 {
12961   tree fn;
12962
12963   if (!validate_arg (dest, POINTER_TYPE)
12964       || !validate_arg (src, POINTER_TYPE)
12965       || !validate_arg (len, INTEGER_TYPE)
12966       || !validate_arg (size, INTEGER_TYPE))
12967     return NULL_TREE;
12968
12969   if (fcode == BUILT_IN_STPNCPY_CHK && ignore)
12970     {
12971        /* If return value of __stpncpy_chk is ignored,
12972           optimize into __strncpy_chk.  */
12973        fn = builtin_decl_explicit (BUILT_IN_STRNCPY_CHK);
12974        if (fn)
12975          return build_call_expr_loc (loc, fn, 4, dest, src, len, size);
12976     }
12977
12978   if (! host_integerp (size, 1))
12979     return NULL_TREE;
12980
12981   if (! integer_all_onesp (size))
12982     {
12983       if (! host_integerp (len, 1))
12984         {
12985           /* If LEN is not constant, try MAXLEN too.
12986              For MAXLEN only allow optimizing into non-_ocs function
12987              if SIZE is >= MAXLEN, never convert to __ocs_fail ().  */
12988           if (maxlen == NULL_TREE || ! host_integerp (maxlen, 1))
12989             return NULL_TREE;
12990         }
12991       else
12992         maxlen = len;
12993
12994       if (tree_int_cst_lt (size, maxlen))
12995         return NULL_TREE;
12996     }
12997
12998   /* If __builtin_st{r,p}ncpy_chk is used, assume st{r,p}ncpy is available.  */
12999   fn = builtin_decl_explicit (fcode == BUILT_IN_STPNCPY_CHK
13000                               ? BUILT_IN_STPNCPY : BUILT_IN_STRNCPY);
13001   if (!fn)
13002     return NULL_TREE;
13003
13004   return build_call_expr_loc (loc, fn, 3, dest, src, len);
13005 }
13006
13007 /* Fold a call to the __strcat_chk builtin FNDECL.  DEST, SRC, and SIZE
13008    are the arguments to the call.  */
13009
13010 static tree
13011 fold_builtin_strcat_chk (location_t loc, tree fndecl, tree dest,
13012                          tree src, tree size)
13013 {
13014   tree fn;
13015   const char *p;
13016
13017   if (!validate_arg (dest, POINTER_TYPE)
13018       || !validate_arg (src, POINTER_TYPE)
13019       || !validate_arg (size, INTEGER_TYPE))
13020     return NULL_TREE;
13021
13022   p = c_getstr (src);
13023   /* If the SRC parameter is "", return DEST.  */
13024   if (p && *p == '\0')
13025     return omit_one_operand_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)), dest, src);
13026
13027   if (! host_integerp (size, 1) || ! integer_all_onesp (size))
13028     return NULL_TREE;
13029
13030   /* If __builtin_strcat_chk is used, assume strcat is available.  */
13031   fn = builtin_decl_explicit (BUILT_IN_STRCAT);
13032   if (!fn)
13033     return NULL_TREE;
13034
13035   return build_call_expr_loc (loc, fn, 2, dest, src);
13036 }
13037
13038 /* Fold a call to the __strncat_chk builtin with arguments DEST, SRC,
13039    LEN, and SIZE.  */
13040
13041 static tree
13042 fold_builtin_strncat_chk (location_t loc, tree fndecl,
13043                           tree dest, tree src, tree len, tree size)
13044 {
13045   tree fn;
13046   const char *p;
13047
13048   if (!validate_arg (dest, POINTER_TYPE)
13049       || !validate_arg (src, POINTER_TYPE)
13050       || !validate_arg (size, INTEGER_TYPE)
13051       || !validate_arg (size, INTEGER_TYPE))
13052     return NULL_TREE;
13053
13054   p = c_getstr (src);
13055   /* If the SRC parameter is "" or if LEN is 0, return DEST.  */
13056   if (p && *p == '\0')
13057     return omit_one_operand_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)), dest, len);
13058   else if (integer_zerop (len))
13059     return omit_one_operand_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)), dest, src);
13060
13061   if (! host_integerp (size, 1))
13062     return NULL_TREE;
13063
13064   if (! integer_all_onesp (size))
13065     {
13066       tree src_len = c_strlen (src, 1);
13067       if (src_len
13068           && host_integerp (src_len, 1)
13069           && host_integerp (len, 1)
13070           && ! tree_int_cst_lt (len, src_len))
13071         {
13072           /* If LEN >= strlen (SRC), optimize into __strcat_chk.  */
13073           fn = builtin_decl_explicit (BUILT_IN_STRCAT_CHK);
13074           if (!fn)
13075             return NULL_TREE;
13076
13077           return build_call_expr_loc (loc, fn, 3, dest, src, size);
13078         }
13079       return NULL_TREE;
13080     }
13081
13082   /* If __builtin_strncat_chk is used, assume strncat is available.  */
13083   fn = builtin_decl_explicit (BUILT_IN_STRNCAT);
13084   if (!fn)
13085     return NULL_TREE;
13086
13087   return build_call_expr_loc (loc, fn, 3, dest, src, len);
13088 }
13089
13090 /* Fold a call EXP to __{,v}sprintf_chk having NARGS passed as ARGS.
13091    Return NULL_TREE if a normal call should be emitted rather than
13092    expanding the function inline.  FCODE is either BUILT_IN_SPRINTF_CHK
13093    or BUILT_IN_VSPRINTF_CHK.  */
13094
13095 static tree
13096 fold_builtin_sprintf_chk_1 (location_t loc, int nargs, tree *args,
13097                             enum built_in_function fcode)
13098 {
13099   tree dest, size, len, fn, fmt, flag;
13100   const char *fmt_str;
13101
13102   /* Verify the required arguments in the original call.  */
13103   if (nargs < 4)
13104     return NULL_TREE;
13105   dest = args[0];
13106   if (!validate_arg (dest, POINTER_TYPE))
13107     return NULL_TREE;
13108   flag = args[1];
13109   if (!validate_arg (flag, INTEGER_TYPE))
13110     return NULL_TREE;
13111   size = args[2];
13112   if (!validate_arg (size, INTEGER_TYPE))
13113     return NULL_TREE;
13114   fmt = args[3];
13115   if (!validate_arg (fmt, POINTER_TYPE))
13116     return NULL_TREE;
13117
13118   if (! host_integerp (size, 1))
13119     return NULL_TREE;
13120
13121   len = NULL_TREE;
13122
13123   if (!init_target_chars ())
13124     return NULL_TREE;
13125
13126   /* Check whether the format is a literal string constant.  */
13127   fmt_str = c_getstr (fmt);
13128   if (fmt_str != NULL)
13129     {
13130       /* If the format doesn't contain % args or %%, we know the size.  */
13131       if (strchr (fmt_str, target_percent) == 0)
13132         {
13133           if (fcode != BUILT_IN_SPRINTF_CHK || nargs == 4)
13134             len = build_int_cstu (size_type_node, strlen (fmt_str));
13135         }
13136       /* If the format is "%s" and first ... argument is a string literal,
13137          we know the size too.  */
13138       else if (fcode == BUILT_IN_SPRINTF_CHK
13139                && strcmp (fmt_str, target_percent_s) == 0)
13140         {
13141           tree arg;
13142
13143           if (nargs == 5)
13144             {
13145               arg = args[4];
13146               if (validate_arg (arg, POINTER_TYPE))
13147                 {
13148                   len = c_strlen (arg, 1);
13149                   if (! len || ! host_integerp (len, 1))
13150                     len = NULL_TREE;
13151                 }
13152             }
13153         }
13154     }
13155
13156   if (! integer_all_onesp (size))
13157     {
13158       if (! len || ! tree_int_cst_lt (len, size))
13159         return NULL_TREE;
13160     }
13161
13162   /* Only convert __{,v}sprintf_chk to {,v}sprintf if flag is 0
13163      or if format doesn't contain % chars or is "%s".  */
13164   if (! integer_zerop (flag))
13165     {
13166       if (fmt_str == NULL)
13167         return NULL_TREE;
13168       if (strchr (fmt_str, target_percent) != NULL
13169           && strcmp (fmt_str, target_percent_s))
13170         return NULL_TREE;
13171     }
13172
13173   /* If __builtin_{,v}sprintf_chk is used, assume {,v}sprintf is available.  */
13174   fn = builtin_decl_explicit (fcode == BUILT_IN_VSPRINTF_CHK
13175                               ? BUILT_IN_VSPRINTF : BUILT_IN_SPRINTF);
13176   if (!fn)
13177     return NULL_TREE;
13178
13179   return rewrite_call_expr_array (loc, nargs, args, 4, fn, 2, dest, fmt);
13180 }
13181
13182 /* Fold a call EXP to __{,v}sprintf_chk.  Return NULL_TREE if
13183    a normal call should be emitted rather than expanding the function
13184    inline.  FCODE is either BUILT_IN_SPRINTF_CHK or BUILT_IN_VSPRINTF_CHK.  */
13185
13186 static tree
13187 fold_builtin_sprintf_chk (location_t loc, tree exp,
13188                           enum built_in_function fcode)
13189 {
13190   return fold_builtin_sprintf_chk_1 (loc, call_expr_nargs (exp),
13191                                      CALL_EXPR_ARGP (exp), fcode);
13192 }
13193
13194 /* Fold a call EXP to {,v}snprintf having NARGS passed as ARGS.  Return
13195    NULL_TREE if a normal call should be emitted rather than expanding
13196    the function inline.  FCODE is either BUILT_IN_SNPRINTF_CHK or
13197    BUILT_IN_VSNPRINTF_CHK.  If MAXLEN is not NULL, it is maximum length
13198    passed as second argument.  */
13199
13200 static tree
13201 fold_builtin_snprintf_chk_1 (location_t loc, int nargs, tree *args,
13202                              tree maxlen, enum built_in_function fcode)
13203 {
13204   tree dest, size, len, fn, fmt, flag;
13205   const char *fmt_str;
13206
13207   /* Verify the required arguments in the original call.  */
13208   if (nargs < 5)
13209     return NULL_TREE;
13210   dest = args[0];
13211   if (!validate_arg (dest, POINTER_TYPE))
13212     return NULL_TREE;
13213   len = args[1];
13214   if (!validate_arg (len, INTEGER_TYPE))
13215     return NULL_TREE;
13216   flag = args[2];
13217   if (!validate_arg (flag, INTEGER_TYPE))
13218     return NULL_TREE;
13219   size = args[3];
13220   if (!validate_arg (size, INTEGER_TYPE))
13221     return NULL_TREE;
13222   fmt = args[4];
13223   if (!validate_arg (fmt, POINTER_TYPE))
13224     return NULL_TREE;
13225
13226   if (! host_integerp (size, 1))
13227     return NULL_TREE;
13228
13229   if (! integer_all_onesp (size))
13230     {
13231       if (! host_integerp (len, 1))
13232         {
13233           /* If LEN is not constant, try MAXLEN too.
13234              For MAXLEN only allow optimizing into non-_ocs function
13235              if SIZE is >= MAXLEN, never convert to __ocs_fail ().  */
13236           if (maxlen == NULL_TREE || ! host_integerp (maxlen, 1))
13237             return NULL_TREE;
13238         }
13239       else
13240         maxlen = len;
13241
13242       if (tree_int_cst_lt (size, maxlen))
13243         return NULL_TREE;
13244     }
13245
13246   if (!init_target_chars ())
13247     return NULL_TREE;
13248
13249   /* Only convert __{,v}snprintf_chk to {,v}snprintf if flag is 0
13250      or if format doesn't contain % chars or is "%s".  */
13251   if (! integer_zerop (flag))
13252     {
13253       fmt_str = c_getstr (fmt);
13254       if (fmt_str == NULL)
13255         return NULL_TREE;
13256       if (strchr (fmt_str, target_percent) != NULL
13257           && strcmp (fmt_str, target_percent_s))
13258         return NULL_TREE;
13259     }
13260
13261   /* If __builtin_{,v}snprintf_chk is used, assume {,v}snprintf is
13262      available.  */
13263   fn = builtin_decl_explicit (fcode == BUILT_IN_VSNPRINTF_CHK
13264                               ? BUILT_IN_VSNPRINTF : BUILT_IN_SNPRINTF);
13265   if (!fn)
13266     return NULL_TREE;
13267
13268   return rewrite_call_expr_array (loc, nargs, args, 5, fn, 3, dest, len, fmt);
13269 }
13270
13271 /* Fold a call EXP to {,v}snprintf.  Return NULL_TREE if
13272    a normal call should be emitted rather than expanding the function
13273    inline.  FCODE is either BUILT_IN_SNPRINTF_CHK or
13274    BUILT_IN_VSNPRINTF_CHK.  If MAXLEN is not NULL, it is maximum length
13275    passed as second argument.  */
13276
13277 tree
13278 fold_builtin_snprintf_chk (location_t loc, tree exp, tree maxlen,
13279                            enum built_in_function fcode)
13280 {
13281   return fold_builtin_snprintf_chk_1 (loc, call_expr_nargs (exp),
13282                                       CALL_EXPR_ARGP (exp), maxlen, fcode);
13283 }
13284
13285 /* Fold a call to the {,v}printf{,_unlocked} and __{,v}printf_chk builtins.
13286    FMT and ARG are the arguments to the call; we don't fold cases with
13287    more than 2 arguments, and ARG may be null if this is a 1-argument case.
13288
13289    Return NULL_TREE if no simplification was possible, otherwise return the
13290    simplified form of the call as a tree.  FCODE is the BUILT_IN_*
13291    code of the function to be simplified.  */
13292
13293 static tree
13294 fold_builtin_printf (location_t loc, tree fndecl, tree fmt,
13295                      tree arg, bool ignore,
13296                      enum built_in_function fcode)
13297 {
13298   tree fn_putchar, fn_puts, newarg, call = NULL_TREE;
13299   const char *fmt_str = NULL;
13300
13301   /* If the return value is used, don't do the transformation.  */
13302   if (! ignore)
13303     return NULL_TREE;
13304
13305   /* Verify the required arguments in the original call.  */
13306   if (!validate_arg (fmt, POINTER_TYPE))
13307     return NULL_TREE;
13308
13309   /* Check whether the format is a literal string constant.  */
13310   fmt_str = c_getstr (fmt);
13311   if (fmt_str == NULL)
13312     return NULL_TREE;
13313
13314   if (fcode == BUILT_IN_PRINTF_UNLOCKED)
13315     {
13316       /* If we're using an unlocked function, assume the other
13317          unlocked functions exist explicitly.  */
13318       fn_putchar = builtin_decl_explicit (BUILT_IN_PUTCHAR_UNLOCKED);
13319       fn_puts = builtin_decl_explicit (BUILT_IN_PUTS_UNLOCKED);
13320     }
13321   else
13322     {
13323       fn_putchar = builtin_decl_implicit (BUILT_IN_PUTCHAR);
13324       fn_puts = builtin_decl_implicit (BUILT_IN_PUTS);
13325     }
13326
13327   if (!init_target_chars ())
13328     return NULL_TREE;
13329
13330   if (strcmp (fmt_str, target_percent_s) == 0
13331       || strchr (fmt_str, target_percent) == NULL)
13332     {
13333       const char *str;
13334
13335       if (strcmp (fmt_str, target_percent_s) == 0)
13336         {
13337           if (fcode == BUILT_IN_VPRINTF || fcode == BUILT_IN_VPRINTF_CHK)
13338             return NULL_TREE;
13339
13340           if (!arg || !validate_arg (arg, POINTER_TYPE))
13341             return NULL_TREE;
13342
13343           str = c_getstr (arg);
13344           if (str == NULL)
13345             return NULL_TREE;
13346         }
13347       else
13348         {
13349           /* The format specifier doesn't contain any '%' characters.  */
13350           if (fcode != BUILT_IN_VPRINTF && fcode != BUILT_IN_VPRINTF_CHK
13351               && arg)
13352             return NULL_TREE;
13353           str = fmt_str;
13354         }
13355
13356       /* If the string was "", printf does nothing.  */
13357       if (str[0] == '\0')
13358         return build_int_cst (TREE_TYPE (TREE_TYPE (fndecl)), 0);
13359
13360       /* If the string has length of 1, call putchar.  */
13361       if (str[1] == '\0')
13362         {
13363           /* Given printf("c"), (where c is any one character,)
13364              convert "c"[0] to an int and pass that to the replacement
13365              function.  */
13366           newarg = build_int_cst (integer_type_node, str[0]);
13367           if (fn_putchar)
13368             call = build_call_expr_loc (loc, fn_putchar, 1, newarg);
13369         }
13370       else
13371         {
13372           /* If the string was "string\n", call puts("string").  */
13373           size_t len = strlen (str);
13374           if ((unsigned char)str[len - 1] == target_newline
13375               && (size_t) (int) len == len
13376               && (int) len > 0)
13377             {
13378               char *newstr;
13379               tree offset_node, string_cst;
13380
13381               /* Create a NUL-terminated string that's one char shorter
13382                  than the original, stripping off the trailing '\n'.  */
13383               newarg = build_string_literal (len, str);
13384               string_cst = string_constant (newarg, &offset_node);
13385               gcc_checking_assert (string_cst
13386                                    && (TREE_STRING_LENGTH (string_cst)
13387                                        == (int) len)
13388                                    && integer_zerop (offset_node)
13389                                    && (unsigned char)
13390                                       TREE_STRING_POINTER (string_cst)[len - 1]
13391                                       == target_newline);
13392               /* build_string_literal creates a new STRING_CST,
13393                  modify it in place to avoid double copying.  */
13394               newstr = CONST_CAST (char *, TREE_STRING_POINTER (string_cst));
13395               newstr[len - 1] = '\0';
13396               if (fn_puts)
13397                 call = build_call_expr_loc (loc, fn_puts, 1, newarg);
13398             }
13399           else
13400             /* We'd like to arrange to call fputs(string,stdout) here,
13401                but we need stdout and don't have a way to get it yet.  */
13402             return NULL_TREE;
13403         }
13404     }
13405
13406   /* The other optimizations can be done only on the non-va_list variants.  */
13407   else if (fcode == BUILT_IN_VPRINTF || fcode == BUILT_IN_VPRINTF_CHK)
13408     return NULL_TREE;
13409
13410   /* If the format specifier was "%s\n", call __builtin_puts(arg).  */
13411   else if (strcmp (fmt_str, target_percent_s_newline) == 0)
13412     {
13413       if (!arg || !validate_arg (arg, POINTER_TYPE))
13414         return NULL_TREE;
13415       if (fn_puts)
13416         call = build_call_expr_loc (loc, fn_puts, 1, arg);
13417     }
13418
13419   /* If the format specifier was "%c", call __builtin_putchar(arg).  */
13420   else if (strcmp (fmt_str, target_percent_c) == 0)
13421     {
13422       if (!arg || !validate_arg (arg, INTEGER_TYPE))
13423         return NULL_TREE;
13424       if (fn_putchar)
13425         call = build_call_expr_loc (loc, fn_putchar, 1, arg);
13426     }
13427
13428   if (!call)
13429     return NULL_TREE;
13430
13431   return fold_convert_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)), call);
13432 }
13433
13434 /* Fold a call to the {,v}fprintf{,_unlocked} and __{,v}printf_chk builtins.
13435    FP, FMT, and ARG are the arguments to the call.  We don't fold calls with
13436    more than 3 arguments, and ARG may be null in the 2-argument case.
13437
13438    Return NULL_TREE if no simplification was possible, otherwise return the
13439    simplified form of the call as a tree.  FCODE is the BUILT_IN_*
13440    code of the function to be simplified.  */
13441
13442 static tree
13443 fold_builtin_fprintf (location_t loc, tree fndecl, tree fp,
13444                       tree fmt, tree arg, bool ignore,
13445                       enum built_in_function fcode)
13446 {
13447   tree fn_fputc, fn_fputs, call = NULL_TREE;
13448   const char *fmt_str = NULL;
13449
13450   /* If the return value is used, don't do the transformation.  */
13451   if (! ignore)
13452     return NULL_TREE;
13453
13454   /* Verify the required arguments in the original call.  */
13455   if (!validate_arg (fp, POINTER_TYPE))
13456     return NULL_TREE;
13457   if (!validate_arg (fmt, POINTER_TYPE))
13458     return NULL_TREE;
13459
13460   /* Check whether the format is a literal string constant.  */
13461   fmt_str = c_getstr (fmt);
13462   if (fmt_str == NULL)
13463     return NULL_TREE;
13464
13465   if (fcode == BUILT_IN_FPRINTF_UNLOCKED)
13466     {
13467       /* If we're using an unlocked function, assume the other
13468          unlocked functions exist explicitly.  */
13469       fn_fputc = builtin_decl_explicit (BUILT_IN_FPUTC_UNLOCKED);
13470       fn_fputs = builtin_decl_explicit (BUILT_IN_FPUTS_UNLOCKED);
13471     }
13472   else
13473     {
13474       fn_fputc = builtin_decl_implicit (BUILT_IN_FPUTC);
13475       fn_fputs = builtin_decl_implicit (BUILT_IN_FPUTS);
13476     }
13477
13478   if (!init_target_chars ())
13479     return NULL_TREE;
13480
13481   /* If the format doesn't contain % args or %%, use strcpy.  */
13482   if (strchr (fmt_str, target_percent) == NULL)
13483     {
13484       if (fcode != BUILT_IN_VFPRINTF && fcode != BUILT_IN_VFPRINTF_CHK
13485           && arg)
13486         return NULL_TREE;
13487
13488       /* If the format specifier was "", fprintf does nothing.  */
13489       if (fmt_str[0] == '\0')
13490         {
13491           /* If FP has side-effects, just wait until gimplification is
13492              done.  */
13493           if (TREE_SIDE_EFFECTS (fp))
13494             return NULL_TREE;
13495
13496           return build_int_cst (TREE_TYPE (TREE_TYPE (fndecl)), 0);
13497         }
13498
13499       /* When "string" doesn't contain %, replace all cases of
13500          fprintf (fp, string) with fputs (string, fp).  The fputs
13501          builtin will take care of special cases like length == 1.  */
13502       if (fn_fputs)
13503         call = build_call_expr_loc (loc, fn_fputs, 2, fmt, fp);
13504     }
13505
13506   /* The other optimizations can be done only on the non-va_list variants.  */
13507   else if (fcode == BUILT_IN_VFPRINTF || fcode == BUILT_IN_VFPRINTF_CHK)
13508     return NULL_TREE;
13509
13510   /* If the format specifier was "%s", call __builtin_fputs (arg, fp).  */
13511   else if (strcmp (fmt_str, target_percent_s) == 0)
13512     {
13513       if (!arg || !validate_arg (arg, POINTER_TYPE))
13514         return NULL_TREE;
13515       if (fn_fputs)
13516         call = build_call_expr_loc (loc, fn_fputs, 2, arg, fp);
13517     }
13518
13519   /* If the format specifier was "%c", call __builtin_fputc (arg, fp).  */
13520   else if (strcmp (fmt_str, target_percent_c) == 0)
13521     {
13522       if (!arg || !validate_arg (arg, INTEGER_TYPE))
13523         return NULL_TREE;
13524       if (fn_fputc)
13525         call = build_call_expr_loc (loc, fn_fputc, 2, arg, fp);
13526     }
13527
13528   if (!call)
13529     return NULL_TREE;
13530   return fold_convert_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)), call);
13531 }
13532
13533 /* Initialize format string characters in the target charset.  */
13534
13535 static bool
13536 init_target_chars (void)
13537 {
13538   static bool init;
13539   if (!init)
13540     {
13541       target_newline = lang_hooks.to_target_charset ('\n');
13542       target_percent = lang_hooks.to_target_charset ('%');
13543       target_c = lang_hooks.to_target_charset ('c');
13544       target_s = lang_hooks.to_target_charset ('s');
13545       if (target_newline == 0 || target_percent == 0 || target_c == 0
13546           || target_s == 0)
13547         return false;
13548
13549       target_percent_c[0] = target_percent;
13550       target_percent_c[1] = target_c;
13551       target_percent_c[2] = '\0';
13552
13553       target_percent_s[0] = target_percent;
13554       target_percent_s[1] = target_s;
13555       target_percent_s[2] = '\0';
13556
13557       target_percent_s_newline[0] = target_percent;
13558       target_percent_s_newline[1] = target_s;
13559       target_percent_s_newline[2] = target_newline;
13560       target_percent_s_newline[3] = '\0';
13561
13562       init = true;
13563     }
13564   return true;
13565 }
13566
13567 /* Helper function for do_mpfr_arg*().  Ensure M is a normal number
13568    and no overflow/underflow occurred.  INEXACT is true if M was not
13569    exactly calculated.  TYPE is the tree type for the result.  This
13570    function assumes that you cleared the MPFR flags and then
13571    calculated M to see if anything subsequently set a flag prior to
13572    entering this function.  Return NULL_TREE if any checks fail.  */
13573
13574 static tree
13575 do_mpfr_ckconv (mpfr_srcptr m, tree type, int inexact)
13576 {
13577   /* Proceed iff we get a normal number, i.e. not NaN or Inf and no
13578      overflow/underflow occurred.  If -frounding-math, proceed iff the
13579      result of calling FUNC was exact.  */
13580   if (mpfr_number_p (m) && !mpfr_overflow_p () && !mpfr_underflow_p ()
13581       && (!flag_rounding_math || !inexact))
13582     {
13583       REAL_VALUE_TYPE rr;
13584
13585       real_from_mpfr (&rr, m, type, GMP_RNDN);
13586       /* Proceed iff GCC's REAL_VALUE_TYPE can hold the MPFR value,
13587          check for overflow/underflow.  If the REAL_VALUE_TYPE is zero
13588          but the mpft_t is not, then we underflowed in the
13589          conversion.  */
13590       if (real_isfinite (&rr)
13591           && (rr.cl == rvc_zero) == (mpfr_zero_p (m) != 0))
13592         {
13593           REAL_VALUE_TYPE rmode;
13594
13595           real_convert (&rmode, TYPE_MODE (type), &rr);
13596           /* Proceed iff the specified mode can hold the value.  */
13597           if (real_identical (&rmode, &rr))
13598             return build_real (type, rmode);
13599         }
13600     }
13601   return NULL_TREE;
13602 }
13603
13604 /* Helper function for do_mpc_arg*().  Ensure M is a normal complex
13605    number and no overflow/underflow occurred.  INEXACT is true if M
13606    was not exactly calculated.  TYPE is the tree type for the result.
13607    This function assumes that you cleared the MPFR flags and then
13608    calculated M to see if anything subsequently set a flag prior to
13609    entering this function.  Return NULL_TREE if any checks fail, if
13610    FORCE_CONVERT is true, then bypass the checks.  */
13611
13612 static tree
13613 do_mpc_ckconv (mpc_srcptr m, tree type, int inexact, int force_convert)
13614 {
13615   /* Proceed iff we get a normal number, i.e. not NaN or Inf and no
13616      overflow/underflow occurred.  If -frounding-math, proceed iff the
13617      result of calling FUNC was exact.  */
13618   if (force_convert
13619       || (mpfr_number_p (mpc_realref (m)) && mpfr_number_p (mpc_imagref (m))
13620           && !mpfr_overflow_p () && !mpfr_underflow_p ()
13621           && (!flag_rounding_math || !inexact)))
13622     {
13623       REAL_VALUE_TYPE re, im;
13624
13625       real_from_mpfr (&re, mpc_realref (m), TREE_TYPE (type), GMP_RNDN);
13626       real_from_mpfr (&im, mpc_imagref (m), TREE_TYPE (type), GMP_RNDN);
13627       /* Proceed iff GCC's REAL_VALUE_TYPE can hold the MPFR values,
13628          check for overflow/underflow.  If the REAL_VALUE_TYPE is zero
13629          but the mpft_t is not, then we underflowed in the
13630          conversion.  */
13631       if (force_convert
13632           || (real_isfinite (&re) && real_isfinite (&im)
13633               && (re.cl == rvc_zero) == (mpfr_zero_p (mpc_realref (m)) != 0)
13634               && (im.cl == rvc_zero) == (mpfr_zero_p (mpc_imagref (m)) != 0)))
13635         {
13636           REAL_VALUE_TYPE re_mode, im_mode;
13637
13638           real_convert (&re_mode, TYPE_MODE (TREE_TYPE (type)), &re);
13639           real_convert (&im_mode, TYPE_MODE (TREE_TYPE (type)), &im);
13640           /* Proceed iff the specified mode can hold the value.  */
13641           if (force_convert
13642               || (real_identical (&re_mode, &re)
13643                   && real_identical (&im_mode, &im)))
13644             return build_complex (type, build_real (TREE_TYPE (type), re_mode),
13645                                   build_real (TREE_TYPE (type), im_mode));
13646         }
13647     }
13648   return NULL_TREE;
13649 }
13650
13651 /* If argument ARG is a REAL_CST, call the one-argument mpfr function
13652    FUNC on it and return the resulting value as a tree with type TYPE.
13653    If MIN and/or MAX are not NULL, then the supplied ARG must be
13654    within those bounds.  If INCLUSIVE is true, then MIN/MAX are
13655    acceptable values, otherwise they are not.  The mpfr precision is
13656    set to the precision of TYPE.  We assume that function FUNC returns
13657    zero if the result could be calculated exactly within the requested
13658    precision.  */
13659
13660 static tree
13661 do_mpfr_arg1 (tree arg, tree type, int (*func)(mpfr_ptr, mpfr_srcptr, mp_rnd_t),
13662               const REAL_VALUE_TYPE *min, const REAL_VALUE_TYPE *max,
13663               bool inclusive)
13664 {
13665   tree result = NULL_TREE;
13666
13667   STRIP_NOPS (arg);
13668
13669   /* To proceed, MPFR must exactly represent the target floating point
13670      format, which only happens when the target base equals two.  */
13671   if (REAL_MODE_FORMAT (TYPE_MODE (type))->b == 2
13672       && TREE_CODE (arg) == REAL_CST && !TREE_OVERFLOW (arg))
13673     {
13674       const REAL_VALUE_TYPE *const ra = &TREE_REAL_CST (arg);
13675
13676       if (real_isfinite (ra)
13677           && (!min || real_compare (inclusive ? GE_EXPR: GT_EXPR , ra, min))
13678           && (!max || real_compare (inclusive ? LE_EXPR: LT_EXPR , ra, max)))
13679         {
13680           const struct real_format *fmt = REAL_MODE_FORMAT (TYPE_MODE (type));
13681           const int prec = fmt->p;
13682           const mp_rnd_t rnd = fmt->round_towards_zero? GMP_RNDZ : GMP_RNDN;
13683           int inexact;
13684           mpfr_t m;
13685
13686           mpfr_init2 (m, prec);
13687           mpfr_from_real (m, ra, GMP_RNDN);
13688           mpfr_clear_flags ();
13689           inexact = func (m, m, rnd);
13690           result = do_mpfr_ckconv (m, type, inexact);
13691           mpfr_clear (m);
13692         }
13693     }
13694
13695   return result;
13696 }
13697
13698 /* If argument ARG is a REAL_CST, call the two-argument mpfr function
13699    FUNC on it and return the resulting value as a tree with type TYPE.
13700    The mpfr precision is set to the precision of TYPE.  We assume that
13701    function FUNC returns zero if the result could be calculated
13702    exactly within the requested precision.  */
13703
13704 static tree
13705 do_mpfr_arg2 (tree arg1, tree arg2, tree type,
13706               int (*func)(mpfr_ptr, mpfr_srcptr, mpfr_srcptr, mp_rnd_t))
13707 {
13708   tree result = NULL_TREE;
13709
13710   STRIP_NOPS (arg1);
13711   STRIP_NOPS (arg2);
13712
13713   /* To proceed, MPFR must exactly represent the target floating point
13714      format, which only happens when the target base equals two.  */
13715   if (REAL_MODE_FORMAT (TYPE_MODE (type))->b == 2
13716       && TREE_CODE (arg1) == REAL_CST && !TREE_OVERFLOW (arg1)
13717       && TREE_CODE (arg2) == REAL_CST && !TREE_OVERFLOW (arg2))
13718     {
13719       const REAL_VALUE_TYPE *const ra1 = &TREE_REAL_CST (arg1);
13720       const REAL_VALUE_TYPE *const ra2 = &TREE_REAL_CST (arg2);
13721
13722       if (real_isfinite (ra1) && real_isfinite (ra2))
13723         {
13724           const struct real_format *fmt = REAL_MODE_FORMAT (TYPE_MODE (type));
13725           const int prec = fmt->p;
13726           const mp_rnd_t rnd = fmt->round_towards_zero? GMP_RNDZ : GMP_RNDN;
13727           int inexact;
13728           mpfr_t m1, m2;
13729
13730           mpfr_inits2 (prec, m1, m2, NULL);
13731           mpfr_from_real (m1, ra1, GMP_RNDN);
13732           mpfr_from_real (m2, ra2, GMP_RNDN);
13733           mpfr_clear_flags ();
13734           inexact = func (m1, m1, m2, rnd);
13735           result = do_mpfr_ckconv (m1, type, inexact);
13736           mpfr_clears (m1, m2, NULL);
13737         }
13738     }
13739
13740   return result;
13741 }
13742
13743 /* If argument ARG is a REAL_CST, call the three-argument mpfr function
13744    FUNC on it and return the resulting value as a tree with type TYPE.
13745    The mpfr precision is set to the precision of TYPE.  We assume that
13746    function FUNC returns zero if the result could be calculated
13747    exactly within the requested precision.  */
13748
13749 static tree
13750 do_mpfr_arg3 (tree arg1, tree arg2, tree arg3, tree type,
13751               int (*func)(mpfr_ptr, mpfr_srcptr, mpfr_srcptr, mpfr_srcptr, mp_rnd_t))
13752 {
13753   tree result = NULL_TREE;
13754
13755   STRIP_NOPS (arg1);
13756   STRIP_NOPS (arg2);
13757   STRIP_NOPS (arg3);
13758
13759   /* To proceed, MPFR must exactly represent the target floating point
13760      format, which only happens when the target base equals two.  */
13761   if (REAL_MODE_FORMAT (TYPE_MODE (type))->b == 2
13762       && TREE_CODE (arg1) == REAL_CST && !TREE_OVERFLOW (arg1)
13763       && TREE_CODE (arg2) == REAL_CST && !TREE_OVERFLOW (arg2)
13764       && TREE_CODE (arg3) == REAL_CST && !TREE_OVERFLOW (arg3))
13765     {
13766       const REAL_VALUE_TYPE *const ra1 = &TREE_REAL_CST (arg1);
13767       const REAL_VALUE_TYPE *const ra2 = &TREE_REAL_CST (arg2);
13768       const REAL_VALUE_TYPE *const ra3 = &TREE_REAL_CST (arg3);
13769
13770       if (real_isfinite (ra1) && real_isfinite (ra2) && real_isfinite (ra3))
13771         {
13772           const struct real_format *fmt = REAL_MODE_FORMAT (TYPE_MODE (type));
13773           const int prec = fmt->p;
13774           const mp_rnd_t rnd = fmt->round_towards_zero? GMP_RNDZ : GMP_RNDN;
13775           int inexact;
13776           mpfr_t m1, m2, m3;
13777
13778           mpfr_inits2 (prec, m1, m2, m3, NULL);
13779           mpfr_from_real (m1, ra1, GMP_RNDN);
13780           mpfr_from_real (m2, ra2, GMP_RNDN);
13781           mpfr_from_real (m3, ra3, GMP_RNDN);
13782           mpfr_clear_flags ();
13783           inexact = func (m1, m1, m2, m3, rnd);
13784           result = do_mpfr_ckconv (m1, type, inexact);
13785           mpfr_clears (m1, m2, m3, NULL);
13786         }
13787     }
13788
13789   return result;
13790 }
13791
13792 /* If argument ARG is a REAL_CST, call mpfr_sin_cos() on it and set
13793    the pointers *(ARG_SINP) and *(ARG_COSP) to the resulting values.
13794    If ARG_SINP and ARG_COSP are NULL then the result is returned
13795    as a complex value.
13796    The type is taken from the type of ARG and is used for setting the
13797    precision of the calculation and results.  */
13798
13799 static tree
13800 do_mpfr_sincos (tree arg, tree arg_sinp, tree arg_cosp)
13801 {
13802   tree const type = TREE_TYPE (arg);
13803   tree result = NULL_TREE;
13804
13805   STRIP_NOPS (arg);
13806
13807   /* To proceed, MPFR must exactly represent the target floating point
13808      format, which only happens when the target base equals two.  */
13809   if (REAL_MODE_FORMAT (TYPE_MODE (type))->b == 2
13810       && TREE_CODE (arg) == REAL_CST
13811       && !TREE_OVERFLOW (arg))
13812     {
13813       const REAL_VALUE_TYPE *const ra = &TREE_REAL_CST (arg);
13814
13815       if (real_isfinite (ra))
13816         {
13817           const struct real_format *fmt = REAL_MODE_FORMAT (TYPE_MODE (type));
13818           const int prec = fmt->p;
13819           const mp_rnd_t rnd = fmt->round_towards_zero? GMP_RNDZ : GMP_RNDN;
13820           tree result_s, result_c;
13821           int inexact;
13822           mpfr_t m, ms, mc;
13823
13824           mpfr_inits2 (prec, m, ms, mc, NULL);
13825           mpfr_from_real (m, ra, GMP_RNDN);
13826           mpfr_clear_flags ();
13827           inexact = mpfr_sin_cos (ms, mc, m, rnd);
13828           result_s = do_mpfr_ckconv (ms, type, inexact);
13829           result_c = do_mpfr_ckconv (mc, type, inexact);
13830           mpfr_clears (m, ms, mc, NULL);
13831           if (result_s && result_c)
13832             {
13833               /* If we are to return in a complex value do so.  */
13834               if (!arg_sinp && !arg_cosp)
13835                 return build_complex (build_complex_type (type),
13836                                       result_c, result_s);
13837
13838               /* Dereference the sin/cos pointer arguments.  */
13839               arg_sinp = build_fold_indirect_ref (arg_sinp);
13840               arg_cosp = build_fold_indirect_ref (arg_cosp);
13841               /* Proceed if valid pointer type were passed in.  */
13842               if (TYPE_MAIN_VARIANT (TREE_TYPE (arg_sinp)) == TYPE_MAIN_VARIANT (type)
13843                   && TYPE_MAIN_VARIANT (TREE_TYPE (arg_cosp)) == TYPE_MAIN_VARIANT (type))
13844                 {
13845                   /* Set the values. */
13846                   result_s = fold_build2 (MODIFY_EXPR, type, arg_sinp,
13847                                           result_s);
13848                   TREE_SIDE_EFFECTS (result_s) = 1;
13849                   result_c = fold_build2 (MODIFY_EXPR, type, arg_cosp,
13850                                           result_c);
13851                   TREE_SIDE_EFFECTS (result_c) = 1;
13852                   /* Combine the assignments into a compound expr.  */
13853                   result = non_lvalue (fold_build2 (COMPOUND_EXPR, type,
13854                                                     result_s, result_c));
13855                 }
13856             }
13857         }
13858     }
13859   return result;
13860 }
13861
13862 /* If argument ARG1 is an INTEGER_CST and ARG2 is a REAL_CST, call the
13863    two-argument mpfr order N Bessel function FUNC on them and return
13864    the resulting value as a tree with type TYPE.  The mpfr precision
13865    is set to the precision of TYPE.  We assume that function FUNC
13866    returns zero if the result could be calculated exactly within the
13867    requested precision.  */
13868 static tree
13869 do_mpfr_bessel_n (tree arg1, tree arg2, tree type,
13870                   int (*func)(mpfr_ptr, long, mpfr_srcptr, mp_rnd_t),
13871                   const REAL_VALUE_TYPE *min, bool inclusive)
13872 {
13873   tree result = NULL_TREE;
13874
13875   STRIP_NOPS (arg1);
13876   STRIP_NOPS (arg2);
13877
13878   /* To proceed, MPFR must exactly represent the target floating point
13879      format, which only happens when the target base equals two.  */
13880   if (REAL_MODE_FORMAT (TYPE_MODE (type))->b == 2
13881       && host_integerp (arg1, 0)
13882       && TREE_CODE (arg2) == REAL_CST && !TREE_OVERFLOW (arg2))
13883     {
13884       const HOST_WIDE_INT n = tree_low_cst(arg1, 0);
13885       const REAL_VALUE_TYPE *const ra = &TREE_REAL_CST (arg2);
13886
13887       if (n == (long)n
13888           && real_isfinite (ra)
13889           && (!min || real_compare (inclusive ? GE_EXPR: GT_EXPR , ra, min)))
13890         {
13891           const struct real_format *fmt = REAL_MODE_FORMAT (TYPE_MODE (type));
13892           const int prec = fmt->p;
13893           const mp_rnd_t rnd = fmt->round_towards_zero? GMP_RNDZ : GMP_RNDN;
13894           int inexact;
13895           mpfr_t m;
13896
13897           mpfr_init2 (m, prec);
13898           mpfr_from_real (m, ra, GMP_RNDN);
13899           mpfr_clear_flags ();
13900           inexact = func (m, n, m, rnd);
13901           result = do_mpfr_ckconv (m, type, inexact);
13902           mpfr_clear (m);
13903         }
13904     }
13905
13906   return result;
13907 }
13908
13909 /* If arguments ARG0 and ARG1 are REAL_CSTs, call mpfr_remquo() to set
13910    the pointer *(ARG_QUO) and return the result.  The type is taken
13911    from the type of ARG0 and is used for setting the precision of the
13912    calculation and results.  */
13913
13914 static tree
13915 do_mpfr_remquo (tree arg0, tree arg1, tree arg_quo)
13916 {
13917   tree const type = TREE_TYPE (arg0);
13918   tree result = NULL_TREE;
13919
13920   STRIP_NOPS (arg0);
13921   STRIP_NOPS (arg1);
13922
13923   /* To proceed, MPFR must exactly represent the target floating point
13924      format, which only happens when the target base equals two.  */
13925   if (REAL_MODE_FORMAT (TYPE_MODE (type))->b == 2
13926       && TREE_CODE (arg0) == REAL_CST && !TREE_OVERFLOW (arg0)
13927       && TREE_CODE (arg1) == REAL_CST && !TREE_OVERFLOW (arg1))
13928     {
13929       const REAL_VALUE_TYPE *const ra0 = TREE_REAL_CST_PTR (arg0);
13930       const REAL_VALUE_TYPE *const ra1 = TREE_REAL_CST_PTR (arg1);
13931
13932       if (real_isfinite (ra0) && real_isfinite (ra1))
13933         {
13934           const struct real_format *fmt = REAL_MODE_FORMAT (TYPE_MODE (type));
13935           const int prec = fmt->p;
13936           const mp_rnd_t rnd = fmt->round_towards_zero? GMP_RNDZ : GMP_RNDN;
13937           tree result_rem;
13938           long integer_quo;
13939           mpfr_t m0, m1;
13940
13941           mpfr_inits2 (prec, m0, m1, NULL);
13942           mpfr_from_real (m0, ra0, GMP_RNDN);
13943           mpfr_from_real (m1, ra1, GMP_RNDN);
13944           mpfr_clear_flags ();
13945           mpfr_remquo (m0, &integer_quo, m0, m1, rnd);
13946           /* Remquo is independent of the rounding mode, so pass
13947              inexact=0 to do_mpfr_ckconv().  */
13948           result_rem = do_mpfr_ckconv (m0, type, /*inexact=*/ 0);
13949           mpfr_clears (m0, m1, NULL);
13950           if (result_rem)
13951             {
13952               /* MPFR calculates quo in the host's long so it may
13953                  return more bits in quo than the target int can hold
13954                  if sizeof(host long) > sizeof(target int).  This can
13955                  happen even for native compilers in LP64 mode.  In
13956                  these cases, modulo the quo value with the largest
13957                  number that the target int can hold while leaving one
13958                  bit for the sign.  */
13959               if (sizeof (integer_quo) * CHAR_BIT > INT_TYPE_SIZE)
13960                 integer_quo %= (long)(1UL << (INT_TYPE_SIZE - 1));
13961
13962               /* Dereference the quo pointer argument.  */
13963               arg_quo = build_fold_indirect_ref (arg_quo);
13964               /* Proceed iff a valid pointer type was passed in.  */
13965               if (TYPE_MAIN_VARIANT (TREE_TYPE (arg_quo)) == integer_type_node)
13966                 {
13967                   /* Set the value. */
13968                   tree result_quo
13969                     = fold_build2 (MODIFY_EXPR, TREE_TYPE (arg_quo), arg_quo,
13970                                    build_int_cst (TREE_TYPE (arg_quo),
13971                                                   integer_quo));
13972                   TREE_SIDE_EFFECTS (result_quo) = 1;
13973                   /* Combine the quo assignment with the rem.  */
13974                   result = non_lvalue (fold_build2 (COMPOUND_EXPR, type,
13975                                                     result_quo, result_rem));
13976                 }
13977             }
13978         }
13979     }
13980   return result;
13981 }
13982
13983 /* If ARG is a REAL_CST, call mpfr_lgamma() on it and return the
13984    resulting value as a tree with type TYPE.  The mpfr precision is
13985    set to the precision of TYPE.  We assume that this mpfr function
13986    returns zero if the result could be calculated exactly within the
13987    requested precision.  In addition, the integer pointer represented
13988    by ARG_SG will be dereferenced and set to the appropriate signgam
13989    (-1,1) value.  */
13990
13991 static tree
13992 do_mpfr_lgamma_r (tree arg, tree arg_sg, tree type)
13993 {
13994   tree result = NULL_TREE;
13995
13996   STRIP_NOPS (arg);
13997
13998   /* To proceed, MPFR must exactly represent the target floating point
13999      format, which only happens when the target base equals two.  Also
14000      verify ARG is a constant and that ARG_SG is an int pointer.  */
14001   if (REAL_MODE_FORMAT (TYPE_MODE (type))->b == 2
14002       && TREE_CODE (arg) == REAL_CST && !TREE_OVERFLOW (arg)
14003       && TREE_CODE (TREE_TYPE (arg_sg)) == POINTER_TYPE
14004       && TYPE_MAIN_VARIANT (TREE_TYPE (TREE_TYPE (arg_sg))) == integer_type_node)
14005     {
14006       const REAL_VALUE_TYPE *const ra = TREE_REAL_CST_PTR (arg);
14007
14008       /* In addition to NaN and Inf, the argument cannot be zero or a
14009          negative integer.  */
14010       if (real_isfinite (ra)
14011           && ra->cl != rvc_zero
14012           && !(real_isneg(ra) && real_isinteger(ra, TYPE_MODE (type))))
14013         {
14014           const struct real_format *fmt = REAL_MODE_FORMAT (TYPE_MODE (type));
14015           const int prec = fmt->p;
14016           const mp_rnd_t rnd = fmt->round_towards_zero? GMP_RNDZ : GMP_RNDN;
14017           int inexact, sg;
14018           mpfr_t m;
14019           tree result_lg;
14020
14021           mpfr_init2 (m, prec);
14022           mpfr_from_real (m, ra, GMP_RNDN);
14023           mpfr_clear_flags ();
14024           inexact = mpfr_lgamma (m, &sg, m, rnd);
14025           result_lg = do_mpfr_ckconv (m, type, inexact);
14026           mpfr_clear (m);
14027           if (result_lg)
14028             {
14029               tree result_sg;
14030
14031               /* Dereference the arg_sg pointer argument.  */
14032               arg_sg = build_fold_indirect_ref (arg_sg);
14033               /* Assign the signgam value into *arg_sg. */
14034               result_sg = fold_build2 (MODIFY_EXPR,
14035                                        TREE_TYPE (arg_sg), arg_sg,
14036                                        build_int_cst (TREE_TYPE (arg_sg), sg));
14037               TREE_SIDE_EFFECTS (result_sg) = 1;
14038               /* Combine the signgam assignment with the lgamma result.  */
14039               result = non_lvalue (fold_build2 (COMPOUND_EXPR, type,
14040                                                 result_sg, result_lg));
14041             }
14042         }
14043     }
14044
14045   return result;
14046 }
14047
14048 /* If argument ARG is a COMPLEX_CST, call the one-argument mpc
14049    function FUNC on it and return the resulting value as a tree with
14050    type TYPE.  The mpfr precision is set to the precision of TYPE.  We
14051    assume that function FUNC returns zero if the result could be
14052    calculated exactly within the requested precision.  */
14053
14054 static tree
14055 do_mpc_arg1 (tree arg, tree type, int (*func)(mpc_ptr, mpc_srcptr, mpc_rnd_t))
14056 {
14057   tree result = NULL_TREE;
14058
14059   STRIP_NOPS (arg);
14060
14061   /* To proceed, MPFR must exactly represent the target floating point
14062      format, which only happens when the target base equals two.  */
14063   if (TREE_CODE (arg) == COMPLEX_CST && !TREE_OVERFLOW (arg)
14064       && TREE_CODE (TREE_TYPE (TREE_TYPE (arg))) == REAL_TYPE
14065       && REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (TREE_TYPE (arg))))->b == 2)
14066     {
14067       const REAL_VALUE_TYPE *const re = TREE_REAL_CST_PTR (TREE_REALPART (arg));
14068       const REAL_VALUE_TYPE *const im = TREE_REAL_CST_PTR (TREE_IMAGPART (arg));
14069
14070       if (real_isfinite (re) && real_isfinite (im))
14071         {
14072           const struct real_format *const fmt =
14073             REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (type)));
14074           const int prec = fmt->p;
14075           const mp_rnd_t rnd = fmt->round_towards_zero ? GMP_RNDZ : GMP_RNDN;
14076           const mpc_rnd_t crnd = fmt->round_towards_zero ? MPC_RNDZZ : MPC_RNDNN;
14077           int inexact;
14078           mpc_t m;
14079
14080           mpc_init2 (m, prec);
14081           mpfr_from_real (mpc_realref(m), re, rnd);
14082           mpfr_from_real (mpc_imagref(m), im, rnd);
14083           mpfr_clear_flags ();
14084           inexact = func (m, m, crnd);
14085           result = do_mpc_ckconv (m, type, inexact, /*force_convert=*/ 0);
14086           mpc_clear (m);
14087         }
14088     }
14089
14090   return result;
14091 }
14092
14093 /* If arguments ARG0 and ARG1 are a COMPLEX_CST, call the two-argument
14094    mpc function FUNC on it and return the resulting value as a tree
14095    with type TYPE.  The mpfr precision is set to the precision of
14096    TYPE.  We assume that function FUNC returns zero if the result
14097    could be calculated exactly within the requested precision.  If
14098    DO_NONFINITE is true, then fold expressions containing Inf or NaN
14099    in the arguments and/or results.  */
14100
14101 tree
14102 do_mpc_arg2 (tree arg0, tree arg1, tree type, int do_nonfinite,
14103              int (*func)(mpc_ptr, mpc_srcptr, mpc_srcptr, mpc_rnd_t))
14104 {
14105   tree result = NULL_TREE;
14106
14107   STRIP_NOPS (arg0);
14108   STRIP_NOPS (arg1);
14109
14110   /* To proceed, MPFR must exactly represent the target floating point
14111      format, which only happens when the target base equals two.  */
14112   if (TREE_CODE (arg0) == COMPLEX_CST && !TREE_OVERFLOW (arg0)
14113       && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE
14114       && TREE_CODE (arg1) == COMPLEX_CST && !TREE_OVERFLOW (arg1)
14115       && TREE_CODE (TREE_TYPE (TREE_TYPE (arg1))) == REAL_TYPE
14116       && REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (TREE_TYPE (arg0))))->b == 2)
14117     {
14118       const REAL_VALUE_TYPE *const re0 = TREE_REAL_CST_PTR (TREE_REALPART (arg0));
14119       const REAL_VALUE_TYPE *const im0 = TREE_REAL_CST_PTR (TREE_IMAGPART (arg0));
14120       const REAL_VALUE_TYPE *const re1 = TREE_REAL_CST_PTR (TREE_REALPART (arg1));
14121       const REAL_VALUE_TYPE *const im1 = TREE_REAL_CST_PTR (TREE_IMAGPART (arg1));
14122
14123       if (do_nonfinite
14124           || (real_isfinite (re0) && real_isfinite (im0)
14125               && real_isfinite (re1) && real_isfinite (im1)))
14126         {
14127           const struct real_format *const fmt =
14128             REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (type)));
14129           const int prec = fmt->p;
14130           const mp_rnd_t rnd = fmt->round_towards_zero ? GMP_RNDZ : GMP_RNDN;
14131           const mpc_rnd_t crnd = fmt->round_towards_zero ? MPC_RNDZZ : MPC_RNDNN;
14132           int inexact;
14133           mpc_t m0, m1;
14134
14135           mpc_init2 (m0, prec);
14136           mpc_init2 (m1, prec);
14137           mpfr_from_real (mpc_realref(m0), re0, rnd);
14138           mpfr_from_real (mpc_imagref(m0), im0, rnd);
14139           mpfr_from_real (mpc_realref(m1), re1, rnd);
14140           mpfr_from_real (mpc_imagref(m1), im1, rnd);
14141           mpfr_clear_flags ();
14142           inexact = func (m0, m0, m1, crnd);
14143           result = do_mpc_ckconv (m0, type, inexact, do_nonfinite);
14144           mpc_clear (m0);
14145           mpc_clear (m1);
14146         }
14147     }
14148
14149   return result;
14150 }
14151
14152 /* Fold a call STMT to __{,v}sprintf_chk.  Return NULL_TREE if
14153    a normal call should be emitted rather than expanding the function
14154    inline.  FCODE is either BUILT_IN_SPRINTF_CHK or BUILT_IN_VSPRINTF_CHK.  */
14155
14156 static tree
14157 gimple_fold_builtin_sprintf_chk (gimple stmt, enum built_in_function fcode)
14158 {
14159   int nargs = gimple_call_num_args (stmt);
14160
14161   return fold_builtin_sprintf_chk_1 (gimple_location (stmt), nargs,
14162                                      (nargs > 0
14163                                       ? gimple_call_arg_ptr (stmt, 0)
14164                                       : &error_mark_node), fcode);
14165 }
14166
14167 /* Fold a call STMT to {,v}snprintf.  Return NULL_TREE if
14168    a normal call should be emitted rather than expanding the function
14169    inline.  FCODE is either BUILT_IN_SNPRINTF_CHK or
14170    BUILT_IN_VSNPRINTF_CHK.  If MAXLEN is not NULL, it is maximum length
14171    passed as second argument.  */
14172
14173 tree
14174 gimple_fold_builtin_snprintf_chk (gimple stmt, tree maxlen,
14175                                   enum built_in_function fcode)
14176 {
14177   int nargs = gimple_call_num_args (stmt);
14178
14179   return fold_builtin_snprintf_chk_1 (gimple_location (stmt), nargs,
14180                                       (nargs > 0
14181                                        ? gimple_call_arg_ptr (stmt, 0)
14182                                        : &error_mark_node), maxlen, fcode);
14183 }
14184
14185 /* Builtins with folding operations that operate on "..." arguments
14186    need special handling; we need to store the arguments in a convenient
14187    data structure before attempting any folding.  Fortunately there are
14188    only a few builtins that fall into this category.  FNDECL is the
14189    function, EXP is the CALL_EXPR for the call, and IGNORE is true if the
14190    result of the function call is ignored.  */
14191
14192 static tree
14193 gimple_fold_builtin_varargs (tree fndecl, gimple stmt,
14194                              bool ignore ATTRIBUTE_UNUSED)
14195 {
14196   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
14197   tree ret = NULL_TREE;
14198
14199   switch (fcode)
14200     {
14201     case BUILT_IN_SPRINTF_CHK:
14202     case BUILT_IN_VSPRINTF_CHK:
14203       ret = gimple_fold_builtin_sprintf_chk (stmt, fcode);
14204       break;
14205
14206     case BUILT_IN_SNPRINTF_CHK:
14207     case BUILT_IN_VSNPRINTF_CHK:
14208       ret = gimple_fold_builtin_snprintf_chk (stmt, NULL_TREE, fcode);
14209
14210     default:
14211       break;
14212     }
14213   if (ret)
14214     {
14215       ret = build1 (NOP_EXPR, TREE_TYPE (ret), ret);
14216       TREE_NO_WARNING (ret) = 1;
14217       return ret;
14218     }
14219   return NULL_TREE;
14220 }
14221
14222 /* A wrapper function for builtin folding that prevents warnings for
14223    "statement without effect" and the like, caused by removing the
14224    call node earlier than the warning is generated.  */
14225
14226 tree
14227 fold_call_stmt (gimple stmt, bool ignore)
14228 {
14229   tree ret = NULL_TREE;
14230   tree fndecl = gimple_call_fndecl (stmt);
14231   location_t loc = gimple_location (stmt);
14232   if (fndecl
14233       && TREE_CODE (fndecl) == FUNCTION_DECL
14234       && DECL_BUILT_IN (fndecl)
14235       && !gimple_call_va_arg_pack_p (stmt))
14236     {
14237       int nargs = gimple_call_num_args (stmt);
14238       tree *args = (nargs > 0
14239                     ? gimple_call_arg_ptr (stmt, 0)
14240                     : &error_mark_node);
14241
14242       if (avoid_folding_inline_builtin (fndecl))
14243         return NULL_TREE;
14244       if (DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_MD)
14245         {
14246           return targetm.fold_builtin (fndecl, nargs, args, ignore);
14247         }
14248       else
14249         {
14250           if (nargs <= MAX_ARGS_TO_FOLD_BUILTIN)
14251             ret = fold_builtin_n (loc, fndecl, args, nargs, ignore);
14252           if (!ret)
14253             ret = gimple_fold_builtin_varargs (fndecl, stmt, ignore);
14254           if (ret)
14255             {
14256               /* Propagate location information from original call to
14257                  expansion of builtin.  Otherwise things like
14258                  maybe_emit_chk_warning, that operate on the expansion
14259                  of a builtin, will use the wrong location information.  */
14260               if (gimple_has_location (stmt))
14261                 {
14262                   tree realret = ret;
14263                   if (TREE_CODE (ret) == NOP_EXPR)
14264                     realret = TREE_OPERAND (ret, 0);
14265                   if (CAN_HAVE_LOCATION_P (realret)
14266                       && !EXPR_HAS_LOCATION (realret))
14267                     SET_EXPR_LOCATION (realret, loc);
14268                   return realret;
14269                 }
14270               return ret;
14271             }
14272         }
14273     }
14274   return NULL_TREE;
14275 }
14276
14277 /* Look up the function in builtin_decl that corresponds to DECL
14278    and set ASMSPEC as its user assembler name.  DECL must be a
14279    function decl that declares a builtin.  */
14280
14281 void
14282 set_builtin_user_assembler_name (tree decl, const char *asmspec)
14283 {
14284   tree builtin;
14285   gcc_assert (TREE_CODE (decl) == FUNCTION_DECL
14286               && DECL_BUILT_IN_CLASS (decl) == BUILT_IN_NORMAL
14287               && asmspec != 0);
14288
14289   builtin = builtin_decl_explicit (DECL_FUNCTION_CODE (decl));
14290   set_user_assembler_name (builtin, asmspec);
14291   switch (DECL_FUNCTION_CODE (decl))
14292     {
14293     case BUILT_IN_MEMCPY:
14294       init_block_move_fn (asmspec);
14295       memcpy_libfunc = set_user_assembler_libfunc ("memcpy", asmspec);
14296       break;
14297     case BUILT_IN_MEMSET:
14298       init_block_clear_fn (asmspec);
14299       memset_libfunc = set_user_assembler_libfunc ("memset", asmspec);
14300       break;
14301     case BUILT_IN_MEMMOVE:
14302       memmove_libfunc = set_user_assembler_libfunc ("memmove", asmspec);
14303       break;
14304     case BUILT_IN_MEMCMP:
14305       memcmp_libfunc = set_user_assembler_libfunc ("memcmp", asmspec);
14306       break;
14307     case BUILT_IN_ABORT:
14308       abort_libfunc = set_user_assembler_libfunc ("abort", asmspec);
14309       break;
14310     case BUILT_IN_FFS:
14311       if (INT_TYPE_SIZE < BITS_PER_WORD)
14312         {
14313           set_user_assembler_libfunc ("ffs", asmspec);
14314           set_optab_libfunc (ffs_optab, mode_for_size (INT_TYPE_SIZE,
14315                                                        MODE_INT, 0), "ffs");
14316         }
14317       break;
14318     default:
14319       break;
14320     }
14321 }
14322
14323 /* Return true if DECL is a builtin that expands to a constant or similarly
14324    simple code.  */
14325 bool
14326 is_simple_builtin (tree decl)
14327 {
14328   if (decl && DECL_BUILT_IN_CLASS (decl) == BUILT_IN_NORMAL)
14329     switch (DECL_FUNCTION_CODE (decl))
14330       {
14331         /* Builtins that expand to constants.  */
14332       case BUILT_IN_CONSTANT_P:
14333       case BUILT_IN_EXPECT:
14334       case BUILT_IN_OBJECT_SIZE:
14335       case BUILT_IN_UNREACHABLE:
14336         /* Simple register moves or loads from stack.  */
14337       case BUILT_IN_ASSUME_ALIGNED:
14338       case BUILT_IN_RETURN_ADDRESS:
14339       case BUILT_IN_EXTRACT_RETURN_ADDR:
14340       case BUILT_IN_FROB_RETURN_ADDR:
14341       case BUILT_IN_RETURN:
14342       case BUILT_IN_AGGREGATE_INCOMING_ADDRESS:
14343       case BUILT_IN_FRAME_ADDRESS:
14344       case BUILT_IN_VA_END:
14345       case BUILT_IN_STACK_SAVE:
14346       case BUILT_IN_STACK_RESTORE:
14347         /* Exception state returns or moves registers around.  */
14348       case BUILT_IN_EH_FILTER:
14349       case BUILT_IN_EH_POINTER:
14350       case BUILT_IN_EH_COPY_VALUES:
14351         return true;
14352
14353       default:
14354         return false;
14355       }
14356
14357   return false;
14358 }
14359
14360 /* Return true if DECL is a builtin that is not expensive, i.e., they are
14361    most probably expanded inline into reasonably simple code.  This is a
14362    superset of is_simple_builtin.  */
14363 bool
14364 is_inexpensive_builtin (tree decl)
14365 {
14366   if (!decl)
14367     return false;
14368   else if (DECL_BUILT_IN_CLASS (decl) == BUILT_IN_MD)
14369     return true;
14370   else if (DECL_BUILT_IN_CLASS (decl) == BUILT_IN_NORMAL)
14371     switch (DECL_FUNCTION_CODE (decl))
14372       {
14373       case BUILT_IN_ABS:
14374       case BUILT_IN_ALLOCA:
14375       case BUILT_IN_ALLOCA_WITH_ALIGN:
14376       case BUILT_IN_BSWAP16:
14377       case BUILT_IN_BSWAP32:
14378       case BUILT_IN_BSWAP64:
14379       case BUILT_IN_CLZ:
14380       case BUILT_IN_CLZIMAX:
14381       case BUILT_IN_CLZL:
14382       case BUILT_IN_CLZLL:
14383       case BUILT_IN_CTZ:
14384       case BUILT_IN_CTZIMAX:
14385       case BUILT_IN_CTZL:
14386       case BUILT_IN_CTZLL:
14387       case BUILT_IN_FFS:
14388       case BUILT_IN_FFSIMAX:
14389       case BUILT_IN_FFSL:
14390       case BUILT_IN_FFSLL:
14391       case BUILT_IN_IMAXABS:
14392       case BUILT_IN_FINITE:
14393       case BUILT_IN_FINITEF:
14394       case BUILT_IN_FINITEL:
14395       case BUILT_IN_FINITED32:
14396       case BUILT_IN_FINITED64:
14397       case BUILT_IN_FINITED128:
14398       case BUILT_IN_FPCLASSIFY:
14399       case BUILT_IN_ISFINITE:
14400       case BUILT_IN_ISINF_SIGN:
14401       case BUILT_IN_ISINF:
14402       case BUILT_IN_ISINFF:
14403       case BUILT_IN_ISINFL:
14404       case BUILT_IN_ISINFD32:
14405       case BUILT_IN_ISINFD64:
14406       case BUILT_IN_ISINFD128:
14407       case BUILT_IN_ISNAN:
14408       case BUILT_IN_ISNANF:
14409       case BUILT_IN_ISNANL:
14410       case BUILT_IN_ISNAND32:
14411       case BUILT_IN_ISNAND64:
14412       case BUILT_IN_ISNAND128:
14413       case BUILT_IN_ISNORMAL:
14414       case BUILT_IN_ISGREATER:
14415       case BUILT_IN_ISGREATEREQUAL:
14416       case BUILT_IN_ISLESS:
14417       case BUILT_IN_ISLESSEQUAL:
14418       case BUILT_IN_ISLESSGREATER:
14419       case BUILT_IN_ISUNORDERED:
14420       case BUILT_IN_VA_ARG_PACK:
14421       case BUILT_IN_VA_ARG_PACK_LEN:
14422       case BUILT_IN_VA_COPY:
14423       case BUILT_IN_TRAP:
14424       case BUILT_IN_SAVEREGS:
14425       case BUILT_IN_POPCOUNTL:
14426       case BUILT_IN_POPCOUNTLL:
14427       case BUILT_IN_POPCOUNTIMAX:
14428       case BUILT_IN_POPCOUNT:
14429       case BUILT_IN_PARITYL:
14430       case BUILT_IN_PARITYLL:
14431       case BUILT_IN_PARITYIMAX:
14432       case BUILT_IN_PARITY:
14433       case BUILT_IN_LABS:
14434       case BUILT_IN_LLABS:
14435       case BUILT_IN_PREFETCH:
14436         return true;
14437
14438       default:
14439         return is_simple_builtin (decl);
14440       }
14441
14442   return false;
14443 }