OSDN Git Service

* hwint.c: New. Extracted from toplev.c.
[pf3gnuchains/gcc-fork.git] / gcc / builtins.c
1 /* Expand builtin functions.
2    Copyright (C) 1988, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
3    2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010
4    Free Software Foundation, Inc.
5
6 This file is part of GCC.
7
8 GCC is free software; you can redistribute it and/or modify it under
9 the terms of the GNU General Public License as published by the Free
10 Software Foundation; either version 3, or (at your option) any later
11 version.
12
13 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
14 WARRANTY; without even the implied warranty of MERCHANTABILITY or
15 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
16 for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with GCC; see the file COPYING3.  If not see
20 <http://www.gnu.org/licenses/>.  */
21
22 #include "config.h"
23 #include "system.h"
24 #include "coretypes.h"
25 #include "tm.h"
26 #include "machmode.h"
27 #include "rtl.h"
28 #include "tree.h"
29 #include "realmpfr.h"
30 #include "gimple.h"
31 #include "flags.h"
32 #include "regs.h"
33 #include "hard-reg-set.h"
34 #include "except.h"
35 #include "function.h"
36 #include "insn-config.h"
37 #include "expr.h"
38 #include "optabs.h"
39 #include "libfuncs.h"
40 #include "recog.h"
41 #include "output.h"
42 #include "typeclass.h"
43 #include "predict.h"
44 #include "tm_p.h"
45 #include "target.h"
46 #include "langhooks.h"
47 #include "basic-block.h"
48 #include "tree-mudflap.h"
49 #include "tree-flow.h"
50 #include "value-prof.h"
51 #include "diagnostic-core.h"
52 #include "builtins.h"
53
54 #ifndef SLOW_UNALIGNED_ACCESS
55 #define SLOW_UNALIGNED_ACCESS(MODE, ALIGN) STRICT_ALIGNMENT
56 #endif
57
58 #ifndef PAD_VARARGS_DOWN
59 #define PAD_VARARGS_DOWN BYTES_BIG_ENDIAN
60 #endif
61 static tree do_mpc_arg1 (tree, tree, int (*)(mpc_ptr, mpc_srcptr, mpc_rnd_t));
62
63 struct target_builtins default_target_builtins;
64 #if SWITCHABLE_TARGET
65 struct target_builtins *this_target_builtins = &default_target_builtins;
66 #endif
67
68 /* Define the names of the builtin function types and codes.  */
69 const char *const built_in_class_names[4]
70   = {"NOT_BUILT_IN", "BUILT_IN_FRONTEND", "BUILT_IN_MD", "BUILT_IN_NORMAL"};
71
72 #define DEF_BUILTIN(X, N, C, T, LT, B, F, NA, AT, IM, COND) #X,
73 const char * built_in_names[(int) END_BUILTINS] =
74 {
75 #include "builtins.def"
76 };
77 #undef DEF_BUILTIN
78
79 /* Setup an array of _DECL trees, make sure each element is
80    initialized to NULL_TREE.  */
81 tree built_in_decls[(int) END_BUILTINS];
82 /* Declarations used when constructing the builtin implicitly in the compiler.
83    It may be NULL_TREE when this is invalid (for instance runtime is not
84    required to implement the function call in all cases).  */
85 tree implicit_built_in_decls[(int) END_BUILTINS];
86
87 static const char *c_getstr (tree);
88 static rtx c_readstr (const char *, enum machine_mode);
89 static int target_char_cast (tree, char *);
90 static rtx get_memory_rtx (tree, tree);
91 static int apply_args_size (void);
92 static int apply_result_size (void);
93 #if defined (HAVE_untyped_call) || defined (HAVE_untyped_return)
94 static rtx result_vector (int, rtx);
95 #endif
96 static void expand_builtin_update_setjmp_buf (rtx);
97 static void expand_builtin_prefetch (tree);
98 static rtx expand_builtin_apply_args (void);
99 static rtx expand_builtin_apply_args_1 (void);
100 static rtx expand_builtin_apply (rtx, rtx, rtx);
101 static void expand_builtin_return (rtx);
102 static enum type_class type_to_class (tree);
103 static rtx expand_builtin_classify_type (tree);
104 static void expand_errno_check (tree, rtx);
105 static rtx expand_builtin_mathfn (tree, rtx, rtx);
106 static rtx expand_builtin_mathfn_2 (tree, rtx, rtx);
107 static rtx expand_builtin_mathfn_3 (tree, rtx, rtx);
108 static rtx expand_builtin_mathfn_ternary (tree, rtx, rtx);
109 static rtx expand_builtin_interclass_mathfn (tree, rtx);
110 static rtx expand_builtin_sincos (tree);
111 static rtx expand_builtin_cexpi (tree, rtx);
112 static rtx expand_builtin_int_roundingfn (tree, rtx);
113 static rtx expand_builtin_int_roundingfn_2 (tree, rtx);
114 static rtx expand_builtin_next_arg (void);
115 static rtx expand_builtin_va_start (tree);
116 static rtx expand_builtin_va_end (tree);
117 static rtx expand_builtin_va_copy (tree);
118 static rtx expand_builtin_memcmp (tree, rtx, enum machine_mode);
119 static rtx expand_builtin_strcmp (tree, rtx);
120 static rtx expand_builtin_strncmp (tree, rtx, enum machine_mode);
121 static rtx builtin_memcpy_read_str (void *, HOST_WIDE_INT, enum machine_mode);
122 static rtx expand_builtin_memcpy (tree, rtx);
123 static rtx expand_builtin_mempcpy (tree, rtx, enum machine_mode);
124 static rtx expand_builtin_mempcpy_args (tree, tree, tree, rtx,
125                                         enum machine_mode, int);
126 static rtx expand_builtin_strcpy (tree, rtx);
127 static rtx expand_builtin_strcpy_args (tree, tree, rtx);
128 static rtx expand_builtin_stpcpy (tree, rtx, enum machine_mode);
129 static rtx expand_builtin_strncpy (tree, rtx);
130 static rtx builtin_memset_gen_str (void *, HOST_WIDE_INT, enum machine_mode);
131 static rtx expand_builtin_memset (tree, rtx, enum machine_mode);
132 static rtx expand_builtin_memset_args (tree, tree, tree, rtx, enum machine_mode, tree);
133 static rtx expand_builtin_bzero (tree);
134 static rtx expand_builtin_strlen (tree, rtx, enum machine_mode);
135 static rtx expand_builtin_alloca (tree, bool);
136 static rtx expand_builtin_unop (enum machine_mode, tree, rtx, rtx, optab);
137 static rtx expand_builtin_frame_address (tree, tree);
138 static tree stabilize_va_list_loc (location_t, tree, int);
139 static rtx expand_builtin_expect (tree, rtx);
140 static tree fold_builtin_constant_p (tree);
141 static tree fold_builtin_expect (location_t, tree, tree);
142 static tree fold_builtin_classify_type (tree);
143 static tree fold_builtin_strlen (location_t, tree, tree);
144 static tree fold_builtin_inf (location_t, tree, int);
145 static tree fold_builtin_nan (tree, tree, int);
146 static tree rewrite_call_expr (location_t, tree, int, tree, int, ...);
147 static bool validate_arg (const_tree, enum tree_code code);
148 static bool integer_valued_real_p (tree);
149 static tree fold_trunc_transparent_mathfn (location_t, tree, tree);
150 static bool readonly_data_expr (tree);
151 static rtx expand_builtin_fabs (tree, rtx, rtx);
152 static rtx expand_builtin_signbit (tree, rtx);
153 static tree fold_builtin_sqrt (location_t, tree, tree);
154 static tree fold_builtin_cbrt (location_t, tree, tree);
155 static tree fold_builtin_pow (location_t, tree, tree, tree, tree);
156 static tree fold_builtin_powi (location_t, tree, tree, tree, tree);
157 static tree fold_builtin_cos (location_t, tree, tree, tree);
158 static tree fold_builtin_cosh (location_t, tree, tree, tree);
159 static tree fold_builtin_tan (tree, tree);
160 static tree fold_builtin_trunc (location_t, tree, tree);
161 static tree fold_builtin_floor (location_t, tree, tree);
162 static tree fold_builtin_ceil (location_t, tree, tree);
163 static tree fold_builtin_round (location_t, tree, tree);
164 static tree fold_builtin_int_roundingfn (location_t, tree, tree);
165 static tree fold_builtin_bitop (tree, tree);
166 static tree fold_builtin_memory_op (location_t, tree, tree, tree, tree, bool, int);
167 static tree fold_builtin_strchr (location_t, tree, tree, tree);
168 static tree fold_builtin_memchr (location_t, tree, tree, tree, tree);
169 static tree fold_builtin_memcmp (location_t, tree, tree, tree);
170 static tree fold_builtin_strcmp (location_t, tree, tree);
171 static tree fold_builtin_strncmp (location_t, tree, tree, tree);
172 static tree fold_builtin_signbit (location_t, tree, tree);
173 static tree fold_builtin_copysign (location_t, tree, tree, tree, tree);
174 static tree fold_builtin_isascii (location_t, tree);
175 static tree fold_builtin_toascii (location_t, tree);
176 static tree fold_builtin_isdigit (location_t, tree);
177 static tree fold_builtin_fabs (location_t, tree, tree);
178 static tree fold_builtin_abs (location_t, tree, tree);
179 static tree fold_builtin_unordered_cmp (location_t, tree, tree, tree, enum tree_code,
180                                         enum tree_code);
181 static tree fold_builtin_n (location_t, tree, tree *, int, bool);
182 static tree fold_builtin_0 (location_t, tree, bool);
183 static tree fold_builtin_1 (location_t, tree, tree, bool);
184 static tree fold_builtin_2 (location_t, tree, tree, tree, bool);
185 static tree fold_builtin_3 (location_t, tree, tree, tree, tree, bool);
186 static tree fold_builtin_4 (location_t, tree, tree, tree, tree, tree, bool);
187 static tree fold_builtin_varargs (location_t, tree, tree, bool);
188
189 static tree fold_builtin_strpbrk (location_t, tree, tree, tree);
190 static tree fold_builtin_strstr (location_t, tree, tree, tree);
191 static tree fold_builtin_strrchr (location_t, tree, tree, tree);
192 static tree fold_builtin_strcat (location_t, tree, tree);
193 static tree fold_builtin_strncat (location_t, tree, tree, tree);
194 static tree fold_builtin_strspn (location_t, tree, tree);
195 static tree fold_builtin_strcspn (location_t, tree, tree);
196 static tree fold_builtin_sprintf (location_t, tree, tree, tree, int);
197
198 static rtx expand_builtin_object_size (tree);
199 static rtx expand_builtin_memory_chk (tree, rtx, enum machine_mode,
200                                       enum built_in_function);
201 static void maybe_emit_chk_warning (tree, enum built_in_function);
202 static void maybe_emit_sprintf_chk_warning (tree, enum built_in_function);
203 static void maybe_emit_free_warning (tree);
204 static tree fold_builtin_object_size (tree, tree);
205 static tree fold_builtin_strcat_chk (location_t, tree, tree, tree, tree);
206 static tree fold_builtin_strncat_chk (location_t, tree, tree, tree, tree, tree);
207 static tree fold_builtin_sprintf_chk (location_t, tree, enum built_in_function);
208 static tree fold_builtin_printf (location_t, tree, tree, tree, bool, enum built_in_function);
209 static tree fold_builtin_fprintf (location_t, tree, tree, tree, tree, bool,
210                                   enum built_in_function);
211 static bool init_target_chars (void);
212
213 static unsigned HOST_WIDE_INT target_newline;
214 static unsigned HOST_WIDE_INT target_percent;
215 static unsigned HOST_WIDE_INT target_c;
216 static unsigned HOST_WIDE_INT target_s;
217 static char target_percent_c[3];
218 static char target_percent_s[3];
219 static char target_percent_s_newline[4];
220 static tree do_mpfr_arg1 (tree, tree, int (*)(mpfr_ptr, mpfr_srcptr, mp_rnd_t),
221                           const REAL_VALUE_TYPE *, const REAL_VALUE_TYPE *, bool);
222 static tree do_mpfr_arg2 (tree, tree, tree,
223                           int (*)(mpfr_ptr, mpfr_srcptr, mpfr_srcptr, mp_rnd_t));
224 static tree do_mpfr_arg3 (tree, tree, tree, tree,
225                           int (*)(mpfr_ptr, mpfr_srcptr, mpfr_srcptr, mpfr_srcptr, mp_rnd_t));
226 static tree do_mpfr_sincos (tree, tree, tree);
227 static tree do_mpfr_bessel_n (tree, tree, tree,
228                               int (*)(mpfr_ptr, long, mpfr_srcptr, mp_rnd_t),
229                               const REAL_VALUE_TYPE *, bool);
230 static tree do_mpfr_remquo (tree, tree, tree);
231 static tree do_mpfr_lgamma_r (tree, tree, tree);
232
233 /* Return true if NAME starts with __builtin_ or __sync_.  */
234
235 bool
236 is_builtin_name (const char *name)
237 {
238   if (strncmp (name, "__builtin_", 10) == 0)
239     return true;
240   if (strncmp (name, "__sync_", 7) == 0)
241     return true;
242   return false;
243 }
244
245
246 /* Return true if DECL is a function symbol representing a built-in.  */
247
248 bool
249 is_builtin_fn (tree decl)
250 {
251   return TREE_CODE (decl) == FUNCTION_DECL && DECL_BUILT_IN (decl);
252 }
253
254
255 /* Return true if NODE should be considered for inline expansion regardless
256    of the optimization level.  This means whenever a function is invoked with
257    its "internal" name, which normally contains the prefix "__builtin".  */
258
259 static bool
260 called_as_built_in (tree node)
261 {
262   /* Note that we must use DECL_NAME, not DECL_ASSEMBLER_NAME_SET_P since
263      we want the name used to call the function, not the name it
264      will have. */
265   const char *name = IDENTIFIER_POINTER (DECL_NAME (node));
266   return is_builtin_name (name);
267 }
268
269 /* Return the alignment in bits of EXP, an object.
270    Don't return more than MAX_ALIGN no matter what.  */
271
272 unsigned int
273 get_object_alignment (tree exp, unsigned int max_align)
274 {
275   HOST_WIDE_INT bitsize, bitpos;
276   tree offset;
277   enum machine_mode mode;
278   int unsignedp, volatilep;
279   unsigned int align, inner;
280
281   /* Get the innermost object and the constant (bitpos) and possibly
282      variable (offset) offset of the access.  */
283   exp = get_inner_reference (exp, &bitsize, &bitpos, &offset,
284                              &mode, &unsignedp, &volatilep, true);
285
286   /* Extract alignment information from the innermost object and
287      possibly adjust bitpos and offset.  */
288   if (TREE_CODE (exp) == CONST_DECL)
289     exp = DECL_INITIAL (exp);
290   if (DECL_P (exp)
291       && TREE_CODE (exp) != LABEL_DECL)
292     align = DECL_ALIGN (exp);
293   else if (CONSTANT_CLASS_P (exp))
294     {
295       align = TYPE_ALIGN (TREE_TYPE (exp));
296 #ifdef CONSTANT_ALIGNMENT
297       align = (unsigned)CONSTANT_ALIGNMENT (exp, align);
298 #endif
299     }
300   else if (TREE_CODE (exp) == VIEW_CONVERT_EXPR)
301     align = TYPE_ALIGN (TREE_TYPE (exp));
302   else if (TREE_CODE (exp) == INDIRECT_REF)
303     align = TYPE_ALIGN (TREE_TYPE (exp));
304   else if (TREE_CODE (exp) == MEM_REF)
305     {
306       tree addr = TREE_OPERAND (exp, 0);
307       struct ptr_info_def *pi;
308       if (TREE_CODE (addr) == BIT_AND_EXPR
309           && TREE_CODE (TREE_OPERAND (addr, 1)) == INTEGER_CST)
310         {
311           align = (TREE_INT_CST_LOW (TREE_OPERAND (addr, 1))
312                     & -TREE_INT_CST_LOW (TREE_OPERAND (addr, 1)));
313           align *= BITS_PER_UNIT;
314           addr = TREE_OPERAND (addr, 0);
315         }
316       else
317         align = BITS_PER_UNIT;
318       if (TREE_CODE (addr) == SSA_NAME
319           && (pi = SSA_NAME_PTR_INFO (addr)))
320         {
321           bitpos += (pi->misalign * BITS_PER_UNIT) & ~(align - 1);
322           align = MAX (pi->align * BITS_PER_UNIT, align);
323         }
324       else if (TREE_CODE (addr) == ADDR_EXPR)
325         align = MAX (align, get_object_alignment (TREE_OPERAND (addr, 0),
326                                                   max_align));
327       bitpos += mem_ref_offset (exp).low * BITS_PER_UNIT;
328     }
329   else if (TREE_CODE (exp) == TARGET_MEM_REF)
330     {
331       struct ptr_info_def *pi;
332       tree addr = TMR_BASE (exp);
333       if (TREE_CODE (addr) == BIT_AND_EXPR
334           && TREE_CODE (TREE_OPERAND (addr, 1)) == INTEGER_CST)
335         {
336           align = (TREE_INT_CST_LOW (TREE_OPERAND (addr, 1))
337                    & -TREE_INT_CST_LOW (TREE_OPERAND (addr, 1)));
338           align *= BITS_PER_UNIT;
339           addr = TREE_OPERAND (addr, 0);
340         }
341       else
342         align = BITS_PER_UNIT;
343       if (TREE_CODE (addr) == SSA_NAME
344           && (pi = SSA_NAME_PTR_INFO (addr)))
345         {
346           bitpos += (pi->misalign * BITS_PER_UNIT) & ~(align - 1);
347           align = MAX (pi->align * BITS_PER_UNIT, align);
348         }
349       else if (TREE_CODE (addr) == ADDR_EXPR)
350         align = MAX (align, get_object_alignment (TREE_OPERAND (addr, 0),
351                                                   max_align));
352       if (TMR_OFFSET (exp))
353         bitpos += TREE_INT_CST_LOW (TMR_OFFSET (exp)) * BITS_PER_UNIT;
354       if (TMR_INDEX (exp) && TMR_STEP (exp))
355         {
356           unsigned HOST_WIDE_INT step = TREE_INT_CST_LOW (TMR_STEP (exp));
357           align = MIN (align, (step & -step) * BITS_PER_UNIT);
358         }
359       else if (TMR_INDEX (exp))
360         align = BITS_PER_UNIT;
361       if (TMR_INDEX2 (exp))
362         align = BITS_PER_UNIT;
363     }
364   else
365     align = BITS_PER_UNIT;
366
367   /* If there is a non-constant offset part extract the maximum
368      alignment that can prevail.  */
369   inner = max_align;
370   while (offset)
371     {
372       tree next_offset;
373
374       if (TREE_CODE (offset) == PLUS_EXPR)
375         {
376           next_offset = TREE_OPERAND (offset, 0);
377           offset = TREE_OPERAND (offset, 1);
378         }
379       else
380         next_offset = NULL;
381       if (host_integerp (offset, 1))
382         {
383           /* Any overflow in calculating offset_bits won't change
384              the alignment.  */
385           unsigned offset_bits
386             = ((unsigned) tree_low_cst (offset, 1) * BITS_PER_UNIT);
387
388           if (offset_bits)
389             inner = MIN (inner, (offset_bits & -offset_bits));
390         }
391       else if (TREE_CODE (offset) == MULT_EXPR
392                && host_integerp (TREE_OPERAND (offset, 1), 1))
393         {
394           /* Any overflow in calculating offset_factor won't change
395              the alignment.  */
396           unsigned offset_factor
397             = ((unsigned) tree_low_cst (TREE_OPERAND (offset, 1), 1)
398                * BITS_PER_UNIT);
399
400           if (offset_factor)
401             inner = MIN (inner, (offset_factor & -offset_factor));
402         }
403       else
404         {
405           inner = MIN (inner, BITS_PER_UNIT);
406           break;
407         }
408       offset = next_offset;
409     }
410
411   /* Alignment is innermost object alignment adjusted by the constant
412      and non-constant offset parts.  */
413   align = MIN (align, inner);
414   bitpos = bitpos & (align - 1);
415
416   /* align and bitpos now specify known low bits of the pointer.
417      ptr & (align - 1) == bitpos.  */
418
419   if (bitpos != 0)
420     align = (bitpos & -bitpos);
421
422   return MIN (align, max_align);
423 }
424
425 /* Returns true iff we can trust that alignment information has been
426    calculated properly.  */
427
428 bool
429 can_trust_pointer_alignment (void)
430 {
431   /* We rely on TER to compute accurate alignment information.  */
432   return (optimize && flag_tree_ter);
433 }
434
435 /* Return the alignment in bits of EXP, a pointer valued expression.
436    But don't return more than MAX_ALIGN no matter what.
437    The alignment returned is, by default, the alignment of the thing that
438    EXP points to.  If it is not a POINTER_TYPE, 0 is returned.
439
440    Otherwise, look at the expression to see if we can do better, i.e., if the
441    expression is actually pointing at an object whose alignment is tighter.  */
442
443 unsigned int
444 get_pointer_alignment (tree exp, unsigned int max_align)
445 {
446   STRIP_NOPS (exp);
447
448   if (TREE_CODE (exp) == ADDR_EXPR)
449     return get_object_alignment (TREE_OPERAND (exp, 0), max_align);
450   else if (TREE_CODE (exp) == SSA_NAME
451            && POINTER_TYPE_P (TREE_TYPE (exp)))
452     {
453       struct ptr_info_def *pi = SSA_NAME_PTR_INFO (exp);
454       unsigned align;
455       if (!pi)
456         return BITS_PER_UNIT;
457       if (pi->misalign != 0)
458         align = (pi->misalign & -pi->misalign);
459       else
460         align = pi->align;
461       return MIN (max_align, align * BITS_PER_UNIT);
462     }
463
464   return POINTER_TYPE_P (TREE_TYPE (exp)) ? BITS_PER_UNIT : 0;
465 }
466
467 /* Compute the length of a C string.  TREE_STRING_LENGTH is not the right
468    way, because it could contain a zero byte in the middle.
469    TREE_STRING_LENGTH is the size of the character array, not the string.
470
471    ONLY_VALUE should be nonzero if the result is not going to be emitted
472    into the instruction stream and zero if it is going to be expanded.
473    E.g. with i++ ? "foo" : "bar", if ONLY_VALUE is nonzero, constant 3
474    is returned, otherwise NULL, since
475    len = c_strlen (src, 1); if (len) expand_expr (len, ...); would not
476    evaluate the side-effects.
477
478    The value returned is of type `ssizetype'.
479
480    Unfortunately, string_constant can't access the values of const char
481    arrays with initializers, so neither can we do so here.  */
482
483 tree
484 c_strlen (tree src, int only_value)
485 {
486   tree offset_node;
487   HOST_WIDE_INT offset;
488   int max;
489   const char *ptr;
490   location_t loc;
491
492   STRIP_NOPS (src);
493   if (TREE_CODE (src) == COND_EXPR
494       && (only_value || !TREE_SIDE_EFFECTS (TREE_OPERAND (src, 0))))
495     {
496       tree len1, len2;
497
498       len1 = c_strlen (TREE_OPERAND (src, 1), only_value);
499       len2 = c_strlen (TREE_OPERAND (src, 2), only_value);
500       if (tree_int_cst_equal (len1, len2))
501         return len1;
502     }
503
504   if (TREE_CODE (src) == COMPOUND_EXPR
505       && (only_value || !TREE_SIDE_EFFECTS (TREE_OPERAND (src, 0))))
506     return c_strlen (TREE_OPERAND (src, 1), only_value);
507
508   loc = EXPR_LOC_OR_HERE (src);
509
510   src = string_constant (src, &offset_node);
511   if (src == 0)
512     return NULL_TREE;
513
514   max = TREE_STRING_LENGTH (src) - 1;
515   ptr = TREE_STRING_POINTER (src);
516
517   if (offset_node && TREE_CODE (offset_node) != INTEGER_CST)
518     {
519       /* If the string has an internal zero byte (e.g., "foo\0bar"), we can't
520          compute the offset to the following null if we don't know where to
521          start searching for it.  */
522       int i;
523
524       for (i = 0; i < max; i++)
525         if (ptr[i] == 0)
526           return NULL_TREE;
527
528       /* We don't know the starting offset, but we do know that the string
529          has no internal zero bytes.  We can assume that the offset falls
530          within the bounds of the string; otherwise, the programmer deserves
531          what he gets.  Subtract the offset from the length of the string,
532          and return that.  This would perhaps not be valid if we were dealing
533          with named arrays in addition to literal string constants.  */
534
535       return size_diffop_loc (loc, size_int (max), offset_node);
536     }
537
538   /* We have a known offset into the string.  Start searching there for
539      a null character if we can represent it as a single HOST_WIDE_INT.  */
540   if (offset_node == 0)
541     offset = 0;
542   else if (! host_integerp (offset_node, 0))
543     offset = -1;
544   else
545     offset = tree_low_cst (offset_node, 0);
546
547   /* If the offset is known to be out of bounds, warn, and call strlen at
548      runtime.  */
549   if (offset < 0 || offset > max)
550     {
551      /* Suppress multiple warnings for propagated constant strings.  */
552       if (! TREE_NO_WARNING (src))
553         {
554           warning_at (loc, 0, "offset outside bounds of constant string");
555           TREE_NO_WARNING (src) = 1;
556         }
557       return NULL_TREE;
558     }
559
560   /* Use strlen to search for the first zero byte.  Since any strings
561      constructed with build_string will have nulls appended, we win even
562      if we get handed something like (char[4])"abcd".
563
564      Since OFFSET is our starting index into the string, no further
565      calculation is needed.  */
566   return ssize_int (strlen (ptr + offset));
567 }
568
569 /* Return a char pointer for a C string if it is a string constant
570    or sum of string constant and integer constant.  */
571
572 static const char *
573 c_getstr (tree src)
574 {
575   tree offset_node;
576
577   src = string_constant (src, &offset_node);
578   if (src == 0)
579     return 0;
580
581   if (offset_node == 0)
582     return TREE_STRING_POINTER (src);
583   else if (!host_integerp (offset_node, 1)
584            || compare_tree_int (offset_node, TREE_STRING_LENGTH (src) - 1) > 0)
585     return 0;
586
587   return TREE_STRING_POINTER (src) + tree_low_cst (offset_node, 1);
588 }
589
590 /* Return a CONST_INT or CONST_DOUBLE corresponding to target reading
591    GET_MODE_BITSIZE (MODE) bits from string constant STR.  */
592
593 static rtx
594 c_readstr (const char *str, enum machine_mode mode)
595 {
596   HOST_WIDE_INT c[2];
597   HOST_WIDE_INT ch;
598   unsigned int i, j;
599
600   gcc_assert (GET_MODE_CLASS (mode) == MODE_INT);
601
602   c[0] = 0;
603   c[1] = 0;
604   ch = 1;
605   for (i = 0; i < GET_MODE_SIZE (mode); i++)
606     {
607       j = i;
608       if (WORDS_BIG_ENDIAN)
609         j = GET_MODE_SIZE (mode) - i - 1;
610       if (BYTES_BIG_ENDIAN != WORDS_BIG_ENDIAN
611           && GET_MODE_SIZE (mode) > UNITS_PER_WORD)
612         j = j + UNITS_PER_WORD - 2 * (j % UNITS_PER_WORD) - 1;
613       j *= BITS_PER_UNIT;
614       gcc_assert (j < 2 * HOST_BITS_PER_WIDE_INT);
615
616       if (ch)
617         ch = (unsigned char) str[i];
618       c[j / HOST_BITS_PER_WIDE_INT] |= ch << (j % HOST_BITS_PER_WIDE_INT);
619     }
620   return immed_double_const (c[0], c[1], mode);
621 }
622
623 /* Cast a target constant CST to target CHAR and if that value fits into
624    host char type, return zero and put that value into variable pointed to by
625    P.  */
626
627 static int
628 target_char_cast (tree cst, char *p)
629 {
630   unsigned HOST_WIDE_INT val, hostval;
631
632   if (TREE_CODE (cst) != INTEGER_CST
633       || CHAR_TYPE_SIZE > HOST_BITS_PER_WIDE_INT)
634     return 1;
635
636   val = TREE_INT_CST_LOW (cst);
637   if (CHAR_TYPE_SIZE < HOST_BITS_PER_WIDE_INT)
638     val &= (((unsigned HOST_WIDE_INT) 1) << CHAR_TYPE_SIZE) - 1;
639
640   hostval = val;
641   if (HOST_BITS_PER_CHAR < HOST_BITS_PER_WIDE_INT)
642     hostval &= (((unsigned HOST_WIDE_INT) 1) << HOST_BITS_PER_CHAR) - 1;
643
644   if (val != hostval)
645     return 1;
646
647   *p = hostval;
648   return 0;
649 }
650
651 /* Similar to save_expr, but assumes that arbitrary code is not executed
652    in between the multiple evaluations.  In particular, we assume that a
653    non-addressable local variable will not be modified.  */
654
655 static tree
656 builtin_save_expr (tree exp)
657 {
658   if (TREE_ADDRESSABLE (exp) == 0
659       && (TREE_CODE (exp) == PARM_DECL
660           || (TREE_CODE (exp) == VAR_DECL && !TREE_STATIC (exp))))
661     return exp;
662
663   return save_expr (exp);
664 }
665
666 /* Given TEM, a pointer to a stack frame, follow the dynamic chain COUNT
667    times to get the address of either a higher stack frame, or a return
668    address located within it (depending on FNDECL_CODE).  */
669
670 static rtx
671 expand_builtin_return_addr (enum built_in_function fndecl_code, int count)
672 {
673   int i;
674
675 #ifdef INITIAL_FRAME_ADDRESS_RTX
676   rtx tem = INITIAL_FRAME_ADDRESS_RTX;
677 #else
678   rtx tem;
679
680   /* For a zero count with __builtin_return_address, we don't care what
681      frame address we return, because target-specific definitions will
682      override us.  Therefore frame pointer elimination is OK, and using
683      the soft frame pointer is OK.
684
685      For a nonzero count, or a zero count with __builtin_frame_address,
686      we require a stable offset from the current frame pointer to the
687      previous one, so we must use the hard frame pointer, and
688      we must disable frame pointer elimination.  */
689   if (count == 0 && fndecl_code == BUILT_IN_RETURN_ADDRESS)
690     tem = frame_pointer_rtx;
691   else
692     {
693       tem = hard_frame_pointer_rtx;
694
695       /* Tell reload not to eliminate the frame pointer.  */
696       crtl->accesses_prior_frames = 1;
697     }
698 #endif
699
700   /* Some machines need special handling before we can access
701      arbitrary frames.  For example, on the SPARC, we must first flush
702      all register windows to the stack.  */
703 #ifdef SETUP_FRAME_ADDRESSES
704   if (count > 0)
705     SETUP_FRAME_ADDRESSES ();
706 #endif
707
708   /* On the SPARC, the return address is not in the frame, it is in a
709      register.  There is no way to access it off of the current frame
710      pointer, but it can be accessed off the previous frame pointer by
711      reading the value from the register window save area.  */
712 #ifdef RETURN_ADDR_IN_PREVIOUS_FRAME
713   if (fndecl_code == BUILT_IN_RETURN_ADDRESS)
714     count--;
715 #endif
716
717   /* Scan back COUNT frames to the specified frame.  */
718   for (i = 0; i < count; i++)
719     {
720       /* Assume the dynamic chain pointer is in the word that the
721          frame address points to, unless otherwise specified.  */
722 #ifdef DYNAMIC_CHAIN_ADDRESS
723       tem = DYNAMIC_CHAIN_ADDRESS (tem);
724 #endif
725       tem = memory_address (Pmode, tem);
726       tem = gen_frame_mem (Pmode, tem);
727       tem = copy_to_reg (tem);
728     }
729
730   /* For __builtin_frame_address, return what we've got.  But, on
731      the SPARC for example, we may have to add a bias.  */
732   if (fndecl_code == BUILT_IN_FRAME_ADDRESS)
733 #ifdef FRAME_ADDR_RTX
734     return FRAME_ADDR_RTX (tem);
735 #else
736     return tem;
737 #endif
738
739   /* For __builtin_return_address, get the return address from that frame.  */
740 #ifdef RETURN_ADDR_RTX
741   tem = RETURN_ADDR_RTX (count, tem);
742 #else
743   tem = memory_address (Pmode,
744                         plus_constant (tem, GET_MODE_SIZE (Pmode)));
745   tem = gen_frame_mem (Pmode, tem);
746 #endif
747   return tem;
748 }
749
750 /* Alias set used for setjmp buffer.  */
751 static alias_set_type setjmp_alias_set = -1;
752
753 /* Construct the leading half of a __builtin_setjmp call.  Control will
754    return to RECEIVER_LABEL.  This is also called directly by the SJLJ
755    exception handling code.  */
756
757 void
758 expand_builtin_setjmp_setup (rtx buf_addr, rtx receiver_label)
759 {
760   enum machine_mode sa_mode = STACK_SAVEAREA_MODE (SAVE_NONLOCAL);
761   rtx stack_save;
762   rtx mem;
763
764   if (setjmp_alias_set == -1)
765     setjmp_alias_set = new_alias_set ();
766
767   buf_addr = convert_memory_address (Pmode, buf_addr);
768
769   buf_addr = force_reg (Pmode, force_operand (buf_addr, NULL_RTX));
770
771   /* We store the frame pointer and the address of receiver_label in
772      the buffer and use the rest of it for the stack save area, which
773      is machine-dependent.  */
774
775   mem = gen_rtx_MEM (Pmode, buf_addr);
776   set_mem_alias_set (mem, setjmp_alias_set);
777   emit_move_insn (mem, targetm.builtin_setjmp_frame_value ());
778
779   mem = gen_rtx_MEM (Pmode, plus_constant (buf_addr, GET_MODE_SIZE (Pmode))),
780   set_mem_alias_set (mem, setjmp_alias_set);
781
782   emit_move_insn (validize_mem (mem),
783                   force_reg (Pmode, gen_rtx_LABEL_REF (Pmode, receiver_label)));
784
785   stack_save = gen_rtx_MEM (sa_mode,
786                             plus_constant (buf_addr,
787                                            2 * GET_MODE_SIZE (Pmode)));
788   set_mem_alias_set (stack_save, setjmp_alias_set);
789   emit_stack_save (SAVE_NONLOCAL, &stack_save, NULL_RTX);
790
791   /* If there is further processing to do, do it.  */
792 #ifdef HAVE_builtin_setjmp_setup
793   if (HAVE_builtin_setjmp_setup)
794     emit_insn (gen_builtin_setjmp_setup (buf_addr));
795 #endif
796
797   /* Tell optimize_save_area_alloca that extra work is going to
798      need to go on during alloca.  */
799   cfun->calls_setjmp = 1;
800
801   /* We have a nonlocal label.   */
802   cfun->has_nonlocal_label = 1;
803 }
804
805 /* Construct the trailing part of a __builtin_setjmp call.  This is
806    also called directly by the SJLJ exception handling code.  */
807
808 void
809 expand_builtin_setjmp_receiver (rtx receiver_label ATTRIBUTE_UNUSED)
810 {
811   rtx chain;
812
813   /* Clobber the FP when we get here, so we have to make sure it's
814      marked as used by this function.  */
815   emit_use (hard_frame_pointer_rtx);
816
817   /* Mark the static chain as clobbered here so life information
818      doesn't get messed up for it.  */
819   chain = targetm.calls.static_chain (current_function_decl, true);
820   if (chain && REG_P (chain))
821     emit_clobber (chain);
822
823   /* Now put in the code to restore the frame pointer, and argument
824      pointer, if needed.  */
825 #ifdef HAVE_nonlocal_goto
826   if (! HAVE_nonlocal_goto)
827 #endif
828     {
829       emit_move_insn (virtual_stack_vars_rtx, hard_frame_pointer_rtx);
830       /* This might change the hard frame pointer in ways that aren't
831          apparent to early optimization passes, so force a clobber.  */
832       emit_clobber (hard_frame_pointer_rtx);
833     }
834
835 #if !HARD_FRAME_POINTER_IS_ARG_POINTER
836   if (fixed_regs[ARG_POINTER_REGNUM])
837     {
838 #ifdef ELIMINABLE_REGS
839       size_t i;
840       static const struct elims {const int from, to;} elim_regs[] = ELIMINABLE_REGS;
841
842       for (i = 0; i < ARRAY_SIZE (elim_regs); i++)
843         if (elim_regs[i].from == ARG_POINTER_REGNUM
844             && elim_regs[i].to == HARD_FRAME_POINTER_REGNUM)
845           break;
846
847       if (i == ARRAY_SIZE (elim_regs))
848 #endif
849         {
850           /* Now restore our arg pointer from the address at which it
851              was saved in our stack frame.  */
852           emit_move_insn (crtl->args.internal_arg_pointer,
853                           copy_to_reg (get_arg_pointer_save_area ()));
854         }
855     }
856 #endif
857
858 #ifdef HAVE_builtin_setjmp_receiver
859   if (HAVE_builtin_setjmp_receiver)
860     emit_insn (gen_builtin_setjmp_receiver (receiver_label));
861   else
862 #endif
863 #ifdef HAVE_nonlocal_goto_receiver
864     if (HAVE_nonlocal_goto_receiver)
865       emit_insn (gen_nonlocal_goto_receiver ());
866     else
867 #endif
868       { /* Nothing */ }
869
870   /* We must not allow the code we just generated to be reordered by
871      scheduling.  Specifically, the update of the frame pointer must
872      happen immediately, not later.  */
873   emit_insn (gen_blockage ());
874 }
875
876 /* __builtin_longjmp is passed a pointer to an array of five words (not
877    all will be used on all machines).  It operates similarly to the C
878    library function of the same name, but is more efficient.  Much of
879    the code below is copied from the handling of non-local gotos.  */
880
881 static void
882 expand_builtin_longjmp (rtx buf_addr, rtx value)
883 {
884   rtx fp, lab, stack, insn, last;
885   enum machine_mode sa_mode = STACK_SAVEAREA_MODE (SAVE_NONLOCAL);
886
887   /* DRAP is needed for stack realign if longjmp is expanded to current
888      function  */
889   if (SUPPORTS_STACK_ALIGNMENT)
890     crtl->need_drap = true;
891
892   if (setjmp_alias_set == -1)
893     setjmp_alias_set = new_alias_set ();
894
895   buf_addr = convert_memory_address (Pmode, buf_addr);
896
897   buf_addr = force_reg (Pmode, buf_addr);
898
899   /* We require that the user must pass a second argument of 1, because
900      that is what builtin_setjmp will return.  */
901   gcc_assert (value == const1_rtx);
902
903   last = get_last_insn ();
904 #ifdef HAVE_builtin_longjmp
905   if (HAVE_builtin_longjmp)
906     emit_insn (gen_builtin_longjmp (buf_addr));
907   else
908 #endif
909     {
910       fp = gen_rtx_MEM (Pmode, buf_addr);
911       lab = gen_rtx_MEM (Pmode, plus_constant (buf_addr,
912                                                GET_MODE_SIZE (Pmode)));
913
914       stack = gen_rtx_MEM (sa_mode, plus_constant (buf_addr,
915                                                    2 * GET_MODE_SIZE (Pmode)));
916       set_mem_alias_set (fp, setjmp_alias_set);
917       set_mem_alias_set (lab, setjmp_alias_set);
918       set_mem_alias_set (stack, setjmp_alias_set);
919
920       /* Pick up FP, label, and SP from the block and jump.  This code is
921          from expand_goto in stmt.c; see there for detailed comments.  */
922 #ifdef HAVE_nonlocal_goto
923       if (HAVE_nonlocal_goto)
924         /* We have to pass a value to the nonlocal_goto pattern that will
925            get copied into the static_chain pointer, but it does not matter
926            what that value is, because builtin_setjmp does not use it.  */
927         emit_insn (gen_nonlocal_goto (value, lab, stack, fp));
928       else
929 #endif
930         {
931           lab = copy_to_reg (lab);
932
933           emit_clobber (gen_rtx_MEM (BLKmode, gen_rtx_SCRATCH (VOIDmode)));
934           emit_clobber (gen_rtx_MEM (BLKmode, hard_frame_pointer_rtx));
935
936           emit_move_insn (hard_frame_pointer_rtx, fp);
937           emit_stack_restore (SAVE_NONLOCAL, stack, NULL_RTX);
938
939           emit_use (hard_frame_pointer_rtx);
940           emit_use (stack_pointer_rtx);
941           emit_indirect_jump (lab);
942         }
943     }
944
945   /* Search backwards and mark the jump insn as a non-local goto.
946      Note that this precludes the use of __builtin_longjmp to a
947      __builtin_setjmp target in the same function.  However, we've
948      already cautioned the user that these functions are for
949      internal exception handling use only.  */
950   for (insn = get_last_insn (); insn; insn = PREV_INSN (insn))
951     {
952       gcc_assert (insn != last);
953
954       if (JUMP_P (insn))
955         {
956           add_reg_note (insn, REG_NON_LOCAL_GOTO, const0_rtx);
957           break;
958         }
959       else if (CALL_P (insn))
960         break;
961     }
962 }
963
964 /* Expand a call to __builtin_nonlocal_goto.  We're passed the target label
965    and the address of the save area.  */
966
967 static rtx
968 expand_builtin_nonlocal_goto (tree exp)
969 {
970   tree t_label, t_save_area;
971   rtx r_label, r_save_area, r_fp, r_sp, insn;
972
973   if (!validate_arglist (exp, POINTER_TYPE, POINTER_TYPE, VOID_TYPE))
974     return NULL_RTX;
975
976   t_label = CALL_EXPR_ARG (exp, 0);
977   t_save_area = CALL_EXPR_ARG (exp, 1);
978
979   r_label = expand_normal (t_label);
980   r_label = convert_memory_address (Pmode, r_label);
981   r_save_area = expand_normal (t_save_area);
982   r_save_area = convert_memory_address (Pmode, r_save_area);
983   /* Copy the address of the save location to a register just in case it was based
984     on the frame pointer.   */
985   r_save_area = copy_to_reg (r_save_area);
986   r_fp = gen_rtx_MEM (Pmode, r_save_area);
987   r_sp = gen_rtx_MEM (STACK_SAVEAREA_MODE (SAVE_NONLOCAL),
988                       plus_constant (r_save_area, GET_MODE_SIZE (Pmode)));
989
990   crtl->has_nonlocal_goto = 1;
991
992 #ifdef HAVE_nonlocal_goto
993   /* ??? We no longer need to pass the static chain value, afaik.  */
994   if (HAVE_nonlocal_goto)
995     emit_insn (gen_nonlocal_goto (const0_rtx, r_label, r_sp, r_fp));
996   else
997 #endif
998     {
999       r_label = copy_to_reg (r_label);
1000
1001       emit_clobber (gen_rtx_MEM (BLKmode, gen_rtx_SCRATCH (VOIDmode)));
1002       emit_clobber (gen_rtx_MEM (BLKmode, hard_frame_pointer_rtx));
1003
1004       /* Restore frame pointer for containing function.
1005          This sets the actual hard register used for the frame pointer
1006          to the location of the function's incoming static chain info.
1007          The non-local goto handler will then adjust it to contain the
1008          proper value and reload the argument pointer, if needed.  */
1009       emit_move_insn (hard_frame_pointer_rtx, r_fp);
1010       emit_stack_restore (SAVE_NONLOCAL, r_sp, NULL_RTX);
1011
1012       /* USE of hard_frame_pointer_rtx added for consistency;
1013          not clear if really needed.  */
1014       emit_use (hard_frame_pointer_rtx);
1015       emit_use (stack_pointer_rtx);
1016
1017       /* If the architecture is using a GP register, we must
1018          conservatively assume that the target function makes use of it.
1019          The prologue of functions with nonlocal gotos must therefore
1020          initialize the GP register to the appropriate value, and we
1021          must then make sure that this value is live at the point
1022          of the jump.  (Note that this doesn't necessarily apply
1023          to targets with a nonlocal_goto pattern; they are free
1024          to implement it in their own way.  Note also that this is
1025          a no-op if the GP register is a global invariant.)  */
1026       if ((unsigned) PIC_OFFSET_TABLE_REGNUM != INVALID_REGNUM
1027           && fixed_regs[PIC_OFFSET_TABLE_REGNUM])
1028         emit_use (pic_offset_table_rtx);
1029
1030       emit_indirect_jump (r_label);
1031     }
1032
1033   /* Search backwards to the jump insn and mark it as a
1034      non-local goto.  */
1035   for (insn = get_last_insn (); insn; insn = PREV_INSN (insn))
1036     {
1037       if (JUMP_P (insn))
1038         {
1039           add_reg_note (insn, REG_NON_LOCAL_GOTO, const0_rtx);
1040           break;
1041         }
1042       else if (CALL_P (insn))
1043         break;
1044     }
1045
1046   return const0_rtx;
1047 }
1048
1049 /* __builtin_update_setjmp_buf is passed a pointer to an array of five words
1050    (not all will be used on all machines) that was passed to __builtin_setjmp.
1051    It updates the stack pointer in that block to correspond to the current
1052    stack pointer.  */
1053
1054 static void
1055 expand_builtin_update_setjmp_buf (rtx buf_addr)
1056 {
1057   enum machine_mode sa_mode = Pmode;
1058   rtx stack_save;
1059
1060
1061 #ifdef HAVE_save_stack_nonlocal
1062   if (HAVE_save_stack_nonlocal)
1063     sa_mode = insn_data[(int) CODE_FOR_save_stack_nonlocal].operand[0].mode;
1064 #endif
1065 #ifdef STACK_SAVEAREA_MODE
1066   sa_mode = STACK_SAVEAREA_MODE (SAVE_NONLOCAL);
1067 #endif
1068
1069   stack_save
1070     = gen_rtx_MEM (sa_mode,
1071                    memory_address
1072                    (sa_mode,
1073                     plus_constant (buf_addr, 2 * GET_MODE_SIZE (Pmode))));
1074
1075 #ifdef HAVE_setjmp
1076   if (HAVE_setjmp)
1077     emit_insn (gen_setjmp ());
1078 #endif
1079
1080   emit_stack_save (SAVE_NONLOCAL, &stack_save, NULL_RTX);
1081 }
1082
1083 /* Expand a call to __builtin_prefetch.  For a target that does not support
1084    data prefetch, evaluate the memory address argument in case it has side
1085    effects.  */
1086
1087 static void
1088 expand_builtin_prefetch (tree exp)
1089 {
1090   tree arg0, arg1, arg2;
1091   int nargs;
1092   rtx op0, op1, op2;
1093
1094   if (!validate_arglist (exp, POINTER_TYPE, 0))
1095     return;
1096
1097   arg0 = CALL_EXPR_ARG (exp, 0);
1098
1099   /* Arguments 1 and 2 are optional; argument 1 (read/write) defaults to
1100      zero (read) and argument 2 (locality) defaults to 3 (high degree of
1101      locality).  */
1102   nargs = call_expr_nargs (exp);
1103   if (nargs > 1)
1104     arg1 = CALL_EXPR_ARG (exp, 1);
1105   else
1106     arg1 = integer_zero_node;
1107   if (nargs > 2)
1108     arg2 = CALL_EXPR_ARG (exp, 2);
1109   else
1110     arg2 = integer_three_node;
1111
1112   /* Argument 0 is an address.  */
1113   op0 = expand_expr (arg0, NULL_RTX, Pmode, EXPAND_NORMAL);
1114
1115   /* Argument 1 (read/write flag) must be a compile-time constant int.  */
1116   if (TREE_CODE (arg1) != INTEGER_CST)
1117     {
1118       error ("second argument to %<__builtin_prefetch%> must be a constant");
1119       arg1 = integer_zero_node;
1120     }
1121   op1 = expand_normal (arg1);
1122   /* Argument 1 must be either zero or one.  */
1123   if (INTVAL (op1) != 0 && INTVAL (op1) != 1)
1124     {
1125       warning (0, "invalid second argument to %<__builtin_prefetch%>;"
1126                " using zero");
1127       op1 = const0_rtx;
1128     }
1129
1130   /* Argument 2 (locality) must be a compile-time constant int.  */
1131   if (TREE_CODE (arg2) != INTEGER_CST)
1132     {
1133       error ("third argument to %<__builtin_prefetch%> must be a constant");
1134       arg2 = integer_zero_node;
1135     }
1136   op2 = expand_normal (arg2);
1137   /* Argument 2 must be 0, 1, 2, or 3.  */
1138   if (INTVAL (op2) < 0 || INTVAL (op2) > 3)
1139     {
1140       warning (0, "invalid third argument to %<__builtin_prefetch%>; using zero");
1141       op2 = const0_rtx;
1142     }
1143
1144 #ifdef HAVE_prefetch
1145   if (HAVE_prefetch)
1146     {
1147       if ((! (*insn_data[(int) CODE_FOR_prefetch].operand[0].predicate)
1148              (op0,
1149               insn_data[(int) CODE_FOR_prefetch].operand[0].mode))
1150           || (GET_MODE (op0) != Pmode))
1151         {
1152           op0 = convert_memory_address (Pmode, op0);
1153           op0 = force_reg (Pmode, op0);
1154         }
1155       emit_insn (gen_prefetch (op0, op1, op2));
1156     }
1157 #endif
1158
1159   /* Don't do anything with direct references to volatile memory, but
1160      generate code to handle other side effects.  */
1161   if (!MEM_P (op0) && side_effects_p (op0))
1162     emit_insn (op0);
1163 }
1164
1165 /* Get a MEM rtx for expression EXP which is the address of an operand
1166    to be used in a string instruction (cmpstrsi, movmemsi, ..).  LEN is
1167    the maximum length of the block of memory that might be accessed or
1168    NULL if unknown.  */
1169
1170 static rtx
1171 get_memory_rtx (tree exp, tree len)
1172 {
1173   tree orig_exp = exp;
1174   rtx addr, mem;
1175   HOST_WIDE_INT off;
1176
1177   /* When EXP is not resolved SAVE_EXPR, MEM_ATTRS can be still derived
1178      from its expression, for expr->a.b only <variable>.a.b is recorded.  */
1179   if (TREE_CODE (exp) == SAVE_EXPR && !SAVE_EXPR_RESOLVED_P (exp))
1180     exp = TREE_OPERAND (exp, 0);
1181
1182   addr = expand_expr (orig_exp, NULL_RTX, ptr_mode, EXPAND_NORMAL);
1183   mem = gen_rtx_MEM (BLKmode, memory_address (BLKmode, addr));
1184
1185   /* Get an expression we can use to find the attributes to assign to MEM.
1186      If it is an ADDR_EXPR, use the operand.  Otherwise, dereference it if
1187      we can.  First remove any nops.  */
1188   while (CONVERT_EXPR_P (exp)
1189          && POINTER_TYPE_P (TREE_TYPE (TREE_OPERAND (exp, 0))))
1190     exp = TREE_OPERAND (exp, 0);
1191
1192   off = 0;
1193   if (TREE_CODE (exp) == POINTER_PLUS_EXPR
1194       && TREE_CODE (TREE_OPERAND (exp, 0)) == ADDR_EXPR
1195       && host_integerp (TREE_OPERAND (exp, 1), 0)
1196       && (off = tree_low_cst (TREE_OPERAND (exp, 1), 0)) > 0)
1197     exp = TREE_OPERAND (TREE_OPERAND (exp, 0), 0);
1198   else if (TREE_CODE (exp) == ADDR_EXPR)
1199     exp = TREE_OPERAND (exp, 0);
1200   else if (POINTER_TYPE_P (TREE_TYPE (exp)))
1201     exp = build1 (INDIRECT_REF, TREE_TYPE (TREE_TYPE (exp)), exp);
1202   else
1203     exp = NULL;
1204
1205   /* Honor attributes derived from exp, except for the alias set
1206      (as builtin stringops may alias with anything) and the size
1207      (as stringops may access multiple array elements).  */
1208   if (exp)
1209     {
1210       set_mem_attributes (mem, exp, 0);
1211
1212       if (off)
1213         mem = adjust_automodify_address_nv (mem, BLKmode, NULL, off);
1214
1215       /* Allow the string and memory builtins to overflow from one
1216          field into another, see http://gcc.gnu.org/PR23561.
1217          Thus avoid COMPONENT_REFs in MEM_EXPR unless we know the whole
1218          memory accessed by the string or memory builtin will fit
1219          within the field.  */
1220       if (MEM_EXPR (mem) && TREE_CODE (MEM_EXPR (mem)) == COMPONENT_REF)
1221         {
1222           tree mem_expr = MEM_EXPR (mem);
1223           HOST_WIDE_INT offset = -1, length = -1;
1224           tree inner = exp;
1225
1226           while (TREE_CODE (inner) == ARRAY_REF
1227                  || CONVERT_EXPR_P (inner)
1228                  || TREE_CODE (inner) == VIEW_CONVERT_EXPR
1229                  || TREE_CODE (inner) == SAVE_EXPR)
1230             inner = TREE_OPERAND (inner, 0);
1231
1232           gcc_assert (TREE_CODE (inner) == COMPONENT_REF);
1233
1234           if (MEM_OFFSET (mem)
1235               && CONST_INT_P (MEM_OFFSET (mem)))
1236             offset = INTVAL (MEM_OFFSET (mem));
1237
1238           if (offset >= 0 && len && host_integerp (len, 0))
1239             length = tree_low_cst (len, 0);
1240
1241           while (TREE_CODE (inner) == COMPONENT_REF)
1242             {
1243               tree field = TREE_OPERAND (inner, 1);
1244               gcc_assert (TREE_CODE (mem_expr) == COMPONENT_REF);
1245               gcc_assert (field == TREE_OPERAND (mem_expr, 1));
1246
1247               /* Bitfields are generally not byte-addressable.  */
1248               gcc_assert (!DECL_BIT_FIELD (field)
1249                           || ((tree_low_cst (DECL_FIELD_BIT_OFFSET (field), 1)
1250                                % BITS_PER_UNIT) == 0
1251                               && host_integerp (DECL_SIZE (field), 0)
1252                               && (TREE_INT_CST_LOW (DECL_SIZE (field))
1253                                   % BITS_PER_UNIT) == 0));
1254
1255               /* If we can prove that the memory starting at XEXP (mem, 0) and
1256                  ending at XEXP (mem, 0) + LENGTH will fit into this field, we
1257                  can keep the COMPONENT_REF in MEM_EXPR.  But be careful with
1258                  fields without DECL_SIZE_UNIT like flexible array members.  */
1259               if (length >= 0
1260                   && DECL_SIZE_UNIT (field)
1261                   && host_integerp (DECL_SIZE_UNIT (field), 0))
1262                 {
1263                   HOST_WIDE_INT size
1264                     = TREE_INT_CST_LOW (DECL_SIZE_UNIT (field));
1265                   if (offset <= size
1266                       && length <= size
1267                       && offset + length <= size)
1268                     break;
1269                 }
1270
1271               if (offset >= 0
1272                   && host_integerp (DECL_FIELD_OFFSET (field), 0))
1273                 offset += TREE_INT_CST_LOW (DECL_FIELD_OFFSET (field))
1274                           + tree_low_cst (DECL_FIELD_BIT_OFFSET (field), 1)
1275                             / BITS_PER_UNIT;
1276               else
1277                 {
1278                   offset = -1;
1279                   length = -1;
1280                 }
1281
1282               mem_expr = TREE_OPERAND (mem_expr, 0);
1283               inner = TREE_OPERAND (inner, 0);
1284             }
1285
1286           if (mem_expr == NULL)
1287             offset = -1;
1288           if (mem_expr != MEM_EXPR (mem))
1289             {
1290               set_mem_expr (mem, mem_expr);
1291               set_mem_offset (mem, offset >= 0 ? GEN_INT (offset) : NULL_RTX);
1292             }
1293         }
1294       set_mem_alias_set (mem, 0);
1295       set_mem_size (mem, NULL_RTX);
1296     }
1297
1298   return mem;
1299 }
1300 \f
1301 /* Built-in functions to perform an untyped call and return.  */
1302
1303 #define apply_args_mode \
1304   (this_target_builtins->x_apply_args_mode)
1305 #define apply_result_mode \
1306   (this_target_builtins->x_apply_result_mode)
1307
1308 /* Return the size required for the block returned by __builtin_apply_args,
1309    and initialize apply_args_mode.  */
1310
1311 static int
1312 apply_args_size (void)
1313 {
1314   static int size = -1;
1315   int align;
1316   unsigned int regno;
1317   enum machine_mode mode;
1318
1319   /* The values computed by this function never change.  */
1320   if (size < 0)
1321     {
1322       /* The first value is the incoming arg-pointer.  */
1323       size = GET_MODE_SIZE (Pmode);
1324
1325       /* The second value is the structure value address unless this is
1326          passed as an "invisible" first argument.  */
1327       if (targetm.calls.struct_value_rtx (cfun ? TREE_TYPE (cfun->decl) : 0, 0))
1328         size += GET_MODE_SIZE (Pmode);
1329
1330       for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
1331         if (FUNCTION_ARG_REGNO_P (regno))
1332           {
1333             mode = targetm.calls.get_raw_arg_mode (regno);
1334
1335             gcc_assert (mode != VOIDmode);
1336
1337             align = GET_MODE_ALIGNMENT (mode) / BITS_PER_UNIT;
1338             if (size % align != 0)
1339               size = CEIL (size, align) * align;
1340             size += GET_MODE_SIZE (mode);
1341             apply_args_mode[regno] = mode;
1342           }
1343         else
1344           {
1345             apply_args_mode[regno] = VOIDmode;
1346           }
1347     }
1348   return size;
1349 }
1350
1351 /* Return the size required for the block returned by __builtin_apply,
1352    and initialize apply_result_mode.  */
1353
1354 static int
1355 apply_result_size (void)
1356 {
1357   static int size = -1;
1358   int align, regno;
1359   enum machine_mode mode;
1360
1361   /* The values computed by this function never change.  */
1362   if (size < 0)
1363     {
1364       size = 0;
1365
1366       for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
1367         if (targetm.calls.function_value_regno_p (regno))
1368           {
1369             mode = targetm.calls.get_raw_result_mode (regno);
1370
1371             gcc_assert (mode != VOIDmode);
1372
1373             align = GET_MODE_ALIGNMENT (mode) / BITS_PER_UNIT;
1374             if (size % align != 0)
1375               size = CEIL (size, align) * align;
1376             size += GET_MODE_SIZE (mode);
1377             apply_result_mode[regno] = mode;
1378           }
1379         else
1380           apply_result_mode[regno] = VOIDmode;
1381
1382       /* Allow targets that use untyped_call and untyped_return to override
1383          the size so that machine-specific information can be stored here.  */
1384 #ifdef APPLY_RESULT_SIZE
1385       size = APPLY_RESULT_SIZE;
1386 #endif
1387     }
1388   return size;
1389 }
1390
1391 #if defined (HAVE_untyped_call) || defined (HAVE_untyped_return)
1392 /* Create a vector describing the result block RESULT.  If SAVEP is true,
1393    the result block is used to save the values; otherwise it is used to
1394    restore the values.  */
1395
1396 static rtx
1397 result_vector (int savep, rtx result)
1398 {
1399   int regno, size, align, nelts;
1400   enum machine_mode mode;
1401   rtx reg, mem;
1402   rtx *savevec = XALLOCAVEC (rtx, FIRST_PSEUDO_REGISTER);
1403
1404   size = nelts = 0;
1405   for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
1406     if ((mode = apply_result_mode[regno]) != VOIDmode)
1407       {
1408         align = GET_MODE_ALIGNMENT (mode) / BITS_PER_UNIT;
1409         if (size % align != 0)
1410           size = CEIL (size, align) * align;
1411         reg = gen_rtx_REG (mode, savep ? regno : INCOMING_REGNO (regno));
1412         mem = adjust_address (result, mode, size);
1413         savevec[nelts++] = (savep
1414                             ? gen_rtx_SET (VOIDmode, mem, reg)
1415                             : gen_rtx_SET (VOIDmode, reg, mem));
1416         size += GET_MODE_SIZE (mode);
1417       }
1418   return gen_rtx_PARALLEL (VOIDmode, gen_rtvec_v (nelts, savevec));
1419 }
1420 #endif /* HAVE_untyped_call or HAVE_untyped_return */
1421
1422 /* Save the state required to perform an untyped call with the same
1423    arguments as were passed to the current function.  */
1424
1425 static rtx
1426 expand_builtin_apply_args_1 (void)
1427 {
1428   rtx registers, tem;
1429   int size, align, regno;
1430   enum machine_mode mode;
1431   rtx struct_incoming_value = targetm.calls.struct_value_rtx (cfun ? TREE_TYPE (cfun->decl) : 0, 1);
1432
1433   /* Create a block where the arg-pointer, structure value address,
1434      and argument registers can be saved.  */
1435   registers = assign_stack_local (BLKmode, apply_args_size (), -1);
1436
1437   /* Walk past the arg-pointer and structure value address.  */
1438   size = GET_MODE_SIZE (Pmode);
1439   if (targetm.calls.struct_value_rtx (cfun ? TREE_TYPE (cfun->decl) : 0, 0))
1440     size += GET_MODE_SIZE (Pmode);
1441
1442   /* Save each register used in calling a function to the block.  */
1443   for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
1444     if ((mode = apply_args_mode[regno]) != VOIDmode)
1445       {
1446         align = GET_MODE_ALIGNMENT (mode) / BITS_PER_UNIT;
1447         if (size % align != 0)
1448           size = CEIL (size, align) * align;
1449
1450         tem = gen_rtx_REG (mode, INCOMING_REGNO (regno));
1451
1452         emit_move_insn (adjust_address (registers, mode, size), tem);
1453         size += GET_MODE_SIZE (mode);
1454       }
1455
1456   /* Save the arg pointer to the block.  */
1457   tem = copy_to_reg (crtl->args.internal_arg_pointer);
1458 #ifdef STACK_GROWS_DOWNWARD
1459   /* We need the pointer as the caller actually passed them to us, not
1460      as we might have pretended they were passed.  Make sure it's a valid
1461      operand, as emit_move_insn isn't expected to handle a PLUS.  */
1462   tem
1463     = force_operand (plus_constant (tem, crtl->args.pretend_args_size),
1464                      NULL_RTX);
1465 #endif
1466   emit_move_insn (adjust_address (registers, Pmode, 0), tem);
1467
1468   size = GET_MODE_SIZE (Pmode);
1469
1470   /* Save the structure value address unless this is passed as an
1471      "invisible" first argument.  */
1472   if (struct_incoming_value)
1473     {
1474       emit_move_insn (adjust_address (registers, Pmode, size),
1475                       copy_to_reg (struct_incoming_value));
1476       size += GET_MODE_SIZE (Pmode);
1477     }
1478
1479   /* Return the address of the block.  */
1480   return copy_addr_to_reg (XEXP (registers, 0));
1481 }
1482
1483 /* __builtin_apply_args returns block of memory allocated on
1484    the stack into which is stored the arg pointer, structure
1485    value address, static chain, and all the registers that might
1486    possibly be used in performing a function call.  The code is
1487    moved to the start of the function so the incoming values are
1488    saved.  */
1489
1490 static rtx
1491 expand_builtin_apply_args (void)
1492 {
1493   /* Don't do __builtin_apply_args more than once in a function.
1494      Save the result of the first call and reuse it.  */
1495   if (apply_args_value != 0)
1496     return apply_args_value;
1497   {
1498     /* When this function is called, it means that registers must be
1499        saved on entry to this function.  So we migrate the
1500        call to the first insn of this function.  */
1501     rtx temp;
1502     rtx seq;
1503
1504     start_sequence ();
1505     temp = expand_builtin_apply_args_1 ();
1506     seq = get_insns ();
1507     end_sequence ();
1508
1509     apply_args_value = temp;
1510
1511     /* Put the insns after the NOTE that starts the function.
1512        If this is inside a start_sequence, make the outer-level insn
1513        chain current, so the code is placed at the start of the
1514        function.  If internal_arg_pointer is a non-virtual pseudo,
1515        it needs to be placed after the function that initializes
1516        that pseudo.  */
1517     push_topmost_sequence ();
1518     if (REG_P (crtl->args.internal_arg_pointer)
1519         && REGNO (crtl->args.internal_arg_pointer) > LAST_VIRTUAL_REGISTER)
1520       emit_insn_before (seq, parm_birth_insn);
1521     else
1522       emit_insn_before (seq, NEXT_INSN (entry_of_function ()));
1523     pop_topmost_sequence ();
1524     return temp;
1525   }
1526 }
1527
1528 /* Perform an untyped call and save the state required to perform an
1529    untyped return of whatever value was returned by the given function.  */
1530
1531 static rtx
1532 expand_builtin_apply (rtx function, rtx arguments, rtx argsize)
1533 {
1534   int size, align, regno;
1535   enum machine_mode mode;
1536   rtx incoming_args, result, reg, dest, src, call_insn;
1537   rtx old_stack_level = 0;
1538   rtx call_fusage = 0;
1539   rtx struct_value = targetm.calls.struct_value_rtx (cfun ? TREE_TYPE (cfun->decl) : 0, 0);
1540
1541   arguments = convert_memory_address (Pmode, arguments);
1542
1543   /* Create a block where the return registers can be saved.  */
1544   result = assign_stack_local (BLKmode, apply_result_size (), -1);
1545
1546   /* Fetch the arg pointer from the ARGUMENTS block.  */
1547   incoming_args = gen_reg_rtx (Pmode);
1548   emit_move_insn (incoming_args, gen_rtx_MEM (Pmode, arguments));
1549 #ifndef STACK_GROWS_DOWNWARD
1550   incoming_args = expand_simple_binop (Pmode, MINUS, incoming_args, argsize,
1551                                        incoming_args, 0, OPTAB_LIB_WIDEN);
1552 #endif
1553
1554   /* Push a new argument block and copy the arguments.  Do not allow
1555      the (potential) memcpy call below to interfere with our stack
1556      manipulations.  */
1557   do_pending_stack_adjust ();
1558   NO_DEFER_POP;
1559
1560   /* Save the stack with nonlocal if available.  */
1561 #ifdef HAVE_save_stack_nonlocal
1562   if (HAVE_save_stack_nonlocal)
1563     emit_stack_save (SAVE_NONLOCAL, &old_stack_level, NULL_RTX);
1564   else
1565 #endif
1566     emit_stack_save (SAVE_BLOCK, &old_stack_level, NULL_RTX);
1567
1568   /* Allocate a block of memory onto the stack and copy the memory
1569      arguments to the outgoing arguments address.  We can pass TRUE
1570      as the 4th argument because we just saved the stack pointer
1571      and will restore it right after the call.  */
1572   allocate_dynamic_stack_space (argsize, 0, BIGGEST_ALIGNMENT, true);
1573
1574   /* Set DRAP flag to true, even though allocate_dynamic_stack_space
1575      may have already set current_function_calls_alloca to true.
1576      current_function_calls_alloca won't be set if argsize is zero,
1577      so we have to guarantee need_drap is true here.  */
1578   if (SUPPORTS_STACK_ALIGNMENT)
1579     crtl->need_drap = true;
1580
1581   dest = virtual_outgoing_args_rtx;
1582 #ifndef STACK_GROWS_DOWNWARD
1583   if (CONST_INT_P (argsize))
1584     dest = plus_constant (dest, -INTVAL (argsize));
1585   else
1586     dest = gen_rtx_PLUS (Pmode, dest, negate_rtx (Pmode, argsize));
1587 #endif
1588   dest = gen_rtx_MEM (BLKmode, dest);
1589   set_mem_align (dest, PARM_BOUNDARY);
1590   src = gen_rtx_MEM (BLKmode, incoming_args);
1591   set_mem_align (src, PARM_BOUNDARY);
1592   emit_block_move (dest, src, argsize, BLOCK_OP_NORMAL);
1593
1594   /* Refer to the argument block.  */
1595   apply_args_size ();
1596   arguments = gen_rtx_MEM (BLKmode, arguments);
1597   set_mem_align (arguments, PARM_BOUNDARY);
1598
1599   /* Walk past the arg-pointer and structure value address.  */
1600   size = GET_MODE_SIZE (Pmode);
1601   if (struct_value)
1602     size += GET_MODE_SIZE (Pmode);
1603
1604   /* Restore each of the registers previously saved.  Make USE insns
1605      for each of these registers for use in making the call.  */
1606   for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
1607     if ((mode = apply_args_mode[regno]) != VOIDmode)
1608       {
1609         align = GET_MODE_ALIGNMENT (mode) / BITS_PER_UNIT;
1610         if (size % align != 0)
1611           size = CEIL (size, align) * align;
1612         reg = gen_rtx_REG (mode, regno);
1613         emit_move_insn (reg, adjust_address (arguments, mode, size));
1614         use_reg (&call_fusage, reg);
1615         size += GET_MODE_SIZE (mode);
1616       }
1617
1618   /* Restore the structure value address unless this is passed as an
1619      "invisible" first argument.  */
1620   size = GET_MODE_SIZE (Pmode);
1621   if (struct_value)
1622     {
1623       rtx value = gen_reg_rtx (Pmode);
1624       emit_move_insn (value, adjust_address (arguments, Pmode, size));
1625       emit_move_insn (struct_value, value);
1626       if (REG_P (struct_value))
1627         use_reg (&call_fusage, struct_value);
1628       size += GET_MODE_SIZE (Pmode);
1629     }
1630
1631   /* All arguments and registers used for the call are set up by now!  */
1632   function = prepare_call_address (NULL, function, NULL, &call_fusage, 0, 0);
1633
1634   /* Ensure address is valid.  SYMBOL_REF is already valid, so no need,
1635      and we don't want to load it into a register as an optimization,
1636      because prepare_call_address already did it if it should be done.  */
1637   if (GET_CODE (function) != SYMBOL_REF)
1638     function = memory_address (FUNCTION_MODE, function);
1639
1640   /* Generate the actual call instruction and save the return value.  */
1641 #ifdef HAVE_untyped_call
1642   if (HAVE_untyped_call)
1643     emit_call_insn (gen_untyped_call (gen_rtx_MEM (FUNCTION_MODE, function),
1644                                       result, result_vector (1, result)));
1645   else
1646 #endif
1647 #ifdef HAVE_call_value
1648   if (HAVE_call_value)
1649     {
1650       rtx valreg = 0;
1651
1652       /* Locate the unique return register.  It is not possible to
1653          express a call that sets more than one return register using
1654          call_value; use untyped_call for that.  In fact, untyped_call
1655          only needs to save the return registers in the given block.  */
1656       for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
1657         if ((mode = apply_result_mode[regno]) != VOIDmode)
1658           {
1659             gcc_assert (!valreg); /* HAVE_untyped_call required.  */
1660
1661             valreg = gen_rtx_REG (mode, regno);
1662           }
1663
1664       emit_call_insn (GEN_CALL_VALUE (valreg,
1665                                       gen_rtx_MEM (FUNCTION_MODE, function),
1666                                       const0_rtx, NULL_RTX, const0_rtx));
1667
1668       emit_move_insn (adjust_address (result, GET_MODE (valreg), 0), valreg);
1669     }
1670   else
1671 #endif
1672     gcc_unreachable ();
1673
1674   /* Find the CALL insn we just emitted, and attach the register usage
1675      information.  */
1676   call_insn = last_call_insn ();
1677   add_function_usage_to (call_insn, call_fusage);
1678
1679   /* Restore the stack.  */
1680 #ifdef HAVE_save_stack_nonlocal
1681   if (HAVE_save_stack_nonlocal)
1682     emit_stack_restore (SAVE_NONLOCAL, old_stack_level, NULL_RTX);
1683   else
1684 #endif
1685     emit_stack_restore (SAVE_BLOCK, old_stack_level, NULL_RTX);
1686
1687   OK_DEFER_POP;
1688
1689   /* Return the address of the result block.  */
1690   result = copy_addr_to_reg (XEXP (result, 0));
1691   return convert_memory_address (ptr_mode, result);
1692 }
1693
1694 /* Perform an untyped return.  */
1695
1696 static void
1697 expand_builtin_return (rtx result)
1698 {
1699   int size, align, regno;
1700   enum machine_mode mode;
1701   rtx reg;
1702   rtx call_fusage = 0;
1703
1704   result = convert_memory_address (Pmode, result);
1705
1706   apply_result_size ();
1707   result = gen_rtx_MEM (BLKmode, result);
1708
1709 #ifdef HAVE_untyped_return
1710   if (HAVE_untyped_return)
1711     {
1712       emit_jump_insn (gen_untyped_return (result, result_vector (0, result)));
1713       emit_barrier ();
1714       return;
1715     }
1716 #endif
1717
1718   /* Restore the return value and note that each value is used.  */
1719   size = 0;
1720   for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
1721     if ((mode = apply_result_mode[regno]) != VOIDmode)
1722       {
1723         align = GET_MODE_ALIGNMENT (mode) / BITS_PER_UNIT;
1724         if (size % align != 0)
1725           size = CEIL (size, align) * align;
1726         reg = gen_rtx_REG (mode, INCOMING_REGNO (regno));
1727         emit_move_insn (reg, adjust_address (result, mode, size));
1728
1729         push_to_sequence (call_fusage);
1730         emit_use (reg);
1731         call_fusage = get_insns ();
1732         end_sequence ();
1733         size += GET_MODE_SIZE (mode);
1734       }
1735
1736   /* Put the USE insns before the return.  */
1737   emit_insn (call_fusage);
1738
1739   /* Return whatever values was restored by jumping directly to the end
1740      of the function.  */
1741   expand_naked_return ();
1742 }
1743
1744 /* Used by expand_builtin_classify_type and fold_builtin_classify_type.  */
1745
1746 static enum type_class
1747 type_to_class (tree type)
1748 {
1749   switch (TREE_CODE (type))
1750     {
1751     case VOID_TYPE:        return void_type_class;
1752     case INTEGER_TYPE:     return integer_type_class;
1753     case ENUMERAL_TYPE:    return enumeral_type_class;
1754     case BOOLEAN_TYPE:     return boolean_type_class;
1755     case POINTER_TYPE:     return pointer_type_class;
1756     case REFERENCE_TYPE:   return reference_type_class;
1757     case OFFSET_TYPE:      return offset_type_class;
1758     case REAL_TYPE:        return real_type_class;
1759     case COMPLEX_TYPE:     return complex_type_class;
1760     case FUNCTION_TYPE:    return function_type_class;
1761     case METHOD_TYPE:      return method_type_class;
1762     case RECORD_TYPE:      return record_type_class;
1763     case UNION_TYPE:
1764     case QUAL_UNION_TYPE:  return union_type_class;
1765     case ARRAY_TYPE:       return (TYPE_STRING_FLAG (type)
1766                                    ? string_type_class : array_type_class);
1767     case LANG_TYPE:        return lang_type_class;
1768     default:               return no_type_class;
1769     }
1770 }
1771
1772 /* Expand a call EXP to __builtin_classify_type.  */
1773
1774 static rtx
1775 expand_builtin_classify_type (tree exp)
1776 {
1777   if (call_expr_nargs (exp))
1778     return GEN_INT (type_to_class (TREE_TYPE (CALL_EXPR_ARG (exp, 0))));
1779   return GEN_INT (no_type_class);
1780 }
1781
1782 /* This helper macro, meant to be used in mathfn_built_in below,
1783    determines which among a set of three builtin math functions is
1784    appropriate for a given type mode.  The `F' and `L' cases are
1785    automatically generated from the `double' case.  */
1786 #define CASE_MATHFN(BUILT_IN_MATHFN) \
1787   case BUILT_IN_MATHFN: case BUILT_IN_MATHFN##F: case BUILT_IN_MATHFN##L: \
1788   fcode = BUILT_IN_MATHFN; fcodef = BUILT_IN_MATHFN##F ; \
1789   fcodel = BUILT_IN_MATHFN##L ; break;
1790 /* Similar to above, but appends _R after any F/L suffix.  */
1791 #define CASE_MATHFN_REENT(BUILT_IN_MATHFN) \
1792   case BUILT_IN_MATHFN##_R: case BUILT_IN_MATHFN##F_R: case BUILT_IN_MATHFN##L_R: \
1793   fcode = BUILT_IN_MATHFN##_R; fcodef = BUILT_IN_MATHFN##F_R ; \
1794   fcodel = BUILT_IN_MATHFN##L_R ; break;
1795
1796 /* Return mathematic function equivalent to FN but operating directly
1797    on TYPE, if available.  If IMPLICIT is true find the function in
1798    implicit_built_in_decls[], otherwise use built_in_decls[].  If we
1799    can't do the conversion, return zero.  */
1800
1801 static tree
1802 mathfn_built_in_1 (tree type, enum built_in_function fn, bool implicit)
1803 {
1804   tree const *const fn_arr
1805     = implicit ? implicit_built_in_decls : built_in_decls;
1806   enum built_in_function fcode, fcodef, fcodel;
1807
1808   switch (fn)
1809     {
1810       CASE_MATHFN (BUILT_IN_ACOS)
1811       CASE_MATHFN (BUILT_IN_ACOSH)
1812       CASE_MATHFN (BUILT_IN_ASIN)
1813       CASE_MATHFN (BUILT_IN_ASINH)
1814       CASE_MATHFN (BUILT_IN_ATAN)
1815       CASE_MATHFN (BUILT_IN_ATAN2)
1816       CASE_MATHFN (BUILT_IN_ATANH)
1817       CASE_MATHFN (BUILT_IN_CBRT)
1818       CASE_MATHFN (BUILT_IN_CEIL)
1819       CASE_MATHFN (BUILT_IN_CEXPI)
1820       CASE_MATHFN (BUILT_IN_COPYSIGN)
1821       CASE_MATHFN (BUILT_IN_COS)
1822       CASE_MATHFN (BUILT_IN_COSH)
1823       CASE_MATHFN (BUILT_IN_DREM)
1824       CASE_MATHFN (BUILT_IN_ERF)
1825       CASE_MATHFN (BUILT_IN_ERFC)
1826       CASE_MATHFN (BUILT_IN_EXP)
1827       CASE_MATHFN (BUILT_IN_EXP10)
1828       CASE_MATHFN (BUILT_IN_EXP2)
1829       CASE_MATHFN (BUILT_IN_EXPM1)
1830       CASE_MATHFN (BUILT_IN_FABS)
1831       CASE_MATHFN (BUILT_IN_FDIM)
1832       CASE_MATHFN (BUILT_IN_FLOOR)
1833       CASE_MATHFN (BUILT_IN_FMA)
1834       CASE_MATHFN (BUILT_IN_FMAX)
1835       CASE_MATHFN (BUILT_IN_FMIN)
1836       CASE_MATHFN (BUILT_IN_FMOD)
1837       CASE_MATHFN (BUILT_IN_FREXP)
1838       CASE_MATHFN (BUILT_IN_GAMMA)
1839       CASE_MATHFN_REENT (BUILT_IN_GAMMA) /* GAMMA_R */
1840       CASE_MATHFN (BUILT_IN_HUGE_VAL)
1841       CASE_MATHFN (BUILT_IN_HYPOT)
1842       CASE_MATHFN (BUILT_IN_ILOGB)
1843       CASE_MATHFN (BUILT_IN_INF)
1844       CASE_MATHFN (BUILT_IN_ISINF)
1845       CASE_MATHFN (BUILT_IN_J0)
1846       CASE_MATHFN (BUILT_IN_J1)
1847       CASE_MATHFN (BUILT_IN_JN)
1848       CASE_MATHFN (BUILT_IN_LCEIL)
1849       CASE_MATHFN (BUILT_IN_LDEXP)
1850       CASE_MATHFN (BUILT_IN_LFLOOR)
1851       CASE_MATHFN (BUILT_IN_LGAMMA)
1852       CASE_MATHFN_REENT (BUILT_IN_LGAMMA) /* LGAMMA_R */
1853       CASE_MATHFN (BUILT_IN_LLCEIL)
1854       CASE_MATHFN (BUILT_IN_LLFLOOR)
1855       CASE_MATHFN (BUILT_IN_LLRINT)
1856       CASE_MATHFN (BUILT_IN_LLROUND)
1857       CASE_MATHFN (BUILT_IN_LOG)
1858       CASE_MATHFN (BUILT_IN_LOG10)
1859       CASE_MATHFN (BUILT_IN_LOG1P)
1860       CASE_MATHFN (BUILT_IN_LOG2)
1861       CASE_MATHFN (BUILT_IN_LOGB)
1862       CASE_MATHFN (BUILT_IN_LRINT)
1863       CASE_MATHFN (BUILT_IN_LROUND)
1864       CASE_MATHFN (BUILT_IN_MODF)
1865       CASE_MATHFN (BUILT_IN_NAN)
1866       CASE_MATHFN (BUILT_IN_NANS)
1867       CASE_MATHFN (BUILT_IN_NEARBYINT)
1868       CASE_MATHFN (BUILT_IN_NEXTAFTER)
1869       CASE_MATHFN (BUILT_IN_NEXTTOWARD)
1870       CASE_MATHFN (BUILT_IN_POW)
1871       CASE_MATHFN (BUILT_IN_POWI)
1872       CASE_MATHFN (BUILT_IN_POW10)
1873       CASE_MATHFN (BUILT_IN_REMAINDER)
1874       CASE_MATHFN (BUILT_IN_REMQUO)
1875       CASE_MATHFN (BUILT_IN_RINT)
1876       CASE_MATHFN (BUILT_IN_ROUND)
1877       CASE_MATHFN (BUILT_IN_SCALB)
1878       CASE_MATHFN (BUILT_IN_SCALBLN)
1879       CASE_MATHFN (BUILT_IN_SCALBN)
1880       CASE_MATHFN (BUILT_IN_SIGNBIT)
1881       CASE_MATHFN (BUILT_IN_SIGNIFICAND)
1882       CASE_MATHFN (BUILT_IN_SIN)
1883       CASE_MATHFN (BUILT_IN_SINCOS)
1884       CASE_MATHFN (BUILT_IN_SINH)
1885       CASE_MATHFN (BUILT_IN_SQRT)
1886       CASE_MATHFN (BUILT_IN_TAN)
1887       CASE_MATHFN (BUILT_IN_TANH)
1888       CASE_MATHFN (BUILT_IN_TGAMMA)
1889       CASE_MATHFN (BUILT_IN_TRUNC)
1890       CASE_MATHFN (BUILT_IN_Y0)
1891       CASE_MATHFN (BUILT_IN_Y1)
1892       CASE_MATHFN (BUILT_IN_YN)
1893
1894       default:
1895         return NULL_TREE;
1896       }
1897
1898   if (TYPE_MAIN_VARIANT (type) == double_type_node)
1899     return fn_arr[fcode];
1900   else if (TYPE_MAIN_VARIANT (type) == float_type_node)
1901     return fn_arr[fcodef];
1902   else if (TYPE_MAIN_VARIANT (type) == long_double_type_node)
1903     return fn_arr[fcodel];
1904   else
1905     return NULL_TREE;
1906 }
1907
1908 /* Like mathfn_built_in_1(), but always use the implicit array.  */
1909
1910 tree
1911 mathfn_built_in (tree type, enum built_in_function fn)
1912 {
1913   return mathfn_built_in_1 (type, fn, /*implicit=*/ 1);
1914 }
1915
1916 /* If errno must be maintained, expand the RTL to check if the result,
1917    TARGET, of a built-in function call, EXP, is NaN, and if so set
1918    errno to EDOM.  */
1919
1920 static void
1921 expand_errno_check (tree exp, rtx target)
1922 {
1923   rtx lab = gen_label_rtx ();
1924
1925   /* Test the result; if it is NaN, set errno=EDOM because
1926      the argument was not in the domain.  */
1927   do_compare_rtx_and_jump (target, target, EQ, 0, GET_MODE (target),
1928                            NULL_RTX, NULL_RTX, lab,
1929                            /* The jump is very likely.  */
1930                            REG_BR_PROB_BASE - (REG_BR_PROB_BASE / 2000 - 1));
1931
1932 #ifdef TARGET_EDOM
1933   /* If this built-in doesn't throw an exception, set errno directly.  */
1934   if (TREE_NOTHROW (TREE_OPERAND (CALL_EXPR_FN (exp), 0)))
1935     {
1936 #ifdef GEN_ERRNO_RTX
1937       rtx errno_rtx = GEN_ERRNO_RTX;
1938 #else
1939       rtx errno_rtx
1940           = gen_rtx_MEM (word_mode, gen_rtx_SYMBOL_REF (Pmode, "errno"));
1941 #endif
1942       emit_move_insn (errno_rtx, GEN_INT (TARGET_EDOM));
1943       emit_label (lab);
1944       return;
1945     }
1946 #endif
1947
1948   /* Make sure the library call isn't expanded as a tail call.  */
1949   CALL_EXPR_TAILCALL (exp) = 0;
1950
1951   /* We can't set errno=EDOM directly; let the library call do it.
1952      Pop the arguments right away in case the call gets deleted.  */
1953   NO_DEFER_POP;
1954   expand_call (exp, target, 0);
1955   OK_DEFER_POP;
1956   emit_label (lab);
1957 }
1958
1959 /* Expand a call to one of the builtin math functions (sqrt, exp, or log).
1960    Return NULL_RTX if a normal call should be emitted rather than expanding
1961    the function in-line.  EXP is the expression that is a call to the builtin
1962    function; if convenient, the result should be placed in TARGET.
1963    SUBTARGET may be used as the target for computing one of EXP's operands.  */
1964
1965 static rtx
1966 expand_builtin_mathfn (tree exp, rtx target, rtx subtarget)
1967 {
1968   optab builtin_optab;
1969   rtx op0, insns;
1970   tree fndecl = get_callee_fndecl (exp);
1971   enum machine_mode mode;
1972   bool errno_set = false;
1973   tree arg;
1974
1975   if (!validate_arglist (exp, REAL_TYPE, VOID_TYPE))
1976     return NULL_RTX;
1977
1978   arg = CALL_EXPR_ARG (exp, 0);
1979
1980   switch (DECL_FUNCTION_CODE (fndecl))
1981     {
1982     CASE_FLT_FN (BUILT_IN_SQRT):
1983       errno_set = ! tree_expr_nonnegative_p (arg);
1984       builtin_optab = sqrt_optab;
1985       break;
1986     CASE_FLT_FN (BUILT_IN_EXP):
1987       errno_set = true; builtin_optab = exp_optab; break;
1988     CASE_FLT_FN (BUILT_IN_EXP10):
1989     CASE_FLT_FN (BUILT_IN_POW10):
1990       errno_set = true; builtin_optab = exp10_optab; break;
1991     CASE_FLT_FN (BUILT_IN_EXP2):
1992       errno_set = true; builtin_optab = exp2_optab; break;
1993     CASE_FLT_FN (BUILT_IN_EXPM1):
1994       errno_set = true; builtin_optab = expm1_optab; break;
1995     CASE_FLT_FN (BUILT_IN_LOGB):
1996       errno_set = true; builtin_optab = logb_optab; break;
1997     CASE_FLT_FN (BUILT_IN_LOG):
1998       errno_set = true; builtin_optab = log_optab; break;
1999     CASE_FLT_FN (BUILT_IN_LOG10):
2000       errno_set = true; builtin_optab = log10_optab; break;
2001     CASE_FLT_FN (BUILT_IN_LOG2):
2002       errno_set = true; builtin_optab = log2_optab; break;
2003     CASE_FLT_FN (BUILT_IN_LOG1P):
2004       errno_set = true; builtin_optab = log1p_optab; break;
2005     CASE_FLT_FN (BUILT_IN_ASIN):
2006       builtin_optab = asin_optab; break;
2007     CASE_FLT_FN (BUILT_IN_ACOS):
2008       builtin_optab = acos_optab; break;
2009     CASE_FLT_FN (BUILT_IN_TAN):
2010       builtin_optab = tan_optab; break;
2011     CASE_FLT_FN (BUILT_IN_ATAN):
2012       builtin_optab = atan_optab; break;
2013     CASE_FLT_FN (BUILT_IN_FLOOR):
2014       builtin_optab = floor_optab; break;
2015     CASE_FLT_FN (BUILT_IN_CEIL):
2016       builtin_optab = ceil_optab; break;
2017     CASE_FLT_FN (BUILT_IN_TRUNC):
2018       builtin_optab = btrunc_optab; break;
2019     CASE_FLT_FN (BUILT_IN_ROUND):
2020       builtin_optab = round_optab; break;
2021     CASE_FLT_FN (BUILT_IN_NEARBYINT):
2022       builtin_optab = nearbyint_optab;
2023       if (flag_trapping_math)
2024         break;
2025       /* Else fallthrough and expand as rint.  */
2026     CASE_FLT_FN (BUILT_IN_RINT):
2027       builtin_optab = rint_optab; break;
2028     CASE_FLT_FN (BUILT_IN_SIGNIFICAND):
2029       builtin_optab = significand_optab; break;
2030     default:
2031       gcc_unreachable ();
2032     }
2033
2034   /* Make a suitable register to place result in.  */
2035   mode = TYPE_MODE (TREE_TYPE (exp));
2036
2037   if (! flag_errno_math || ! HONOR_NANS (mode))
2038     errno_set = false;
2039
2040   /* Before working hard, check whether the instruction is available.  */
2041   if (optab_handler (builtin_optab, mode) != CODE_FOR_nothing
2042       && (!errno_set || !optimize_insn_for_size_p ()))
2043     {
2044       target = gen_reg_rtx (mode);
2045
2046       /* Wrap the computation of the argument in a SAVE_EXPR, as we may
2047          need to expand the argument again.  This way, we will not perform
2048          side-effects more the once.  */
2049       CALL_EXPR_ARG (exp, 0) = arg = builtin_save_expr (arg);
2050
2051       op0 = expand_expr (arg, subtarget, VOIDmode, EXPAND_NORMAL);
2052
2053       start_sequence ();
2054
2055       /* Compute into TARGET.
2056          Set TARGET to wherever the result comes back.  */
2057       target = expand_unop (mode, builtin_optab, op0, target, 0);
2058
2059       if (target != 0)
2060         {
2061           if (errno_set)
2062             expand_errno_check (exp, target);
2063
2064           /* Output the entire sequence.  */
2065           insns = get_insns ();
2066           end_sequence ();
2067           emit_insn (insns);
2068           return target;
2069         }
2070
2071       /* If we were unable to expand via the builtin, stop the sequence
2072          (without outputting the insns) and call to the library function
2073          with the stabilized argument list.  */
2074       end_sequence ();
2075     }
2076
2077   return expand_call (exp, target, target == const0_rtx);
2078 }
2079
2080 /* Expand a call to the builtin binary math functions (pow and atan2).
2081    Return NULL_RTX if a normal call should be emitted rather than expanding the
2082    function in-line.  EXP is the expression that is a call to the builtin
2083    function; if convenient, the result should be placed in TARGET.
2084    SUBTARGET may be used as the target for computing one of EXP's
2085    operands.  */
2086
2087 static rtx
2088 expand_builtin_mathfn_2 (tree exp, rtx target, rtx subtarget)
2089 {
2090   optab builtin_optab;
2091   rtx op0, op1, insns;
2092   int op1_type = REAL_TYPE;
2093   tree fndecl = get_callee_fndecl (exp);
2094   tree arg0, arg1;
2095   enum machine_mode mode;
2096   bool errno_set = true;
2097
2098   switch (DECL_FUNCTION_CODE (fndecl))
2099     {
2100     CASE_FLT_FN (BUILT_IN_SCALBN):
2101     CASE_FLT_FN (BUILT_IN_SCALBLN):
2102     CASE_FLT_FN (BUILT_IN_LDEXP):
2103       op1_type = INTEGER_TYPE;
2104     default:
2105       break;
2106     }
2107
2108   if (!validate_arglist (exp, REAL_TYPE, op1_type, VOID_TYPE))
2109     return NULL_RTX;
2110
2111   arg0 = CALL_EXPR_ARG (exp, 0);
2112   arg1 = CALL_EXPR_ARG (exp, 1);
2113
2114   switch (DECL_FUNCTION_CODE (fndecl))
2115     {
2116     CASE_FLT_FN (BUILT_IN_POW):
2117       builtin_optab = pow_optab; break;
2118     CASE_FLT_FN (BUILT_IN_ATAN2):
2119       builtin_optab = atan2_optab; break;
2120     CASE_FLT_FN (BUILT_IN_SCALB):
2121       if (REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (exp)))->b != 2)
2122         return 0;
2123       builtin_optab = scalb_optab; break;
2124     CASE_FLT_FN (BUILT_IN_SCALBN):
2125     CASE_FLT_FN (BUILT_IN_SCALBLN):
2126       if (REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (exp)))->b != 2)
2127         return 0;
2128     /* Fall through... */
2129     CASE_FLT_FN (BUILT_IN_LDEXP):
2130       builtin_optab = ldexp_optab; break;
2131     CASE_FLT_FN (BUILT_IN_FMOD):
2132       builtin_optab = fmod_optab; break;
2133     CASE_FLT_FN (BUILT_IN_REMAINDER):
2134     CASE_FLT_FN (BUILT_IN_DREM):
2135       builtin_optab = remainder_optab; break;
2136     default:
2137       gcc_unreachable ();
2138     }
2139
2140   /* Make a suitable register to place result in.  */
2141   mode = TYPE_MODE (TREE_TYPE (exp));
2142
2143   /* Before working hard, check whether the instruction is available.  */
2144   if (optab_handler (builtin_optab, mode) == CODE_FOR_nothing)
2145     return NULL_RTX;
2146
2147   target = gen_reg_rtx (mode);
2148
2149   if (! flag_errno_math || ! HONOR_NANS (mode))
2150     errno_set = false;
2151
2152   if (errno_set && optimize_insn_for_size_p ())
2153     return 0;
2154
2155   /* Always stabilize the argument list.  */
2156   CALL_EXPR_ARG (exp, 0) = arg0 = builtin_save_expr (arg0);
2157   CALL_EXPR_ARG (exp, 1) = arg1 = builtin_save_expr (arg1);
2158
2159   op0 = expand_expr (arg0, subtarget, VOIDmode, EXPAND_NORMAL);
2160   op1 = expand_normal (arg1);
2161
2162   start_sequence ();
2163
2164   /* Compute into TARGET.
2165      Set TARGET to wherever the result comes back.  */
2166   target = expand_binop (mode, builtin_optab, op0, op1,
2167                          target, 0, OPTAB_DIRECT);
2168
2169   /* If we were unable to expand via the builtin, stop the sequence
2170      (without outputting the insns) and call to the library function
2171      with the stabilized argument list.  */
2172   if (target == 0)
2173     {
2174       end_sequence ();
2175       return expand_call (exp, target, target == const0_rtx);
2176     }
2177
2178   if (errno_set)
2179     expand_errno_check (exp, target);
2180
2181   /* Output the entire sequence.  */
2182   insns = get_insns ();
2183   end_sequence ();
2184   emit_insn (insns);
2185
2186   return target;
2187 }
2188
2189 /* Expand a call to the builtin trinary math functions (fma).
2190    Return NULL_RTX if a normal call should be emitted rather than expanding the
2191    function in-line.  EXP is the expression that is a call to the builtin
2192    function; if convenient, the result should be placed in TARGET.
2193    SUBTARGET may be used as the target for computing one of EXP's
2194    operands.  */
2195
2196 static rtx
2197 expand_builtin_mathfn_ternary (tree exp, rtx target, rtx subtarget)
2198 {
2199   optab builtin_optab;
2200   rtx op0, op1, op2, insns;
2201   tree fndecl = get_callee_fndecl (exp);
2202   tree arg0, arg1, arg2;
2203   enum machine_mode mode;
2204
2205   if (!validate_arglist (exp, REAL_TYPE, REAL_TYPE, REAL_TYPE, VOID_TYPE))
2206     return NULL_RTX;
2207
2208   arg0 = CALL_EXPR_ARG (exp, 0);
2209   arg1 = CALL_EXPR_ARG (exp, 1);
2210   arg2 = CALL_EXPR_ARG (exp, 2);
2211
2212   switch (DECL_FUNCTION_CODE (fndecl))
2213     {
2214     CASE_FLT_FN (BUILT_IN_FMA):
2215       builtin_optab = fma_optab; break;
2216     default:
2217       gcc_unreachable ();
2218     }
2219
2220   /* Make a suitable register to place result in.  */
2221   mode = TYPE_MODE (TREE_TYPE (exp));
2222
2223   /* Before working hard, check whether the instruction is available.  */
2224   if (optab_handler (builtin_optab, mode) == CODE_FOR_nothing)
2225     return NULL_RTX;
2226
2227   target = gen_reg_rtx (mode);
2228
2229   /* Always stabilize the argument list.  */
2230   CALL_EXPR_ARG (exp, 0) = arg0 = builtin_save_expr (arg0);
2231   CALL_EXPR_ARG (exp, 1) = arg1 = builtin_save_expr (arg1);
2232   CALL_EXPR_ARG (exp, 2) = arg2 = builtin_save_expr (arg2);
2233
2234   op0 = expand_expr (arg0, subtarget, VOIDmode, EXPAND_NORMAL);
2235   op1 = expand_normal (arg1);
2236   op2 = expand_normal (arg2);
2237
2238   start_sequence ();
2239
2240   /* Compute into TARGET.
2241      Set TARGET to wherever the result comes back.  */
2242   target = expand_ternary_op (mode, builtin_optab, op0, op1, op2,
2243                               target, 0);
2244
2245   /* If we were unable to expand via the builtin, stop the sequence
2246      (without outputting the insns) and call to the library function
2247      with the stabilized argument list.  */
2248   if (target == 0)
2249     {
2250       end_sequence ();
2251       return expand_call (exp, target, target == const0_rtx);
2252     }
2253
2254   /* Output the entire sequence.  */
2255   insns = get_insns ();
2256   end_sequence ();
2257   emit_insn (insns);
2258
2259   return target;
2260 }
2261
2262 /* Expand a call to the builtin sin and cos math functions.
2263    Return NULL_RTX if a normal call should be emitted rather than expanding the
2264    function in-line.  EXP is the expression that is a call to the builtin
2265    function; if convenient, the result should be placed in TARGET.
2266    SUBTARGET may be used as the target for computing one of EXP's
2267    operands.  */
2268
2269 static rtx
2270 expand_builtin_mathfn_3 (tree exp, rtx target, rtx subtarget)
2271 {
2272   optab builtin_optab;
2273   rtx op0, insns;
2274   tree fndecl = get_callee_fndecl (exp);
2275   enum machine_mode mode;
2276   tree arg;
2277
2278   if (!validate_arglist (exp, REAL_TYPE, VOID_TYPE))
2279     return NULL_RTX;
2280
2281   arg = CALL_EXPR_ARG (exp, 0);
2282
2283   switch (DECL_FUNCTION_CODE (fndecl))
2284     {
2285     CASE_FLT_FN (BUILT_IN_SIN):
2286     CASE_FLT_FN (BUILT_IN_COS):
2287       builtin_optab = sincos_optab; break;
2288     default:
2289       gcc_unreachable ();
2290     }
2291
2292   /* Make a suitable register to place result in.  */
2293   mode = TYPE_MODE (TREE_TYPE (exp));
2294
2295   /* Check if sincos insn is available, otherwise fallback
2296      to sin or cos insn.  */
2297   if (optab_handler (builtin_optab, mode) == CODE_FOR_nothing)
2298     switch (DECL_FUNCTION_CODE (fndecl))
2299       {
2300       CASE_FLT_FN (BUILT_IN_SIN):
2301         builtin_optab = sin_optab; break;
2302       CASE_FLT_FN (BUILT_IN_COS):
2303         builtin_optab = cos_optab; break;
2304       default:
2305         gcc_unreachable ();
2306       }
2307
2308   /* Before working hard, check whether the instruction is available.  */
2309   if (optab_handler (builtin_optab, mode) != CODE_FOR_nothing)
2310     {
2311       target = gen_reg_rtx (mode);
2312
2313       /* Wrap the computation of the argument in a SAVE_EXPR, as we may
2314          need to expand the argument again.  This way, we will not perform
2315          side-effects more the once.  */
2316       CALL_EXPR_ARG (exp, 0) = arg = builtin_save_expr (arg);
2317
2318       op0 = expand_expr (arg, subtarget, VOIDmode, EXPAND_NORMAL);
2319
2320       start_sequence ();
2321
2322       /* Compute into TARGET.
2323          Set TARGET to wherever the result comes back.  */
2324       if (builtin_optab == sincos_optab)
2325         {
2326           int result;
2327
2328           switch (DECL_FUNCTION_CODE (fndecl))
2329             {
2330             CASE_FLT_FN (BUILT_IN_SIN):
2331               result = expand_twoval_unop (builtin_optab, op0, 0, target, 0);
2332               break;
2333             CASE_FLT_FN (BUILT_IN_COS):
2334               result = expand_twoval_unop (builtin_optab, op0, target, 0, 0);
2335               break;
2336             default:
2337               gcc_unreachable ();
2338             }
2339           gcc_assert (result);
2340         }
2341       else
2342         {
2343           target = expand_unop (mode, builtin_optab, op0, target, 0);
2344         }
2345
2346       if (target != 0)
2347         {
2348           /* Output the entire sequence.  */
2349           insns = get_insns ();
2350           end_sequence ();
2351           emit_insn (insns);
2352           return target;
2353         }
2354
2355       /* If we were unable to expand via the builtin, stop the sequence
2356          (without outputting the insns) and call to the library function
2357          with the stabilized argument list.  */
2358       end_sequence ();
2359     }
2360
2361   target = expand_call (exp, target, target == const0_rtx);
2362
2363   return target;
2364 }
2365
2366 /* Given an interclass math builtin decl FNDECL and it's argument ARG
2367    return an RTL instruction code that implements the functionality.
2368    If that isn't possible or available return CODE_FOR_nothing.  */
2369
2370 static enum insn_code
2371 interclass_mathfn_icode (tree arg, tree fndecl)
2372 {
2373   bool errno_set = false;
2374   optab builtin_optab = 0;
2375   enum machine_mode mode;
2376
2377   switch (DECL_FUNCTION_CODE (fndecl))
2378     {
2379     CASE_FLT_FN (BUILT_IN_ILOGB):
2380       errno_set = true; builtin_optab = ilogb_optab; break;
2381     CASE_FLT_FN (BUILT_IN_ISINF):
2382       builtin_optab = isinf_optab; break;
2383     case BUILT_IN_ISNORMAL:
2384     case BUILT_IN_ISFINITE:
2385     CASE_FLT_FN (BUILT_IN_FINITE):
2386     case BUILT_IN_FINITED32:
2387     case BUILT_IN_FINITED64:
2388     case BUILT_IN_FINITED128:
2389     case BUILT_IN_ISINFD32:
2390     case BUILT_IN_ISINFD64:
2391     case BUILT_IN_ISINFD128:
2392       /* These builtins have no optabs (yet).  */
2393       break;
2394     default:
2395       gcc_unreachable ();
2396     }
2397
2398   /* There's no easy way to detect the case we need to set EDOM.  */
2399   if (flag_errno_math && errno_set)
2400     return CODE_FOR_nothing;
2401
2402   /* Optab mode depends on the mode of the input argument.  */
2403   mode = TYPE_MODE (TREE_TYPE (arg));
2404
2405   if (builtin_optab)
2406     return optab_handler (builtin_optab, mode);
2407   return CODE_FOR_nothing;
2408 }
2409
2410 /* Expand a call to one of the builtin math functions that operate on
2411    floating point argument and output an integer result (ilogb, isinf,
2412    isnan, etc).
2413    Return 0 if a normal call should be emitted rather than expanding the
2414    function in-line.  EXP is the expression that is a call to the builtin
2415    function; if convenient, the result should be placed in TARGET.  */
2416
2417 static rtx
2418 expand_builtin_interclass_mathfn (tree exp, rtx target)
2419 {
2420   enum insn_code icode = CODE_FOR_nothing;
2421   rtx op0;
2422   tree fndecl = get_callee_fndecl (exp);
2423   enum machine_mode mode;
2424   tree arg;
2425
2426   if (!validate_arglist (exp, REAL_TYPE, VOID_TYPE))
2427     return NULL_RTX;
2428
2429   arg = CALL_EXPR_ARG (exp, 0);
2430   icode = interclass_mathfn_icode (arg, fndecl);
2431   mode = TYPE_MODE (TREE_TYPE (arg));
2432
2433   if (icode != CODE_FOR_nothing)
2434     {
2435       rtx last = get_last_insn ();
2436       tree orig_arg = arg;
2437       /* Make a suitable register to place result in.  */
2438       if (!target
2439           || GET_MODE (target) != TYPE_MODE (TREE_TYPE (exp))
2440           || !insn_data[icode].operand[0].predicate (target, GET_MODE (target)))
2441          target = gen_reg_rtx (TYPE_MODE (TREE_TYPE (exp)));
2442
2443       gcc_assert (insn_data[icode].operand[0].predicate
2444                   (target, GET_MODE (target)));
2445
2446       /* Wrap the computation of the argument in a SAVE_EXPR, as we may
2447          need to expand the argument again.  This way, we will not perform
2448          side-effects more the once.  */
2449       CALL_EXPR_ARG (exp, 0) = arg = builtin_save_expr (arg);
2450
2451       op0 = expand_expr (arg, NULL_RTX, VOIDmode, EXPAND_NORMAL);
2452
2453       if (mode != GET_MODE (op0))
2454         op0 = convert_to_mode (mode, op0, 0);
2455
2456       /* Compute into TARGET.
2457          Set TARGET to wherever the result comes back.  */
2458       if (maybe_emit_unop_insn (icode, target, op0, UNKNOWN))
2459         return target;
2460       delete_insns_since (last);
2461       CALL_EXPR_ARG (exp, 0) = orig_arg;
2462     }
2463
2464   return NULL_RTX;
2465 }
2466
2467 /* Expand a call to the builtin sincos math function.
2468    Return NULL_RTX if a normal call should be emitted rather than expanding the
2469    function in-line.  EXP is the expression that is a call to the builtin
2470    function.  */
2471
2472 static rtx
2473 expand_builtin_sincos (tree exp)
2474 {
2475   rtx op0, op1, op2, target1, target2;
2476   enum machine_mode mode;
2477   tree arg, sinp, cosp;
2478   int result;
2479   location_t loc = EXPR_LOCATION (exp);
2480   tree alias_type, alias_off;
2481
2482   if (!validate_arglist (exp, REAL_TYPE,
2483                          POINTER_TYPE, POINTER_TYPE, VOID_TYPE))
2484     return NULL_RTX;
2485
2486   arg = CALL_EXPR_ARG (exp, 0);
2487   sinp = CALL_EXPR_ARG (exp, 1);
2488   cosp = CALL_EXPR_ARG (exp, 2);
2489
2490   /* Make a suitable register to place result in.  */
2491   mode = TYPE_MODE (TREE_TYPE (arg));
2492
2493   /* Check if sincos insn is available, otherwise emit the call.  */
2494   if (optab_handler (sincos_optab, mode) == CODE_FOR_nothing)
2495     return NULL_RTX;
2496
2497   target1 = gen_reg_rtx (mode);
2498   target2 = gen_reg_rtx (mode);
2499
2500   op0 = expand_normal (arg);
2501   alias_type = build_pointer_type_for_mode (TREE_TYPE (arg), ptr_mode, true);
2502   alias_off = build_int_cst (alias_type, 0);
2503   op1 = expand_normal (fold_build2_loc (loc, MEM_REF, TREE_TYPE (arg),
2504                                         sinp, alias_off));
2505   op2 = expand_normal (fold_build2_loc (loc, MEM_REF, TREE_TYPE (arg),
2506                                         cosp, alias_off));
2507
2508   /* Compute into target1 and target2.
2509      Set TARGET to wherever the result comes back.  */
2510   result = expand_twoval_unop (sincos_optab, op0, target2, target1, 0);
2511   gcc_assert (result);
2512
2513   /* Move target1 and target2 to the memory locations indicated
2514      by op1 and op2.  */
2515   emit_move_insn (op1, target1);
2516   emit_move_insn (op2, target2);
2517
2518   return const0_rtx;
2519 }
2520
2521 /* Expand a call to the internal cexpi builtin to the sincos math function.
2522    EXP is the expression that is a call to the builtin function; if convenient,
2523    the result should be placed in TARGET.  */
2524
2525 static rtx
2526 expand_builtin_cexpi (tree exp, rtx target)
2527 {
2528   tree fndecl = get_callee_fndecl (exp);
2529   tree arg, type;
2530   enum machine_mode mode;
2531   rtx op0, op1, op2;
2532   location_t loc = EXPR_LOCATION (exp);
2533
2534   if (!validate_arglist (exp, REAL_TYPE, VOID_TYPE))
2535     return NULL_RTX;
2536
2537   arg = CALL_EXPR_ARG (exp, 0);
2538   type = TREE_TYPE (arg);
2539   mode = TYPE_MODE (TREE_TYPE (arg));
2540
2541   /* Try expanding via a sincos optab, fall back to emitting a libcall
2542      to sincos or cexp.  We are sure we have sincos or cexp because cexpi
2543      is only generated from sincos, cexp or if we have either of them.  */
2544   if (optab_handler (sincos_optab, mode) != CODE_FOR_nothing)
2545     {
2546       op1 = gen_reg_rtx (mode);
2547       op2 = gen_reg_rtx (mode);
2548
2549       op0 = expand_expr (arg, NULL_RTX, VOIDmode, EXPAND_NORMAL);
2550
2551       /* Compute into op1 and op2.  */
2552       expand_twoval_unop (sincos_optab, op0, op2, op1, 0);
2553     }
2554   else if (TARGET_HAS_SINCOS)
2555     {
2556       tree call, fn = NULL_TREE;
2557       tree top1, top2;
2558       rtx op1a, op2a;
2559
2560       if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPIF)
2561         fn = built_in_decls[BUILT_IN_SINCOSF];
2562       else if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPI)
2563         fn = built_in_decls[BUILT_IN_SINCOS];
2564       else if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPIL)
2565         fn = built_in_decls[BUILT_IN_SINCOSL];
2566       else
2567         gcc_unreachable ();
2568
2569       op1 = assign_temp (TREE_TYPE (arg), 0, 1, 1);
2570       op2 = assign_temp (TREE_TYPE (arg), 0, 1, 1);
2571       op1a = copy_to_mode_reg (Pmode, XEXP (op1, 0));
2572       op2a = copy_to_mode_reg (Pmode, XEXP (op2, 0));
2573       top1 = make_tree (build_pointer_type (TREE_TYPE (arg)), op1a);
2574       top2 = make_tree (build_pointer_type (TREE_TYPE (arg)), op2a);
2575
2576       /* Make sure not to fold the sincos call again.  */
2577       call = build1 (ADDR_EXPR, build_pointer_type (TREE_TYPE (fn)), fn);
2578       expand_normal (build_call_nary (TREE_TYPE (TREE_TYPE (fn)),
2579                                       call, 3, arg, top1, top2));
2580     }
2581   else
2582     {
2583       tree call, fn = NULL_TREE, narg;
2584       tree ctype = build_complex_type (type);
2585
2586       if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPIF)
2587         fn = built_in_decls[BUILT_IN_CEXPF];
2588       else if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPI)
2589         fn = built_in_decls[BUILT_IN_CEXP];
2590       else if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPIL)
2591         fn = built_in_decls[BUILT_IN_CEXPL];
2592       else
2593         gcc_unreachable ();
2594
2595       /* If we don't have a decl for cexp create one.  This is the
2596          friendliest fallback if the user calls __builtin_cexpi
2597          without full target C99 function support.  */
2598       if (fn == NULL_TREE)
2599         {
2600           tree fntype;
2601           const char *name = NULL;
2602
2603           if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPIF)
2604             name = "cexpf";
2605           else if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPI)
2606             name = "cexp";
2607           else if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPIL)
2608             name = "cexpl";
2609
2610           fntype = build_function_type_list (ctype, ctype, NULL_TREE);
2611           fn = build_fn_decl (name, fntype);
2612         }
2613
2614       narg = fold_build2_loc (loc, COMPLEX_EXPR, ctype,
2615                           build_real (type, dconst0), arg);
2616
2617       /* Make sure not to fold the cexp call again.  */
2618       call = build1 (ADDR_EXPR, build_pointer_type (TREE_TYPE (fn)), fn);
2619       return expand_expr (build_call_nary (ctype, call, 1, narg),
2620                           target, VOIDmode, EXPAND_NORMAL);
2621     }
2622
2623   /* Now build the proper return type.  */
2624   return expand_expr (build2 (COMPLEX_EXPR, build_complex_type (type),
2625                               make_tree (TREE_TYPE (arg), op2),
2626                               make_tree (TREE_TYPE (arg), op1)),
2627                       target, VOIDmode, EXPAND_NORMAL);
2628 }
2629
2630 /* Conveniently construct a function call expression.  FNDECL names the
2631    function to be called, N is the number of arguments, and the "..."
2632    parameters are the argument expressions.  Unlike build_call_exr
2633    this doesn't fold the call, hence it will always return a CALL_EXPR.  */
2634
2635 static tree
2636 build_call_nofold_loc (location_t loc, tree fndecl, int n, ...)
2637 {
2638   va_list ap;
2639   tree fntype = TREE_TYPE (fndecl);
2640   tree fn = build1 (ADDR_EXPR, build_pointer_type (fntype), fndecl);
2641
2642   va_start (ap, n);
2643   fn = build_call_valist (TREE_TYPE (fntype), fn, n, ap);
2644   va_end (ap);
2645   SET_EXPR_LOCATION (fn, loc);
2646   return fn;
2647 }
2648
2649 /* Expand a call to one of the builtin rounding functions gcc defines
2650    as an extension (lfloor and lceil).  As these are gcc extensions we
2651    do not need to worry about setting errno to EDOM.
2652    If expanding via optab fails, lower expression to (int)(floor(x)).
2653    EXP is the expression that is a call to the builtin function;
2654    if convenient, the result should be placed in TARGET.  */
2655
2656 static rtx
2657 expand_builtin_int_roundingfn (tree exp, rtx target)
2658 {
2659   convert_optab builtin_optab;
2660   rtx op0, insns, tmp;
2661   tree fndecl = get_callee_fndecl (exp);
2662   enum built_in_function fallback_fn;
2663   tree fallback_fndecl;
2664   enum machine_mode mode;
2665   tree arg;
2666
2667   if (!validate_arglist (exp, REAL_TYPE, VOID_TYPE))
2668     gcc_unreachable ();
2669
2670   arg = CALL_EXPR_ARG (exp, 0);
2671
2672   switch (DECL_FUNCTION_CODE (fndecl))
2673     {
2674     CASE_FLT_FN (BUILT_IN_LCEIL):
2675     CASE_FLT_FN (BUILT_IN_LLCEIL):
2676       builtin_optab = lceil_optab;
2677       fallback_fn = BUILT_IN_CEIL;
2678       break;
2679
2680     CASE_FLT_FN (BUILT_IN_LFLOOR):
2681     CASE_FLT_FN (BUILT_IN_LLFLOOR):
2682       builtin_optab = lfloor_optab;
2683       fallback_fn = BUILT_IN_FLOOR;
2684       break;
2685
2686     default:
2687       gcc_unreachable ();
2688     }
2689
2690   /* Make a suitable register to place result in.  */
2691   mode = TYPE_MODE (TREE_TYPE (exp));
2692
2693   target = gen_reg_rtx (mode);
2694
2695   /* Wrap the computation of the argument in a SAVE_EXPR, as we may
2696      need to expand the argument again.  This way, we will not perform
2697      side-effects more the once.  */
2698   CALL_EXPR_ARG (exp, 0) = arg = builtin_save_expr (arg);
2699
2700   op0 = expand_expr (arg, NULL, VOIDmode, EXPAND_NORMAL);
2701
2702   start_sequence ();
2703
2704   /* Compute into TARGET.  */
2705   if (expand_sfix_optab (target, op0, builtin_optab))
2706     {
2707       /* Output the entire sequence.  */
2708       insns = get_insns ();
2709       end_sequence ();
2710       emit_insn (insns);
2711       return target;
2712     }
2713
2714   /* If we were unable to expand via the builtin, stop the sequence
2715      (without outputting the insns).  */
2716   end_sequence ();
2717
2718   /* Fall back to floating point rounding optab.  */
2719   fallback_fndecl = mathfn_built_in (TREE_TYPE (arg), fallback_fn);
2720
2721   /* For non-C99 targets we may end up without a fallback fndecl here
2722      if the user called __builtin_lfloor directly.  In this case emit
2723      a call to the floor/ceil variants nevertheless.  This should result
2724      in the best user experience for not full C99 targets.  */
2725   if (fallback_fndecl == NULL_TREE)
2726     {
2727       tree fntype;
2728       const char *name = NULL;
2729
2730       switch (DECL_FUNCTION_CODE (fndecl))
2731         {
2732         case BUILT_IN_LCEIL:
2733         case BUILT_IN_LLCEIL:
2734           name = "ceil";
2735           break;
2736         case BUILT_IN_LCEILF:
2737         case BUILT_IN_LLCEILF:
2738           name = "ceilf";
2739           break;
2740         case BUILT_IN_LCEILL:
2741         case BUILT_IN_LLCEILL:
2742           name = "ceill";
2743           break;
2744         case BUILT_IN_LFLOOR:
2745         case BUILT_IN_LLFLOOR:
2746           name = "floor";
2747           break;
2748         case BUILT_IN_LFLOORF:
2749         case BUILT_IN_LLFLOORF:
2750           name = "floorf";
2751           break;
2752         case BUILT_IN_LFLOORL:
2753         case BUILT_IN_LLFLOORL:
2754           name = "floorl";
2755           break;
2756         default:
2757           gcc_unreachable ();
2758         }
2759
2760       fntype = build_function_type_list (TREE_TYPE (arg),
2761                                          TREE_TYPE (arg), NULL_TREE);
2762       fallback_fndecl = build_fn_decl (name, fntype);
2763     }
2764
2765   exp = build_call_nofold_loc (EXPR_LOCATION (exp), fallback_fndecl, 1, arg);
2766
2767   tmp = expand_normal (exp);
2768
2769   /* Truncate the result of floating point optab to integer
2770      via expand_fix ().  */
2771   target = gen_reg_rtx (mode);
2772   expand_fix (target, tmp, 0);
2773
2774   return target;
2775 }
2776
2777 /* Expand a call to one of the builtin math functions doing integer
2778    conversion (lrint).
2779    Return 0 if a normal call should be emitted rather than expanding the
2780    function in-line.  EXP is the expression that is a call to the builtin
2781    function; if convenient, the result should be placed in TARGET.  */
2782
2783 static rtx
2784 expand_builtin_int_roundingfn_2 (tree exp, rtx target)
2785 {
2786   convert_optab builtin_optab;
2787   rtx op0, insns;
2788   tree fndecl = get_callee_fndecl (exp);
2789   tree arg;
2790   enum machine_mode mode;
2791
2792   /* There's no easy way to detect the case we need to set EDOM.  */
2793   if (flag_errno_math)
2794     return NULL_RTX;
2795
2796   if (!validate_arglist (exp, REAL_TYPE, VOID_TYPE))
2797      gcc_unreachable ();
2798
2799   arg = CALL_EXPR_ARG (exp, 0);
2800
2801   switch (DECL_FUNCTION_CODE (fndecl))
2802     {
2803     CASE_FLT_FN (BUILT_IN_LRINT):
2804     CASE_FLT_FN (BUILT_IN_LLRINT):
2805       builtin_optab = lrint_optab; break;
2806     CASE_FLT_FN (BUILT_IN_LROUND):
2807     CASE_FLT_FN (BUILT_IN_LLROUND):
2808       builtin_optab = lround_optab; break;
2809     default:
2810       gcc_unreachable ();
2811     }
2812
2813   /* Make a suitable register to place result in.  */
2814   mode = TYPE_MODE (TREE_TYPE (exp));
2815
2816   target = gen_reg_rtx (mode);
2817
2818   /* Wrap the computation of the argument in a SAVE_EXPR, as we may
2819      need to expand the argument again.  This way, we will not perform
2820      side-effects more the once.  */
2821   CALL_EXPR_ARG (exp, 0) = arg = builtin_save_expr (arg);
2822
2823   op0 = expand_expr (arg, NULL, VOIDmode, EXPAND_NORMAL);
2824
2825   start_sequence ();
2826
2827   if (expand_sfix_optab (target, op0, builtin_optab))
2828     {
2829       /* Output the entire sequence.  */
2830       insns = get_insns ();
2831       end_sequence ();
2832       emit_insn (insns);
2833       return target;
2834     }
2835
2836   /* If we were unable to expand via the builtin, stop the sequence
2837      (without outputting the insns) and call to the library function
2838      with the stabilized argument list.  */
2839   end_sequence ();
2840
2841   target = expand_call (exp, target, target == const0_rtx);
2842
2843   return target;
2844 }
2845
2846 /* To evaluate powi(x,n), the floating point value x raised to the
2847    constant integer exponent n, we use a hybrid algorithm that
2848    combines the "window method" with look-up tables.  For an
2849    introduction to exponentiation algorithms and "addition chains",
2850    see section 4.6.3, "Evaluation of Powers" of Donald E. Knuth,
2851    "Seminumerical Algorithms", Vol. 2, "The Art of Computer Programming",
2852    3rd Edition, 1998, and Daniel M. Gordon, "A Survey of Fast Exponentiation
2853    Methods", Journal of Algorithms, Vol. 27, pp. 129-146, 1998.  */
2854
2855 /* Provide a default value for POWI_MAX_MULTS, the maximum number of
2856    multiplications to inline before calling the system library's pow
2857    function.  powi(x,n) requires at worst 2*bits(n)-2 multiplications,
2858    so this default never requires calling pow, powf or powl.  */
2859
2860 #ifndef POWI_MAX_MULTS
2861 #define POWI_MAX_MULTS  (2*HOST_BITS_PER_WIDE_INT-2)
2862 #endif
2863
2864 /* The size of the "optimal power tree" lookup table.  All
2865    exponents less than this value are simply looked up in the
2866    powi_table below.  This threshold is also used to size the
2867    cache of pseudo registers that hold intermediate results.  */
2868 #define POWI_TABLE_SIZE 256
2869
2870 /* The size, in bits of the window, used in the "window method"
2871    exponentiation algorithm.  This is equivalent to a radix of
2872    (1<<POWI_WINDOW_SIZE) in the corresponding "m-ary method".  */
2873 #define POWI_WINDOW_SIZE 3
2874
2875 /* The following table is an efficient representation of an
2876    "optimal power tree".  For each value, i, the corresponding
2877    value, j, in the table states than an optimal evaluation
2878    sequence for calculating pow(x,i) can be found by evaluating
2879    pow(x,j)*pow(x,i-j).  An optimal power tree for the first
2880    100 integers is given in Knuth's "Seminumerical algorithms".  */
2881
2882 static const unsigned char powi_table[POWI_TABLE_SIZE] =
2883   {
2884       0,   1,   1,   2,   2,   3,   3,   4,  /*   0 -   7 */
2885       4,   6,   5,   6,   6,  10,   7,   9,  /*   8 -  15 */
2886       8,  16,   9,  16,  10,  12,  11,  13,  /*  16 -  23 */
2887      12,  17,  13,  18,  14,  24,  15,  26,  /*  24 -  31 */
2888      16,  17,  17,  19,  18,  33,  19,  26,  /*  32 -  39 */
2889      20,  25,  21,  40,  22,  27,  23,  44,  /*  40 -  47 */
2890      24,  32,  25,  34,  26,  29,  27,  44,  /*  48 -  55 */
2891      28,  31,  29,  34,  30,  60,  31,  36,  /*  56 -  63 */
2892      32,  64,  33,  34,  34,  46,  35,  37,  /*  64 -  71 */
2893      36,  65,  37,  50,  38,  48,  39,  69,  /*  72 -  79 */
2894      40,  49,  41,  43,  42,  51,  43,  58,  /*  80 -  87 */
2895      44,  64,  45,  47,  46,  59,  47,  76,  /*  88 -  95 */
2896      48,  65,  49,  66,  50,  67,  51,  66,  /*  96 - 103 */
2897      52,  70,  53,  74,  54, 104,  55,  74,  /* 104 - 111 */
2898      56,  64,  57,  69,  58,  78,  59,  68,  /* 112 - 119 */
2899      60,  61,  61,  80,  62,  75,  63,  68,  /* 120 - 127 */
2900      64,  65,  65, 128,  66, 129,  67,  90,  /* 128 - 135 */
2901      68,  73,  69, 131,  70,  94,  71,  88,  /* 136 - 143 */
2902      72, 128,  73,  98,  74, 132,  75, 121,  /* 144 - 151 */
2903      76, 102,  77, 124,  78, 132,  79, 106,  /* 152 - 159 */
2904      80,  97,  81, 160,  82,  99,  83, 134,  /* 160 - 167 */
2905      84,  86,  85,  95,  86, 160,  87, 100,  /* 168 - 175 */
2906      88, 113,  89,  98,  90, 107,  91, 122,  /* 176 - 183 */
2907      92, 111,  93, 102,  94, 126,  95, 150,  /* 184 - 191 */
2908      96, 128,  97, 130,  98, 133,  99, 195,  /* 192 - 199 */
2909     100, 128, 101, 123, 102, 164, 103, 138,  /* 200 - 207 */
2910     104, 145, 105, 146, 106, 109, 107, 149,  /* 208 - 215 */
2911     108, 200, 109, 146, 110, 170, 111, 157,  /* 216 - 223 */
2912     112, 128, 113, 130, 114, 182, 115, 132,  /* 224 - 231 */
2913     116, 200, 117, 132, 118, 158, 119, 206,  /* 232 - 239 */
2914     120, 240, 121, 162, 122, 147, 123, 152,  /* 240 - 247 */
2915     124, 166, 125, 214, 126, 138, 127, 153,  /* 248 - 255 */
2916   };
2917
2918
2919 /* Return the number of multiplications required to calculate
2920    powi(x,n) where n is less than POWI_TABLE_SIZE.  This is a
2921    subroutine of powi_cost.  CACHE is an array indicating
2922    which exponents have already been calculated.  */
2923
2924 static int
2925 powi_lookup_cost (unsigned HOST_WIDE_INT n, bool *cache)
2926 {
2927   /* If we've already calculated this exponent, then this evaluation
2928      doesn't require any additional multiplications.  */
2929   if (cache[n])
2930     return 0;
2931
2932   cache[n] = true;
2933   return powi_lookup_cost (n - powi_table[n], cache)
2934          + powi_lookup_cost (powi_table[n], cache) + 1;
2935 }
2936
2937 /* Return the number of multiplications required to calculate
2938    powi(x,n) for an arbitrary x, given the exponent N.  This
2939    function needs to be kept in sync with expand_powi below.  */
2940
2941 static int
2942 powi_cost (HOST_WIDE_INT n)
2943 {
2944   bool cache[POWI_TABLE_SIZE];
2945   unsigned HOST_WIDE_INT digit;
2946   unsigned HOST_WIDE_INT val;
2947   int result;
2948
2949   if (n == 0)
2950     return 0;
2951
2952   /* Ignore the reciprocal when calculating the cost.  */
2953   val = (n < 0) ? -n : n;
2954
2955   /* Initialize the exponent cache.  */
2956   memset (cache, 0, POWI_TABLE_SIZE * sizeof (bool));
2957   cache[1] = true;
2958
2959   result = 0;
2960
2961   while (val >= POWI_TABLE_SIZE)
2962     {
2963       if (val & 1)
2964         {
2965           digit = val & ((1 << POWI_WINDOW_SIZE) - 1);
2966           result += powi_lookup_cost (digit, cache)
2967                     + POWI_WINDOW_SIZE + 1;
2968           val >>= POWI_WINDOW_SIZE;
2969         }
2970       else
2971         {
2972           val >>= 1;
2973           result++;
2974         }
2975     }
2976
2977   return result + powi_lookup_cost (val, cache);
2978 }
2979
2980 /* Recursive subroutine of expand_powi.  This function takes the array,
2981    CACHE, of already calculated exponents and an exponent N and returns
2982    an RTX that corresponds to CACHE[1]**N, as calculated in mode MODE.  */
2983
2984 static rtx
2985 expand_powi_1 (enum machine_mode mode, unsigned HOST_WIDE_INT n, rtx *cache)
2986 {
2987   unsigned HOST_WIDE_INT digit;
2988   rtx target, result;
2989   rtx op0, op1;
2990
2991   if (n < POWI_TABLE_SIZE)
2992     {
2993       if (cache[n])
2994         return cache[n];
2995
2996       target = gen_reg_rtx (mode);
2997       cache[n] = target;
2998
2999       op0 = expand_powi_1 (mode, n - powi_table[n], cache);
3000       op1 = expand_powi_1 (mode, powi_table[n], cache);
3001     }
3002   else if (n & 1)
3003     {
3004       target = gen_reg_rtx (mode);
3005       digit = n & ((1 << POWI_WINDOW_SIZE) - 1);
3006       op0 = expand_powi_1 (mode, n - digit, cache);
3007       op1 = expand_powi_1 (mode, digit, cache);
3008     }
3009   else
3010     {
3011       target = gen_reg_rtx (mode);
3012       op0 = expand_powi_1 (mode, n >> 1, cache);
3013       op1 = op0;
3014     }
3015
3016   result = expand_mult (mode, op0, op1, target, 0);
3017   if (result != target)
3018     emit_move_insn (target, result);
3019   return target;
3020 }
3021
3022 /* Expand the RTL to evaluate powi(x,n) in mode MODE.  X is the
3023    floating point operand in mode MODE, and N is the exponent.  This
3024    function needs to be kept in sync with powi_cost above.  */
3025
3026 static rtx
3027 expand_powi (rtx x, enum machine_mode mode, HOST_WIDE_INT n)
3028 {
3029   rtx cache[POWI_TABLE_SIZE];
3030   rtx result;
3031
3032   if (n == 0)
3033     return CONST1_RTX (mode);
3034
3035   memset (cache, 0, sizeof (cache));
3036   cache[1] = x;
3037
3038   result = expand_powi_1 (mode, (n < 0) ? -n : n, cache);
3039
3040   /* If the original exponent was negative, reciprocate the result.  */
3041   if (n < 0)
3042     result = expand_binop (mode, sdiv_optab, CONST1_RTX (mode),
3043                            result, NULL_RTX, 0, OPTAB_LIB_WIDEN);
3044
3045   return result;
3046 }
3047
3048 /* Fold a builtin function call to pow, powf, or powl into a series of sqrts or
3049    cbrts.  Return NULL_RTX if no simplification can be made or expand the tree
3050    if we can simplify it.  */
3051 static rtx
3052 expand_builtin_pow_root (location_t loc, tree arg0, tree arg1, tree type,
3053                          rtx subtarget)
3054 {
3055   if (TREE_CODE (arg1) == REAL_CST
3056       && !TREE_OVERFLOW (arg1)
3057       && flag_unsafe_math_optimizations)
3058     {
3059       enum machine_mode mode = TYPE_MODE (type);
3060       tree sqrtfn = mathfn_built_in (type, BUILT_IN_SQRT);
3061       tree cbrtfn = mathfn_built_in (type, BUILT_IN_CBRT);
3062       REAL_VALUE_TYPE c = TREE_REAL_CST (arg1);
3063       tree op = NULL_TREE;
3064
3065       if (sqrtfn)
3066         {
3067           /* Optimize pow (x, 0.5) into sqrt.  */
3068           if (REAL_VALUES_EQUAL (c, dconsthalf))
3069             op = build_call_nofold_loc (loc, sqrtfn, 1, arg0);
3070
3071           else
3072             {
3073               REAL_VALUE_TYPE dconst1_4 = dconst1;
3074               REAL_VALUE_TYPE dconst3_4;
3075               SET_REAL_EXP (&dconst1_4, REAL_EXP (&dconst1_4) - 2);
3076
3077               real_from_integer (&dconst3_4, VOIDmode, 3, 0, 0);
3078               SET_REAL_EXP (&dconst3_4, REAL_EXP (&dconst3_4) - 2);
3079
3080               /* Optimize pow (x, 0.25) into sqrt (sqrt (x)).  Assume on most
3081                  machines that a builtin sqrt instruction is smaller than a
3082                  call to pow with 0.25, so do this optimization even if
3083                  -Os.  */
3084               if (REAL_VALUES_EQUAL (c, dconst1_4))
3085                 {
3086                   op = build_call_nofold_loc (loc, sqrtfn, 1, arg0);
3087                   op = build_call_nofold_loc (loc, sqrtfn, 1, op);
3088                 }
3089
3090               /* Optimize pow (x, 0.75) = sqrt (x) * sqrt (sqrt (x)) unless we
3091                  are optimizing for space.  */
3092               else if (optimize_insn_for_speed_p ()
3093                        && !TREE_SIDE_EFFECTS (arg0)
3094                        && REAL_VALUES_EQUAL (c, dconst3_4))
3095                 {
3096                   tree sqrt1 = build_call_expr_loc (loc, sqrtfn, 1, arg0);
3097                   tree sqrt2 = builtin_save_expr (sqrt1);
3098                   tree sqrt3 = build_call_expr_loc (loc, sqrtfn, 1, sqrt1);
3099                   op = fold_build2_loc (loc, MULT_EXPR, type, sqrt2, sqrt3);
3100                 }
3101             }
3102         }
3103
3104       /* Check whether we can do cbrt insstead of pow (x, 1./3.) and
3105          cbrt/sqrts instead of pow (x, 1./6.).  */
3106       if (cbrtfn && ! op
3107           && (tree_expr_nonnegative_p (arg0) || !HONOR_NANS (mode)))
3108         {
3109           /* First try 1/3.  */
3110           REAL_VALUE_TYPE dconst1_3
3111             = real_value_truncate (mode, dconst_third ());
3112
3113           if (REAL_VALUES_EQUAL (c, dconst1_3))
3114             op = build_call_nofold_loc (loc, cbrtfn, 1, arg0);
3115
3116               /* Now try 1/6.  */
3117           else if (optimize_insn_for_speed_p ())
3118             {
3119               REAL_VALUE_TYPE dconst1_6 = dconst1_3;
3120               SET_REAL_EXP (&dconst1_6, REAL_EXP (&dconst1_6) - 1);
3121
3122               if (REAL_VALUES_EQUAL (c, dconst1_6))
3123                 {
3124                   op = build_call_nofold_loc (loc, sqrtfn, 1, arg0);
3125                   op = build_call_nofold_loc (loc, cbrtfn, 1, op);
3126                 }
3127             }
3128         }
3129
3130       if (op)
3131         return expand_expr (op, subtarget, mode, EXPAND_NORMAL);
3132     }
3133
3134   return NULL_RTX;
3135 }
3136
3137 /* Expand a call to the pow built-in mathematical function.  Return NULL_RTX if
3138    a normal call should be emitted rather than expanding the function
3139    in-line.  EXP is the expression that is a call to the builtin
3140    function; if convenient, the result should be placed in TARGET.  */
3141
3142 static rtx
3143 expand_builtin_pow (tree exp, rtx target, rtx subtarget)
3144 {
3145   tree arg0, arg1;
3146   tree fn, narg0;
3147   tree type = TREE_TYPE (exp);
3148   REAL_VALUE_TYPE cint, c, c2;
3149   HOST_WIDE_INT n;
3150   rtx op, op2;
3151   enum machine_mode mode = TYPE_MODE (type);
3152
3153   if (! validate_arglist (exp, REAL_TYPE, REAL_TYPE, VOID_TYPE))
3154     return NULL_RTX;
3155
3156   arg0 = CALL_EXPR_ARG (exp, 0);
3157   arg1 = CALL_EXPR_ARG (exp, 1);
3158
3159   if (TREE_CODE (arg1) != REAL_CST
3160       || TREE_OVERFLOW (arg1))
3161     return expand_builtin_mathfn_2 (exp, target, subtarget);
3162
3163   /* Handle constant exponents.  */
3164
3165   /* For integer valued exponents we can expand to an optimal multiplication
3166      sequence using expand_powi.  */
3167   c = TREE_REAL_CST (arg1);
3168   n = real_to_integer (&c);
3169   real_from_integer (&cint, VOIDmode, n, n < 0 ? -1 : 0, 0);
3170   if (real_identical (&c, &cint)
3171       && ((n >= -1 && n <= 2)
3172           || (flag_unsafe_math_optimizations
3173               && optimize_insn_for_speed_p ()
3174               && powi_cost (n) <= POWI_MAX_MULTS)))
3175     {
3176       op = expand_expr (arg0, subtarget, VOIDmode, EXPAND_NORMAL);
3177       if (n != 1)
3178         {
3179           op = force_reg (mode, op);
3180           op = expand_powi (op, mode, n);
3181         }
3182       return op;
3183     }
3184
3185   narg0 = builtin_save_expr (arg0);
3186
3187   /* If the exponent is not integer valued, check if it is half of an integer.
3188      In this case we can expand to sqrt (x) * x**(n/2).  */
3189   fn = mathfn_built_in (type, BUILT_IN_SQRT);
3190   if (fn != NULL_TREE)
3191     {
3192       real_arithmetic (&c2, MULT_EXPR, &c, &dconst2);
3193       n = real_to_integer (&c2);
3194       real_from_integer (&cint, VOIDmode, n, n < 0 ? -1 : 0, 0);
3195       if (real_identical (&c2, &cint)
3196           && ((flag_unsafe_math_optimizations
3197                && optimize_insn_for_speed_p ()
3198                && powi_cost (n/2) <= POWI_MAX_MULTS)
3199               /* Even the c == 0.5 case cannot be done unconditionally
3200                  when we need to preserve signed zeros, as
3201                  pow (-0, 0.5) is +0, while sqrt(-0) is -0.  */
3202               || (!HONOR_SIGNED_ZEROS (mode) && n == 1)
3203               /* For c == 1.5 we can assume that x * sqrt (x) is always
3204                  smaller than pow (x, 1.5) if sqrt will not be expanded
3205                  as a call.  */
3206               || (n == 3
3207                   && optab_handler (sqrt_optab, mode) != CODE_FOR_nothing)))
3208         {
3209           tree call_expr = build_call_nofold_loc (EXPR_LOCATION (exp), fn, 1,
3210                                                   narg0);
3211           /* Use expand_expr in case the newly built call expression
3212              was folded to a non-call.  */
3213           op = expand_expr (call_expr, subtarget, mode, EXPAND_NORMAL);
3214           if (n != 1)
3215             {
3216               op2 = expand_expr (narg0, subtarget, VOIDmode, EXPAND_NORMAL);
3217               op2 = force_reg (mode, op2);
3218               op2 = expand_powi (op2, mode, abs (n / 2));
3219               op = expand_simple_binop (mode, MULT, op, op2, NULL_RTX,
3220                                         0, OPTAB_LIB_WIDEN);
3221               /* If the original exponent was negative, reciprocate the
3222                  result.  */
3223               if (n < 0)
3224                 op = expand_binop (mode, sdiv_optab, CONST1_RTX (mode),
3225                                    op, NULL_RTX, 0, OPTAB_LIB_WIDEN);
3226             }
3227           return op;
3228         }
3229     }
3230
3231   /* Check whether we can do a series of sqrt or cbrt's instead of the pow
3232      call.  */
3233   op = expand_builtin_pow_root (EXPR_LOCATION (exp), arg0, arg1, type,
3234                                 subtarget);
3235   if (op)
3236     return op;
3237
3238   /* Try if the exponent is a third of an integer.  In this case
3239      we can expand to x**(n/3) * cbrt(x)**(n%3).  As cbrt (x) is
3240      different from pow (x, 1./3.) due to rounding and behavior
3241      with negative x we need to constrain this transformation to
3242      unsafe math and positive x or finite math.  */
3243   fn = mathfn_built_in (type, BUILT_IN_CBRT);
3244   if (fn != NULL_TREE
3245       && flag_unsafe_math_optimizations
3246       && (tree_expr_nonnegative_p (arg0)
3247           || !HONOR_NANS (mode)))
3248     {
3249       REAL_VALUE_TYPE dconst3;
3250       real_from_integer (&dconst3, VOIDmode, 3, 0, 0);
3251       real_arithmetic (&c2, MULT_EXPR, &c, &dconst3);
3252       real_round (&c2, mode, &c2);
3253       n = real_to_integer (&c2);
3254       real_from_integer (&cint, VOIDmode, n, n < 0 ? -1 : 0, 0);
3255       real_arithmetic (&c2, RDIV_EXPR, &cint, &dconst3);
3256       real_convert (&c2, mode, &c2);
3257       if (real_identical (&c2, &c)
3258           && ((optimize_insn_for_speed_p ()
3259                && powi_cost (n/3) <= POWI_MAX_MULTS)
3260               || n == 1))
3261         {
3262           tree call_expr = build_call_nofold_loc (EXPR_LOCATION (exp), fn, 1,
3263                                                   narg0);
3264           op = expand_builtin (call_expr, NULL_RTX, subtarget, mode, 0);
3265           if (abs (n) % 3 == 2)
3266             op = expand_simple_binop (mode, MULT, op, op, op,
3267                                       0, OPTAB_LIB_WIDEN);
3268           if (n != 1)
3269             {
3270               op2 = expand_expr (narg0, subtarget, VOIDmode, EXPAND_NORMAL);
3271               op2 = force_reg (mode, op2);
3272               op2 = expand_powi (op2, mode, abs (n / 3));
3273               op = expand_simple_binop (mode, MULT, op, op2, NULL_RTX,
3274                                         0, OPTAB_LIB_WIDEN);
3275               /* If the original exponent was negative, reciprocate the
3276                  result.  */
3277               if (n < 0)
3278                 op = expand_binop (mode, sdiv_optab, CONST1_RTX (mode),
3279                                    op, NULL_RTX, 0, OPTAB_LIB_WIDEN);
3280             }
3281           return op;
3282         }
3283     }
3284
3285   /* Fall back to optab expansion.  */
3286   return expand_builtin_mathfn_2 (exp, target, subtarget);
3287 }
3288
3289 /* Expand a call to the powi built-in mathematical function.  Return NULL_RTX if
3290    a normal call should be emitted rather than expanding the function
3291    in-line.  EXP is the expression that is a call to the builtin
3292    function; if convenient, the result should be placed in TARGET.  */
3293
3294 static rtx
3295 expand_builtin_powi (tree exp, rtx target)
3296 {
3297   tree arg0, arg1;
3298   rtx op0, op1;
3299   enum machine_mode mode;
3300   enum machine_mode mode2;
3301
3302   if (! validate_arglist (exp, REAL_TYPE, INTEGER_TYPE, VOID_TYPE))
3303     return NULL_RTX;
3304
3305   arg0 = CALL_EXPR_ARG (exp, 0);
3306   arg1 = CALL_EXPR_ARG (exp, 1);
3307   mode = TYPE_MODE (TREE_TYPE (exp));
3308
3309   /* Handle constant power.  */
3310
3311   if (TREE_CODE (arg1) == INTEGER_CST
3312       && !TREE_OVERFLOW (arg1))
3313     {
3314       HOST_WIDE_INT n = TREE_INT_CST_LOW (arg1);
3315
3316       /* If the exponent is -1, 0, 1 or 2, then expand_powi is exact.
3317          Otherwise, check the number of multiplications required.  */
3318       if ((TREE_INT_CST_HIGH (arg1) == 0
3319            || TREE_INT_CST_HIGH (arg1) == -1)
3320           && ((n >= -1 && n <= 2)
3321               || (optimize_insn_for_speed_p ()
3322                   && powi_cost (n) <= POWI_MAX_MULTS)))
3323         {
3324           op0 = expand_expr (arg0, NULL_RTX, VOIDmode, EXPAND_NORMAL);
3325           op0 = force_reg (mode, op0);
3326           return expand_powi (op0, mode, n);
3327         }
3328     }
3329
3330   /* Emit a libcall to libgcc.  */
3331
3332   /* Mode of the 2nd argument must match that of an int.  */
3333   mode2 = mode_for_size (INT_TYPE_SIZE, MODE_INT, 0);
3334
3335   if (target == NULL_RTX)
3336     target = gen_reg_rtx (mode);
3337
3338   op0 = expand_expr (arg0, NULL_RTX, mode, EXPAND_NORMAL);
3339   if (GET_MODE (op0) != mode)
3340     op0 = convert_to_mode (mode, op0, 0);
3341   op1 = expand_expr (arg1, NULL_RTX, mode2, EXPAND_NORMAL);
3342   if (GET_MODE (op1) != mode2)
3343     op1 = convert_to_mode (mode2, op1, 0);
3344
3345   target = emit_library_call_value (optab_libfunc (powi_optab, mode),
3346                                     target, LCT_CONST, mode, 2,
3347                                     op0, mode, op1, mode2);
3348
3349   return target;
3350 }
3351
3352 /* Expand expression EXP which is a call to the strlen builtin.  Return
3353    NULL_RTX if we failed the caller should emit a normal call, otherwise
3354    try to get the result in TARGET, if convenient.  */
3355
3356 static rtx
3357 expand_builtin_strlen (tree exp, rtx target,
3358                        enum machine_mode target_mode)
3359 {
3360   if (!validate_arglist (exp, POINTER_TYPE, VOID_TYPE))
3361     return NULL_RTX;
3362   else
3363     {
3364       rtx pat;
3365       tree len;
3366       tree src = CALL_EXPR_ARG (exp, 0);
3367       rtx result, src_reg, char_rtx, before_strlen;
3368       enum machine_mode insn_mode = target_mode, char_mode;
3369       enum insn_code icode = CODE_FOR_nothing;
3370       unsigned int align;
3371
3372       /* If the length can be computed at compile-time, return it.  */
3373       len = c_strlen (src, 0);
3374       if (len)
3375         return expand_expr (len, target, target_mode, EXPAND_NORMAL);
3376
3377       /* If the length can be computed at compile-time and is constant
3378          integer, but there are side-effects in src, evaluate
3379          src for side-effects, then return len.
3380          E.g. x = strlen (i++ ? "xfoo" + 1 : "bar");
3381          can be optimized into: i++; x = 3;  */
3382       len = c_strlen (src, 1);
3383       if (len && TREE_CODE (len) == INTEGER_CST)
3384         {
3385           expand_expr (src, const0_rtx, VOIDmode, EXPAND_NORMAL);
3386           return expand_expr (len, target, target_mode, EXPAND_NORMAL);
3387         }
3388
3389       align = get_pointer_alignment (src, BIGGEST_ALIGNMENT) / BITS_PER_UNIT;
3390
3391       /* If SRC is not a pointer type, don't do this operation inline.  */
3392       if (align == 0)
3393         return NULL_RTX;
3394
3395       /* Bail out if we can't compute strlen in the right mode.  */
3396       while (insn_mode != VOIDmode)
3397         {
3398           icode = optab_handler (strlen_optab, insn_mode);
3399           if (icode != CODE_FOR_nothing)
3400             break;
3401
3402           insn_mode = GET_MODE_WIDER_MODE (insn_mode);
3403         }
3404       if (insn_mode == VOIDmode)
3405         return NULL_RTX;
3406
3407       /* Make a place to write the result of the instruction.  */
3408       result = target;
3409       if (! (result != 0
3410              && REG_P (result)
3411              && GET_MODE (result) == insn_mode
3412              && REGNO (result) >= FIRST_PSEUDO_REGISTER))
3413         result = gen_reg_rtx (insn_mode);
3414
3415       /* Make a place to hold the source address.  We will not expand
3416          the actual source until we are sure that the expansion will
3417          not fail -- there are trees that cannot be expanded twice.  */
3418       src_reg = gen_reg_rtx (Pmode);
3419
3420       /* Mark the beginning of the strlen sequence so we can emit the
3421          source operand later.  */
3422       before_strlen = get_last_insn ();
3423
3424       char_rtx = const0_rtx;
3425       char_mode = insn_data[(int) icode].operand[2].mode;
3426       if (! (*insn_data[(int) icode].operand[2].predicate) (char_rtx,
3427                                                             char_mode))
3428         char_rtx = copy_to_mode_reg (char_mode, char_rtx);
3429
3430       pat = GEN_FCN (icode) (result, gen_rtx_MEM (BLKmode, src_reg),
3431                              char_rtx, GEN_INT (align));
3432       if (! pat)
3433         return NULL_RTX;
3434       emit_insn (pat);
3435
3436       /* Now that we are assured of success, expand the source.  */
3437       start_sequence ();
3438       pat = expand_expr (src, src_reg, ptr_mode, EXPAND_NORMAL);
3439       if (pat != src_reg)
3440         emit_move_insn (src_reg, pat);
3441       pat = get_insns ();
3442       end_sequence ();
3443
3444       if (before_strlen)
3445         emit_insn_after (pat, before_strlen);
3446       else
3447         emit_insn_before (pat, get_insns ());
3448
3449       /* Return the value in the proper mode for this function.  */
3450       if (GET_MODE (result) == target_mode)
3451         target = result;
3452       else if (target != 0)
3453         convert_move (target, result, 0);
3454       else
3455         target = convert_to_mode (target_mode, result, 0);
3456
3457       return target;
3458     }
3459 }
3460
3461 /* Callback routine for store_by_pieces.  Read GET_MODE_BITSIZE (MODE)
3462    bytes from constant string DATA + OFFSET and return it as target
3463    constant.  */
3464
3465 static rtx
3466 builtin_memcpy_read_str (void *data, HOST_WIDE_INT offset,
3467                          enum machine_mode mode)
3468 {
3469   const char *str = (const char *) data;
3470
3471   gcc_assert (offset >= 0
3472               && ((unsigned HOST_WIDE_INT) offset + GET_MODE_SIZE (mode)
3473                   <= strlen (str) + 1));
3474
3475   return c_readstr (str + offset, mode);
3476 }
3477
3478 /* Expand a call EXP to the memcpy builtin.
3479    Return NULL_RTX if we failed, the caller should emit a normal call,
3480    otherwise try to get the result in TARGET, if convenient (and in
3481    mode MODE if that's convenient).  */
3482
3483 static rtx
3484 expand_builtin_memcpy (tree exp, rtx target)
3485 {
3486   if (!validate_arglist (exp,
3487                          POINTER_TYPE, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
3488     return NULL_RTX;
3489   else
3490     {
3491       tree dest = CALL_EXPR_ARG (exp, 0);
3492       tree src = CALL_EXPR_ARG (exp, 1);
3493       tree len = CALL_EXPR_ARG (exp, 2);
3494       const char *src_str;
3495       unsigned int src_align = get_pointer_alignment (src, BIGGEST_ALIGNMENT);
3496       unsigned int dest_align
3497         = get_pointer_alignment (dest, BIGGEST_ALIGNMENT);
3498       rtx dest_mem, src_mem, dest_addr, len_rtx;
3499       HOST_WIDE_INT expected_size = -1;
3500       unsigned int expected_align = 0;
3501
3502       /* If DEST is not a pointer type, call the normal function.  */
3503       if (dest_align == 0)
3504         return NULL_RTX;
3505
3506       /* If either SRC is not a pointer type, don't do this
3507          operation in-line.  */
3508       if (src_align == 0)
3509         return NULL_RTX;
3510
3511       if (currently_expanding_gimple_stmt)
3512         stringop_block_profile (currently_expanding_gimple_stmt,
3513                                 &expected_align, &expected_size);
3514
3515       if (expected_align < dest_align)
3516         expected_align = dest_align;
3517       dest_mem = get_memory_rtx (dest, len);
3518       set_mem_align (dest_mem, dest_align);
3519       len_rtx = expand_normal (len);
3520       src_str = c_getstr (src);
3521
3522       /* If SRC is a string constant and block move would be done
3523          by pieces, we can avoid loading the string from memory
3524          and only stored the computed constants.  */
3525       if (src_str
3526           && CONST_INT_P (len_rtx)
3527           && (unsigned HOST_WIDE_INT) INTVAL (len_rtx) <= strlen (src_str) + 1
3528           && can_store_by_pieces (INTVAL (len_rtx), builtin_memcpy_read_str,
3529                                   CONST_CAST (char *, src_str),
3530                                   dest_align, false))
3531         {
3532           dest_mem = store_by_pieces (dest_mem, INTVAL (len_rtx),
3533                                       builtin_memcpy_read_str,
3534                                       CONST_CAST (char *, src_str),
3535                                       dest_align, false, 0);
3536           dest_mem = force_operand (XEXP (dest_mem, 0), target);
3537           dest_mem = convert_memory_address (ptr_mode, dest_mem);
3538           return dest_mem;
3539         }
3540
3541       src_mem = get_memory_rtx (src, len);
3542       set_mem_align (src_mem, src_align);
3543
3544       /* Copy word part most expediently.  */
3545       dest_addr = emit_block_move_hints (dest_mem, src_mem, len_rtx,
3546                                          CALL_EXPR_TAILCALL (exp)
3547                                          ? BLOCK_OP_TAILCALL : BLOCK_OP_NORMAL,
3548                                          expected_align, expected_size);
3549
3550       if (dest_addr == 0)
3551         {
3552           dest_addr = force_operand (XEXP (dest_mem, 0), target);
3553           dest_addr = convert_memory_address (ptr_mode, dest_addr);
3554         }
3555       return dest_addr;
3556     }
3557 }
3558
3559 /* Expand a call EXP to the mempcpy builtin.
3560    Return NULL_RTX if we failed; the caller should emit a normal call,
3561    otherwise try to get the result in TARGET, if convenient (and in
3562    mode MODE if that's convenient).  If ENDP is 0 return the
3563    destination pointer, if ENDP is 1 return the end pointer ala
3564    mempcpy, and if ENDP is 2 return the end pointer minus one ala
3565    stpcpy.  */
3566
3567 static rtx
3568 expand_builtin_mempcpy (tree exp, rtx target, enum machine_mode mode)
3569 {
3570   if (!validate_arglist (exp,
3571                          POINTER_TYPE, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
3572     return NULL_RTX;
3573   else
3574     {
3575       tree dest = CALL_EXPR_ARG (exp, 0);
3576       tree src = CALL_EXPR_ARG (exp, 1);
3577       tree len = CALL_EXPR_ARG (exp, 2);
3578       return expand_builtin_mempcpy_args (dest, src, len,
3579                                           target, mode, /*endp=*/ 1);
3580     }
3581 }
3582
3583 /* Helper function to do the actual work for expand_builtin_mempcpy.  The
3584    arguments to the builtin_mempcpy call DEST, SRC, and LEN are broken out
3585    so that this can also be called without constructing an actual CALL_EXPR.
3586    The other arguments and return value are the same as for
3587    expand_builtin_mempcpy.  */
3588
3589 static rtx
3590 expand_builtin_mempcpy_args (tree dest, tree src, tree len,
3591                              rtx target, enum machine_mode mode, int endp)
3592 {
3593     /* If return value is ignored, transform mempcpy into memcpy.  */
3594   if (target == const0_rtx && implicit_built_in_decls[BUILT_IN_MEMCPY])
3595     {
3596       tree fn = implicit_built_in_decls[BUILT_IN_MEMCPY];
3597       tree result = build_call_nofold_loc (UNKNOWN_LOCATION, fn, 3,
3598                                            dest, src, len);
3599       return expand_expr (result, target, mode, EXPAND_NORMAL);
3600     }
3601   else
3602     {
3603       const char *src_str;
3604       unsigned int src_align = get_pointer_alignment (src, BIGGEST_ALIGNMENT);
3605       unsigned int dest_align
3606         = get_pointer_alignment (dest, BIGGEST_ALIGNMENT);
3607       rtx dest_mem, src_mem, len_rtx;
3608
3609       /* If either SRC or DEST is not a pointer type, don't do this
3610          operation in-line.  */
3611       if (dest_align == 0 || src_align == 0)
3612         return NULL_RTX;
3613
3614       /* If LEN is not constant, call the normal function.  */
3615       if (! host_integerp (len, 1))
3616         return NULL_RTX;
3617
3618       len_rtx = expand_normal (len);
3619       src_str = c_getstr (src);
3620
3621       /* If SRC is a string constant and block move would be done
3622          by pieces, we can avoid loading the string from memory
3623          and only stored the computed constants.  */
3624       if (src_str
3625           && CONST_INT_P (len_rtx)
3626           && (unsigned HOST_WIDE_INT) INTVAL (len_rtx) <= strlen (src_str) + 1
3627           && can_store_by_pieces (INTVAL (len_rtx), builtin_memcpy_read_str,
3628                                   CONST_CAST (char *, src_str),
3629                                   dest_align, false))
3630         {
3631           dest_mem = get_memory_rtx (dest, len);
3632           set_mem_align (dest_mem, dest_align);
3633           dest_mem = store_by_pieces (dest_mem, INTVAL (len_rtx),
3634                                       builtin_memcpy_read_str,
3635                                       CONST_CAST (char *, src_str),
3636                                       dest_align, false, endp);
3637           dest_mem = force_operand (XEXP (dest_mem, 0), NULL_RTX);
3638           dest_mem = convert_memory_address (ptr_mode, dest_mem);
3639           return dest_mem;
3640         }
3641
3642       if (CONST_INT_P (len_rtx)
3643           && can_move_by_pieces (INTVAL (len_rtx),
3644                                  MIN (dest_align, src_align)))
3645         {
3646           dest_mem = get_memory_rtx (dest, len);
3647           set_mem_align (dest_mem, dest_align);
3648           src_mem = get_memory_rtx (src, len);
3649           set_mem_align (src_mem, src_align);
3650           dest_mem = move_by_pieces (dest_mem, src_mem, INTVAL (len_rtx),
3651                                      MIN (dest_align, src_align), endp);
3652           dest_mem = force_operand (XEXP (dest_mem, 0), NULL_RTX);
3653           dest_mem = convert_memory_address (ptr_mode, dest_mem);
3654           return dest_mem;
3655         }
3656
3657       return NULL_RTX;
3658     }
3659 }
3660
3661 #ifndef HAVE_movstr
3662 # define HAVE_movstr 0
3663 # define CODE_FOR_movstr CODE_FOR_nothing
3664 #endif
3665
3666 /* Expand into a movstr instruction, if one is available.  Return NULL_RTX if
3667    we failed, the caller should emit a normal call, otherwise try to
3668    get the result in TARGET, if convenient.  If ENDP is 0 return the
3669    destination pointer, if ENDP is 1 return the end pointer ala
3670    mempcpy, and if ENDP is 2 return the end pointer minus one ala
3671    stpcpy.  */
3672
3673 static rtx
3674 expand_movstr (tree dest, tree src, rtx target, int endp)
3675 {
3676   rtx end;
3677   rtx dest_mem;
3678   rtx src_mem;
3679   rtx insn;
3680   const struct insn_data_d * data;
3681
3682   if (!HAVE_movstr)
3683     return NULL_RTX;
3684
3685   dest_mem = get_memory_rtx (dest, NULL);
3686   src_mem = get_memory_rtx (src, NULL);
3687   data = insn_data + CODE_FOR_movstr;
3688   if (!endp)
3689     {
3690       target = force_reg (Pmode, XEXP (dest_mem, 0));
3691       dest_mem = replace_equiv_address (dest_mem, target);
3692       end = gen_reg_rtx (Pmode);
3693     }
3694   else
3695     {
3696       if (target == 0
3697           || target == const0_rtx
3698           || ! (*data->operand[0].predicate) (target, Pmode))
3699         {
3700           end = gen_reg_rtx (Pmode);
3701           if (target != const0_rtx)
3702             target = end;
3703         }
3704       else
3705         end = target;
3706     }
3707
3708   if (data->operand[0].mode != VOIDmode)
3709     end = gen_lowpart (data->operand[0].mode, end);
3710
3711   insn = data->genfun (end, dest_mem, src_mem);
3712
3713   gcc_assert (insn);
3714
3715   emit_insn (insn);
3716
3717   /* movstr is supposed to set end to the address of the NUL
3718      terminator.  If the caller requested a mempcpy-like return value,
3719      adjust it.  */
3720   if (endp == 1 && target != const0_rtx)
3721     {
3722       rtx tem = plus_constant (gen_lowpart (GET_MODE (target), end), 1);
3723       emit_move_insn (target, force_operand (tem, NULL_RTX));
3724     }
3725
3726   return target;
3727 }
3728
3729 /* Expand expression EXP, which is a call to the strcpy builtin.  Return
3730    NULL_RTX if we failed the caller should emit a normal call, otherwise
3731    try to get the result in TARGET, if convenient (and in mode MODE if that's
3732    convenient).  */
3733
3734 static rtx
3735 expand_builtin_strcpy (tree exp, rtx target)
3736 {
3737   if (validate_arglist (exp, POINTER_TYPE, POINTER_TYPE, VOID_TYPE))
3738    {
3739      tree dest = CALL_EXPR_ARG (exp, 0);
3740      tree src = CALL_EXPR_ARG (exp, 1);
3741      return expand_builtin_strcpy_args (dest, src, target);
3742    }
3743    return NULL_RTX;
3744 }
3745
3746 /* Helper function to do the actual work for expand_builtin_strcpy.  The
3747    arguments to the builtin_strcpy call DEST and SRC are broken out
3748    so that this can also be called without constructing an actual CALL_EXPR.
3749    The other arguments and return value are the same as for
3750    expand_builtin_strcpy.  */
3751
3752 static rtx
3753 expand_builtin_strcpy_args (tree dest, tree src, rtx target)
3754 {
3755   return expand_movstr (dest, src, target, /*endp=*/0);
3756 }
3757
3758 /* Expand a call EXP to the stpcpy builtin.
3759    Return NULL_RTX if we failed the caller should emit a normal call,
3760    otherwise try to get the result in TARGET, if convenient (and in
3761    mode MODE if that's convenient).  */
3762
3763 static rtx
3764 expand_builtin_stpcpy (tree exp, rtx target, enum machine_mode mode)
3765 {
3766   tree dst, src;
3767   location_t loc = EXPR_LOCATION (exp);
3768
3769   if (!validate_arglist (exp, POINTER_TYPE, POINTER_TYPE, VOID_TYPE))
3770     return NULL_RTX;
3771
3772   dst = CALL_EXPR_ARG (exp, 0);
3773   src = CALL_EXPR_ARG (exp, 1);
3774
3775   /* If return value is ignored, transform stpcpy into strcpy.  */
3776   if (target == const0_rtx && implicit_built_in_decls[BUILT_IN_STRCPY])
3777     {
3778       tree fn = implicit_built_in_decls[BUILT_IN_STRCPY];
3779       tree result = build_call_nofold_loc (loc, fn, 2, dst, src);
3780       return expand_expr (result, target, mode, EXPAND_NORMAL);
3781     }
3782   else
3783     {
3784       tree len, lenp1;
3785       rtx ret;
3786
3787       /* Ensure we get an actual string whose length can be evaluated at
3788          compile-time, not an expression containing a string.  This is
3789          because the latter will potentially produce pessimized code
3790          when used to produce the return value.  */
3791       if (! c_getstr (src) || ! (len = c_strlen (src, 0)))
3792         return expand_movstr (dst, src, target, /*endp=*/2);
3793
3794       lenp1 = size_binop_loc (loc, PLUS_EXPR, len, ssize_int (1));
3795       ret = expand_builtin_mempcpy_args (dst, src, lenp1,
3796                                          target, mode, /*endp=*/2);
3797
3798       if (ret)
3799         return ret;
3800
3801       if (TREE_CODE (len) == INTEGER_CST)
3802         {
3803           rtx len_rtx = expand_normal (len);
3804
3805           if (CONST_INT_P (len_rtx))
3806             {
3807               ret = expand_builtin_strcpy_args (dst, src, target);
3808
3809               if (ret)
3810                 {
3811                   if (! target)
3812                     {
3813                       if (mode != VOIDmode)
3814                         target = gen_reg_rtx (mode);
3815                       else
3816                         target = gen_reg_rtx (GET_MODE (ret));
3817                     }
3818                   if (GET_MODE (target) != GET_MODE (ret))
3819                     ret = gen_lowpart (GET_MODE (target), ret);
3820
3821                   ret = plus_constant (ret, INTVAL (len_rtx));
3822                   ret = emit_move_insn (target, force_operand (ret, NULL_RTX));
3823                   gcc_assert (ret);
3824
3825                   return target;
3826                 }
3827             }
3828         }
3829
3830       return expand_movstr (dst, src, target, /*endp=*/2);
3831     }
3832 }
3833
3834 /* Callback routine for store_by_pieces.  Read GET_MODE_BITSIZE (MODE)
3835    bytes from constant string DATA + OFFSET and return it as target
3836    constant.  */
3837
3838 rtx
3839 builtin_strncpy_read_str (void *data, HOST_WIDE_INT offset,
3840                           enum machine_mode mode)
3841 {
3842   const char *str = (const char *) data;
3843
3844   if ((unsigned HOST_WIDE_INT) offset > strlen (str))
3845     return const0_rtx;
3846
3847   return c_readstr (str + offset, mode);
3848 }
3849
3850 /* Expand expression EXP, which is a call to the strncpy builtin.  Return
3851    NULL_RTX if we failed the caller should emit a normal call.  */
3852
3853 static rtx
3854 expand_builtin_strncpy (tree exp, rtx target)
3855 {
3856   location_t loc = EXPR_LOCATION (exp);
3857
3858   if (validate_arglist (exp,
3859                         POINTER_TYPE, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
3860     {
3861       tree dest = CALL_EXPR_ARG (exp, 0);
3862       tree src = CALL_EXPR_ARG (exp, 1);
3863       tree len = CALL_EXPR_ARG (exp, 2);
3864       tree slen = c_strlen (src, 1);
3865
3866       /* We must be passed a constant len and src parameter.  */
3867       if (!host_integerp (len, 1) || !slen || !host_integerp (slen, 1))
3868         return NULL_RTX;
3869
3870       slen = size_binop_loc (loc, PLUS_EXPR, slen, ssize_int (1));
3871
3872       /* We're required to pad with trailing zeros if the requested
3873          len is greater than strlen(s2)+1.  In that case try to
3874          use store_by_pieces, if it fails, punt.  */
3875       if (tree_int_cst_lt (slen, len))
3876         {
3877           unsigned int dest_align
3878             = get_pointer_alignment (dest, BIGGEST_ALIGNMENT);
3879           const char *p = c_getstr (src);
3880           rtx dest_mem;
3881
3882           if (!p || dest_align == 0 || !host_integerp (len, 1)
3883               || !can_store_by_pieces (tree_low_cst (len, 1),
3884                                        builtin_strncpy_read_str,
3885                                        CONST_CAST (char *, p),
3886                                        dest_align, false))
3887             return NULL_RTX;
3888
3889           dest_mem = get_memory_rtx (dest, len);
3890           store_by_pieces (dest_mem, tree_low_cst (len, 1),
3891                            builtin_strncpy_read_str,
3892                            CONST_CAST (char *, p), dest_align, false, 0);
3893           dest_mem = force_operand (XEXP (dest_mem, 0), target);
3894           dest_mem = convert_memory_address (ptr_mode, dest_mem);
3895           return dest_mem;
3896         }
3897     }
3898   return NULL_RTX;
3899 }
3900
3901 /* Callback routine for store_by_pieces.  Read GET_MODE_BITSIZE (MODE)
3902    bytes from constant string DATA + OFFSET and return it as target
3903    constant.  */
3904
3905 rtx
3906 builtin_memset_read_str (void *data, HOST_WIDE_INT offset ATTRIBUTE_UNUSED,
3907                          enum machine_mode mode)
3908 {
3909   const char *c = (const char *) data;
3910   char *p = XALLOCAVEC (char, GET_MODE_SIZE (mode));
3911
3912   memset (p, *c, GET_MODE_SIZE (mode));
3913
3914   return c_readstr (p, mode);
3915 }
3916
3917 /* Callback routine for store_by_pieces.  Return the RTL of a register
3918    containing GET_MODE_SIZE (MODE) consecutive copies of the unsigned
3919    char value given in the RTL register data.  For example, if mode is
3920    4 bytes wide, return the RTL for 0x01010101*data.  */
3921
3922 static rtx
3923 builtin_memset_gen_str (void *data, HOST_WIDE_INT offset ATTRIBUTE_UNUSED,
3924                         enum machine_mode mode)
3925 {
3926   rtx target, coeff;
3927   size_t size;
3928   char *p;
3929
3930   size = GET_MODE_SIZE (mode);
3931   if (size == 1)
3932     return (rtx) data;
3933
3934   p = XALLOCAVEC (char, size);
3935   memset (p, 1, size);
3936   coeff = c_readstr (p, mode);
3937
3938   target = convert_to_mode (mode, (rtx) data, 1);
3939   target = expand_mult (mode, target, coeff, NULL_RTX, 1);
3940   return force_reg (mode, target);
3941 }
3942
3943 /* Expand expression EXP, which is a call to the memset builtin.  Return
3944    NULL_RTX if we failed the caller should emit a normal call, otherwise
3945    try to get the result in TARGET, if convenient (and in mode MODE if that's
3946    convenient).  */
3947
3948 static rtx
3949 expand_builtin_memset (tree exp, rtx target, enum machine_mode mode)
3950 {
3951   if (!validate_arglist (exp,
3952                          POINTER_TYPE, INTEGER_TYPE, INTEGER_TYPE, VOID_TYPE))
3953     return NULL_RTX;
3954   else
3955     {
3956       tree dest = CALL_EXPR_ARG (exp, 0);
3957       tree val = CALL_EXPR_ARG (exp, 1);
3958       tree len = CALL_EXPR_ARG (exp, 2);
3959       return expand_builtin_memset_args (dest, val, len, target, mode, exp);
3960     }
3961 }
3962
3963 /* Helper function to do the actual work for expand_builtin_memset.  The
3964    arguments to the builtin_memset call DEST, VAL, and LEN are broken out
3965    so that this can also be called without constructing an actual CALL_EXPR.
3966    The other arguments and return value are the same as for
3967    expand_builtin_memset.  */
3968
3969 static rtx
3970 expand_builtin_memset_args (tree dest, tree val, tree len,
3971                             rtx target, enum machine_mode mode, tree orig_exp)
3972 {
3973   tree fndecl, fn;
3974   enum built_in_function fcode;
3975   char c;
3976   unsigned int dest_align;
3977   rtx dest_mem, dest_addr, len_rtx;
3978   HOST_WIDE_INT expected_size = -1;
3979   unsigned int expected_align = 0;
3980
3981   dest_align = get_pointer_alignment (dest, BIGGEST_ALIGNMENT);
3982
3983   /* If DEST is not a pointer type, don't do this operation in-line.  */
3984   if (dest_align == 0)
3985     return NULL_RTX;
3986
3987   if (currently_expanding_gimple_stmt)
3988     stringop_block_profile (currently_expanding_gimple_stmt,
3989                             &expected_align, &expected_size);
3990
3991   if (expected_align < dest_align)
3992     expected_align = dest_align;
3993
3994   /* If the LEN parameter is zero, return DEST.  */
3995   if (integer_zerop (len))
3996     {
3997       /* Evaluate and ignore VAL in case it has side-effects.  */
3998       expand_expr (val, const0_rtx, VOIDmode, EXPAND_NORMAL);
3999       return expand_expr (dest, target, mode, EXPAND_NORMAL);
4000     }
4001
4002   /* Stabilize the arguments in case we fail.  */
4003   dest = builtin_save_expr (dest);
4004   val = builtin_save_expr (val);
4005   len = builtin_save_expr (len);
4006
4007   len_rtx = expand_normal (len);
4008   dest_mem = get_memory_rtx (dest, len);
4009
4010   if (TREE_CODE (val) != INTEGER_CST)
4011     {
4012       rtx val_rtx;
4013
4014       val_rtx = expand_normal (val);
4015       val_rtx = convert_to_mode (TYPE_MODE (unsigned_char_type_node),
4016                                  val_rtx, 0);
4017
4018       /* Assume that we can memset by pieces if we can store
4019        * the coefficients by pieces (in the required modes).
4020        * We can't pass builtin_memset_gen_str as that emits RTL.  */
4021       c = 1;
4022       if (host_integerp (len, 1)
4023           && can_store_by_pieces (tree_low_cst (len, 1),
4024                                   builtin_memset_read_str, &c, dest_align,
4025                                   true))
4026         {
4027           val_rtx = force_reg (TYPE_MODE (unsigned_char_type_node),
4028                                val_rtx);
4029           store_by_pieces (dest_mem, tree_low_cst (len, 1),
4030                            builtin_memset_gen_str, val_rtx, dest_align,
4031                            true, 0);
4032         }
4033       else if (!set_storage_via_setmem (dest_mem, len_rtx, val_rtx,
4034                                         dest_align, expected_align,
4035                                         expected_size))
4036         goto do_libcall;
4037
4038       dest_mem = force_operand (XEXP (dest_mem, 0), NULL_RTX);
4039       dest_mem = convert_memory_address (ptr_mode, dest_mem);
4040       return dest_mem;
4041     }
4042
4043   if (target_char_cast (val, &c))
4044     goto do_libcall;
4045
4046   if (c)
4047     {
4048       if (host_integerp (len, 1)
4049           && can_store_by_pieces (tree_low_cst (len, 1),
4050                                   builtin_memset_read_str, &c, dest_align,
4051                                   true))
4052         store_by_pieces (dest_mem, tree_low_cst (len, 1),
4053                          builtin_memset_read_str, &c, dest_align, true, 0);
4054       else if (!set_storage_via_setmem (dest_mem, len_rtx, GEN_INT (c),
4055                                         dest_align, expected_align,
4056                                         expected_size))
4057         goto do_libcall;
4058
4059       dest_mem = force_operand (XEXP (dest_mem, 0), NULL_RTX);
4060       dest_mem = convert_memory_address (ptr_mode, dest_mem);
4061       return dest_mem;
4062     }
4063
4064   set_mem_align (dest_mem, dest_align);
4065   dest_addr = clear_storage_hints (dest_mem, len_rtx,
4066                                    CALL_EXPR_TAILCALL (orig_exp)
4067                                    ? BLOCK_OP_TAILCALL : BLOCK_OP_NORMAL,
4068                                    expected_align, expected_size);
4069
4070   if (dest_addr == 0)
4071     {
4072       dest_addr = force_operand (XEXP (dest_mem, 0), NULL_RTX);
4073       dest_addr = convert_memory_address (ptr_mode, dest_addr);
4074     }
4075
4076   return dest_addr;
4077
4078  do_libcall:
4079   fndecl = get_callee_fndecl (orig_exp);
4080   fcode = DECL_FUNCTION_CODE (fndecl);
4081   if (fcode == BUILT_IN_MEMSET)
4082     fn = build_call_nofold_loc (EXPR_LOCATION (orig_exp), fndecl, 3,
4083                                 dest, val, len);
4084   else if (fcode == BUILT_IN_BZERO)
4085     fn = build_call_nofold_loc (EXPR_LOCATION (orig_exp), fndecl, 2,
4086                                 dest, len);
4087   else
4088     gcc_unreachable ();
4089   gcc_assert (TREE_CODE (fn) == CALL_EXPR);
4090   CALL_EXPR_TAILCALL (fn) = CALL_EXPR_TAILCALL (orig_exp);
4091   return expand_call (fn, target, target == const0_rtx);
4092 }
4093
4094 /* Expand expression EXP, which is a call to the bzero builtin.  Return
4095    NULL_RTX if we failed the caller should emit a normal call.  */
4096
4097 static rtx
4098 expand_builtin_bzero (tree exp)
4099 {
4100   tree dest, size;
4101   location_t loc = EXPR_LOCATION (exp);
4102
4103   if (!validate_arglist (exp, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
4104     return NULL_RTX;
4105
4106   dest = CALL_EXPR_ARG (exp, 0);
4107   size = CALL_EXPR_ARG (exp, 1);
4108
4109   /* New argument list transforming bzero(ptr x, int y) to
4110      memset(ptr x, int 0, size_t y).   This is done this way
4111      so that if it isn't expanded inline, we fallback to
4112      calling bzero instead of memset.  */
4113
4114   return expand_builtin_memset_args (dest, integer_zero_node,
4115                                      fold_convert_loc (loc, sizetype, size),
4116                                      const0_rtx, VOIDmode, exp);
4117 }
4118
4119 /* Expand expression EXP, which is a call to the memcmp built-in function.
4120    Return NULL_RTX if we failed and the
4121    caller should emit a normal call, otherwise try to get the result in
4122    TARGET, if convenient (and in mode MODE, if that's convenient).  */
4123
4124 static rtx
4125 expand_builtin_memcmp (tree exp, ATTRIBUTE_UNUSED rtx target,
4126                        ATTRIBUTE_UNUSED enum machine_mode mode)
4127 {
4128   location_t loc ATTRIBUTE_UNUSED = EXPR_LOCATION (exp);
4129
4130   if (!validate_arglist (exp,
4131                          POINTER_TYPE, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
4132     return NULL_RTX;
4133
4134 #if defined HAVE_cmpmemsi || defined HAVE_cmpstrnsi
4135   {
4136     rtx arg1_rtx, arg2_rtx, arg3_rtx;
4137     rtx result;
4138     rtx insn;
4139     tree arg1 = CALL_EXPR_ARG (exp, 0);
4140     tree arg2 = CALL_EXPR_ARG (exp, 1);
4141     tree len = CALL_EXPR_ARG (exp, 2);
4142
4143     unsigned int arg1_align
4144       = get_pointer_alignment (arg1, BIGGEST_ALIGNMENT) / BITS_PER_UNIT;
4145     unsigned int arg2_align
4146       = get_pointer_alignment (arg2, BIGGEST_ALIGNMENT) / BITS_PER_UNIT;
4147     enum machine_mode insn_mode;
4148
4149 #ifdef HAVE_cmpmemsi
4150     if (HAVE_cmpmemsi)
4151       insn_mode = insn_data[(int) CODE_FOR_cmpmemsi].operand[0].mode;
4152     else
4153 #endif
4154 #ifdef HAVE_cmpstrnsi
4155     if (HAVE_cmpstrnsi)
4156       insn_mode = insn_data[(int) CODE_FOR_cmpstrnsi].operand[0].mode;
4157     else
4158 #endif
4159       return NULL_RTX;
4160
4161     /* If we don't have POINTER_TYPE, call the function.  */
4162     if (arg1_align == 0 || arg2_align == 0)
4163       return NULL_RTX;
4164
4165     /* Make a place to write the result of the instruction.  */
4166     result = target;
4167     if (! (result != 0
4168            && REG_P (result) && GET_MODE (result) == insn_mode
4169            && REGNO (result) >= FIRST_PSEUDO_REGISTER))
4170       result = gen_reg_rtx (insn_mode);
4171
4172     arg1_rtx = get_memory_rtx (arg1, len);
4173     arg2_rtx = get_memory_rtx (arg2, len);
4174     arg3_rtx = expand_normal (fold_convert_loc (loc, sizetype, len));
4175
4176     /* Set MEM_SIZE as appropriate.  */
4177     if (CONST_INT_P (arg3_rtx))
4178       {
4179         set_mem_size (arg1_rtx, arg3_rtx);
4180         set_mem_size (arg2_rtx, arg3_rtx);
4181       }
4182
4183 #ifdef HAVE_cmpmemsi
4184     if (HAVE_cmpmemsi)
4185       insn = gen_cmpmemsi (result, arg1_rtx, arg2_rtx, arg3_rtx,
4186                            GEN_INT (MIN (arg1_align, arg2_align)));
4187     else
4188 #endif
4189 #ifdef HAVE_cmpstrnsi
4190     if (HAVE_cmpstrnsi)
4191       insn = gen_cmpstrnsi (result, arg1_rtx, arg2_rtx, arg3_rtx,
4192                             GEN_INT (MIN (arg1_align, arg2_align)));
4193     else
4194 #endif
4195       gcc_unreachable ();
4196
4197     if (insn)
4198       emit_insn (insn);
4199     else
4200       emit_library_call_value (memcmp_libfunc, result, LCT_PURE,
4201                                TYPE_MODE (integer_type_node), 3,
4202                                XEXP (arg1_rtx, 0), Pmode,
4203                                XEXP (arg2_rtx, 0), Pmode,
4204                                convert_to_mode (TYPE_MODE (sizetype), arg3_rtx,
4205                                                 TYPE_UNSIGNED (sizetype)),
4206                                TYPE_MODE (sizetype));
4207
4208     /* Return the value in the proper mode for this function.  */
4209     mode = TYPE_MODE (TREE_TYPE (exp));
4210     if (GET_MODE (result) == mode)
4211       return result;
4212     else if (target != 0)
4213       {
4214         convert_move (target, result, 0);
4215         return target;
4216       }
4217     else
4218       return convert_to_mode (mode, result, 0);
4219   }
4220 #endif
4221
4222   return NULL_RTX;
4223 }
4224
4225 /* Expand expression EXP, which is a call to the strcmp builtin.  Return NULL_RTX
4226    if we failed the caller should emit a normal call, otherwise try to get
4227    the result in TARGET, if convenient.  */
4228
4229 static rtx
4230 expand_builtin_strcmp (tree exp, ATTRIBUTE_UNUSED rtx target)
4231 {
4232   if (!validate_arglist (exp, POINTER_TYPE, POINTER_TYPE, VOID_TYPE))
4233     return NULL_RTX;
4234
4235 #if defined HAVE_cmpstrsi || defined HAVE_cmpstrnsi
4236   if (direct_optab_handler (cmpstr_optab, SImode) != CODE_FOR_nothing
4237       || direct_optab_handler (cmpstrn_optab, SImode) != CODE_FOR_nothing)
4238     {
4239       rtx arg1_rtx, arg2_rtx;
4240       rtx result, insn = NULL_RTX;
4241       tree fndecl, fn;
4242       tree arg1 = CALL_EXPR_ARG (exp, 0);
4243       tree arg2 = CALL_EXPR_ARG (exp, 1);
4244
4245       unsigned int arg1_align
4246         = get_pointer_alignment (arg1, BIGGEST_ALIGNMENT) / BITS_PER_UNIT;
4247       unsigned int arg2_align
4248         = get_pointer_alignment (arg2, BIGGEST_ALIGNMENT) / BITS_PER_UNIT;
4249
4250       /* If we don't have POINTER_TYPE, call the function.  */
4251       if (arg1_align == 0 || arg2_align == 0)
4252         return NULL_RTX;
4253
4254       /* Stabilize the arguments in case gen_cmpstr(n)si fail.  */
4255       arg1 = builtin_save_expr (arg1);
4256       arg2 = builtin_save_expr (arg2);
4257
4258       arg1_rtx = get_memory_rtx (arg1, NULL);
4259       arg2_rtx = get_memory_rtx (arg2, NULL);
4260
4261 #ifdef HAVE_cmpstrsi
4262       /* Try to call cmpstrsi.  */
4263       if (HAVE_cmpstrsi)
4264         {
4265           enum machine_mode insn_mode
4266             = insn_data[(int) CODE_FOR_cmpstrsi].operand[0].mode;
4267
4268           /* Make a place to write the result of the instruction.  */
4269           result = target;
4270           if (! (result != 0
4271                  && REG_P (result) && GET_MODE (result) == insn_mode
4272                  && REGNO (result) >= FIRST_PSEUDO_REGISTER))
4273             result = gen_reg_rtx (insn_mode);
4274
4275           insn = gen_cmpstrsi (result, arg1_rtx, arg2_rtx,
4276                                GEN_INT (MIN (arg1_align, arg2_align)));
4277         }
4278 #endif
4279 #ifdef HAVE_cmpstrnsi
4280       /* Try to determine at least one length and call cmpstrnsi.  */
4281       if (!insn && HAVE_cmpstrnsi)
4282         {
4283           tree len;
4284           rtx arg3_rtx;
4285
4286           enum machine_mode insn_mode
4287             = insn_data[(int) CODE_FOR_cmpstrnsi].operand[0].mode;
4288           tree len1 = c_strlen (arg1, 1);
4289           tree len2 = c_strlen (arg2, 1);
4290
4291           if (len1)
4292             len1 = size_binop (PLUS_EXPR, ssize_int (1), len1);
4293           if (len2)
4294             len2 = size_binop (PLUS_EXPR, ssize_int (1), len2);
4295
4296           /* If we don't have a constant length for the first, use the length
4297              of the second, if we know it.  We don't require a constant for
4298              this case; some cost analysis could be done if both are available
4299              but neither is constant.  For now, assume they're equally cheap,
4300              unless one has side effects.  If both strings have constant lengths,
4301              use the smaller.  */
4302
4303           if (!len1)
4304             len = len2;
4305           else if (!len2)
4306             len = len1;
4307           else if (TREE_SIDE_EFFECTS (len1))
4308             len = len2;
4309           else if (TREE_SIDE_EFFECTS (len2))
4310             len = len1;
4311           else if (TREE_CODE (len1) != INTEGER_CST)
4312             len = len2;
4313           else if (TREE_CODE (len2) != INTEGER_CST)
4314             len = len1;
4315           else if (tree_int_cst_lt (len1, len2))
4316             len = len1;
4317           else
4318             len = len2;
4319
4320           /* If both arguments have side effects, we cannot optimize.  */
4321           if (!len || TREE_SIDE_EFFECTS (len))
4322             goto do_libcall;
4323
4324           arg3_rtx = expand_normal (len);
4325
4326           /* Make a place to write the result of the instruction.  */
4327           result = target;
4328           if (! (result != 0
4329                  && REG_P (result) && GET_MODE (result) == insn_mode
4330                  && REGNO (result) >= FIRST_PSEUDO_REGISTER))
4331             result = gen_reg_rtx (insn_mode);
4332
4333           insn = gen_cmpstrnsi (result, arg1_rtx, arg2_rtx, arg3_rtx,
4334                                 GEN_INT (MIN (arg1_align, arg2_align)));
4335         }
4336 #endif
4337
4338       if (insn)
4339         {
4340           enum machine_mode mode;
4341           emit_insn (insn);
4342
4343           /* Return the value in the proper mode for this function.  */
4344           mode = TYPE_MODE (TREE_TYPE (exp));
4345           if (GET_MODE (result) == mode)
4346             return result;
4347           if (target == 0)
4348             return convert_to_mode (mode, result, 0);
4349           convert_move (target, result, 0);
4350           return target;
4351         }
4352
4353       /* Expand the library call ourselves using a stabilized argument
4354          list to avoid re-evaluating the function's arguments twice.  */
4355 #ifdef HAVE_cmpstrnsi
4356     do_libcall:
4357 #endif
4358       fndecl = get_callee_fndecl (exp);
4359       fn = build_call_nofold_loc (EXPR_LOCATION (exp), fndecl, 2, arg1, arg2);
4360       gcc_assert (TREE_CODE (fn) == CALL_EXPR);
4361       CALL_EXPR_TAILCALL (fn) = CALL_EXPR_TAILCALL (exp);
4362       return expand_call (fn, target, target == const0_rtx);
4363     }
4364 #endif
4365   return NULL_RTX;
4366 }
4367
4368 /* Expand expression EXP, which is a call to the strncmp builtin. Return
4369    NULL_RTX if we failed the caller should emit a normal call, otherwise try to get
4370    the result in TARGET, if convenient.  */
4371
4372 static rtx
4373 expand_builtin_strncmp (tree exp, ATTRIBUTE_UNUSED rtx target,
4374                         ATTRIBUTE_UNUSED enum machine_mode mode)
4375 {
4376   location_t loc ATTRIBUTE_UNUSED = EXPR_LOCATION (exp);
4377
4378   if (!validate_arglist (exp,
4379                          POINTER_TYPE, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
4380     return NULL_RTX;
4381
4382   /* If c_strlen can determine an expression for one of the string
4383      lengths, and it doesn't have side effects, then emit cmpstrnsi
4384      using length MIN(strlen(string)+1, arg3).  */
4385 #ifdef HAVE_cmpstrnsi
4386   if (HAVE_cmpstrnsi)
4387   {
4388     tree len, len1, len2;
4389     rtx arg1_rtx, arg2_rtx, arg3_rtx;
4390     rtx result, insn;
4391     tree fndecl, fn;
4392     tree arg1 = CALL_EXPR_ARG (exp, 0);
4393     tree arg2 = CALL_EXPR_ARG (exp, 1);
4394     tree arg3 = CALL_EXPR_ARG (exp, 2);
4395
4396     unsigned int arg1_align
4397       = get_pointer_alignment (arg1, BIGGEST_ALIGNMENT) / BITS_PER_UNIT;
4398     unsigned int arg2_align
4399       = get_pointer_alignment (arg2, BIGGEST_ALIGNMENT) / BITS_PER_UNIT;
4400     enum machine_mode insn_mode
4401       = insn_data[(int) CODE_FOR_cmpstrnsi].operand[0].mode;
4402
4403     len1 = c_strlen (arg1, 1);
4404     len2 = c_strlen (arg2, 1);
4405
4406     if (len1)
4407       len1 = size_binop_loc (loc, PLUS_EXPR, ssize_int (1), len1);
4408     if (len2)
4409       len2 = size_binop_loc (loc, PLUS_EXPR, ssize_int (1), len2);
4410
4411     /* If we don't have a constant length for the first, use the length
4412        of the second, if we know it.  We don't require a constant for
4413        this case; some cost analysis could be done if both are available
4414        but neither is constant.  For now, assume they're equally cheap,
4415        unless one has side effects.  If both strings have constant lengths,
4416        use the smaller.  */
4417
4418     if (!len1)
4419       len = len2;
4420     else if (!len2)
4421       len = len1;
4422     else if (TREE_SIDE_EFFECTS (len1))
4423       len = len2;
4424     else if (TREE_SIDE_EFFECTS (len2))
4425       len = len1;
4426     else if (TREE_CODE (len1) != INTEGER_CST)
4427       len = len2;
4428     else if (TREE_CODE (len2) != INTEGER_CST)
4429       len = len1;
4430     else if (tree_int_cst_lt (len1, len2))
4431       len = len1;
4432     else
4433       len = len2;
4434
4435     /* If both arguments have side effects, we cannot optimize.  */
4436     if (!len || TREE_SIDE_EFFECTS (len))
4437       return NULL_RTX;
4438
4439     /* The actual new length parameter is MIN(len,arg3).  */
4440     len = fold_build2_loc (loc, MIN_EXPR, TREE_TYPE (len), len,
4441                        fold_convert_loc (loc, TREE_TYPE (len), arg3));
4442
4443     /* If we don't have POINTER_TYPE, call the function.  */
4444     if (arg1_align == 0 || arg2_align == 0)
4445       return NULL_RTX;
4446
4447     /* Make a place to write the result of the instruction.  */
4448     result = target;
4449     if (! (result != 0
4450            && REG_P (result) && GET_MODE (result) == insn_mode
4451            && REGNO (result) >= FIRST_PSEUDO_REGISTER))
4452       result = gen_reg_rtx (insn_mode);
4453
4454     /* Stabilize the arguments in case gen_cmpstrnsi fails.  */
4455     arg1 = builtin_save_expr (arg1);
4456     arg2 = builtin_save_expr (arg2);
4457     len = builtin_save_expr (len);
4458
4459     arg1_rtx = get_memory_rtx (arg1, len);
4460     arg2_rtx = get_memory_rtx (arg2, len);
4461     arg3_rtx = expand_normal (len);
4462     insn = gen_cmpstrnsi (result, arg1_rtx, arg2_rtx, arg3_rtx,
4463                           GEN_INT (MIN (arg1_align, arg2_align)));
4464     if (insn)
4465       {
4466         emit_insn (insn);
4467
4468         /* Return the value in the proper mode for this function.  */
4469         mode = TYPE_MODE (TREE_TYPE (exp));
4470         if (GET_MODE (result) == mode)
4471           return result;
4472         if (target == 0)
4473           return convert_to_mode (mode, result, 0);
4474         convert_move (target, result, 0);
4475         return target;
4476       }
4477
4478     /* Expand the library call ourselves using a stabilized argument
4479        list to avoid re-evaluating the function's arguments twice.  */
4480     fndecl = get_callee_fndecl (exp);
4481     fn = build_call_nofold_loc (EXPR_LOCATION (exp), fndecl, 3,
4482                                 arg1, arg2, len);
4483     gcc_assert (TREE_CODE (fn) == CALL_EXPR);
4484     CALL_EXPR_TAILCALL (fn) = CALL_EXPR_TAILCALL (exp);
4485     return expand_call (fn, target, target == const0_rtx);
4486   }
4487 #endif
4488   return NULL_RTX;
4489 }
4490
4491 /* Expand a call to __builtin_saveregs, generating the result in TARGET,
4492    if that's convenient.  */
4493
4494 rtx
4495 expand_builtin_saveregs (void)
4496 {
4497   rtx val, seq;
4498
4499   /* Don't do __builtin_saveregs more than once in a function.
4500      Save the result of the first call and reuse it.  */
4501   if (saveregs_value != 0)
4502     return saveregs_value;
4503
4504   /* When this function is called, it means that registers must be
4505      saved on entry to this function.  So we migrate the call to the
4506      first insn of this function.  */
4507
4508   start_sequence ();
4509
4510   /* Do whatever the machine needs done in this case.  */
4511   val = targetm.calls.expand_builtin_saveregs ();
4512
4513   seq = get_insns ();
4514   end_sequence ();
4515
4516   saveregs_value = val;
4517
4518   /* Put the insns after the NOTE that starts the function.  If this
4519      is inside a start_sequence, make the outer-level insn chain current, so
4520      the code is placed at the start of the function.  */
4521   push_topmost_sequence ();
4522   emit_insn_after (seq, entry_of_function ());
4523   pop_topmost_sequence ();
4524
4525   return val;
4526 }
4527
4528 /* Expand a call to __builtin_next_arg.  */
4529
4530 static rtx
4531 expand_builtin_next_arg (void)
4532 {
4533   /* Checking arguments is already done in fold_builtin_next_arg
4534      that must be called before this function.  */
4535   return expand_binop (ptr_mode, add_optab,
4536                        crtl->args.internal_arg_pointer,
4537                        crtl->args.arg_offset_rtx,
4538                        NULL_RTX, 0, OPTAB_LIB_WIDEN);
4539 }
4540
4541 /* Make it easier for the backends by protecting the valist argument
4542    from multiple evaluations.  */
4543
4544 static tree
4545 stabilize_va_list_loc (location_t loc, tree valist, int needs_lvalue)
4546 {
4547   tree vatype = targetm.canonical_va_list_type (TREE_TYPE (valist));
4548
4549   /* The current way of determining the type of valist is completely
4550      bogus.  We should have the information on the va builtin instead.  */
4551   if (!vatype)
4552     vatype = targetm.fn_abi_va_list (cfun->decl);
4553
4554   if (TREE_CODE (vatype) == ARRAY_TYPE)
4555     {
4556       if (TREE_SIDE_EFFECTS (valist))
4557         valist = save_expr (valist);
4558
4559       /* For this case, the backends will be expecting a pointer to
4560          vatype, but it's possible we've actually been given an array
4561          (an actual TARGET_CANONICAL_VA_LIST_TYPE (valist)).
4562          So fix it.  */
4563       if (TREE_CODE (TREE_TYPE (valist)) == ARRAY_TYPE)
4564         {
4565           tree p1 = build_pointer_type (TREE_TYPE (vatype));
4566           valist = build_fold_addr_expr_with_type_loc (loc, valist, p1);
4567         }
4568     }
4569   else
4570     {
4571       tree pt = build_pointer_type (vatype);
4572
4573       if (! needs_lvalue)
4574         {
4575           if (! TREE_SIDE_EFFECTS (valist))
4576             return valist;
4577
4578           valist = fold_build1_loc (loc, ADDR_EXPR, pt, valist);
4579           TREE_SIDE_EFFECTS (valist) = 1;
4580         }
4581
4582       if (TREE_SIDE_EFFECTS (valist))
4583         valist = save_expr (valist);
4584       valist = fold_build2_loc (loc, MEM_REF,
4585                                 vatype, valist, build_int_cst (pt, 0));
4586     }
4587
4588   return valist;
4589 }
4590
4591 /* The "standard" definition of va_list is void*.  */
4592
4593 tree
4594 std_build_builtin_va_list (void)
4595 {
4596   return ptr_type_node;
4597 }
4598
4599 /* The "standard" abi va_list is va_list_type_node.  */
4600
4601 tree
4602 std_fn_abi_va_list (tree fndecl ATTRIBUTE_UNUSED)
4603 {
4604   return va_list_type_node;
4605 }
4606
4607 /* The "standard" type of va_list is va_list_type_node.  */
4608
4609 tree
4610 std_canonical_va_list_type (tree type)
4611 {
4612   tree wtype, htype;
4613
4614   if (INDIRECT_REF_P (type))
4615     type = TREE_TYPE (type);
4616   else if (POINTER_TYPE_P (type) && POINTER_TYPE_P (TREE_TYPE(type)))
4617     type = TREE_TYPE (type);
4618   wtype = va_list_type_node;
4619   htype = type;
4620   /* Treat structure va_list types.  */
4621   if (TREE_CODE (wtype) == RECORD_TYPE && POINTER_TYPE_P (htype))
4622     htype = TREE_TYPE (htype);
4623   else if (TREE_CODE (wtype) == ARRAY_TYPE)
4624     {
4625       /* If va_list is an array type, the argument may have decayed
4626          to a pointer type, e.g. by being passed to another function.
4627          In that case, unwrap both types so that we can compare the
4628          underlying records.  */
4629       if (TREE_CODE (htype) == ARRAY_TYPE
4630           || POINTER_TYPE_P (htype))
4631         {
4632           wtype = TREE_TYPE (wtype);
4633           htype = TREE_TYPE (htype);
4634         }
4635     }
4636   if (TYPE_MAIN_VARIANT (wtype) == TYPE_MAIN_VARIANT (htype))
4637     return va_list_type_node;
4638
4639   return NULL_TREE;
4640 }
4641
4642 /* The "standard" implementation of va_start: just assign `nextarg' to
4643    the variable.  */
4644
4645 void
4646 std_expand_builtin_va_start (tree valist, rtx nextarg)
4647 {
4648   rtx va_r = expand_expr (valist, NULL_RTX, VOIDmode, EXPAND_WRITE);
4649   convert_move (va_r, nextarg, 0);
4650 }
4651
4652 /* Expand EXP, a call to __builtin_va_start.  */
4653
4654 static rtx
4655 expand_builtin_va_start (tree exp)
4656 {
4657   rtx nextarg;
4658   tree valist;
4659   location_t loc = EXPR_LOCATION (exp);
4660
4661   if (call_expr_nargs (exp) < 2)
4662     {
4663       error_at (loc, "too few arguments to function %<va_start%>");
4664       return const0_rtx;
4665     }
4666
4667   if (fold_builtin_next_arg (exp, true))
4668     return const0_rtx;
4669
4670   nextarg = expand_builtin_next_arg ();
4671   valist = stabilize_va_list_loc (loc, CALL_EXPR_ARG (exp, 0), 1);
4672
4673   if (targetm.expand_builtin_va_start)
4674     targetm.expand_builtin_va_start (valist, nextarg);
4675   else
4676     std_expand_builtin_va_start (valist, nextarg);
4677
4678   return const0_rtx;
4679 }
4680
4681 /* The "standard" implementation of va_arg: read the value from the
4682    current (padded) address and increment by the (padded) size.  */
4683
4684 tree
4685 std_gimplify_va_arg_expr (tree valist, tree type, gimple_seq *pre_p,
4686                           gimple_seq *post_p)
4687 {
4688   tree addr, t, type_size, rounded_size, valist_tmp;
4689   unsigned HOST_WIDE_INT align, boundary;
4690   bool indirect;
4691
4692 #ifdef ARGS_GROW_DOWNWARD
4693   /* All of the alignment and movement below is for args-grow-up machines.
4694      As of 2004, there are only 3 ARGS_GROW_DOWNWARD targets, and they all
4695      implement their own specialized gimplify_va_arg_expr routines.  */
4696   gcc_unreachable ();
4697 #endif
4698
4699   indirect = pass_by_reference (NULL, TYPE_MODE (type), type, false);
4700   if (indirect)
4701     type = build_pointer_type (type);
4702
4703   align = PARM_BOUNDARY / BITS_PER_UNIT;
4704   boundary = targetm.calls.function_arg_boundary (TYPE_MODE (type), type);
4705
4706   /* When we align parameter on stack for caller, if the parameter
4707      alignment is beyond MAX_SUPPORTED_STACK_ALIGNMENT, it will be
4708      aligned at MAX_SUPPORTED_STACK_ALIGNMENT.  We will match callee
4709      here with caller.  */
4710   if (boundary > MAX_SUPPORTED_STACK_ALIGNMENT)
4711     boundary = MAX_SUPPORTED_STACK_ALIGNMENT;
4712
4713   boundary /= BITS_PER_UNIT;
4714
4715   /* Hoist the valist value into a temporary for the moment.  */
4716   valist_tmp = get_initialized_tmp_var (valist, pre_p, NULL);
4717
4718   /* va_list pointer is aligned to PARM_BOUNDARY.  If argument actually
4719      requires greater alignment, we must perform dynamic alignment.  */
4720   if (boundary > align
4721       && !integer_zerop (TYPE_SIZE (type)))
4722     {
4723       t = build2 (MODIFY_EXPR, TREE_TYPE (valist), valist_tmp,
4724                   fold_build2 (POINTER_PLUS_EXPR,
4725                                TREE_TYPE (valist),
4726                                valist_tmp, size_int (boundary - 1)));
4727       gimplify_and_add (t, pre_p);
4728
4729       t = fold_convert (sizetype, valist_tmp);
4730       t = build2 (MODIFY_EXPR, TREE_TYPE (valist), valist_tmp,
4731                   fold_convert (TREE_TYPE (valist),
4732                                 fold_build2 (BIT_AND_EXPR, sizetype, t,
4733                                              size_int (-boundary))));
4734       gimplify_and_add (t, pre_p);
4735     }
4736   else
4737     boundary = align;
4738
4739   /* If the actual alignment is less than the alignment of the type,
4740      adjust the type accordingly so that we don't assume strict alignment
4741      when dereferencing the pointer.  */
4742   boundary *= BITS_PER_UNIT;
4743   if (boundary < TYPE_ALIGN (type))
4744     {
4745       type = build_variant_type_copy (type);
4746       TYPE_ALIGN (type) = boundary;
4747     }
4748
4749   /* Compute the rounded size of the type.  */
4750   type_size = size_in_bytes (type);
4751   rounded_size = round_up (type_size, align);
4752
4753   /* Reduce rounded_size so it's sharable with the postqueue.  */
4754   gimplify_expr (&rounded_size, pre_p, post_p, is_gimple_val, fb_rvalue);
4755
4756   /* Get AP.  */
4757   addr = valist_tmp;
4758   if (PAD_VARARGS_DOWN && !integer_zerop (rounded_size))
4759     {
4760       /* Small args are padded downward.  */
4761       t = fold_build2_loc (input_location, GT_EXPR, sizetype,
4762                        rounded_size, size_int (align));
4763       t = fold_build3 (COND_EXPR, sizetype, t, size_zero_node,
4764                        size_binop (MINUS_EXPR, rounded_size, type_size));
4765       addr = fold_build2 (POINTER_PLUS_EXPR,
4766                           TREE_TYPE (addr), addr, t);
4767     }
4768
4769   /* Compute new value for AP.  */
4770   t = build2 (POINTER_PLUS_EXPR, TREE_TYPE (valist), valist_tmp, rounded_size);
4771   t = build2 (MODIFY_EXPR, TREE_TYPE (valist), valist, t);
4772   gimplify_and_add (t, pre_p);
4773
4774   addr = fold_convert (build_pointer_type (type), addr);
4775
4776   if (indirect)
4777     addr = build_va_arg_indirect_ref (addr);
4778
4779   return build_va_arg_indirect_ref (addr);
4780 }
4781
4782 /* Build an indirect-ref expression over the given TREE, which represents a
4783    piece of a va_arg() expansion.  */
4784 tree
4785 build_va_arg_indirect_ref (tree addr)
4786 {
4787   addr = build_fold_indirect_ref_loc (EXPR_LOCATION (addr), addr);
4788
4789   if (flag_mudflap) /* Don't instrument va_arg INDIRECT_REF.  */
4790     mf_mark (addr);
4791
4792   return addr;
4793 }
4794
4795 /* Return a dummy expression of type TYPE in order to keep going after an
4796    error.  */
4797
4798 static tree
4799 dummy_object (tree type)
4800 {
4801   tree t = build_int_cst (build_pointer_type (type), 0);
4802   return build2 (MEM_REF, type, t, t);
4803 }
4804
4805 /* Gimplify __builtin_va_arg, aka VA_ARG_EXPR, which is not really a
4806    builtin function, but a very special sort of operator.  */
4807
4808 enum gimplify_status
4809 gimplify_va_arg_expr (tree *expr_p, gimple_seq *pre_p, gimple_seq *post_p)
4810 {
4811   tree promoted_type, have_va_type;
4812   tree valist = TREE_OPERAND (*expr_p, 0);
4813   tree type = TREE_TYPE (*expr_p);
4814   tree t;
4815   location_t loc = EXPR_LOCATION (*expr_p);
4816
4817   /* Verify that valist is of the proper type.  */
4818   have_va_type = TREE_TYPE (valist);
4819   if (have_va_type == error_mark_node)
4820     return GS_ERROR;
4821   have_va_type = targetm.canonical_va_list_type (have_va_type);
4822
4823   if (have_va_type == NULL_TREE)
4824     {
4825       error_at (loc, "first argument to %<va_arg%> not of type %<va_list%>");
4826       return GS_ERROR;
4827     }
4828
4829   /* Generate a diagnostic for requesting data of a type that cannot
4830      be passed through `...' due to type promotion at the call site.  */
4831   if ((promoted_type = lang_hooks.types.type_promotes_to (type))
4832            != type)
4833     {
4834       static bool gave_help;
4835       bool warned;
4836
4837       /* Unfortunately, this is merely undefined, rather than a constraint
4838          violation, so we cannot make this an error.  If this call is never
4839          executed, the program is still strictly conforming.  */
4840       warned = warning_at (loc, 0,
4841                            "%qT is promoted to %qT when passed through %<...%>",
4842                            type, promoted_type);
4843       if (!gave_help && warned)
4844         {
4845           gave_help = true;
4846           inform (loc, "(so you should pass %qT not %qT to %<va_arg%>)",
4847                   promoted_type, type);
4848         }
4849
4850       /* We can, however, treat "undefined" any way we please.
4851          Call abort to encourage the user to fix the program.  */
4852       if (warned)
4853         inform (loc, "if this code is reached, the program will abort");
4854       /* Before the abort, allow the evaluation of the va_list
4855          expression to exit or longjmp.  */
4856       gimplify_and_add (valist, pre_p);
4857       t = build_call_expr_loc (loc,
4858                                implicit_built_in_decls[BUILT_IN_TRAP], 0);
4859       gimplify_and_add (t, pre_p);
4860
4861       /* This is dead code, but go ahead and finish so that the
4862          mode of the result comes out right.  */
4863       *expr_p = dummy_object (type);
4864       return GS_ALL_DONE;
4865     }
4866   else
4867     {
4868       /* Make it easier for the backends by protecting the valist argument
4869          from multiple evaluations.  */
4870       if (TREE_CODE (have_va_type) == ARRAY_TYPE)
4871         {
4872           /* For this case, the backends will be expecting a pointer to
4873              TREE_TYPE (abi), but it's possible we've
4874              actually been given an array (an actual TARGET_FN_ABI_VA_LIST).
4875              So fix it.  */
4876           if (TREE_CODE (TREE_TYPE (valist)) == ARRAY_TYPE)
4877             {
4878               tree p1 = build_pointer_type (TREE_TYPE (have_va_type));
4879               valist = fold_convert_loc (loc, p1,
4880                                          build_fold_addr_expr_loc (loc, valist));
4881             }
4882
4883           gimplify_expr (&valist, pre_p, post_p, is_gimple_val, fb_rvalue);
4884         }
4885       else
4886         gimplify_expr (&valist, pre_p, post_p, is_gimple_min_lval, fb_lvalue);
4887
4888       if (!targetm.gimplify_va_arg_expr)
4889         /* FIXME: Once most targets are converted we should merely
4890            assert this is non-null.  */
4891         return GS_ALL_DONE;
4892
4893       *expr_p = targetm.gimplify_va_arg_expr (valist, type, pre_p, post_p);
4894       return GS_OK;
4895     }
4896 }
4897
4898 /* Expand EXP, a call to __builtin_va_end.  */
4899
4900 static rtx
4901 expand_builtin_va_end (tree exp)
4902 {
4903   tree valist = CALL_EXPR_ARG (exp, 0);
4904
4905   /* Evaluate for side effects, if needed.  I hate macros that don't
4906      do that.  */
4907   if (TREE_SIDE_EFFECTS (valist))
4908     expand_expr (valist, const0_rtx, VOIDmode, EXPAND_NORMAL);
4909
4910   return const0_rtx;
4911 }
4912
4913 /* Expand EXP, a call to __builtin_va_copy.  We do this as a
4914    builtin rather than just as an assignment in stdarg.h because of the
4915    nastiness of array-type va_list types.  */
4916
4917 static rtx
4918 expand_builtin_va_copy (tree exp)
4919 {
4920   tree dst, src, t;
4921   location_t loc = EXPR_LOCATION (exp);
4922
4923   dst = CALL_EXPR_ARG (exp, 0);
4924   src = CALL_EXPR_ARG (exp, 1);
4925
4926   dst = stabilize_va_list_loc (loc, dst, 1);
4927   src = stabilize_va_list_loc (loc, src, 0);
4928
4929   gcc_assert (cfun != NULL && cfun->decl != NULL_TREE);
4930
4931   if (TREE_CODE (targetm.fn_abi_va_list (cfun->decl)) != ARRAY_TYPE)
4932     {
4933       t = build2 (MODIFY_EXPR, targetm.fn_abi_va_list (cfun->decl), dst, src);
4934       TREE_SIDE_EFFECTS (t) = 1;
4935       expand_expr (t, const0_rtx, VOIDmode, EXPAND_NORMAL);
4936     }
4937   else
4938     {
4939       rtx dstb, srcb, size;
4940
4941       /* Evaluate to pointers.  */
4942       dstb = expand_expr (dst, NULL_RTX, Pmode, EXPAND_NORMAL);
4943       srcb = expand_expr (src, NULL_RTX, Pmode, EXPAND_NORMAL);
4944       size = expand_expr (TYPE_SIZE_UNIT (targetm.fn_abi_va_list (cfun->decl)),
4945                   NULL_RTX, VOIDmode, EXPAND_NORMAL);
4946
4947       dstb = convert_memory_address (Pmode, dstb);
4948       srcb = convert_memory_address (Pmode, srcb);
4949
4950       /* "Dereference" to BLKmode memories.  */
4951       dstb = gen_rtx_MEM (BLKmode, dstb);
4952       set_mem_alias_set (dstb, get_alias_set (TREE_TYPE (TREE_TYPE (dst))));
4953       set_mem_align (dstb, TYPE_ALIGN (targetm.fn_abi_va_list (cfun->decl)));
4954       srcb = gen_rtx_MEM (BLKmode, srcb);
4955       set_mem_alias_set (srcb, get_alias_set (TREE_TYPE (TREE_TYPE (src))));
4956       set_mem_align (srcb, TYPE_ALIGN (targetm.fn_abi_va_list (cfun->decl)));
4957
4958       /* Copy.  */
4959       emit_block_move (dstb, srcb, size, BLOCK_OP_NORMAL);
4960     }
4961
4962   return const0_rtx;
4963 }
4964
4965 /* Expand a call to one of the builtin functions __builtin_frame_address or
4966    __builtin_return_address.  */
4967
4968 static rtx
4969 expand_builtin_frame_address (tree fndecl, tree exp)
4970 {
4971   /* The argument must be a nonnegative integer constant.
4972      It counts the number of frames to scan up the stack.
4973      The value is the return address saved in that frame.  */
4974   if (call_expr_nargs (exp) == 0)
4975     /* Warning about missing arg was already issued.  */
4976     return const0_rtx;
4977   else if (! host_integerp (CALL_EXPR_ARG (exp, 0), 1))
4978     {
4979       if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_FRAME_ADDRESS)
4980         error ("invalid argument to %<__builtin_frame_address%>");
4981       else
4982         error ("invalid argument to %<__builtin_return_address%>");
4983       return const0_rtx;
4984     }
4985   else
4986     {
4987       rtx tem
4988         = expand_builtin_return_addr (DECL_FUNCTION_CODE (fndecl),
4989                                       tree_low_cst (CALL_EXPR_ARG (exp, 0), 1));
4990
4991       /* Some ports cannot access arbitrary stack frames.  */
4992       if (tem == NULL)
4993         {
4994           if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_FRAME_ADDRESS)
4995             warning (0, "unsupported argument to %<__builtin_frame_address%>");
4996           else
4997             warning (0, "unsupported argument to %<__builtin_return_address%>");
4998           return const0_rtx;
4999         }
5000
5001       /* For __builtin_frame_address, return what we've got.  */
5002       if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_FRAME_ADDRESS)
5003         return tem;
5004
5005       if (!REG_P (tem)
5006           && ! CONSTANT_P (tem))
5007         tem = copy_to_mode_reg (Pmode, tem);
5008       return tem;
5009     }
5010 }
5011
5012 /* Expand EXP, a call to the alloca builtin.  Return NULL_RTX if we
5013    failed and the caller should emit a normal call.  CANNOT_ACCUMULATE
5014    is the same as for allocate_dynamic_stack_space.  */
5015
5016 static rtx
5017 expand_builtin_alloca (tree exp, bool cannot_accumulate)
5018 {
5019   rtx op0;
5020   rtx result;
5021
5022   /* Emit normal call if marked not-inlineable.  */
5023   if (CALL_CANNOT_INLINE_P (exp))
5024     return NULL_RTX;
5025
5026   if (!validate_arglist (exp, INTEGER_TYPE, VOID_TYPE))
5027     return NULL_RTX;
5028
5029   /* Compute the argument.  */
5030   op0 = expand_normal (CALL_EXPR_ARG (exp, 0));
5031
5032   /* Allocate the desired space.  */
5033   result = allocate_dynamic_stack_space (op0, 0, BIGGEST_ALIGNMENT,
5034                                          cannot_accumulate);
5035   result = convert_memory_address (ptr_mode, result);
5036
5037   return result;
5038 }
5039
5040 /* Expand a call to a bswap builtin with argument ARG0.  MODE
5041    is the mode to expand with.  */
5042
5043 static rtx
5044 expand_builtin_bswap (tree exp, rtx target, rtx subtarget)
5045 {
5046   enum machine_mode mode;
5047   tree arg;
5048   rtx op0;
5049
5050   if (!validate_arglist (exp, INTEGER_TYPE, VOID_TYPE))
5051     return NULL_RTX;
5052
5053   arg = CALL_EXPR_ARG (exp, 0);
5054   mode = TYPE_MODE (TREE_TYPE (arg));
5055   op0 = expand_expr (arg, subtarget, VOIDmode, EXPAND_NORMAL);
5056
5057   target = expand_unop (mode, bswap_optab, op0, target, 1);
5058
5059   gcc_assert (target);
5060
5061   return convert_to_mode (mode, target, 0);
5062 }
5063
5064 /* Expand a call to a unary builtin in EXP.
5065    Return NULL_RTX if a normal call should be emitted rather than expanding the
5066    function in-line.  If convenient, the result should be placed in TARGET.
5067    SUBTARGET may be used as the target for computing one of EXP's operands.  */
5068
5069 static rtx
5070 expand_builtin_unop (enum machine_mode target_mode, tree exp, rtx target,
5071                      rtx subtarget, optab op_optab)
5072 {
5073   rtx op0;
5074
5075   if (!validate_arglist (exp, INTEGER_TYPE, VOID_TYPE))
5076     return NULL_RTX;
5077
5078   /* Compute the argument.  */
5079   op0 = expand_expr (CALL_EXPR_ARG (exp, 0),
5080                      (subtarget
5081                       && (TYPE_MODE (TREE_TYPE (CALL_EXPR_ARG (exp, 0)))
5082                           == GET_MODE (subtarget))) ? subtarget : NULL_RTX,
5083                      VOIDmode, EXPAND_NORMAL);
5084   /* Compute op, into TARGET if possible.
5085      Set TARGET to wherever the result comes back.  */
5086   target = expand_unop (TYPE_MODE (TREE_TYPE (CALL_EXPR_ARG (exp, 0))),
5087                         op_optab, op0, target, 1);
5088   gcc_assert (target);
5089
5090   return convert_to_mode (target_mode, target, 0);
5091 }
5092
5093 /* Expand a call to __builtin_expect.  We just return our argument
5094    as the builtin_expect semantic should've been already executed by
5095    tree branch prediction pass. */
5096
5097 static rtx
5098 expand_builtin_expect (tree exp, rtx target)
5099 {
5100   tree arg;
5101
5102   if (call_expr_nargs (exp) < 2)
5103     return const0_rtx;
5104   arg = CALL_EXPR_ARG (exp, 0);
5105
5106   target = expand_expr (arg, target, VOIDmode, EXPAND_NORMAL);
5107   /* When guessing was done, the hints should be already stripped away.  */
5108   gcc_assert (!flag_guess_branch_prob
5109               || optimize == 0 || seen_error ());
5110   return target;
5111 }
5112
5113 void
5114 expand_builtin_trap (void)
5115 {
5116 #ifdef HAVE_trap
5117   if (HAVE_trap)
5118     emit_insn (gen_trap ());
5119   else
5120 #endif
5121     emit_library_call (abort_libfunc, LCT_NORETURN, VOIDmode, 0);
5122   emit_barrier ();
5123 }
5124
5125 /* Expand a call to __builtin_unreachable.  We do nothing except emit
5126    a barrier saying that control flow will not pass here.
5127
5128    It is the responsibility of the program being compiled to ensure
5129    that control flow does never reach __builtin_unreachable.  */
5130 static void
5131 expand_builtin_unreachable (void)
5132 {
5133   emit_barrier ();
5134 }
5135
5136 /* Expand EXP, a call to fabs, fabsf or fabsl.
5137    Return NULL_RTX if a normal call should be emitted rather than expanding
5138    the function inline.  If convenient, the result should be placed
5139    in TARGET.  SUBTARGET may be used as the target for computing
5140    the operand.  */
5141
5142 static rtx
5143 expand_builtin_fabs (tree exp, rtx target, rtx subtarget)
5144 {
5145   enum machine_mode mode;
5146   tree arg;
5147   rtx op0;
5148
5149   if (!validate_arglist (exp, REAL_TYPE, VOID_TYPE))
5150     return NULL_RTX;
5151
5152   arg = CALL_EXPR_ARG (exp, 0);
5153   CALL_EXPR_ARG (exp, 0) = arg = builtin_save_expr (arg);
5154   mode = TYPE_MODE (TREE_TYPE (arg));
5155   op0 = expand_expr (arg, subtarget, VOIDmode, EXPAND_NORMAL);
5156   return expand_abs (mode, op0, target, 0, safe_from_p (target, arg, 1));
5157 }
5158
5159 /* Expand EXP, a call to copysign, copysignf, or copysignl.
5160    Return NULL is a normal call should be emitted rather than expanding the
5161    function inline.  If convenient, the result should be placed in TARGET.
5162    SUBTARGET may be used as the target for computing the operand.  */
5163
5164 static rtx
5165 expand_builtin_copysign (tree exp, rtx target, rtx subtarget)
5166 {
5167   rtx op0, op1;
5168   tree arg;
5169
5170   if (!validate_arglist (exp, REAL_TYPE, REAL_TYPE, VOID_TYPE))
5171     return NULL_RTX;
5172
5173   arg = CALL_EXPR_ARG (exp, 0);
5174   op0 = expand_expr (arg, subtarget, VOIDmode, EXPAND_NORMAL);
5175
5176   arg = CALL_EXPR_ARG (exp, 1);
5177   op1 = expand_normal (arg);
5178
5179   return expand_copysign (op0, op1, target);
5180 }
5181
5182 /* Create a new constant string literal and return a char* pointer to it.
5183    The STRING_CST value is the LEN characters at STR.  */
5184 tree
5185 build_string_literal (int len, const char *str)
5186 {
5187   tree t, elem, index, type;
5188
5189   t = build_string (len, str);
5190   elem = build_type_variant (char_type_node, 1, 0);
5191   index = build_index_type (size_int (len - 1));
5192   type = build_array_type (elem, index);
5193   TREE_TYPE (t) = type;
5194   TREE_CONSTANT (t) = 1;
5195   TREE_READONLY (t) = 1;
5196   TREE_STATIC (t) = 1;
5197
5198   type = build_pointer_type (elem);
5199   t = build1 (ADDR_EXPR, type,
5200               build4 (ARRAY_REF, elem,
5201                       t, integer_zero_node, NULL_TREE, NULL_TREE));
5202   return t;
5203 }
5204
5205 /* Expand a call to either the entry or exit function profiler.  */
5206
5207 static rtx
5208 expand_builtin_profile_func (bool exitp)
5209 {
5210   rtx this_rtx, which;
5211
5212   this_rtx = DECL_RTL (current_function_decl);
5213   gcc_assert (MEM_P (this_rtx));
5214   this_rtx = XEXP (this_rtx, 0);
5215
5216   if (exitp)
5217     which = profile_function_exit_libfunc;
5218   else
5219     which = profile_function_entry_libfunc;
5220
5221   emit_library_call (which, LCT_NORMAL, VOIDmode, 2, this_rtx, Pmode,
5222                      expand_builtin_return_addr (BUILT_IN_RETURN_ADDRESS,
5223                                                  0),
5224                      Pmode);
5225
5226   return const0_rtx;
5227 }
5228
5229 /* Expand a call to __builtin___clear_cache.  */
5230
5231 static rtx
5232 expand_builtin___clear_cache (tree exp ATTRIBUTE_UNUSED)
5233 {
5234 #ifndef HAVE_clear_cache
5235 #ifdef CLEAR_INSN_CACHE
5236   /* There is no "clear_cache" insn, and __clear_cache() in libgcc
5237      does something.  Just do the default expansion to a call to
5238      __clear_cache().  */
5239   return NULL_RTX;
5240 #else
5241   /* There is no "clear_cache" insn, and __clear_cache() in libgcc
5242      does nothing.  There is no need to call it.  Do nothing.  */
5243   return const0_rtx;
5244 #endif /* CLEAR_INSN_CACHE */
5245 #else
5246   /* We have a "clear_cache" insn, and it will handle everything.  */
5247   tree begin, end;
5248   rtx begin_rtx, end_rtx;
5249   enum insn_code icode;
5250
5251   /* We must not expand to a library call.  If we did, any
5252      fallback library function in libgcc that might contain a call to
5253      __builtin___clear_cache() would recurse infinitely.  */
5254   if (!validate_arglist (exp, POINTER_TYPE, POINTER_TYPE, VOID_TYPE))
5255     {
5256       error ("both arguments to %<__builtin___clear_cache%> must be pointers");
5257       return const0_rtx;
5258     }
5259
5260   if (HAVE_clear_cache)
5261     {
5262       icode = CODE_FOR_clear_cache;
5263
5264       begin = CALL_EXPR_ARG (exp, 0);
5265       begin_rtx = expand_expr (begin, NULL_RTX, Pmode, EXPAND_NORMAL);
5266       begin_rtx = convert_memory_address (Pmode, begin_rtx);
5267       if (!insn_data[icode].operand[0].predicate (begin_rtx, Pmode))
5268         begin_rtx = copy_to_mode_reg (Pmode, begin_rtx);
5269
5270       end = CALL_EXPR_ARG (exp, 1);
5271       end_rtx = expand_expr (end, NULL_RTX, Pmode, EXPAND_NORMAL);
5272       end_rtx = convert_memory_address (Pmode, end_rtx);
5273       if (!insn_data[icode].operand[1].predicate (end_rtx, Pmode))
5274         end_rtx = copy_to_mode_reg (Pmode, end_rtx);
5275
5276       emit_insn (gen_clear_cache (begin_rtx, end_rtx));
5277     }
5278   return const0_rtx;
5279 #endif /* HAVE_clear_cache */
5280 }
5281
5282 /* Given a trampoline address, make sure it satisfies TRAMPOLINE_ALIGNMENT.  */
5283
5284 static rtx
5285 round_trampoline_addr (rtx tramp)
5286 {
5287   rtx temp, addend, mask;
5288
5289   /* If we don't need too much alignment, we'll have been guaranteed
5290      proper alignment by get_trampoline_type.  */
5291   if (TRAMPOLINE_ALIGNMENT <= STACK_BOUNDARY)
5292     return tramp;
5293
5294   /* Round address up to desired boundary.  */
5295   temp = gen_reg_rtx (Pmode);
5296   addend = GEN_INT (TRAMPOLINE_ALIGNMENT / BITS_PER_UNIT - 1);
5297   mask = GEN_INT (-TRAMPOLINE_ALIGNMENT / BITS_PER_UNIT);
5298
5299   temp  = expand_simple_binop (Pmode, PLUS, tramp, addend,
5300                                temp, 0, OPTAB_LIB_WIDEN);
5301   tramp = expand_simple_binop (Pmode, AND, temp, mask,
5302                                temp, 0, OPTAB_LIB_WIDEN);
5303
5304   return tramp;
5305 }
5306
5307 static rtx
5308 expand_builtin_init_trampoline (tree exp)
5309 {
5310   tree t_tramp, t_func, t_chain;
5311   rtx m_tramp, r_tramp, r_chain, tmp;
5312
5313   if (!validate_arglist (exp, POINTER_TYPE, POINTER_TYPE,
5314                          POINTER_TYPE, VOID_TYPE))
5315     return NULL_RTX;
5316
5317   t_tramp = CALL_EXPR_ARG (exp, 0);
5318   t_func = CALL_EXPR_ARG (exp, 1);
5319   t_chain = CALL_EXPR_ARG (exp, 2);
5320
5321   r_tramp = expand_normal (t_tramp);
5322   m_tramp = gen_rtx_MEM (BLKmode, r_tramp);
5323   MEM_NOTRAP_P (m_tramp) = 1;
5324
5325   /* The TRAMP argument should be the address of a field within the
5326      local function's FRAME decl.  Let's see if we can fill in the
5327      to fill in the MEM_ATTRs for this memory.  */
5328   if (TREE_CODE (t_tramp) == ADDR_EXPR)
5329     set_mem_attributes_minus_bitpos (m_tramp, TREE_OPERAND (t_tramp, 0),
5330                                      true, 0);
5331
5332   tmp = round_trampoline_addr (r_tramp);
5333   if (tmp != r_tramp)
5334     {
5335       m_tramp = change_address (m_tramp, BLKmode, tmp);
5336       set_mem_align (m_tramp, TRAMPOLINE_ALIGNMENT);
5337       set_mem_size (m_tramp, GEN_INT (TRAMPOLINE_SIZE));
5338     }
5339
5340   /* The FUNC argument should be the address of the nested function.
5341      Extract the actual function decl to pass to the hook.  */
5342   gcc_assert (TREE_CODE (t_func) == ADDR_EXPR);
5343   t_func = TREE_OPERAND (t_func, 0);
5344   gcc_assert (TREE_CODE (t_func) == FUNCTION_DECL);
5345
5346   r_chain = expand_normal (t_chain);
5347
5348   /* Generate insns to initialize the trampoline.  */
5349   targetm.calls.trampoline_init (m_tramp, t_func, r_chain);
5350
5351   trampolines_created = 1;
5352
5353   warning_at (DECL_SOURCE_LOCATION (t_func), OPT_Wtrampolines,
5354               "trampoline generated for nested function %qD", t_func);
5355
5356   return const0_rtx;
5357 }
5358
5359 static rtx
5360 expand_builtin_adjust_trampoline (tree exp)
5361 {
5362   rtx tramp;
5363
5364   if (!validate_arglist (exp, POINTER_TYPE, VOID_TYPE))
5365     return NULL_RTX;
5366
5367   tramp = expand_normal (CALL_EXPR_ARG (exp, 0));
5368   tramp = round_trampoline_addr (tramp);
5369   if (targetm.calls.trampoline_adjust_address)
5370     tramp = targetm.calls.trampoline_adjust_address (tramp);
5371
5372   return tramp;
5373 }
5374
5375 /* Expand the call EXP to the built-in signbit, signbitf or signbitl
5376    function.  The function first checks whether the back end provides
5377    an insn to implement signbit for the respective mode.  If not, it
5378    checks whether the floating point format of the value is such that
5379    the sign bit can be extracted.  If that is not the case, the
5380    function returns NULL_RTX to indicate that a normal call should be
5381    emitted rather than expanding the function in-line.  EXP is the
5382    expression that is a call to the builtin function; if convenient,
5383    the result should be placed in TARGET.  */
5384 static rtx
5385 expand_builtin_signbit (tree exp, rtx target)
5386 {
5387   const struct real_format *fmt;
5388   enum machine_mode fmode, imode, rmode;
5389   tree arg;
5390   int word, bitpos;
5391   enum insn_code icode;
5392   rtx temp;
5393   location_t loc = EXPR_LOCATION (exp);
5394
5395   if (!validate_arglist (exp, REAL_TYPE, VOID_TYPE))
5396     return NULL_RTX;
5397
5398   arg = CALL_EXPR_ARG (exp, 0);
5399   fmode = TYPE_MODE (TREE_TYPE (arg));
5400   rmode = TYPE_MODE (TREE_TYPE (exp));
5401   fmt = REAL_MODE_FORMAT (fmode);
5402
5403   arg = builtin_save_expr (arg);
5404
5405   /* Expand the argument yielding a RTX expression. */
5406   temp = expand_normal (arg);
5407
5408   /* Check if the back end provides an insn that handles signbit for the
5409      argument's mode. */
5410   icode = optab_handler (signbit_optab, fmode);
5411   if (icode != CODE_FOR_nothing)
5412     {
5413       rtx last = get_last_insn ();
5414       target = gen_reg_rtx (TYPE_MODE (TREE_TYPE (exp)));
5415       if (maybe_emit_unop_insn (icode, target, temp, UNKNOWN))
5416         return target;
5417       delete_insns_since (last);
5418     }
5419
5420   /* For floating point formats without a sign bit, implement signbit
5421      as "ARG < 0.0".  */
5422   bitpos = fmt->signbit_ro;
5423   if (bitpos < 0)
5424   {
5425     /* But we can't do this if the format supports signed zero.  */
5426     if (fmt->has_signed_zero && HONOR_SIGNED_ZEROS (fmode))
5427       return NULL_RTX;
5428
5429     arg = fold_build2_loc (loc, LT_EXPR, TREE_TYPE (exp), arg,
5430                        build_real (TREE_TYPE (arg), dconst0));
5431     return expand_expr (arg, target, VOIDmode, EXPAND_NORMAL);
5432   }
5433
5434   if (GET_MODE_SIZE (fmode) <= UNITS_PER_WORD)
5435     {
5436       imode = int_mode_for_mode (fmode);
5437       if (imode == BLKmode)
5438         return NULL_RTX;
5439       temp = gen_lowpart (imode, temp);
5440     }
5441   else
5442     {
5443       imode = word_mode;
5444       /* Handle targets with different FP word orders.  */
5445       if (FLOAT_WORDS_BIG_ENDIAN)
5446         word = (GET_MODE_BITSIZE (fmode) - bitpos) / BITS_PER_WORD;
5447       else
5448         word = bitpos / BITS_PER_WORD;
5449       temp = operand_subword_force (temp, word, fmode);
5450       bitpos = bitpos % BITS_PER_WORD;
5451     }
5452
5453   /* Force the intermediate word_mode (or narrower) result into a
5454      register.  This avoids attempting to create paradoxical SUBREGs
5455      of floating point modes below.  */
5456   temp = force_reg (imode, temp);
5457
5458   /* If the bitpos is within the "result mode" lowpart, the operation
5459      can be implement with a single bitwise AND.  Otherwise, we need
5460      a right shift and an AND.  */
5461
5462   if (bitpos < GET_MODE_BITSIZE (rmode))
5463     {
5464       double_int mask = double_int_setbit (double_int_zero, bitpos);
5465
5466       if (GET_MODE_SIZE (imode) > GET_MODE_SIZE (rmode))
5467         temp = gen_lowpart (rmode, temp);
5468       temp = expand_binop (rmode, and_optab, temp,
5469                            immed_double_int_const (mask, rmode),
5470                            NULL_RTX, 1, OPTAB_LIB_WIDEN);
5471     }
5472   else
5473     {
5474       /* Perform a logical right shift to place the signbit in the least
5475          significant bit, then truncate the result to the desired mode
5476          and mask just this bit.  */
5477       temp = expand_shift (RSHIFT_EXPR, imode, temp,
5478                            build_int_cst (NULL_TREE, bitpos), NULL_RTX, 1);
5479       temp = gen_lowpart (rmode, temp);
5480       temp = expand_binop (rmode, and_optab, temp, const1_rtx,
5481                            NULL_RTX, 1, OPTAB_LIB_WIDEN);
5482     }
5483
5484   return temp;
5485 }
5486
5487 /* Expand fork or exec calls.  TARGET is the desired target of the
5488    call.  EXP is the call. FN is the
5489    identificator of the actual function.  IGNORE is nonzero if the
5490    value is to be ignored.  */
5491
5492 static rtx
5493 expand_builtin_fork_or_exec (tree fn, tree exp, rtx target, int ignore)
5494 {
5495   tree id, decl;
5496   tree call;
5497
5498   /* If we are not profiling, just call the function.  */
5499   if (!profile_arc_flag)
5500     return NULL_RTX;
5501
5502   /* Otherwise call the wrapper.  This should be equivalent for the rest of
5503      compiler, so the code does not diverge, and the wrapper may run the
5504      code necessary for keeping the profiling sane.  */
5505
5506   switch (DECL_FUNCTION_CODE (fn))
5507     {
5508     case BUILT_IN_FORK:
5509       id = get_identifier ("__gcov_fork");
5510       break;
5511
5512     case BUILT_IN_EXECL:
5513       id = get_identifier ("__gcov_execl");
5514       break;
5515
5516     case BUILT_IN_EXECV:
5517       id = get_identifier ("__gcov_execv");
5518       break;
5519
5520     case BUILT_IN_EXECLP:
5521       id = get_identifier ("__gcov_execlp");
5522       break;
5523
5524     case BUILT_IN_EXECLE:
5525       id = get_identifier ("__gcov_execle");
5526       break;
5527
5528     case BUILT_IN_EXECVP:
5529       id = get_identifier ("__gcov_execvp");
5530       break;
5531
5532     case BUILT_IN_EXECVE:
5533       id = get_identifier ("__gcov_execve");
5534       break;
5535
5536     default:
5537       gcc_unreachable ();
5538     }
5539
5540   decl = build_decl (DECL_SOURCE_LOCATION (fn),
5541                      FUNCTION_DECL, id, TREE_TYPE (fn));
5542   DECL_EXTERNAL (decl) = 1;
5543   TREE_PUBLIC (decl) = 1;
5544   DECL_ARTIFICIAL (decl) = 1;
5545   TREE_NOTHROW (decl) = 1;
5546   DECL_VISIBILITY (decl) = VISIBILITY_DEFAULT;
5547   DECL_VISIBILITY_SPECIFIED (decl) = 1;
5548   call = rewrite_call_expr (EXPR_LOCATION (exp), exp, 0, decl, 0);
5549   return expand_call (call, target, ignore);
5550  }
5551
5552
5553 \f
5554 /* Reconstitute a mode for a __sync intrinsic operation.  Since the type of
5555    the pointer in these functions is void*, the tree optimizers may remove
5556    casts.  The mode computed in expand_builtin isn't reliable either, due
5557    to __sync_bool_compare_and_swap.
5558
5559    FCODE_DIFF should be fcode - base, where base is the FOO_1 code for the
5560    group of builtins.  This gives us log2 of the mode size.  */
5561
5562 static inline enum machine_mode
5563 get_builtin_sync_mode (int fcode_diff)
5564 {
5565   /* The size is not negotiable, so ask not to get BLKmode in return
5566      if the target indicates that a smaller size would be better.  */
5567   return mode_for_size (BITS_PER_UNIT << fcode_diff, MODE_INT, 0);
5568 }
5569
5570 /* Expand the memory expression LOC and return the appropriate memory operand
5571    for the builtin_sync operations.  */
5572
5573 static rtx
5574 get_builtin_sync_mem (tree loc, enum machine_mode mode)
5575 {
5576   rtx addr, mem;
5577
5578   addr = expand_expr (loc, NULL_RTX, ptr_mode, EXPAND_SUM);
5579   addr = convert_memory_address (Pmode, addr);
5580
5581   /* Note that we explicitly do not want any alias information for this
5582      memory, so that we kill all other live memories.  Otherwise we don't
5583      satisfy the full barrier semantics of the intrinsic.  */
5584   mem = validize_mem (gen_rtx_MEM (mode, addr));
5585
5586   /* The alignment needs to be at least according to that of the mode.  */
5587   set_mem_align (mem, MAX (GET_MODE_ALIGNMENT (mode),
5588                            get_pointer_alignment (loc, BIGGEST_ALIGNMENT)));
5589   set_mem_alias_set (mem, ALIAS_SET_MEMORY_BARRIER);
5590   MEM_VOLATILE_P (mem) = 1;
5591
5592   return mem;
5593 }
5594
5595 /* Expand the __sync_xxx_and_fetch and __sync_fetch_and_xxx intrinsics.
5596    EXP is the CALL_EXPR.  CODE is the rtx code
5597    that corresponds to the arithmetic or logical operation from the name;
5598    an exception here is that NOT actually means NAND.  TARGET is an optional
5599    place for us to store the results; AFTER is true if this is the
5600    fetch_and_xxx form.  IGNORE is true if we don't actually care about
5601    the result of the operation at all.  */
5602
5603 static rtx
5604 expand_builtin_sync_operation (enum machine_mode mode, tree exp,
5605                                enum rtx_code code, bool after,
5606                                rtx target, bool ignore)
5607 {
5608   rtx val, mem;
5609   enum machine_mode old_mode;
5610   location_t loc = EXPR_LOCATION (exp);
5611
5612   if (code == NOT && warn_sync_nand)
5613     {
5614       tree fndecl = get_callee_fndecl (exp);
5615       enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
5616
5617       static bool warned_f_a_n, warned_n_a_f;
5618
5619       switch (fcode)
5620         {
5621         case BUILT_IN_FETCH_AND_NAND_1:
5622         case BUILT_IN_FETCH_AND_NAND_2:
5623         case BUILT_IN_FETCH_AND_NAND_4:
5624         case BUILT_IN_FETCH_AND_NAND_8:
5625         case BUILT_IN_FETCH_AND_NAND_16:
5626
5627           if (warned_f_a_n)
5628             break;
5629
5630           fndecl = implicit_built_in_decls[BUILT_IN_FETCH_AND_NAND_N];
5631           inform (loc, "%qD changed semantics in GCC 4.4", fndecl);
5632           warned_f_a_n = true;
5633           break;
5634
5635         case BUILT_IN_NAND_AND_FETCH_1:
5636         case BUILT_IN_NAND_AND_FETCH_2:
5637         case BUILT_IN_NAND_AND_FETCH_4:
5638         case BUILT_IN_NAND_AND_FETCH_8:
5639         case BUILT_IN_NAND_AND_FETCH_16:
5640
5641           if (warned_n_a_f)
5642             break;
5643
5644           fndecl = implicit_built_in_decls[BUILT_IN_NAND_AND_FETCH_N];
5645           inform (loc, "%qD changed semantics in GCC 4.4", fndecl);
5646           warned_n_a_f = true;
5647           break;
5648
5649         default:
5650           gcc_unreachable ();
5651         }
5652     }
5653
5654   /* Expand the operands.  */
5655   mem = get_builtin_sync_mem (CALL_EXPR_ARG (exp, 0), mode);
5656
5657   val = expand_expr (CALL_EXPR_ARG (exp, 1), NULL_RTX, mode, EXPAND_NORMAL);
5658   /* If VAL is promoted to a wider mode, convert it back to MODE.  Take care
5659      of CONST_INTs, where we know the old_mode only from the call argument.  */
5660   old_mode = GET_MODE (val);
5661   if (old_mode == VOIDmode)
5662     old_mode = TYPE_MODE (TREE_TYPE (CALL_EXPR_ARG (exp, 1)));
5663   val = convert_modes (mode, old_mode, val, 1);
5664
5665   if (ignore)
5666     return expand_sync_operation (mem, val, code);
5667   else
5668     return expand_sync_fetch_operation (mem, val, code, after, target);
5669 }
5670
5671 /* Expand the __sync_val_compare_and_swap and __sync_bool_compare_and_swap
5672    intrinsics. EXP is the CALL_EXPR.  IS_BOOL is
5673    true if this is the boolean form.  TARGET is a place for us to store the
5674    results; this is NOT optional if IS_BOOL is true.  */
5675
5676 static rtx
5677 expand_builtin_compare_and_swap (enum machine_mode mode, tree exp,
5678                                  bool is_bool, rtx target)
5679 {
5680   rtx old_val, new_val, mem;
5681   enum machine_mode old_mode;
5682
5683   /* Expand the operands.  */
5684   mem = get_builtin_sync_mem (CALL_EXPR_ARG (exp, 0), mode);
5685
5686
5687   old_val = expand_expr (CALL_EXPR_ARG (exp, 1), NULL_RTX,
5688                          mode, EXPAND_NORMAL);
5689   /* If VAL is promoted to a wider mode, convert it back to MODE.  Take care
5690      of CONST_INTs, where we know the old_mode only from the call argument.  */
5691   old_mode = GET_MODE (old_val);
5692   if (old_mode == VOIDmode)
5693     old_mode = TYPE_MODE (TREE_TYPE (CALL_EXPR_ARG (exp, 1)));
5694   old_val = convert_modes (mode, old_mode, old_val, 1);
5695
5696   new_val = expand_expr (CALL_EXPR_ARG (exp, 2), NULL_RTX,
5697                          mode, EXPAND_NORMAL);
5698   /* If VAL is promoted to a wider mode, convert it back to MODE.  Take care
5699      of CONST_INTs, where we know the old_mode only from the call argument.  */
5700   old_mode = GET_MODE (new_val);
5701   if (old_mode == VOIDmode)
5702     old_mode = TYPE_MODE (TREE_TYPE (CALL_EXPR_ARG (exp, 2)));
5703   new_val = convert_modes (mode, old_mode, new_val, 1);
5704
5705   if (is_bool)
5706     return expand_bool_compare_and_swap (mem, old_val, new_val, target);
5707   else
5708     return expand_val_compare_and_swap (mem, old_val, new_val, target);
5709 }
5710
5711 /* Expand the __sync_lock_test_and_set intrinsic.  Note that the most
5712    general form is actually an atomic exchange, and some targets only
5713    support a reduced form with the second argument being a constant 1.
5714    EXP is the CALL_EXPR; TARGET is an optional place for us to store
5715    the results.  */
5716
5717 static rtx
5718 expand_builtin_lock_test_and_set (enum machine_mode mode, tree exp,
5719                                   rtx target)
5720 {
5721   rtx val, mem;
5722   enum machine_mode old_mode;
5723
5724   /* Expand the operands.  */
5725   mem = get_builtin_sync_mem (CALL_EXPR_ARG (exp, 0), mode);
5726   val = expand_expr (CALL_EXPR_ARG (exp, 1), NULL_RTX, mode, EXPAND_NORMAL);
5727   /* If VAL is promoted to a wider mode, convert it back to MODE.  Take care
5728      of CONST_INTs, where we know the old_mode only from the call argument.  */
5729   old_mode = GET_MODE (val);
5730   if (old_mode == VOIDmode)
5731     old_mode = TYPE_MODE (TREE_TYPE (CALL_EXPR_ARG (exp, 1)));
5732   val = convert_modes (mode, old_mode, val, 1);
5733
5734   return expand_sync_lock_test_and_set (mem, val, target);
5735 }
5736
5737 /* Expand the __sync_synchronize intrinsic.  */
5738
5739 static void
5740 expand_builtin_synchronize (void)
5741 {
5742   gimple x;
5743   VEC (tree, gc) *v_clobbers;
5744
5745 #ifdef HAVE_memory_barrier
5746   if (HAVE_memory_barrier)
5747     {
5748       emit_insn (gen_memory_barrier ());
5749       return;
5750     }
5751 #endif
5752
5753   if (synchronize_libfunc != NULL_RTX)
5754     {
5755       emit_library_call (synchronize_libfunc, LCT_NORMAL, VOIDmode, 0);
5756       return;
5757     }
5758
5759   /* If no explicit memory barrier instruction is available, create an
5760      empty asm stmt with a memory clobber.  */
5761   v_clobbers = VEC_alloc (tree, gc, 1);
5762   VEC_quick_push (tree, v_clobbers,
5763                   tree_cons (NULL, build_string (6, "memory"), NULL));
5764   x = gimple_build_asm_vec ("", NULL, NULL, v_clobbers, NULL);
5765   gimple_asm_set_volatile (x, true);
5766   expand_asm_stmt (x);
5767 }
5768
5769 /* Expand the __sync_lock_release intrinsic.  EXP is the CALL_EXPR.  */
5770
5771 static void
5772 expand_builtin_lock_release (enum machine_mode mode, tree exp)
5773 {
5774   enum insn_code icode;
5775   rtx mem, insn;
5776   rtx val = const0_rtx;
5777
5778   /* Expand the operands.  */
5779   mem = get_builtin_sync_mem (CALL_EXPR_ARG (exp, 0), mode);
5780
5781   /* If there is an explicit operation in the md file, use it.  */
5782   icode = direct_optab_handler (sync_lock_release_optab, mode);
5783   if (icode != CODE_FOR_nothing)
5784     {
5785       if (!insn_data[icode].operand[1].predicate (val, mode))
5786         val = force_reg (mode, val);
5787
5788       insn = GEN_FCN (icode) (mem, val);
5789       if (insn)
5790         {
5791           emit_insn (insn);
5792           return;
5793         }
5794     }
5795
5796   /* Otherwise we can implement this operation by emitting a barrier
5797      followed by a store of zero.  */
5798   expand_builtin_synchronize ();
5799   emit_move_insn (mem, val);
5800 }
5801 \f
5802 /* Expand an expression EXP that calls a built-in function,
5803    with result going to TARGET if that's convenient
5804    (and in mode MODE if that's convenient).
5805    SUBTARGET may be used as the target for computing one of EXP's operands.
5806    IGNORE is nonzero if the value is to be ignored.  */
5807
5808 rtx
5809 expand_builtin (tree exp, rtx target, rtx subtarget, enum machine_mode mode,
5810                 int ignore)
5811 {
5812   tree fndecl = get_callee_fndecl (exp);
5813   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
5814   enum machine_mode target_mode = TYPE_MODE (TREE_TYPE (exp));
5815   int flags;
5816
5817   if (DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_MD)
5818     return targetm.expand_builtin (exp, target, subtarget, mode, ignore);
5819
5820   /* When not optimizing, generate calls to library functions for a certain
5821      set of builtins.  */
5822   if (!optimize
5823       && !called_as_built_in (fndecl)
5824       && DECL_ASSEMBLER_NAME_SET_P (fndecl)
5825       && fcode != BUILT_IN_ALLOCA
5826       && fcode != BUILT_IN_FREE)
5827     return expand_call (exp, target, ignore);
5828
5829   /* The built-in function expanders test for target == const0_rtx
5830      to determine whether the function's result will be ignored.  */
5831   if (ignore)
5832     target = const0_rtx;
5833
5834   /* If the result of a pure or const built-in function is ignored, and
5835      none of its arguments are volatile, we can avoid expanding the
5836      built-in call and just evaluate the arguments for side-effects.  */
5837   if (target == const0_rtx
5838       && ((flags = flags_from_decl_or_type (fndecl)) & (ECF_CONST | ECF_PURE))
5839       && !(flags & ECF_LOOPING_CONST_OR_PURE))
5840     {
5841       bool volatilep = false;
5842       tree arg;
5843       call_expr_arg_iterator iter;
5844
5845       FOR_EACH_CALL_EXPR_ARG (arg, iter, exp)
5846         if (TREE_THIS_VOLATILE (arg))
5847           {
5848             volatilep = true;
5849             break;
5850           }
5851
5852       if (! volatilep)
5853         {
5854           FOR_EACH_CALL_EXPR_ARG (arg, iter, exp)
5855             expand_expr (arg, const0_rtx, VOIDmode, EXPAND_NORMAL);
5856           return const0_rtx;
5857         }
5858     }
5859
5860   switch (fcode)
5861     {
5862     CASE_FLT_FN (BUILT_IN_FABS):
5863       target = expand_builtin_fabs (exp, target, subtarget);
5864       if (target)
5865         return target;
5866       break;
5867
5868     CASE_FLT_FN (BUILT_IN_COPYSIGN):
5869       target = expand_builtin_copysign (exp, target, subtarget);
5870       if (target)
5871         return target;
5872       break;
5873
5874       /* Just do a normal library call if we were unable to fold
5875          the values.  */
5876     CASE_FLT_FN (BUILT_IN_CABS):
5877       break;
5878
5879     CASE_FLT_FN (BUILT_IN_EXP):
5880     CASE_FLT_FN (BUILT_IN_EXP10):
5881     CASE_FLT_FN (BUILT_IN_POW10):
5882     CASE_FLT_FN (BUILT_IN_EXP2):
5883     CASE_FLT_FN (BUILT_IN_EXPM1):
5884     CASE_FLT_FN (BUILT_IN_LOGB):
5885     CASE_FLT_FN (BUILT_IN_LOG):
5886     CASE_FLT_FN (BUILT_IN_LOG10):
5887     CASE_FLT_FN (BUILT_IN_LOG2):
5888     CASE_FLT_FN (BUILT_IN_LOG1P):
5889     CASE_FLT_FN (BUILT_IN_TAN):
5890     CASE_FLT_FN (BUILT_IN_ASIN):
5891     CASE_FLT_FN (BUILT_IN_ACOS):
5892     CASE_FLT_FN (BUILT_IN_ATAN):
5893     CASE_FLT_FN (BUILT_IN_SIGNIFICAND):
5894       /* Treat these like sqrt only if unsafe math optimizations are allowed,
5895          because of possible accuracy problems.  */
5896       if (! flag_unsafe_math_optimizations)
5897         break;
5898     CASE_FLT_FN (BUILT_IN_SQRT):
5899     CASE_FLT_FN (BUILT_IN_FLOOR):
5900     CASE_FLT_FN (BUILT_IN_CEIL):
5901     CASE_FLT_FN (BUILT_IN_TRUNC):
5902     CASE_FLT_FN (BUILT_IN_ROUND):
5903     CASE_FLT_FN (BUILT_IN_NEARBYINT):
5904     CASE_FLT_FN (BUILT_IN_RINT):
5905       target = expand_builtin_mathfn (exp, target, subtarget);
5906       if (target)
5907         return target;
5908       break;
5909
5910     CASE_FLT_FN (BUILT_IN_FMA):
5911       target = expand_builtin_mathfn_ternary (exp, target, subtarget);
5912       if (target)
5913         return target;
5914       break;
5915
5916     CASE_FLT_FN (BUILT_IN_ILOGB):
5917       if (! flag_unsafe_math_optimizations)
5918         break;
5919     CASE_FLT_FN (BUILT_IN_ISINF):
5920     CASE_FLT_FN (BUILT_IN_FINITE):
5921     case BUILT_IN_ISFINITE:
5922     case BUILT_IN_ISNORMAL:
5923       target = expand_builtin_interclass_mathfn (exp, target);
5924       if (target)
5925         return target;
5926       break;
5927
5928     CASE_FLT_FN (BUILT_IN_LCEIL):
5929     CASE_FLT_FN (BUILT_IN_LLCEIL):
5930     CASE_FLT_FN (BUILT_IN_LFLOOR):
5931     CASE_FLT_FN (BUILT_IN_LLFLOOR):
5932       target = expand_builtin_int_roundingfn (exp, target);
5933       if (target)
5934         return target;
5935       break;
5936
5937     CASE_FLT_FN (BUILT_IN_LRINT):
5938     CASE_FLT_FN (BUILT_IN_LLRINT):
5939     CASE_FLT_FN (BUILT_IN_LROUND):
5940     CASE_FLT_FN (BUILT_IN_LLROUND):
5941       target = expand_builtin_int_roundingfn_2 (exp, target);
5942       if (target)
5943         return target;
5944       break;
5945
5946     CASE_FLT_FN (BUILT_IN_POW):
5947       target = expand_builtin_pow (exp, target, subtarget);
5948       if (target)
5949         return target;
5950       break;
5951
5952     CASE_FLT_FN (BUILT_IN_POWI):
5953       target = expand_builtin_powi (exp, target);
5954       if (target)
5955         return target;
5956       break;
5957
5958     CASE_FLT_FN (BUILT_IN_ATAN2):
5959     CASE_FLT_FN (BUILT_IN_LDEXP):
5960     CASE_FLT_FN (BUILT_IN_SCALB):
5961     CASE_FLT_FN (BUILT_IN_SCALBN):
5962     CASE_FLT_FN (BUILT_IN_SCALBLN):
5963       if (! flag_unsafe_math_optimizations)
5964         break;
5965
5966     CASE_FLT_FN (BUILT_IN_FMOD):
5967     CASE_FLT_FN (BUILT_IN_REMAINDER):
5968     CASE_FLT_FN (BUILT_IN_DREM):
5969       target = expand_builtin_mathfn_2 (exp, target, subtarget);
5970       if (target)
5971         return target;
5972       break;
5973
5974     CASE_FLT_FN (BUILT_IN_CEXPI):
5975       target = expand_builtin_cexpi (exp, target);
5976       gcc_assert (target);
5977       return target;
5978
5979     CASE_FLT_FN (BUILT_IN_SIN):
5980     CASE_FLT_FN (BUILT_IN_COS):
5981       if (! flag_unsafe_math_optimizations)
5982         break;
5983       target = expand_builtin_mathfn_3 (exp, target, subtarget);
5984       if (target)
5985         return target;
5986       break;
5987
5988     CASE_FLT_FN (BUILT_IN_SINCOS):
5989       if (! flag_unsafe_math_optimizations)
5990         break;
5991       target = expand_builtin_sincos (exp);
5992       if (target)
5993         return target;
5994       break;
5995
5996     case BUILT_IN_APPLY_ARGS:
5997       return expand_builtin_apply_args ();
5998
5999       /* __builtin_apply (FUNCTION, ARGUMENTS, ARGSIZE) invokes
6000          FUNCTION with a copy of the parameters described by
6001          ARGUMENTS, and ARGSIZE.  It returns a block of memory
6002          allocated on the stack into which is stored all the registers
6003          that might possibly be used for returning the result of a
6004          function.  ARGUMENTS is the value returned by
6005          __builtin_apply_args.  ARGSIZE is the number of bytes of
6006          arguments that must be copied.  ??? How should this value be
6007          computed?  We'll also need a safe worst case value for varargs
6008          functions.  */
6009     case BUILT_IN_APPLY:
6010       if (!validate_arglist (exp, POINTER_TYPE,
6011                              POINTER_TYPE, INTEGER_TYPE, VOID_TYPE)
6012           && !validate_arglist (exp, REFERENCE_TYPE,
6013                                 POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
6014         return const0_rtx;
6015       else
6016         {
6017           rtx ops[3];
6018
6019           ops[0] = expand_normal (CALL_EXPR_ARG (exp, 0));
6020           ops[1] = expand_normal (CALL_EXPR_ARG (exp, 1));
6021           ops[2] = expand_normal (CALL_EXPR_ARG (exp, 2));
6022
6023           return expand_builtin_apply (ops[0], ops[1], ops[2]);
6024         }
6025
6026       /* __builtin_return (RESULT) causes the function to return the
6027          value described by RESULT.  RESULT is address of the block of
6028          memory returned by __builtin_apply.  */
6029     case BUILT_IN_RETURN:
6030       if (validate_arglist (exp, POINTER_TYPE, VOID_TYPE))
6031         expand_builtin_return (expand_normal (CALL_EXPR_ARG (exp, 0)));
6032       return const0_rtx;
6033
6034     case BUILT_IN_SAVEREGS:
6035       return expand_builtin_saveregs ();
6036
6037     case BUILT_IN_VA_ARG_PACK:
6038       /* All valid uses of __builtin_va_arg_pack () are removed during
6039          inlining.  */
6040       error ("%Kinvalid use of %<__builtin_va_arg_pack ()%>", exp);
6041       return const0_rtx;
6042
6043     case BUILT_IN_VA_ARG_PACK_LEN:
6044       /* All valid uses of __builtin_va_arg_pack_len () are removed during
6045          inlining.  */
6046       error ("%Kinvalid use of %<__builtin_va_arg_pack_len ()%>", exp);
6047       return const0_rtx;
6048
6049       /* Return the address of the first anonymous stack arg.  */
6050     case BUILT_IN_NEXT_ARG:
6051       if (fold_builtin_next_arg (exp, false))
6052         return const0_rtx;
6053       return expand_builtin_next_arg ();
6054
6055     case BUILT_IN_CLEAR_CACHE:
6056       target = expand_builtin___clear_cache (exp);
6057       if (target)
6058         return target;
6059       break;
6060
6061     case BUILT_IN_CLASSIFY_TYPE:
6062       return expand_builtin_classify_type (exp);
6063
6064     case BUILT_IN_CONSTANT_P:
6065       return const0_rtx;
6066
6067     case BUILT_IN_FRAME_ADDRESS:
6068     case BUILT_IN_RETURN_ADDRESS:
6069       return expand_builtin_frame_address (fndecl, exp);
6070
6071     /* Returns the address of the area where the structure is returned.
6072        0 otherwise.  */
6073     case BUILT_IN_AGGREGATE_INCOMING_ADDRESS:
6074       if (call_expr_nargs (exp) != 0
6075           || ! AGGREGATE_TYPE_P (TREE_TYPE (TREE_TYPE (current_function_decl)))
6076           || !MEM_P (DECL_RTL (DECL_RESULT (current_function_decl))))
6077         return const0_rtx;
6078       else
6079         return XEXP (DECL_RTL (DECL_RESULT (current_function_decl)), 0);
6080
6081     case BUILT_IN_ALLOCA:
6082       /* If the allocation stems from the declaration of a variable-sized
6083          object, it cannot accumulate.  */
6084       target = expand_builtin_alloca (exp, ALLOCA_FOR_VAR_P (exp));
6085       if (target)
6086         return target;
6087       break;
6088
6089     case BUILT_IN_STACK_SAVE:
6090       return expand_stack_save ();
6091
6092     case BUILT_IN_STACK_RESTORE:
6093       expand_stack_restore (CALL_EXPR_ARG (exp, 0));
6094       return const0_rtx;
6095
6096     case BUILT_IN_BSWAP32:
6097     case BUILT_IN_BSWAP64:
6098       target = expand_builtin_bswap (exp, target, subtarget);
6099
6100       if (target)
6101         return target;
6102       break;
6103
6104     CASE_INT_FN (BUILT_IN_FFS):
6105     case BUILT_IN_FFSIMAX:
6106       target = expand_builtin_unop (target_mode, exp, target,
6107                                     subtarget, ffs_optab);
6108       if (target)
6109         return target;
6110       break;
6111
6112     CASE_INT_FN (BUILT_IN_CLZ):
6113     case BUILT_IN_CLZIMAX:
6114       target = expand_builtin_unop (target_mode, exp, target,
6115                                     subtarget, clz_optab);
6116       if (target)
6117         return target;
6118       break;
6119
6120     CASE_INT_FN (BUILT_IN_CTZ):
6121     case BUILT_IN_CTZIMAX:
6122       target = expand_builtin_unop (target_mode, exp, target,
6123                                     subtarget, ctz_optab);
6124       if (target)
6125         return target;
6126       break;
6127
6128     CASE_INT_FN (BUILT_IN_POPCOUNT):
6129     case BUILT_IN_POPCOUNTIMAX:
6130       target = expand_builtin_unop (target_mode, exp, target,
6131                                     subtarget, popcount_optab);
6132       if (target)
6133         return target;
6134       break;
6135
6136     CASE_INT_FN (BUILT_IN_PARITY):
6137     case BUILT_IN_PARITYIMAX:
6138       target = expand_builtin_unop (target_mode, exp, target,
6139                                     subtarget, parity_optab);
6140       if (target)
6141         return target;
6142       break;
6143
6144     case BUILT_IN_STRLEN:
6145       target = expand_builtin_strlen (exp, target, target_mode);
6146       if (target)
6147         return target;
6148       break;
6149
6150     case BUILT_IN_STRCPY:
6151       target = expand_builtin_strcpy (exp, target);
6152       if (target)
6153         return target;
6154       break;
6155
6156     case BUILT_IN_STRNCPY:
6157       target = expand_builtin_strncpy (exp, target);
6158       if (target)
6159         return target;
6160       break;
6161
6162     case BUILT_IN_STPCPY:
6163       target = expand_builtin_stpcpy (exp, target, mode);
6164       if (target)
6165         return target;
6166       break;
6167
6168     case BUILT_IN_MEMCPY:
6169       target = expand_builtin_memcpy (exp, target);
6170       if (target)
6171         return target;
6172       break;
6173
6174     case BUILT_IN_MEMPCPY:
6175       target = expand_builtin_mempcpy (exp, target, mode);
6176       if (target)
6177         return target;
6178       break;
6179
6180     case BUILT_IN_MEMSET:
6181       target = expand_builtin_memset (exp, target, mode);
6182       if (target)
6183         return target;
6184       break;
6185
6186     case BUILT_IN_BZERO:
6187       target = expand_builtin_bzero (exp);
6188       if (target)
6189         return target;
6190       break;
6191
6192     case BUILT_IN_STRCMP:
6193       target = expand_builtin_strcmp (exp, target);
6194       if (target)
6195         return target;
6196       break;
6197
6198     case BUILT_IN_STRNCMP:
6199       target = expand_builtin_strncmp (exp, target, mode);
6200       if (target)
6201         return target;
6202       break;
6203
6204     case BUILT_IN_BCMP:
6205     case BUILT_IN_MEMCMP:
6206       target = expand_builtin_memcmp (exp, target, mode);
6207       if (target)
6208         return target;
6209       break;
6210
6211     case BUILT_IN_SETJMP:
6212       /* This should have been lowered to the builtins below.  */
6213       gcc_unreachable ();
6214
6215     case BUILT_IN_SETJMP_SETUP:
6216       /* __builtin_setjmp_setup is passed a pointer to an array of five words
6217           and the receiver label.  */
6218       if (validate_arglist (exp, POINTER_TYPE, POINTER_TYPE, VOID_TYPE))
6219         {
6220           rtx buf_addr = expand_expr (CALL_EXPR_ARG (exp, 0), subtarget,
6221                                       VOIDmode, EXPAND_NORMAL);
6222           tree label = TREE_OPERAND (CALL_EXPR_ARG (exp, 1), 0);
6223           rtx label_r = label_rtx (label);
6224
6225           /* This is copied from the handling of non-local gotos.  */
6226           expand_builtin_setjmp_setup (buf_addr, label_r);
6227           nonlocal_goto_handler_labels
6228             = gen_rtx_EXPR_LIST (VOIDmode, label_r,
6229                                  nonlocal_goto_handler_labels);
6230           /* ??? Do not let expand_label treat us as such since we would
6231              not want to be both on the list of non-local labels and on
6232              the list of forced labels.  */
6233           FORCED_LABEL (label) = 0;
6234           return const0_rtx;
6235         }
6236       break;
6237
6238     case BUILT_IN_SETJMP_DISPATCHER:
6239        /* __builtin_setjmp_dispatcher is passed the dispatcher label.  */
6240       if (validate_arglist (exp, POINTER_TYPE, VOID_TYPE))
6241         {
6242           tree label = TREE_OPERAND (CALL_EXPR_ARG (exp, 0), 0);
6243           rtx label_r = label_rtx (label);
6244
6245           /* Remove the dispatcher label from the list of non-local labels
6246              since the receiver labels have been added to it above.  */
6247           remove_node_from_expr_list (label_r, &nonlocal_goto_handler_labels);
6248           return const0_rtx;
6249         }
6250       break;
6251
6252     case BUILT_IN_SETJMP_RECEIVER:
6253        /* __builtin_setjmp_receiver is passed the receiver label.  */
6254       if (validate_arglist (exp, POINTER_TYPE, VOID_TYPE))
6255         {
6256           tree label = TREE_OPERAND (CALL_EXPR_ARG (exp, 0), 0);
6257           rtx label_r = label_rtx (label);
6258
6259           expand_builtin_setjmp_receiver (label_r);
6260           return const0_rtx;
6261         }
6262       break;
6263
6264       /* __builtin_longjmp is passed a pointer to an array of five words.
6265          It's similar to the C library longjmp function but works with
6266          __builtin_setjmp above.  */
6267     case BUILT_IN_LONGJMP:
6268       if (validate_arglist (exp, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
6269         {
6270           rtx buf_addr = expand_expr (CALL_EXPR_ARG (exp, 0), subtarget,
6271                                       VOIDmode, EXPAND_NORMAL);
6272           rtx value = expand_normal (CALL_EXPR_ARG (exp, 1));
6273
6274           if (value != const1_rtx)
6275             {
6276               error ("%<__builtin_longjmp%> second argument must be 1");
6277               return const0_rtx;
6278             }
6279
6280           expand_builtin_longjmp (buf_addr, value);
6281           return const0_rtx;
6282         }
6283       break;
6284
6285     case BUILT_IN_NONLOCAL_GOTO:
6286       target = expand_builtin_nonlocal_goto (exp);
6287       if (target)
6288         return target;
6289       break;
6290
6291       /* This updates the setjmp buffer that is its argument with the value
6292          of the current stack pointer.  */
6293     case BUILT_IN_UPDATE_SETJMP_BUF:
6294       if (validate_arglist (exp, POINTER_TYPE, VOID_TYPE))
6295         {
6296           rtx buf_addr
6297             = expand_normal (CALL_EXPR_ARG (exp, 0));
6298
6299           expand_builtin_update_setjmp_buf (buf_addr);
6300           return const0_rtx;
6301         }
6302       break;
6303
6304     case BUILT_IN_TRAP:
6305       expand_builtin_trap ();
6306       return const0_rtx;
6307
6308     case BUILT_IN_UNREACHABLE:
6309       expand_builtin_unreachable ();
6310       return const0_rtx;
6311
6312     CASE_FLT_FN (BUILT_IN_SIGNBIT):
6313     case BUILT_IN_SIGNBITD32:
6314     case BUILT_IN_SIGNBITD64:
6315     case BUILT_IN_SIGNBITD128:
6316       target = expand_builtin_signbit (exp, target);
6317       if (target)
6318         return target;
6319       break;
6320
6321       /* Various hooks for the DWARF 2 __throw routine.  */
6322     case BUILT_IN_UNWIND_INIT:
6323       expand_builtin_unwind_init ();
6324       return const0_rtx;
6325     case BUILT_IN_DWARF_CFA:
6326       return virtual_cfa_rtx;
6327 #ifdef DWARF2_UNWIND_INFO
6328     case BUILT_IN_DWARF_SP_COLUMN:
6329       return expand_builtin_dwarf_sp_column ();
6330     case BUILT_IN_INIT_DWARF_REG_SIZES:
6331       expand_builtin_init_dwarf_reg_sizes (CALL_EXPR_ARG (exp, 0));
6332       return const0_rtx;
6333 #endif
6334     case BUILT_IN_FROB_RETURN_ADDR:
6335       return expand_builtin_frob_return_addr (CALL_EXPR_ARG (exp, 0));
6336     case BUILT_IN_EXTRACT_RETURN_ADDR:
6337       return expand_builtin_extract_return_addr (CALL_EXPR_ARG (exp, 0));
6338     case BUILT_IN_EH_RETURN:
6339       expand_builtin_eh_return (CALL_EXPR_ARG (exp, 0),
6340                                 CALL_EXPR_ARG (exp, 1));
6341       return const0_rtx;
6342 #ifdef EH_RETURN_DATA_REGNO
6343     case BUILT_IN_EH_RETURN_DATA_REGNO:
6344       return expand_builtin_eh_return_data_regno (exp);
6345 #endif
6346     case BUILT_IN_EXTEND_POINTER:
6347       return expand_builtin_extend_pointer (CALL_EXPR_ARG (exp, 0));
6348     case BUILT_IN_EH_POINTER:
6349       return expand_builtin_eh_pointer (exp);
6350     case BUILT_IN_EH_FILTER:
6351       return expand_builtin_eh_filter (exp);
6352     case BUILT_IN_EH_COPY_VALUES:
6353       return expand_builtin_eh_copy_values (exp);
6354
6355     case BUILT_IN_VA_START:
6356       return expand_builtin_va_start (exp);
6357     case BUILT_IN_VA_END:
6358       return expand_builtin_va_end (exp);
6359     case BUILT_IN_VA_COPY:
6360       return expand_builtin_va_copy (exp);
6361     case BUILT_IN_EXPECT:
6362       return expand_builtin_expect (exp, target);
6363     case BUILT_IN_PREFETCH:
6364       expand_builtin_prefetch (exp);
6365       return const0_rtx;
6366
6367     case BUILT_IN_PROFILE_FUNC_ENTER:
6368       return expand_builtin_profile_func (false);
6369     case BUILT_IN_PROFILE_FUNC_EXIT:
6370       return expand_builtin_profile_func (true);
6371
6372     case BUILT_IN_INIT_TRAMPOLINE:
6373       return expand_builtin_init_trampoline (exp);
6374     case BUILT_IN_ADJUST_TRAMPOLINE:
6375       return expand_builtin_adjust_trampoline (exp);
6376
6377     case BUILT_IN_FORK:
6378     case BUILT_IN_EXECL:
6379     case BUILT_IN_EXECV:
6380     case BUILT_IN_EXECLP:
6381     case BUILT_IN_EXECLE:
6382     case BUILT_IN_EXECVP:
6383     case BUILT_IN_EXECVE:
6384       target = expand_builtin_fork_or_exec (fndecl, exp, target, ignore);
6385       if (target)
6386         return target;
6387       break;
6388
6389     case BUILT_IN_FETCH_AND_ADD_1:
6390     case BUILT_IN_FETCH_AND_ADD_2:
6391     case BUILT_IN_FETCH_AND_ADD_4:
6392     case BUILT_IN_FETCH_AND_ADD_8:
6393     case BUILT_IN_FETCH_AND_ADD_16:
6394       mode = get_builtin_sync_mode (fcode - BUILT_IN_FETCH_AND_ADD_1);
6395       target = expand_builtin_sync_operation (mode, exp, PLUS,
6396                                               false, target, ignore);
6397       if (target)
6398         return target;
6399       break;
6400
6401     case BUILT_IN_FETCH_AND_SUB_1:
6402     case BUILT_IN_FETCH_AND_SUB_2:
6403     case BUILT_IN_FETCH_AND_SUB_4:
6404     case BUILT_IN_FETCH_AND_SUB_8:
6405     case BUILT_IN_FETCH_AND_SUB_16:
6406       mode = get_builtin_sync_mode (fcode - BUILT_IN_FETCH_AND_SUB_1);
6407       target = expand_builtin_sync_operation (mode, exp, MINUS,
6408                                               false, target, ignore);
6409       if (target)
6410         return target;
6411       break;
6412
6413     case BUILT_IN_FETCH_AND_OR_1:
6414     case BUILT_IN_FETCH_AND_OR_2:
6415     case BUILT_IN_FETCH_AND_OR_4:
6416     case BUILT_IN_FETCH_AND_OR_8:
6417     case BUILT_IN_FETCH_AND_OR_16:
6418       mode = get_builtin_sync_mode (fcode - BUILT_IN_FETCH_AND_OR_1);
6419       target = expand_builtin_sync_operation (mode, exp, IOR,
6420                                               false, target, ignore);
6421       if (target)
6422         return target;
6423       break;
6424
6425     case BUILT_IN_FETCH_AND_AND_1:
6426     case BUILT_IN_FETCH_AND_AND_2:
6427     case BUILT_IN_FETCH_AND_AND_4:
6428     case BUILT_IN_FETCH_AND_AND_8:
6429     case BUILT_IN_FETCH_AND_AND_16:
6430       mode = get_builtin_sync_mode (fcode - BUILT_IN_FETCH_AND_AND_1);
6431       target = expand_builtin_sync_operation (mode, exp, AND,
6432                                               false, target, ignore);
6433       if (target)
6434         return target;
6435       break;
6436
6437     case BUILT_IN_FETCH_AND_XOR_1:
6438     case BUILT_IN_FETCH_AND_XOR_2:
6439     case BUILT_IN_FETCH_AND_XOR_4:
6440     case BUILT_IN_FETCH_AND_XOR_8:
6441     case BUILT_IN_FETCH_AND_XOR_16:
6442       mode = get_builtin_sync_mode (fcode - BUILT_IN_FETCH_AND_XOR_1);
6443       target = expand_builtin_sync_operation (mode, exp, XOR,
6444                                               false, target, ignore);
6445       if (target)
6446         return target;
6447       break;
6448
6449     case BUILT_IN_FETCH_AND_NAND_1:
6450     case BUILT_IN_FETCH_AND_NAND_2:
6451     case BUILT_IN_FETCH_AND_NAND_4:
6452     case BUILT_IN_FETCH_AND_NAND_8:
6453     case BUILT_IN_FETCH_AND_NAND_16:
6454       mode = get_builtin_sync_mode (fcode - BUILT_IN_FETCH_AND_NAND_1);
6455       target = expand_builtin_sync_operation (mode, exp, NOT,
6456                                               false, target, ignore);
6457       if (target)
6458         return target;
6459       break;
6460
6461     case BUILT_IN_ADD_AND_FETCH_1:
6462     case BUILT_IN_ADD_AND_FETCH_2:
6463     case BUILT_IN_ADD_AND_FETCH_4:
6464     case BUILT_IN_ADD_AND_FETCH_8:
6465     case BUILT_IN_ADD_AND_FETCH_16:
6466       mode = get_builtin_sync_mode (fcode - BUILT_IN_ADD_AND_FETCH_1);
6467       target = expand_builtin_sync_operation (mode, exp, PLUS,
6468                                               true, target, ignore);
6469       if (target)
6470         return target;
6471       break;
6472
6473     case BUILT_IN_SUB_AND_FETCH_1:
6474     case BUILT_IN_SUB_AND_FETCH_2:
6475     case BUILT_IN_SUB_AND_FETCH_4:
6476     case BUILT_IN_SUB_AND_FETCH_8:
6477     case BUILT_IN_SUB_AND_FETCH_16:
6478       mode = get_builtin_sync_mode (fcode - BUILT_IN_SUB_AND_FETCH_1);
6479       target = expand_builtin_sync_operation (mode, exp, MINUS,
6480                                               true, target, ignore);
6481       if (target)
6482         return target;
6483       break;
6484
6485     case BUILT_IN_OR_AND_FETCH_1:
6486     case BUILT_IN_OR_AND_FETCH_2:
6487     case BUILT_IN_OR_AND_FETCH_4:
6488     case BUILT_IN_OR_AND_FETCH_8:
6489     case BUILT_IN_OR_AND_FETCH_16:
6490       mode = get_builtin_sync_mode (fcode - BUILT_IN_OR_AND_FETCH_1);
6491       target = expand_builtin_sync_operation (mode, exp, IOR,
6492                                               true, target, ignore);
6493       if (target)
6494         return target;
6495       break;
6496
6497     case BUILT_IN_AND_AND_FETCH_1:
6498     case BUILT_IN_AND_AND_FETCH_2:
6499     case BUILT_IN_AND_AND_FETCH_4:
6500     case BUILT_IN_AND_AND_FETCH_8:
6501     case BUILT_IN_AND_AND_FETCH_16:
6502       mode = get_builtin_sync_mode (fcode - BUILT_IN_AND_AND_FETCH_1);
6503       target = expand_builtin_sync_operation (mode, exp, AND,
6504                                               true, target, ignore);
6505       if (target)
6506         return target;
6507       break;
6508
6509     case BUILT_IN_XOR_AND_FETCH_1:
6510     case BUILT_IN_XOR_AND_FETCH_2:
6511     case BUILT_IN_XOR_AND_FETCH_4:
6512     case BUILT_IN_XOR_AND_FETCH_8:
6513     case BUILT_IN_XOR_AND_FETCH_16:
6514       mode = get_builtin_sync_mode (fcode - BUILT_IN_XOR_AND_FETCH_1);
6515       target = expand_builtin_sync_operation (mode, exp, XOR,
6516                                               true, target, ignore);
6517       if (target)
6518         return target;
6519       break;
6520
6521     case BUILT_IN_NAND_AND_FETCH_1:
6522     case BUILT_IN_NAND_AND_FETCH_2:
6523     case BUILT_IN_NAND_AND_FETCH_4:
6524     case BUILT_IN_NAND_AND_FETCH_8:
6525     case BUILT_IN_NAND_AND_FETCH_16:
6526       mode = get_builtin_sync_mode (fcode - BUILT_IN_NAND_AND_FETCH_1);
6527       target = expand_builtin_sync_operation (mode, exp, NOT,
6528                                               true, target, ignore);
6529       if (target)
6530         return target;
6531       break;
6532
6533     case BUILT_IN_BOOL_COMPARE_AND_SWAP_1:
6534     case BUILT_IN_BOOL_COMPARE_AND_SWAP_2:
6535     case BUILT_IN_BOOL_COMPARE_AND_SWAP_4:
6536     case BUILT_IN_BOOL_COMPARE_AND_SWAP_8:
6537     case BUILT_IN_BOOL_COMPARE_AND_SWAP_16:
6538       if (mode == VOIDmode)
6539         mode = TYPE_MODE (boolean_type_node);
6540       if (!target || !register_operand (target, mode))
6541         target = gen_reg_rtx (mode);
6542
6543       mode = get_builtin_sync_mode (fcode - BUILT_IN_BOOL_COMPARE_AND_SWAP_1);
6544       target = expand_builtin_compare_and_swap (mode, exp, true, target);
6545       if (target)
6546         return target;
6547       break;
6548
6549     case BUILT_IN_VAL_COMPARE_AND_SWAP_1:
6550     case BUILT_IN_VAL_COMPARE_AND_SWAP_2:
6551     case BUILT_IN_VAL_COMPARE_AND_SWAP_4:
6552     case BUILT_IN_VAL_COMPARE_AND_SWAP_8:
6553     case BUILT_IN_VAL_COMPARE_AND_SWAP_16:
6554       mode = get_builtin_sync_mode (fcode - BUILT_IN_VAL_COMPARE_AND_SWAP_1);
6555       target = expand_builtin_compare_and_swap (mode, exp, false, target);
6556       if (target)
6557         return target;
6558       break;
6559
6560     case BUILT_IN_LOCK_TEST_AND_SET_1:
6561     case BUILT_IN_LOCK_TEST_AND_SET_2:
6562     case BUILT_IN_LOCK_TEST_AND_SET_4:
6563     case BUILT_IN_LOCK_TEST_AND_SET_8:
6564     case BUILT_IN_LOCK_TEST_AND_SET_16:
6565       mode = get_builtin_sync_mode (fcode - BUILT_IN_LOCK_TEST_AND_SET_1);
6566       target = expand_builtin_lock_test_and_set (mode, exp, target);
6567       if (target)
6568         return target;
6569       break;
6570
6571     case BUILT_IN_LOCK_RELEASE_1:
6572     case BUILT_IN_LOCK_RELEASE_2:
6573     case BUILT_IN_LOCK_RELEASE_4:
6574     case BUILT_IN_LOCK_RELEASE_8:
6575     case BUILT_IN_LOCK_RELEASE_16:
6576       mode = get_builtin_sync_mode (fcode - BUILT_IN_LOCK_RELEASE_1);
6577       expand_builtin_lock_release (mode, exp);
6578       return const0_rtx;
6579
6580     case BUILT_IN_SYNCHRONIZE:
6581       expand_builtin_synchronize ();
6582       return const0_rtx;
6583
6584     case BUILT_IN_OBJECT_SIZE:
6585       return expand_builtin_object_size (exp);
6586
6587     case BUILT_IN_MEMCPY_CHK:
6588     case BUILT_IN_MEMPCPY_CHK:
6589     case BUILT_IN_MEMMOVE_CHK:
6590     case BUILT_IN_MEMSET_CHK:
6591       target = expand_builtin_memory_chk (exp, target, mode, fcode);
6592       if (target)
6593         return target;
6594       break;
6595
6596     case BUILT_IN_STRCPY_CHK:
6597     case BUILT_IN_STPCPY_CHK:
6598     case BUILT_IN_STRNCPY_CHK:
6599     case BUILT_IN_STRCAT_CHK:
6600     case BUILT_IN_STRNCAT_CHK:
6601     case BUILT_IN_SNPRINTF_CHK:
6602     case BUILT_IN_VSNPRINTF_CHK:
6603       maybe_emit_chk_warning (exp, fcode);
6604       break;
6605
6606     case BUILT_IN_SPRINTF_CHK:
6607     case BUILT_IN_VSPRINTF_CHK:
6608       maybe_emit_sprintf_chk_warning (exp, fcode);
6609       break;
6610
6611     case BUILT_IN_FREE:
6612       maybe_emit_free_warning (exp);
6613       break;
6614
6615     default:    /* just do library call, if unknown builtin */
6616       break;
6617     }
6618
6619   /* The switch statement above can drop through to cause the function
6620      to be called normally.  */
6621   return expand_call (exp, target, ignore);
6622 }
6623
6624 /* Determine whether a tree node represents a call to a built-in
6625    function.  If the tree T is a call to a built-in function with
6626    the right number of arguments of the appropriate types, return
6627    the DECL_FUNCTION_CODE of the call, e.g. BUILT_IN_SQRT.
6628    Otherwise the return value is END_BUILTINS.  */
6629
6630 enum built_in_function
6631 builtin_mathfn_code (const_tree t)
6632 {
6633   const_tree fndecl, arg, parmlist;
6634   const_tree argtype, parmtype;
6635   const_call_expr_arg_iterator iter;
6636
6637   if (TREE_CODE (t) != CALL_EXPR
6638       || TREE_CODE (CALL_EXPR_FN (t)) != ADDR_EXPR)
6639     return END_BUILTINS;
6640
6641   fndecl = get_callee_fndecl (t);
6642   if (fndecl == NULL_TREE
6643       || TREE_CODE (fndecl) != FUNCTION_DECL
6644       || ! DECL_BUILT_IN (fndecl)
6645       || DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_MD)
6646     return END_BUILTINS;
6647
6648   parmlist = TYPE_ARG_TYPES (TREE_TYPE (fndecl));
6649   init_const_call_expr_arg_iterator (t, &iter);
6650   for (; parmlist; parmlist = TREE_CHAIN (parmlist))
6651     {
6652       /* If a function doesn't take a variable number of arguments,
6653          the last element in the list will have type `void'.  */
6654       parmtype = TREE_VALUE (parmlist);
6655       if (VOID_TYPE_P (parmtype))
6656         {
6657           if (more_const_call_expr_args_p (&iter))
6658             return END_BUILTINS;
6659           return DECL_FUNCTION_CODE (fndecl);
6660         }
6661
6662       if (! more_const_call_expr_args_p (&iter))
6663         return END_BUILTINS;
6664
6665       arg = next_const_call_expr_arg (&iter);
6666       argtype = TREE_TYPE (arg);
6667
6668       if (SCALAR_FLOAT_TYPE_P (parmtype))
6669         {
6670           if (! SCALAR_FLOAT_TYPE_P (argtype))
6671             return END_BUILTINS;
6672         }
6673       else if (COMPLEX_FLOAT_TYPE_P (parmtype))
6674         {
6675           if (! COMPLEX_FLOAT_TYPE_P (argtype))
6676             return END_BUILTINS;
6677         }
6678       else if (POINTER_TYPE_P (parmtype))
6679         {
6680           if (! POINTER_TYPE_P (argtype))
6681             return END_BUILTINS;
6682         }
6683       else if (INTEGRAL_TYPE_P (parmtype))
6684         {
6685           if (! INTEGRAL_TYPE_P (argtype))
6686             return END_BUILTINS;
6687         }
6688       else
6689         return END_BUILTINS;
6690     }
6691
6692   /* Variable-length argument list.  */
6693   return DECL_FUNCTION_CODE (fndecl);
6694 }
6695
6696 /* Fold a call to __builtin_constant_p, if we know its argument ARG will
6697    evaluate to a constant.  */
6698
6699 static tree
6700 fold_builtin_constant_p (tree arg)
6701 {
6702   /* We return 1 for a numeric type that's known to be a constant
6703      value at compile-time or for an aggregate type that's a
6704      literal constant.  */
6705   STRIP_NOPS (arg);
6706
6707   /* If we know this is a constant, emit the constant of one.  */
6708   if (CONSTANT_CLASS_P (arg)
6709       || (TREE_CODE (arg) == CONSTRUCTOR
6710           && TREE_CONSTANT (arg)))
6711     return integer_one_node;
6712   if (TREE_CODE (arg) == ADDR_EXPR)
6713     {
6714        tree op = TREE_OPERAND (arg, 0);
6715        if (TREE_CODE (op) == STRING_CST
6716            || (TREE_CODE (op) == ARRAY_REF
6717                && integer_zerop (TREE_OPERAND (op, 1))
6718                && TREE_CODE (TREE_OPERAND (op, 0)) == STRING_CST))
6719          return integer_one_node;
6720     }
6721
6722   /* If this expression has side effects, show we don't know it to be a
6723      constant.  Likewise if it's a pointer or aggregate type since in
6724      those case we only want literals, since those are only optimized
6725      when generating RTL, not later.
6726      And finally, if we are compiling an initializer, not code, we
6727      need to return a definite result now; there's not going to be any
6728      more optimization done.  */
6729   if (TREE_SIDE_EFFECTS (arg)
6730       || AGGREGATE_TYPE_P (TREE_TYPE (arg))
6731       || POINTER_TYPE_P (TREE_TYPE (arg))
6732       || cfun == 0
6733       || folding_initializer)
6734     return integer_zero_node;
6735
6736   return NULL_TREE;
6737 }
6738
6739 /* Create builtin_expect with PRED and EXPECTED as its arguments and
6740    return it as a truthvalue.  */
6741
6742 static tree
6743 build_builtin_expect_predicate (location_t loc, tree pred, tree expected)
6744 {
6745   tree fn, arg_types, pred_type, expected_type, call_expr, ret_type;
6746
6747   fn = built_in_decls[BUILT_IN_EXPECT];
6748   arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
6749   ret_type = TREE_TYPE (TREE_TYPE (fn));
6750   pred_type = TREE_VALUE (arg_types);
6751   expected_type = TREE_VALUE (TREE_CHAIN (arg_types));
6752
6753   pred = fold_convert_loc (loc, pred_type, pred);
6754   expected = fold_convert_loc (loc, expected_type, expected);
6755   call_expr = build_call_expr_loc (loc, fn, 2, pred, expected);
6756
6757   return build2 (NE_EXPR, TREE_TYPE (pred), call_expr,
6758                  build_int_cst (ret_type, 0));
6759 }
6760
6761 /* Fold a call to builtin_expect with arguments ARG0 and ARG1.  Return
6762    NULL_TREE if no simplification is possible.  */
6763
6764 static tree
6765 fold_builtin_expect (location_t loc, tree arg0, tree arg1)
6766 {
6767   tree inner, fndecl;
6768   enum tree_code code;
6769
6770   /* If this is a builtin_expect within a builtin_expect keep the
6771      inner one.  See through a comparison against a constant.  It
6772      might have been added to create a thruthvalue.  */
6773   inner = arg0;
6774   if (COMPARISON_CLASS_P (inner)
6775       && TREE_CODE (TREE_OPERAND (inner, 1)) == INTEGER_CST)
6776     inner = TREE_OPERAND (inner, 0);
6777
6778   if (TREE_CODE (inner) == CALL_EXPR
6779       && (fndecl = get_callee_fndecl (inner))
6780       && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL
6781       && DECL_FUNCTION_CODE (fndecl) == BUILT_IN_EXPECT)
6782     return arg0;
6783
6784   /* Distribute the expected value over short-circuiting operators.
6785      See through the cast from truthvalue_type_node to long.  */
6786   inner = arg0;
6787   while (TREE_CODE (inner) == NOP_EXPR
6788          && INTEGRAL_TYPE_P (TREE_TYPE (inner))
6789          && INTEGRAL_TYPE_P (TREE_TYPE (TREE_OPERAND (inner, 0))))
6790     inner = TREE_OPERAND (inner, 0);
6791
6792   code = TREE_CODE (inner);
6793   if (code == TRUTH_ANDIF_EXPR || code == TRUTH_ORIF_EXPR)
6794     {
6795       tree op0 = TREE_OPERAND (inner, 0);
6796       tree op1 = TREE_OPERAND (inner, 1);
6797
6798       op0 = build_builtin_expect_predicate (loc, op0, arg1);
6799       op1 = build_builtin_expect_predicate (loc, op1, arg1);
6800       inner = build2 (code, TREE_TYPE (inner), op0, op1);
6801
6802       return fold_convert_loc (loc, TREE_TYPE (arg0), inner);
6803     }
6804
6805   /* If the argument isn't invariant then there's nothing else we can do.  */
6806   if (!TREE_CONSTANT (arg0))
6807     return NULL_TREE;
6808
6809   /* If we expect that a comparison against the argument will fold to
6810      a constant return the constant.  In practice, this means a true
6811      constant or the address of a non-weak symbol.  */
6812   inner = arg0;
6813   STRIP_NOPS (inner);
6814   if (TREE_CODE (inner) == ADDR_EXPR)
6815     {
6816       do
6817         {
6818           inner = TREE_OPERAND (inner, 0);
6819         }
6820       while (TREE_CODE (inner) == COMPONENT_REF
6821              || TREE_CODE (inner) == ARRAY_REF);
6822       if ((TREE_CODE (inner) == VAR_DECL
6823            || TREE_CODE (inner) == FUNCTION_DECL)
6824           && DECL_WEAK (inner))
6825         return NULL_TREE;
6826     }
6827
6828   /* Otherwise, ARG0 already has the proper type for the return value.  */
6829   return arg0;
6830 }
6831
6832 /* Fold a call to __builtin_classify_type with argument ARG.  */
6833
6834 static tree
6835 fold_builtin_classify_type (tree arg)
6836 {
6837   if (arg == 0)
6838     return build_int_cst (NULL_TREE, no_type_class);
6839
6840   return build_int_cst (NULL_TREE, type_to_class (TREE_TYPE (arg)));
6841 }
6842
6843 /* Fold a call to __builtin_strlen with argument ARG.  */
6844
6845 static tree
6846 fold_builtin_strlen (location_t loc, tree type, tree arg)
6847 {
6848   if (!validate_arg (arg, POINTER_TYPE))
6849     return NULL_TREE;
6850   else
6851     {
6852       tree len = c_strlen (arg, 0);
6853
6854       if (len)
6855         return fold_convert_loc (loc, type, len);
6856
6857       return NULL_TREE;
6858     }
6859 }
6860
6861 /* Fold a call to __builtin_inf or __builtin_huge_val.  */
6862
6863 static tree
6864 fold_builtin_inf (location_t loc, tree type, int warn)
6865 {
6866   REAL_VALUE_TYPE real;
6867
6868   /* __builtin_inff is intended to be usable to define INFINITY on all
6869      targets.  If an infinity is not available, INFINITY expands "to a
6870      positive constant of type float that overflows at translation
6871      time", footnote "In this case, using INFINITY will violate the
6872      constraint in 6.4.4 and thus require a diagnostic." (C99 7.12#4).
6873      Thus we pedwarn to ensure this constraint violation is
6874      diagnosed.  */
6875   if (!MODE_HAS_INFINITIES (TYPE_MODE (type)) && warn)
6876     pedwarn (loc, 0, "target format does not support infinity");
6877
6878   real_inf (&real);
6879   return build_real (type, real);
6880 }
6881
6882 /* Fold a call to __builtin_nan or __builtin_nans with argument ARG.  */
6883
6884 static tree
6885 fold_builtin_nan (tree arg, tree type, int quiet)
6886 {
6887   REAL_VALUE_TYPE real;
6888   const char *str;
6889
6890   if (!validate_arg (arg, POINTER_TYPE))
6891     return NULL_TREE;
6892   str = c_getstr (arg);
6893   if (!str)
6894     return NULL_TREE;
6895
6896   if (!real_nan (&real, str, quiet, TYPE_MODE (type)))
6897     return NULL_TREE;
6898
6899   return build_real (type, real);
6900 }
6901
6902 /* Return true if the floating point expression T has an integer value.
6903    We also allow +Inf, -Inf and NaN to be considered integer values.  */
6904
6905 static bool
6906 integer_valued_real_p (tree t)
6907 {
6908   switch (TREE_CODE (t))
6909     {
6910     case FLOAT_EXPR:
6911       return true;
6912
6913     case ABS_EXPR:
6914     case SAVE_EXPR:
6915       return integer_valued_real_p (TREE_OPERAND (t, 0));
6916
6917     case COMPOUND_EXPR:
6918     case MODIFY_EXPR:
6919     case BIND_EXPR:
6920       return integer_valued_real_p (TREE_OPERAND (t, 1));
6921
6922     case PLUS_EXPR:
6923     case MINUS_EXPR:
6924     case MULT_EXPR:
6925     case MIN_EXPR:
6926     case MAX_EXPR:
6927       return integer_valued_real_p (TREE_OPERAND (t, 0))
6928              && integer_valued_real_p (TREE_OPERAND (t, 1));
6929
6930     case COND_EXPR:
6931       return integer_valued_real_p (TREE_OPERAND (t, 1))
6932              && integer_valued_real_p (TREE_OPERAND (t, 2));
6933
6934     case REAL_CST:
6935       return real_isinteger (TREE_REAL_CST_PTR (t), TYPE_MODE (TREE_TYPE (t)));
6936
6937     case NOP_EXPR:
6938       {
6939         tree type = TREE_TYPE (TREE_OPERAND (t, 0));
6940         if (TREE_CODE (type) == INTEGER_TYPE)
6941           return true;
6942         if (TREE_CODE (type) == REAL_TYPE)
6943           return integer_valued_real_p (TREE_OPERAND (t, 0));
6944         break;
6945       }
6946
6947     case CALL_EXPR:
6948       switch (builtin_mathfn_code (t))
6949         {
6950         CASE_FLT_FN (BUILT_IN_CEIL):
6951         CASE_FLT_FN (BUILT_IN_FLOOR):
6952         CASE_FLT_FN (BUILT_IN_NEARBYINT):
6953         CASE_FLT_FN (BUILT_IN_RINT):
6954         CASE_FLT_FN (BUILT_IN_ROUND):
6955         CASE_FLT_FN (BUILT_IN_TRUNC):
6956           return true;
6957
6958         CASE_FLT_FN (BUILT_IN_FMIN):
6959         CASE_FLT_FN (BUILT_IN_FMAX):
6960           return integer_valued_real_p (CALL_EXPR_ARG (t, 0))
6961             && integer_valued_real_p (CALL_EXPR_ARG (t, 1));
6962
6963         default:
6964           break;
6965         }
6966       break;
6967
6968     default:
6969       break;
6970     }
6971   return false;
6972 }
6973
6974 /* FNDECL is assumed to be a builtin where truncation can be propagated
6975    across (for instance floor((double)f) == (double)floorf (f).
6976    Do the transformation for a call with argument ARG.  */
6977
6978 static tree
6979 fold_trunc_transparent_mathfn (location_t loc, tree fndecl, tree arg)
6980 {
6981   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
6982
6983   if (!validate_arg (arg, REAL_TYPE))
6984     return NULL_TREE;
6985
6986   /* Integer rounding functions are idempotent.  */
6987   if (fcode == builtin_mathfn_code (arg))
6988     return arg;
6989
6990   /* If argument is already integer valued, and we don't need to worry
6991      about setting errno, there's no need to perform rounding.  */
6992   if (! flag_errno_math && integer_valued_real_p (arg))
6993     return arg;
6994
6995   if (optimize)
6996     {
6997       tree arg0 = strip_float_extensions (arg);
6998       tree ftype = TREE_TYPE (TREE_TYPE (fndecl));
6999       tree newtype = TREE_TYPE (arg0);
7000       tree decl;
7001
7002       if (TYPE_PRECISION (newtype) < TYPE_PRECISION (ftype)
7003           && (decl = mathfn_built_in (newtype, fcode)))
7004         return fold_convert_loc (loc, ftype,
7005                                  build_call_expr_loc (loc, decl, 1,
7006                                                   fold_convert_loc (loc,
7007                                                                     newtype,
7008                                                                     arg0)));
7009     }
7010   return NULL_TREE;
7011 }
7012
7013 /* FNDECL is assumed to be builtin which can narrow the FP type of
7014    the argument, for instance lround((double)f) -> lroundf (f).
7015    Do the transformation for a call with argument ARG.  */
7016
7017 static tree
7018 fold_fixed_mathfn (location_t loc, tree fndecl, tree arg)
7019 {
7020   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
7021
7022   if (!validate_arg (arg, REAL_TYPE))
7023     return NULL_TREE;
7024
7025   /* If argument is already integer valued, and we don't need to worry
7026      about setting errno, there's no need to perform rounding.  */
7027   if (! flag_errno_math && integer_valued_real_p (arg))
7028     return fold_build1_loc (loc, FIX_TRUNC_EXPR,
7029                         TREE_TYPE (TREE_TYPE (fndecl)), arg);
7030
7031   if (optimize)
7032     {
7033       tree ftype = TREE_TYPE (arg);
7034       tree arg0 = strip_float_extensions (arg);
7035       tree newtype = TREE_TYPE (arg0);
7036       tree decl;
7037
7038       if (TYPE_PRECISION (newtype) < TYPE_PRECISION (ftype)
7039           && (decl = mathfn_built_in (newtype, fcode)))
7040         return build_call_expr_loc (loc, decl, 1,
7041                                 fold_convert_loc (loc, newtype, arg0));
7042     }
7043
7044   /* Canonicalize llround (x) to lround (x) on LP64 targets where
7045      sizeof (long long) == sizeof (long).  */
7046   if (TYPE_PRECISION (long_long_integer_type_node)
7047       == TYPE_PRECISION (long_integer_type_node))
7048     {
7049       tree newfn = NULL_TREE;
7050       switch (fcode)
7051         {
7052         CASE_FLT_FN (BUILT_IN_LLCEIL):
7053           newfn = mathfn_built_in (TREE_TYPE (arg), BUILT_IN_LCEIL);
7054           break;
7055
7056         CASE_FLT_FN (BUILT_IN_LLFLOOR):
7057           newfn = mathfn_built_in (TREE_TYPE (arg), BUILT_IN_LFLOOR);
7058           break;
7059
7060         CASE_FLT_FN (BUILT_IN_LLROUND):
7061           newfn = mathfn_built_in (TREE_TYPE (arg), BUILT_IN_LROUND);
7062           break;
7063
7064         CASE_FLT_FN (BUILT_IN_LLRINT):
7065           newfn = mathfn_built_in (TREE_TYPE (arg), BUILT_IN_LRINT);
7066           break;
7067
7068         default:
7069           break;
7070         }
7071
7072       if (newfn)
7073         {
7074           tree newcall = build_call_expr_loc (loc, newfn, 1, arg);
7075           return fold_convert_loc (loc,
7076                                    TREE_TYPE (TREE_TYPE (fndecl)), newcall);
7077         }
7078     }
7079
7080   return NULL_TREE;
7081 }
7082
7083 /* Fold call to builtin cabs, cabsf or cabsl with argument ARG.  TYPE is the
7084    return type.  Return NULL_TREE if no simplification can be made.  */
7085
7086 static tree
7087 fold_builtin_cabs (location_t loc, tree arg, tree type, tree fndecl)
7088 {
7089   tree res;
7090
7091   if (!validate_arg (arg, COMPLEX_TYPE)
7092       || TREE_CODE (TREE_TYPE (TREE_TYPE (arg))) != REAL_TYPE)
7093     return NULL_TREE;
7094
7095   /* Calculate the result when the argument is a constant.  */
7096   if (TREE_CODE (arg) == COMPLEX_CST
7097       && (res = do_mpfr_arg2 (TREE_REALPART (arg), TREE_IMAGPART (arg),
7098                               type, mpfr_hypot)))
7099     return res;
7100
7101   if (TREE_CODE (arg) == COMPLEX_EXPR)
7102     {
7103       tree real = TREE_OPERAND (arg, 0);
7104       tree imag = TREE_OPERAND (arg, 1);
7105
7106       /* If either part is zero, cabs is fabs of the other.  */
7107       if (real_zerop (real))
7108         return fold_build1_loc (loc, ABS_EXPR, type, imag);
7109       if (real_zerop (imag))
7110         return fold_build1_loc (loc, ABS_EXPR, type, real);
7111
7112       /* cabs(x+xi) -> fabs(x)*sqrt(2).  */
7113       if (flag_unsafe_math_optimizations
7114           && operand_equal_p (real, imag, OEP_PURE_SAME))
7115         {
7116           const REAL_VALUE_TYPE sqrt2_trunc
7117             = real_value_truncate (TYPE_MODE (type), dconst_sqrt2 ());
7118           STRIP_NOPS (real);
7119           return fold_build2_loc (loc, MULT_EXPR, type,
7120                               fold_build1_loc (loc, ABS_EXPR, type, real),
7121                               build_real (type, sqrt2_trunc));
7122         }
7123     }
7124
7125   /* Optimize cabs(-z) and cabs(conj(z)) as cabs(z).  */
7126   if (TREE_CODE (arg) == NEGATE_EXPR
7127       || TREE_CODE (arg) == CONJ_EXPR)
7128     return build_call_expr_loc (loc, fndecl, 1, TREE_OPERAND (arg, 0));
7129
7130   /* Don't do this when optimizing for size.  */
7131   if (flag_unsafe_math_optimizations
7132       && optimize && optimize_function_for_speed_p (cfun))
7133     {
7134       tree sqrtfn = mathfn_built_in (type, BUILT_IN_SQRT);
7135
7136       if (sqrtfn != NULL_TREE)
7137         {
7138           tree rpart, ipart, result;
7139
7140           arg = builtin_save_expr (arg);
7141
7142           rpart = fold_build1_loc (loc, REALPART_EXPR, type, arg);
7143           ipart = fold_build1_loc (loc, IMAGPART_EXPR, type, arg);
7144
7145           rpart = builtin_save_expr (rpart);
7146           ipart = builtin_save_expr (ipart);
7147
7148           result = fold_build2_loc (loc, PLUS_EXPR, type,
7149                                 fold_build2_loc (loc, MULT_EXPR, type,
7150                                              rpart, rpart),
7151                                 fold_build2_loc (loc, MULT_EXPR, type,
7152                                              ipart, ipart));
7153
7154           return build_call_expr_loc (loc, sqrtfn, 1, result);
7155         }
7156     }
7157
7158   return NULL_TREE;
7159 }
7160
7161 /* Build a complex (inf +- 0i) for the result of cproj.  TYPE is the
7162    complex tree type of the result.  If NEG is true, the imaginary
7163    zero is negative.  */
7164
7165 static tree
7166 build_complex_cproj (tree type, bool neg)
7167 {
7168   REAL_VALUE_TYPE rinf, rzero = dconst0;
7169   
7170   real_inf (&rinf);
7171   rzero.sign = neg;
7172   return build_complex (type, build_real (TREE_TYPE (type), rinf),
7173                         build_real (TREE_TYPE (type), rzero));
7174 }
7175
7176 /* Fold call to builtin cproj, cprojf or cprojl with argument ARG.  TYPE is the
7177    return type.  Return NULL_TREE if no simplification can be made.  */
7178
7179 static tree
7180 fold_builtin_cproj (location_t loc, tree arg, tree type)
7181 {
7182   if (!validate_arg (arg, COMPLEX_TYPE)
7183       || TREE_CODE (TREE_TYPE (TREE_TYPE (arg))) != REAL_TYPE)
7184     return NULL_TREE;
7185
7186   /* If there are no infinities, return arg.  */
7187   if (! HONOR_INFINITIES (TYPE_MODE (TREE_TYPE (type))))
7188     return non_lvalue_loc (loc, arg);
7189
7190   /* Calculate the result when the argument is a constant.  */
7191   if (TREE_CODE (arg) == COMPLEX_CST)
7192     {
7193       const REAL_VALUE_TYPE *real = TREE_REAL_CST_PTR (TREE_REALPART (arg));
7194       const REAL_VALUE_TYPE *imag = TREE_REAL_CST_PTR (TREE_IMAGPART (arg));
7195       
7196       if (real_isinf (real) || real_isinf (imag))
7197         return build_complex_cproj (type, imag->sign);
7198       else
7199         return arg;
7200     }
7201   else if (TREE_CODE (arg) == COMPLEX_EXPR)
7202     {
7203       tree real = TREE_OPERAND (arg, 0);
7204       tree imag = TREE_OPERAND (arg, 1);
7205
7206       STRIP_NOPS (real);
7207       STRIP_NOPS (imag);
7208       
7209       /* If the real part is inf and the imag part is known to be
7210          nonnegative, return (inf + 0i).  Remember side-effects are
7211          possible in the imag part.  */
7212       if (TREE_CODE (real) == REAL_CST
7213           && real_isinf (TREE_REAL_CST_PTR (real))
7214           && tree_expr_nonnegative_p (imag))
7215         return omit_one_operand_loc (loc, type,
7216                                      build_complex_cproj (type, false),
7217                                      arg);
7218       
7219       /* If the imag part is inf, return (inf+I*copysign(0,imag)).
7220          Remember side-effects are possible in the real part.  */
7221       if (TREE_CODE (imag) == REAL_CST
7222           && real_isinf (TREE_REAL_CST_PTR (imag)))
7223         return
7224           omit_one_operand_loc (loc, type,
7225                                 build_complex_cproj (type, TREE_REAL_CST_PTR
7226                                                      (imag)->sign), arg);
7227     }
7228
7229   return NULL_TREE;
7230 }
7231
7232 /* Fold a builtin function call to sqrt, sqrtf, or sqrtl with argument ARG.
7233    Return NULL_TREE if no simplification can be made.  */
7234
7235 static tree
7236 fold_builtin_sqrt (location_t loc, tree arg, tree type)
7237 {
7238
7239   enum built_in_function fcode;
7240   tree res;
7241
7242   if (!validate_arg (arg, REAL_TYPE))
7243     return NULL_TREE;
7244
7245   /* Calculate the result when the argument is a constant.  */
7246   if ((res = do_mpfr_arg1 (arg, type, mpfr_sqrt, &dconst0, NULL, true)))
7247     return res;
7248
7249   /* Optimize sqrt(expN(x)) = expN(x*0.5).  */
7250   fcode = builtin_mathfn_code (arg);
7251   if (flag_unsafe_math_optimizations && BUILTIN_EXPONENT_P (fcode))
7252     {
7253       tree expfn = TREE_OPERAND (CALL_EXPR_FN (arg), 0);
7254       arg = fold_build2_loc (loc, MULT_EXPR, type,
7255                          CALL_EXPR_ARG (arg, 0),
7256                          build_real (type, dconsthalf));
7257       return build_call_expr_loc (loc, expfn, 1, arg);
7258     }
7259
7260   /* Optimize sqrt(Nroot(x)) -> pow(x,1/(2*N)).  */
7261   if (flag_unsafe_math_optimizations && BUILTIN_ROOT_P (fcode))
7262     {
7263       tree powfn = mathfn_built_in (type, BUILT_IN_POW);
7264
7265       if (powfn)
7266         {
7267           tree arg0 = CALL_EXPR_ARG (arg, 0);
7268           tree tree_root;
7269           /* The inner root was either sqrt or cbrt.  */
7270           /* This was a conditional expression but it triggered a bug
7271              in Sun C 5.5.  */
7272           REAL_VALUE_TYPE dconstroot;
7273           if (BUILTIN_SQRT_P (fcode))
7274             dconstroot = dconsthalf;
7275           else
7276             dconstroot = dconst_third ();
7277
7278           /* Adjust for the outer root.  */
7279           SET_REAL_EXP (&dconstroot, REAL_EXP (&dconstroot) - 1);
7280           dconstroot = real_value_truncate (TYPE_MODE (type), dconstroot);
7281           tree_root = build_real (type, dconstroot);
7282           return build_call_expr_loc (loc, powfn, 2, arg0, tree_root);
7283         }
7284     }
7285
7286   /* Optimize sqrt(pow(x,y)) = pow(|x|,y*0.5).  */
7287   if (flag_unsafe_math_optimizations
7288       && (fcode == BUILT_IN_POW
7289           || fcode == BUILT_IN_POWF
7290           || fcode == BUILT_IN_POWL))
7291     {
7292       tree powfn = TREE_OPERAND (CALL_EXPR_FN (arg), 0);
7293       tree arg0 = CALL_EXPR_ARG (arg, 0);
7294       tree arg1 = CALL_EXPR_ARG (arg, 1);
7295       tree narg1;
7296       if (!tree_expr_nonnegative_p (arg0))
7297         arg0 = build1 (ABS_EXPR, type, arg0);
7298       narg1 = fold_build2_loc (loc, MULT_EXPR, type, arg1,
7299                            build_real (type, dconsthalf));
7300       return build_call_expr_loc (loc, powfn, 2, arg0, narg1);
7301     }
7302
7303   return NULL_TREE;
7304 }
7305
7306 /* Fold a builtin function call to cbrt, cbrtf, or cbrtl with argument ARG.
7307    Return NULL_TREE if no simplification can be made.  */
7308
7309 static tree
7310 fold_builtin_cbrt (location_t loc, tree arg, tree type)
7311 {
7312   const enum built_in_function fcode = builtin_mathfn_code (arg);
7313   tree res;
7314
7315   if (!validate_arg (arg, REAL_TYPE))
7316     return NULL_TREE;
7317
7318   /* Calculate the result when the argument is a constant.  */
7319   if ((res = do_mpfr_arg1 (arg, type, mpfr_cbrt, NULL, NULL, 0)))
7320     return res;
7321
7322   if (flag_unsafe_math_optimizations)
7323     {
7324       /* Optimize cbrt(expN(x)) -> expN(x/3).  */
7325       if (BUILTIN_EXPONENT_P (fcode))
7326         {
7327           tree expfn = TREE_OPERAND (CALL_EXPR_FN (arg), 0);
7328           const REAL_VALUE_TYPE third_trunc =
7329             real_value_truncate (TYPE_MODE (type), dconst_third ());
7330           arg = fold_build2_loc (loc, MULT_EXPR, type,
7331                              CALL_EXPR_ARG (arg, 0),
7332                              build_real (type, third_trunc));
7333           return build_call_expr_loc (loc, expfn, 1, arg);
7334         }
7335
7336       /* Optimize cbrt(sqrt(x)) -> pow(x,1/6).  */
7337       if (BUILTIN_SQRT_P (fcode))
7338         {
7339           tree powfn = mathfn_built_in (type, BUILT_IN_POW);
7340
7341           if (powfn)
7342             {
7343               tree arg0 = CALL_EXPR_ARG (arg, 0);
7344               tree tree_root;
7345               REAL_VALUE_TYPE dconstroot = dconst_third ();
7346
7347               SET_REAL_EXP (&dconstroot, REAL_EXP (&dconstroot) - 1);
7348               dconstroot = real_value_truncate (TYPE_MODE (type), dconstroot);
7349               tree_root = build_real (type, dconstroot);
7350               return build_call_expr_loc (loc, powfn, 2, arg0, tree_root);
7351             }
7352         }
7353
7354       /* Optimize cbrt(cbrt(x)) -> pow(x,1/9) iff x is nonnegative.  */
7355       if (BUILTIN_CBRT_P (fcode))
7356         {
7357           tree arg0 = CALL_EXPR_ARG (arg, 0);
7358           if (tree_expr_nonnegative_p (arg0))
7359             {
7360               tree powfn = mathfn_built_in (type, BUILT_IN_POW);
7361
7362               if (powfn)
7363                 {
7364                   tree tree_root;
7365                   REAL_VALUE_TYPE dconstroot;
7366
7367                   real_arithmetic (&dconstroot, MULT_EXPR,
7368                                    dconst_third_ptr (), dconst_third_ptr ());
7369                   dconstroot = real_value_truncate (TYPE_MODE (type), dconstroot);
7370                   tree_root = build_real (type, dconstroot);
7371                   return build_call_expr_loc (loc, powfn, 2, arg0, tree_root);
7372                 }
7373             }
7374         }
7375
7376       /* Optimize cbrt(pow(x,y)) -> pow(x,y/3) iff x is nonnegative.  */
7377       if (fcode == BUILT_IN_POW
7378           || fcode == BUILT_IN_POWF
7379           || fcode == BUILT_IN_POWL)
7380         {
7381           tree arg00 = CALL_EXPR_ARG (arg, 0);
7382           tree arg01 = CALL_EXPR_ARG (arg, 1);
7383           if (tree_expr_nonnegative_p (arg00))
7384             {
7385               tree powfn = TREE_OPERAND (CALL_EXPR_FN (arg), 0);
7386               const REAL_VALUE_TYPE dconstroot
7387                 = real_value_truncate (TYPE_MODE (type), dconst_third ());
7388               tree narg01 = fold_build2_loc (loc, MULT_EXPR, type, arg01,
7389                                          build_real (type, dconstroot));
7390               return build_call_expr_loc (loc, powfn, 2, arg00, narg01);
7391             }
7392         }
7393     }
7394   return NULL_TREE;
7395 }
7396
7397 /* Fold function call to builtin cos, cosf, or cosl with argument ARG.
7398    TYPE is the type of the return value.  Return NULL_TREE if no
7399    simplification can be made.  */
7400
7401 static tree
7402 fold_builtin_cos (location_t loc,
7403                   tree arg, tree type, tree fndecl)
7404 {
7405   tree res, narg;
7406
7407   if (!validate_arg (arg, REAL_TYPE))
7408     return NULL_TREE;
7409
7410   /* Calculate the result when the argument is a constant.  */
7411   if ((res = do_mpfr_arg1 (arg, type, mpfr_cos, NULL, NULL, 0)))
7412     return res;
7413
7414   /* Optimize cos(-x) into cos (x).  */
7415   if ((narg = fold_strip_sign_ops (arg)))
7416     return build_call_expr_loc (loc, fndecl, 1, narg);
7417
7418   return NULL_TREE;
7419 }
7420
7421 /* Fold function call to builtin cosh, coshf, or coshl with argument ARG.
7422    Return NULL_TREE if no simplification can be made.  */
7423
7424 static tree
7425 fold_builtin_cosh (location_t loc, tree arg, tree type, tree fndecl)
7426 {
7427   if (validate_arg (arg, REAL_TYPE))
7428     {
7429       tree res, narg;
7430
7431       /* Calculate the result when the argument is a constant.  */
7432       if ((res = do_mpfr_arg1 (arg, type, mpfr_cosh, NULL, NULL, 0)))
7433         return res;
7434
7435       /* Optimize cosh(-x) into cosh (x).  */
7436       if ((narg = fold_strip_sign_ops (arg)))
7437         return build_call_expr_loc (loc, fndecl, 1, narg);
7438     }
7439
7440   return NULL_TREE;
7441 }
7442
7443 /* Fold function call to builtin ccos (or ccosh if HYPER is TRUE) with
7444    argument ARG.  TYPE is the type of the return value.  Return
7445    NULL_TREE if no simplification can be made.  */
7446
7447 static tree
7448 fold_builtin_ccos (location_t loc, tree arg, tree type, tree fndecl,
7449                    bool hyper)
7450 {
7451   if (validate_arg (arg, COMPLEX_TYPE)
7452       && TREE_CODE (TREE_TYPE (TREE_TYPE (arg))) == REAL_TYPE)
7453     {
7454       tree tmp;
7455
7456       /* Calculate the result when the argument is a constant.  */
7457       if ((tmp = do_mpc_arg1 (arg, type, (hyper ? mpc_cosh : mpc_cos))))
7458         return tmp;
7459
7460       /* Optimize fn(-x) into fn(x).  */
7461       if ((tmp = fold_strip_sign_ops (arg)))
7462         return build_call_expr_loc (loc, fndecl, 1, tmp);
7463     }
7464
7465   return NULL_TREE;
7466 }
7467
7468 /* Fold function call to builtin tan, tanf, or tanl with argument ARG.
7469    Return NULL_TREE if no simplification can be made.  */
7470
7471 static tree
7472 fold_builtin_tan (tree arg, tree type)
7473 {
7474   enum built_in_function fcode;
7475   tree res;
7476
7477   if (!validate_arg (arg, REAL_TYPE))
7478     return NULL_TREE;
7479
7480   /* Calculate the result when the argument is a constant.  */
7481   if ((res = do_mpfr_arg1 (arg, type, mpfr_tan, NULL, NULL, 0)))
7482     return res;
7483
7484   /* Optimize tan(atan(x)) = x.  */
7485   fcode = builtin_mathfn_code (arg);
7486   if (flag_unsafe_math_optimizations
7487       && (fcode == BUILT_IN_ATAN
7488           || fcode == BUILT_IN_ATANF
7489           || fcode == BUILT_IN_ATANL))
7490     return CALL_EXPR_ARG (arg, 0);
7491
7492   return NULL_TREE;
7493 }
7494
7495 /* Fold function call to builtin sincos, sincosf, or sincosl.  Return
7496    NULL_TREE if no simplification can be made.  */
7497
7498 static tree
7499 fold_builtin_sincos (location_t loc,
7500                      tree arg0, tree arg1, tree arg2)
7501 {
7502   tree type;
7503   tree res, fn, call;
7504
7505   if (!validate_arg (arg0, REAL_TYPE)
7506       || !validate_arg (arg1, POINTER_TYPE)
7507       || !validate_arg (arg2, POINTER_TYPE))
7508     return NULL_TREE;
7509
7510   type = TREE_TYPE (arg0);
7511
7512   /* Calculate the result when the argument is a constant.  */
7513   if ((res = do_mpfr_sincos (arg0, arg1, arg2)))
7514     return res;
7515
7516   /* Canonicalize sincos to cexpi.  */
7517   if (!TARGET_C99_FUNCTIONS)
7518     return NULL_TREE;
7519   fn = mathfn_built_in (type, BUILT_IN_CEXPI);
7520   if (!fn)
7521     return NULL_TREE;
7522
7523   call = build_call_expr_loc (loc, fn, 1, arg0);
7524   call = builtin_save_expr (call);
7525
7526   return build2 (COMPOUND_EXPR, void_type_node,
7527                  build2 (MODIFY_EXPR, void_type_node,
7528                          build_fold_indirect_ref_loc (loc, arg1),
7529                          build1 (IMAGPART_EXPR, type, call)),
7530                  build2 (MODIFY_EXPR, void_type_node,
7531                          build_fold_indirect_ref_loc (loc, arg2),
7532                          build1 (REALPART_EXPR, type, call)));
7533 }
7534
7535 /* Fold function call to builtin cexp, cexpf, or cexpl.  Return
7536    NULL_TREE if no simplification can be made.  */
7537
7538 static tree
7539 fold_builtin_cexp (location_t loc, tree arg0, tree type)
7540 {
7541   tree rtype;
7542   tree realp, imagp, ifn;
7543   tree res;
7544
7545   if (!validate_arg (arg0, COMPLEX_TYPE)
7546       || TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) != REAL_TYPE)
7547     return NULL_TREE;
7548
7549   /* Calculate the result when the argument is a constant.  */
7550   if ((res = do_mpc_arg1 (arg0, type, mpc_exp)))
7551     return res;
7552
7553   rtype = TREE_TYPE (TREE_TYPE (arg0));
7554
7555   /* In case we can figure out the real part of arg0 and it is constant zero
7556      fold to cexpi.  */
7557   if (!TARGET_C99_FUNCTIONS)
7558     return NULL_TREE;
7559   ifn = mathfn_built_in (rtype, BUILT_IN_CEXPI);
7560   if (!ifn)
7561     return NULL_TREE;
7562
7563   if ((realp = fold_unary_loc (loc, REALPART_EXPR, rtype, arg0))
7564       && real_zerop (realp))
7565     {
7566       tree narg = fold_build1_loc (loc, IMAGPART_EXPR, rtype, arg0);
7567       return build_call_expr_loc (loc, ifn, 1, narg);
7568     }
7569
7570   /* In case we can easily decompose real and imaginary parts split cexp
7571      to exp (r) * cexpi (i).  */
7572   if (flag_unsafe_math_optimizations
7573       && realp)
7574     {
7575       tree rfn, rcall, icall;
7576
7577       rfn = mathfn_built_in (rtype, BUILT_IN_EXP);
7578       if (!rfn)
7579         return NULL_TREE;
7580
7581       imagp = fold_unary_loc (loc, IMAGPART_EXPR, rtype, arg0);
7582       if (!imagp)
7583         return NULL_TREE;
7584
7585       icall = build_call_expr_loc (loc, ifn, 1, imagp);
7586       icall = builtin_save_expr (icall);
7587       rcall = build_call_expr_loc (loc, rfn, 1, realp);
7588       rcall = builtin_save_expr (rcall);
7589       return fold_build2_loc (loc, COMPLEX_EXPR, type,
7590                           fold_build2_loc (loc, MULT_EXPR, rtype,
7591                                        rcall,
7592                                        fold_build1_loc (loc, REALPART_EXPR,
7593                                                     rtype, icall)),
7594                           fold_build2_loc (loc, MULT_EXPR, rtype,
7595                                        rcall,
7596                                        fold_build1_loc (loc, IMAGPART_EXPR,
7597                                                     rtype, icall)));
7598     }
7599
7600   return NULL_TREE;
7601 }
7602
7603 /* Fold function call to builtin trunc, truncf or truncl with argument ARG.
7604    Return NULL_TREE if no simplification can be made.  */
7605
7606 static tree
7607 fold_builtin_trunc (location_t loc, tree fndecl, tree arg)
7608 {
7609   if (!validate_arg (arg, REAL_TYPE))
7610     return NULL_TREE;
7611
7612   /* Optimize trunc of constant value.  */
7613   if (TREE_CODE (arg) == REAL_CST && !TREE_OVERFLOW (arg))
7614     {
7615       REAL_VALUE_TYPE r, x;
7616       tree type = TREE_TYPE (TREE_TYPE (fndecl));
7617
7618       x = TREE_REAL_CST (arg);
7619       real_trunc (&r, TYPE_MODE (type), &x);
7620       return build_real (type, r);
7621     }
7622
7623   return fold_trunc_transparent_mathfn (loc, fndecl, arg);
7624 }
7625
7626 /* Fold function call to builtin floor, floorf or floorl with argument ARG.
7627    Return NULL_TREE if no simplification can be made.  */
7628
7629 static tree
7630 fold_builtin_floor (location_t loc, tree fndecl, tree arg)
7631 {
7632   if (!validate_arg (arg, REAL_TYPE))
7633     return NULL_TREE;
7634
7635   /* Optimize floor of constant value.  */
7636   if (TREE_CODE (arg) == REAL_CST && !TREE_OVERFLOW (arg))
7637     {
7638       REAL_VALUE_TYPE x;
7639
7640       x = TREE_REAL_CST (arg);
7641       if (! REAL_VALUE_ISNAN (x) || ! flag_errno_math)
7642         {
7643           tree type = TREE_TYPE (TREE_TYPE (fndecl));
7644           REAL_VALUE_TYPE r;
7645
7646           real_floor (&r, TYPE_MODE (type), &x);
7647           return build_real (type, r);
7648         }
7649     }
7650
7651   /* Fold floor (x) where x is nonnegative to trunc (x).  */
7652   if (tree_expr_nonnegative_p (arg))
7653     {
7654       tree truncfn = mathfn_built_in (TREE_TYPE (arg), BUILT_IN_TRUNC);
7655       if (truncfn)
7656         return build_call_expr_loc (loc, truncfn, 1, arg);
7657     }
7658
7659   return fold_trunc_transparent_mathfn (loc, fndecl, arg);
7660 }
7661
7662 /* Fold function call to builtin ceil, ceilf or ceill with argument ARG.
7663    Return NULL_TREE if no simplification can be made.  */
7664
7665 static tree
7666 fold_builtin_ceil (location_t loc, tree fndecl, tree arg)
7667 {
7668   if (!validate_arg (arg, REAL_TYPE))
7669     return NULL_TREE;
7670
7671   /* Optimize ceil of constant value.  */
7672   if (TREE_CODE (arg) == REAL_CST && !TREE_OVERFLOW (arg))
7673     {
7674       REAL_VALUE_TYPE x;
7675
7676       x = TREE_REAL_CST (arg);
7677       if (! REAL_VALUE_ISNAN (x) || ! flag_errno_math)
7678         {
7679           tree type = TREE_TYPE (TREE_TYPE (fndecl));
7680           REAL_VALUE_TYPE r;
7681
7682           real_ceil (&r, TYPE_MODE (type), &x);
7683           return build_real (type, r);
7684         }
7685     }
7686
7687   return fold_trunc_transparent_mathfn (loc, fndecl, arg);
7688 }
7689
7690 /* Fold function call to builtin round, roundf or roundl with argument ARG.
7691    Return NULL_TREE if no simplification can be made.  */
7692
7693 static tree
7694 fold_builtin_round (location_t loc, tree fndecl, tree arg)
7695 {
7696   if (!validate_arg (arg, REAL_TYPE))
7697     return NULL_TREE;
7698
7699   /* Optimize round of constant value.  */
7700   if (TREE_CODE (arg) == REAL_CST && !TREE_OVERFLOW (arg))
7701     {
7702       REAL_VALUE_TYPE x;
7703
7704       x = TREE_REAL_CST (arg);
7705       if (! REAL_VALUE_ISNAN (x) || ! flag_errno_math)
7706         {
7707           tree type = TREE_TYPE (TREE_TYPE (fndecl));
7708           REAL_VALUE_TYPE r;
7709
7710           real_round (&r, TYPE_MODE (type), &x);
7711           return build_real (type, r);
7712         }
7713     }
7714
7715   return fold_trunc_transparent_mathfn (loc, fndecl, arg);
7716 }
7717
7718 /* Fold function call to builtin lround, lroundf or lroundl (or the
7719    corresponding long long versions) and other rounding functions.  ARG
7720    is the argument to the call.  Return NULL_TREE if no simplification
7721    can be made.  */
7722
7723 static tree
7724 fold_builtin_int_roundingfn (location_t loc, tree fndecl, tree arg)
7725 {
7726   if (!validate_arg (arg, REAL_TYPE))
7727     return NULL_TREE;
7728
7729   /* Optimize lround of constant value.  */
7730   if (TREE_CODE (arg) == REAL_CST && !TREE_OVERFLOW (arg))
7731     {
7732       const REAL_VALUE_TYPE x = TREE_REAL_CST (arg);
7733
7734       if (real_isfinite (&x))
7735         {
7736           tree itype = TREE_TYPE (TREE_TYPE (fndecl));
7737           tree ftype = TREE_TYPE (arg);
7738           double_int val;
7739           REAL_VALUE_TYPE r;
7740
7741           switch (DECL_FUNCTION_CODE (fndecl))
7742             {
7743             CASE_FLT_FN (BUILT_IN_LFLOOR):
7744             CASE_FLT_FN (BUILT_IN_LLFLOOR):
7745               real_floor (&r, TYPE_MODE (ftype), &x);
7746               break;
7747
7748             CASE_FLT_FN (BUILT_IN_LCEIL):
7749             CASE_FLT_FN (BUILT_IN_LLCEIL):
7750               real_ceil (&r, TYPE_MODE (ftype), &x);
7751               break;
7752
7753             CASE_FLT_FN (BUILT_IN_LROUND):
7754             CASE_FLT_FN (BUILT_IN_LLROUND):
7755               real_round (&r, TYPE_MODE (ftype), &x);
7756               break;
7757
7758             default:
7759               gcc_unreachable ();
7760             }
7761
7762           real_to_integer2 ((HOST_WIDE_INT *)&val.low, &val.high, &r);
7763           if (double_int_fits_to_tree_p (itype, val))
7764             return double_int_to_tree (itype, val);
7765         }
7766     }
7767
7768   switch (DECL_FUNCTION_CODE (fndecl))
7769     {
7770     CASE_FLT_FN (BUILT_IN_LFLOOR):
7771     CASE_FLT_FN (BUILT_IN_LLFLOOR):
7772       /* Fold lfloor (x) where x is nonnegative to FIX_TRUNC (x).  */
7773       if (tree_expr_nonnegative_p (arg))
7774         return fold_build1_loc (loc, FIX_TRUNC_EXPR,
7775                             TREE_TYPE (TREE_TYPE (fndecl)), arg);
7776       break;
7777     default:;
7778     }
7779
7780   return fold_fixed_mathfn (loc, fndecl, arg);
7781 }
7782
7783 /* Fold function call to builtin ffs, clz, ctz, popcount and parity
7784    and their long and long long variants (i.e. ffsl and ffsll).  ARG is
7785    the argument to the call.  Return NULL_TREE if no simplification can
7786    be made.  */
7787
7788 static tree
7789 fold_builtin_bitop (tree fndecl, tree arg)
7790 {
7791   if (!validate_arg (arg, INTEGER_TYPE))
7792     return NULL_TREE;
7793
7794   /* Optimize for constant argument.  */
7795   if (TREE_CODE (arg) == INTEGER_CST && !TREE_OVERFLOW (arg))
7796     {
7797       HOST_WIDE_INT hi, width, result;
7798       unsigned HOST_WIDE_INT lo;
7799       tree type;
7800
7801       type = TREE_TYPE (arg);
7802       width = TYPE_PRECISION (type);
7803       lo = TREE_INT_CST_LOW (arg);
7804
7805       /* Clear all the bits that are beyond the type's precision.  */
7806       if (width > HOST_BITS_PER_WIDE_INT)
7807         {
7808           hi = TREE_INT_CST_HIGH (arg);
7809           if (width < 2 * HOST_BITS_PER_WIDE_INT)
7810             hi &= ~((HOST_WIDE_INT) (-1) >> (width - HOST_BITS_PER_WIDE_INT));
7811         }
7812       else
7813         {
7814           hi = 0;
7815           if (width < HOST_BITS_PER_WIDE_INT)
7816             lo &= ~((unsigned HOST_WIDE_INT) (-1) << width);
7817         }
7818
7819       switch (DECL_FUNCTION_CODE (fndecl))
7820         {
7821         CASE_INT_FN (BUILT_IN_FFS):
7822           if (lo != 0)
7823             result = ffs_hwi (lo);
7824           else if (hi != 0)
7825             result = HOST_BITS_PER_WIDE_INT + ffs_hwi (hi);
7826           else
7827             result = 0;
7828           break;
7829
7830         CASE_INT_FN (BUILT_IN_CLZ):
7831           if (hi != 0)
7832             result = width - floor_log2 (hi) - 1 - HOST_BITS_PER_WIDE_INT;
7833           else if (lo != 0)
7834             result = width - floor_log2 (lo) - 1;
7835           else if (! CLZ_DEFINED_VALUE_AT_ZERO (TYPE_MODE (type), result))
7836             result = width;
7837           break;
7838
7839         CASE_INT_FN (BUILT_IN_CTZ):
7840           if (lo != 0)
7841             result = ctz_hwi (lo);
7842           else if (hi != 0)
7843             result = HOST_BITS_PER_WIDE_INT + ctz_hwi (hi);
7844           else if (! CTZ_DEFINED_VALUE_AT_ZERO (TYPE_MODE (type), result))
7845             result = width;
7846           break;
7847
7848         CASE_INT_FN (BUILT_IN_POPCOUNT):
7849           result = 0;
7850           while (lo)
7851             result++, lo &= lo - 1;
7852           while (hi)
7853             result++, hi &= (unsigned HOST_WIDE_INT) hi - 1;
7854           break;
7855
7856         CASE_INT_FN (BUILT_IN_PARITY):
7857           result = 0;
7858           while (lo)
7859             result++, lo &= lo - 1;
7860           while (hi)
7861             result++, hi &= (unsigned HOST_WIDE_INT) hi - 1;
7862           result &= 1;
7863           break;
7864
7865         default:
7866           gcc_unreachable ();
7867         }
7868
7869       return build_int_cst (TREE_TYPE (TREE_TYPE (fndecl)), result);
7870     }
7871
7872   return NULL_TREE;
7873 }
7874
7875 /* Fold function call to builtin_bswap and the long and long long
7876    variants.  Return NULL_TREE if no simplification can be made.  */
7877 static tree
7878 fold_builtin_bswap (tree fndecl, tree arg)
7879 {
7880   if (! validate_arg (arg, INTEGER_TYPE))
7881     return NULL_TREE;
7882
7883   /* Optimize constant value.  */
7884   if (TREE_CODE (arg) == INTEGER_CST && !TREE_OVERFLOW (arg))
7885     {
7886       HOST_WIDE_INT hi, width, r_hi = 0;
7887       unsigned HOST_WIDE_INT lo, r_lo = 0;
7888       tree type;
7889
7890       type = TREE_TYPE (arg);
7891       width = TYPE_PRECISION (type);
7892       lo = TREE_INT_CST_LOW (arg);
7893       hi = TREE_INT_CST_HIGH (arg);
7894
7895       switch (DECL_FUNCTION_CODE (fndecl))
7896         {
7897           case BUILT_IN_BSWAP32:
7898           case BUILT_IN_BSWAP64:
7899             {
7900               int s;
7901
7902               for (s = 0; s < width; s += 8)
7903                 {
7904                   int d = width - s - 8;
7905                   unsigned HOST_WIDE_INT byte;
7906
7907                   if (s < HOST_BITS_PER_WIDE_INT)
7908                     byte = (lo >> s) & 0xff;
7909                   else
7910                     byte = (hi >> (s - HOST_BITS_PER_WIDE_INT)) & 0xff;
7911
7912                   if (d < HOST_BITS_PER_WIDE_INT)
7913                     r_lo |= byte << d;
7914                   else
7915                     r_hi |= byte << (d - HOST_BITS_PER_WIDE_INT);
7916                 }
7917             }
7918
7919             break;
7920
7921         default:
7922           gcc_unreachable ();
7923         }
7924
7925       if (width < HOST_BITS_PER_WIDE_INT)
7926         return build_int_cst (TREE_TYPE (TREE_TYPE (fndecl)), r_lo);
7927       else
7928         return build_int_cst_wide (TREE_TYPE (TREE_TYPE (fndecl)), r_lo, r_hi);
7929     }
7930
7931   return NULL_TREE;
7932 }
7933
7934 /* A subroutine of fold_builtin to fold the various logarithmic
7935    functions.  Return NULL_TREE if no simplification can me made.
7936    FUNC is the corresponding MPFR logarithm function.  */
7937
7938 static tree
7939 fold_builtin_logarithm (location_t loc, tree fndecl, tree arg,
7940                         int (*func)(mpfr_ptr, mpfr_srcptr, mp_rnd_t))
7941 {
7942   if (validate_arg (arg, REAL_TYPE))
7943     {
7944       tree type = TREE_TYPE (TREE_TYPE (fndecl));
7945       tree res;
7946       const enum built_in_function fcode = builtin_mathfn_code (arg);
7947
7948       /* Calculate the result when the argument is a constant.  */
7949       if ((res = do_mpfr_arg1 (arg, type, func, &dconst0, NULL, false)))
7950         return res;
7951
7952       /* Special case, optimize logN(expN(x)) = x.  */
7953       if (flag_unsafe_math_optimizations
7954           && ((func == mpfr_log
7955                && (fcode == BUILT_IN_EXP
7956                    || fcode == BUILT_IN_EXPF
7957                    || fcode == BUILT_IN_EXPL))
7958               || (func == mpfr_log2
7959                   && (fcode == BUILT_IN_EXP2
7960                       || fcode == BUILT_IN_EXP2F
7961                       || fcode == BUILT_IN_EXP2L))
7962               || (func == mpfr_log10 && (BUILTIN_EXP10_P (fcode)))))
7963         return fold_convert_loc (loc, type, CALL_EXPR_ARG (arg, 0));
7964
7965       /* Optimize logN(func()) for various exponential functions.  We
7966          want to determine the value "x" and the power "exponent" in
7967          order to transform logN(x**exponent) into exponent*logN(x).  */
7968       if (flag_unsafe_math_optimizations)
7969         {
7970           tree exponent = 0, x = 0;
7971
7972           switch (fcode)
7973           {
7974           CASE_FLT_FN (BUILT_IN_EXP):
7975             /* Prepare to do logN(exp(exponent) -> exponent*logN(e).  */
7976             x = build_real (type, real_value_truncate (TYPE_MODE (type),
7977                                                        dconst_e ()));
7978             exponent = CALL_EXPR_ARG (arg, 0);
7979             break;
7980           CASE_FLT_FN (BUILT_IN_EXP2):
7981             /* Prepare to do logN(exp2(exponent) -> exponent*logN(2).  */
7982             x = build_real (type, dconst2);
7983             exponent = CALL_EXPR_ARG (arg, 0);
7984             break;
7985           CASE_FLT_FN (BUILT_IN_EXP10):
7986           CASE_FLT_FN (BUILT_IN_POW10):
7987             /* Prepare to do logN(exp10(exponent) -> exponent*logN(10).  */
7988             {
7989               REAL_VALUE_TYPE dconst10;
7990               real_from_integer (&dconst10, VOIDmode, 10, 0, 0);
7991               x = build_real (type, dconst10);
7992             }
7993             exponent = CALL_EXPR_ARG (arg, 0);
7994             break;
7995           CASE_FLT_FN (BUILT_IN_SQRT):
7996             /* Prepare to do logN(sqrt(x) -> 0.5*logN(x).  */
7997             x = CALL_EXPR_ARG (arg, 0);
7998             exponent = build_real (type, dconsthalf);
7999             break;
8000           CASE_FLT_FN (BUILT_IN_CBRT):
8001             /* Prepare to do logN(cbrt(x) -> (1/3)*logN(x).  */
8002             x = CALL_EXPR_ARG (arg, 0);
8003             exponent = build_real (type, real_value_truncate (TYPE_MODE (type),
8004                                                               dconst_third ()));
8005             break;
8006           CASE_FLT_FN (BUILT_IN_POW):
8007             /* Prepare to do logN(pow(x,exponent) -> exponent*logN(x).  */
8008             x = CALL_EXPR_ARG (arg, 0);
8009             exponent = CALL_EXPR_ARG (arg, 1);
8010             break;
8011           default:
8012             break;
8013           }
8014
8015           /* Now perform the optimization.  */
8016           if (x && exponent)
8017             {
8018               tree logfn = build_call_expr_loc (loc, fndecl, 1, x);
8019               return fold_build2_loc (loc, MULT_EXPR, type, exponent, logfn);
8020             }
8021         }
8022     }
8023
8024   return NULL_TREE;
8025 }
8026
8027 /* Fold a builtin function call to hypot, hypotf, or hypotl.  Return
8028    NULL_TREE if no simplification can be made.  */
8029
8030 static tree
8031 fold_builtin_hypot (location_t loc, tree fndecl,
8032                     tree arg0, tree arg1, tree type)
8033 {
8034   tree res, narg0, narg1;
8035
8036   if (!validate_arg (arg0, REAL_TYPE)
8037       || !validate_arg (arg1, REAL_TYPE))
8038     return NULL_TREE;
8039
8040   /* Calculate the result when the argument is a constant.  */
8041   if ((res = do_mpfr_arg2 (arg0, arg1, type, mpfr_hypot)))
8042     return res;
8043
8044   /* If either argument to hypot has a negate or abs, strip that off.
8045      E.g. hypot(-x,fabs(y)) -> hypot(x,y).  */
8046   narg0 = fold_strip_sign_ops (arg0);
8047   narg1 = fold_strip_sign_ops (arg1);
8048   if (narg0 || narg1)
8049     {
8050       return build_call_expr_loc (loc, fndecl, 2, narg0 ? narg0 : arg0,
8051                               narg1 ? narg1 : arg1);
8052     }
8053
8054   /* If either argument is zero, hypot is fabs of the other.  */
8055   if (real_zerop (arg0))
8056     return fold_build1_loc (loc, ABS_EXPR, type, arg1);
8057   else if (real_zerop (arg1))
8058     return fold_build1_loc (loc, ABS_EXPR, type, arg0);
8059
8060   /* hypot(x,x) -> fabs(x)*sqrt(2).  */
8061   if (flag_unsafe_math_optimizations
8062       && operand_equal_p (arg0, arg1, OEP_PURE_SAME))
8063     {
8064       const REAL_VALUE_TYPE sqrt2_trunc
8065         = real_value_truncate (TYPE_MODE (type), dconst_sqrt2 ());
8066       return fold_build2_loc (loc, MULT_EXPR, type,
8067                           fold_build1_loc (loc, ABS_EXPR, type, arg0),
8068                           build_real (type, sqrt2_trunc));
8069     }
8070
8071   return NULL_TREE;
8072 }
8073
8074
8075 /* Fold a builtin function call to pow, powf, or powl.  Return
8076    NULL_TREE if no simplification can be made.  */
8077 static tree
8078 fold_builtin_pow (location_t loc, tree fndecl, tree arg0, tree arg1, tree type)
8079 {
8080   tree res;
8081
8082   if (!validate_arg (arg0, REAL_TYPE)
8083        || !validate_arg (arg1, REAL_TYPE))
8084     return NULL_TREE;
8085
8086   /* Calculate the result when the argument is a constant.  */
8087   if ((res = do_mpfr_arg2 (arg0, arg1, type, mpfr_pow)))
8088     return res;
8089
8090   /* Optimize pow(1.0,y) = 1.0.  */
8091   if (real_onep (arg0))
8092     return omit_one_operand_loc (loc, type, build_real (type, dconst1), arg1);
8093
8094   if (TREE_CODE (arg1) == REAL_CST
8095       && !TREE_OVERFLOW (arg1))
8096     {
8097       REAL_VALUE_TYPE cint;
8098       REAL_VALUE_TYPE c;
8099       HOST_WIDE_INT n;
8100
8101       c = TREE_REAL_CST (arg1);
8102
8103       /* Optimize pow(x,0.0) = 1.0.  */
8104       if (REAL_VALUES_EQUAL (c, dconst0))
8105         return omit_one_operand_loc (loc, type, build_real (type, dconst1),
8106                                  arg0);
8107
8108       /* Optimize pow(x,1.0) = x.  */
8109       if (REAL_VALUES_EQUAL (c, dconst1))
8110         return arg0;
8111
8112       /* Optimize pow(x,-1.0) = 1.0/x.  */
8113       if (REAL_VALUES_EQUAL (c, dconstm1))
8114         return fold_build2_loc (loc, RDIV_EXPR, type,
8115                             build_real (type, dconst1), arg0);
8116
8117       /* Optimize pow(x,0.5) = sqrt(x).  */
8118       if (flag_unsafe_math_optimizations
8119           && REAL_VALUES_EQUAL (c, dconsthalf))
8120         {
8121           tree sqrtfn = mathfn_built_in (type, BUILT_IN_SQRT);
8122
8123           if (sqrtfn != NULL_TREE)
8124             return build_call_expr_loc (loc, sqrtfn, 1, arg0);
8125         }
8126
8127       /* Optimize pow(x,1.0/3.0) = cbrt(x).  */
8128       if (flag_unsafe_math_optimizations)
8129         {
8130           const REAL_VALUE_TYPE dconstroot
8131             = real_value_truncate (TYPE_MODE (type), dconst_third ());
8132
8133           if (REAL_VALUES_EQUAL (c, dconstroot))
8134             {
8135               tree cbrtfn = mathfn_built_in (type, BUILT_IN_CBRT);
8136               if (cbrtfn != NULL_TREE)
8137                 return build_call_expr_loc (loc, cbrtfn, 1, arg0);
8138             }
8139         }
8140
8141       /* Check for an integer exponent.  */
8142       n = real_to_integer (&c);
8143       real_from_integer (&cint, VOIDmode, n, n < 0 ? -1 : 0, 0);
8144       if (real_identical (&c, &cint))
8145         {
8146           /* Attempt to evaluate pow at compile-time, unless this should
8147              raise an exception.  */
8148           if (TREE_CODE (arg0) == REAL_CST
8149               && !TREE_OVERFLOW (arg0)
8150               && (n > 0
8151                   || (!flag_trapping_math && !flag_errno_math)
8152                   || !REAL_VALUES_EQUAL (TREE_REAL_CST (arg0), dconst0)))
8153             {
8154               REAL_VALUE_TYPE x;
8155               bool inexact;
8156
8157               x = TREE_REAL_CST (arg0);
8158               inexact = real_powi (&x, TYPE_MODE (type), &x, n);
8159               if (flag_unsafe_math_optimizations || !inexact)
8160                 return build_real (type, x);
8161             }
8162
8163           /* Strip sign ops from even integer powers.  */
8164           if ((n & 1) == 0 && flag_unsafe_math_optimizations)
8165             {
8166               tree narg0 = fold_strip_sign_ops (arg0);
8167               if (narg0)
8168                 return build_call_expr_loc (loc, fndecl, 2, narg0, arg1);
8169             }
8170         }
8171     }
8172
8173   if (flag_unsafe_math_optimizations)
8174     {
8175       const enum built_in_function fcode = builtin_mathfn_code (arg0);
8176
8177       /* Optimize pow(expN(x),y) = expN(x*y).  */
8178       if (BUILTIN_EXPONENT_P (fcode))
8179         {
8180           tree expfn = TREE_OPERAND (CALL_EXPR_FN (arg0), 0);
8181           tree arg = CALL_EXPR_ARG (arg0, 0);
8182           arg = fold_build2_loc (loc, MULT_EXPR, type, arg, arg1);
8183           return build_call_expr_loc (loc, expfn, 1, arg);
8184         }
8185
8186       /* Optimize pow(sqrt(x),y) = pow(x,y*0.5).  */
8187       if (BUILTIN_SQRT_P (fcode))
8188         {
8189           tree narg0 = CALL_EXPR_ARG (arg0, 0);
8190           tree narg1 = fold_build2_loc (loc, MULT_EXPR, type, arg1,
8191                                     build_real (type, dconsthalf));
8192           return build_call_expr_loc (loc, fndecl, 2, narg0, narg1);
8193         }
8194
8195       /* Optimize pow(cbrt(x),y) = pow(x,y/3) iff x is nonnegative.  */
8196       if (BUILTIN_CBRT_P (fcode))
8197         {
8198           tree arg = CALL_EXPR_ARG (arg0, 0);
8199           if (tree_expr_nonnegative_p (arg))
8200             {
8201               const REAL_VALUE_TYPE dconstroot
8202                 = real_value_truncate (TYPE_MODE (type), dconst_third ());
8203               tree narg1 = fold_build2_loc (loc, MULT_EXPR, type, arg1,
8204                                         build_real (type, dconstroot));
8205               return build_call_expr_loc (loc, fndecl, 2, arg, narg1);
8206             }
8207         }
8208
8209       /* Optimize pow(pow(x,y),z) = pow(x,y*z) iff x is nonnegative.  */
8210       if (fcode == BUILT_IN_POW
8211           || fcode == BUILT_IN_POWF
8212           || fcode == BUILT_IN_POWL)
8213         {
8214           tree arg00 = CALL_EXPR_ARG (arg0, 0);
8215           if (tree_expr_nonnegative_p (arg00))
8216             {
8217               tree arg01 = CALL_EXPR_ARG (arg0, 1);
8218               tree narg1 = fold_build2_loc (loc, MULT_EXPR, type, arg01, arg1);
8219               return build_call_expr_loc (loc, fndecl, 2, arg00, narg1);
8220             }
8221         }
8222     }
8223
8224   return NULL_TREE;
8225 }
8226
8227 /* Fold a builtin function call to powi, powif, or powil with argument ARG.
8228    Return NULL_TREE if no simplification can be made.  */
8229 static tree
8230 fold_builtin_powi (location_t loc, tree fndecl ATTRIBUTE_UNUSED,
8231                    tree arg0, tree arg1, tree type)
8232 {
8233   if (!validate_arg (arg0, REAL_TYPE)
8234       || !validate_arg (arg1, INTEGER_TYPE))
8235     return NULL_TREE;
8236
8237   /* Optimize pow(1.0,y) = 1.0.  */
8238   if (real_onep (arg0))
8239     return omit_one_operand_loc (loc, type, build_real (type, dconst1), arg1);
8240
8241   if (host_integerp (arg1, 0))
8242     {
8243       HOST_WIDE_INT c = TREE_INT_CST_LOW (arg1);
8244
8245       /* Evaluate powi at compile-time.  */
8246       if (TREE_CODE (arg0) == REAL_CST
8247           && !TREE_OVERFLOW (arg0))
8248         {
8249           REAL_VALUE_TYPE x;
8250           x = TREE_REAL_CST (arg0);
8251           real_powi (&x, TYPE_MODE (type), &x, c);
8252           return build_real (type, x);
8253         }
8254
8255       /* Optimize pow(x,0) = 1.0.  */
8256       if (c == 0)
8257         return omit_one_operand_loc (loc, type, build_real (type, dconst1),
8258                                  arg0);
8259
8260       /* Optimize pow(x,1) = x.  */
8261       if (c == 1)
8262         return arg0;
8263
8264       /* Optimize pow(x,-1) = 1.0/x.  */
8265       if (c == -1)
8266         return fold_build2_loc (loc, RDIV_EXPR, type,
8267                            build_real (type, dconst1), arg0);
8268     }
8269
8270   return NULL_TREE;
8271 }
8272
8273 /* A subroutine of fold_builtin to fold the various exponent
8274    functions.  Return NULL_TREE if no simplification can be made.
8275    FUNC is the corresponding MPFR exponent function.  */
8276
8277 static tree
8278 fold_builtin_exponent (location_t loc, tree fndecl, tree arg,
8279                        int (*func)(mpfr_ptr, mpfr_srcptr, mp_rnd_t))
8280 {
8281   if (validate_arg (arg, REAL_TYPE))
8282     {
8283       tree type = TREE_TYPE (TREE_TYPE (fndecl));
8284       tree res;
8285
8286       /* Calculate the result when the argument is a constant.  */
8287       if ((res = do_mpfr_arg1 (arg, type, func, NULL, NULL, 0)))
8288         return res;
8289
8290       /* Optimize expN(logN(x)) = x.  */
8291       if (flag_unsafe_math_optimizations)
8292         {
8293           const enum built_in_function fcode = builtin_mathfn_code (arg);
8294
8295           if ((func == mpfr_exp
8296                && (fcode == BUILT_IN_LOG
8297                    || fcode == BUILT_IN_LOGF
8298                    || fcode == BUILT_IN_LOGL))
8299               || (func == mpfr_exp2
8300                   && (fcode == BUILT_IN_LOG2
8301                       || fcode == BUILT_IN_LOG2F
8302                       || fcode == BUILT_IN_LOG2L))
8303               || (func == mpfr_exp10
8304                   && (fcode == BUILT_IN_LOG10
8305                       || fcode == BUILT_IN_LOG10F
8306                       || fcode == BUILT_IN_LOG10L)))
8307             return fold_convert_loc (loc, type, CALL_EXPR_ARG (arg, 0));
8308         }
8309     }
8310
8311   return NULL_TREE;
8312 }
8313
8314 /* Return true if VAR is a VAR_DECL or a component thereof.  */
8315
8316 static bool
8317 var_decl_component_p (tree var)
8318 {
8319   tree inner = var;
8320   while (handled_component_p (inner))
8321     inner = TREE_OPERAND (inner, 0);
8322   return SSA_VAR_P (inner);
8323 }
8324
8325 /* Fold function call to builtin memset.  Return
8326    NULL_TREE if no simplification can be made.  */
8327
8328 static tree
8329 fold_builtin_memset (location_t loc, tree dest, tree c, tree len,
8330                      tree type, bool ignore)
8331 {
8332   tree var, ret, etype;
8333   unsigned HOST_WIDE_INT length, cval;
8334
8335   if (! validate_arg (dest, POINTER_TYPE)
8336       || ! validate_arg (c, INTEGER_TYPE)
8337       || ! validate_arg (len, INTEGER_TYPE))
8338     return NULL_TREE;
8339
8340   if (! host_integerp (len, 1))
8341     return NULL_TREE;
8342
8343   /* If the LEN parameter is zero, return DEST.  */
8344   if (integer_zerop (len))
8345     return omit_one_operand_loc (loc, type, dest, c);
8346
8347   if (TREE_CODE (c) != INTEGER_CST || TREE_SIDE_EFFECTS (dest))
8348     return NULL_TREE;
8349
8350   var = dest;
8351   STRIP_NOPS (var);
8352   if (TREE_CODE (var) != ADDR_EXPR)
8353     return NULL_TREE;
8354
8355   var = TREE_OPERAND (var, 0);
8356   if (TREE_THIS_VOLATILE (var))
8357     return NULL_TREE;
8358
8359   etype = TREE_TYPE (var);
8360   if (TREE_CODE (etype) == ARRAY_TYPE)
8361     etype = TREE_TYPE (etype);
8362
8363   if (!INTEGRAL_TYPE_P (etype)
8364       && !POINTER_TYPE_P (etype))
8365     return NULL_TREE;
8366
8367   if (! var_decl_component_p (var))
8368     return NULL_TREE;
8369
8370   length = tree_low_cst (len, 1);
8371   if (GET_MODE_SIZE (TYPE_MODE (etype)) != length
8372       || get_pointer_alignment (dest, BIGGEST_ALIGNMENT) / BITS_PER_UNIT
8373          < length)
8374     return NULL_TREE;
8375
8376   if (length > HOST_BITS_PER_WIDE_INT / BITS_PER_UNIT)
8377     return NULL_TREE;
8378
8379   if (integer_zerop (c))
8380     cval = 0;
8381   else
8382     {
8383       if (CHAR_BIT != 8 || BITS_PER_UNIT != 8 || HOST_BITS_PER_WIDE_INT > 64)
8384         return NULL_TREE;
8385
8386       cval = TREE_INT_CST_LOW (c);
8387       cval &= 0xff;
8388       cval |= cval << 8;
8389       cval |= cval << 16;
8390       cval |= (cval << 31) << 1;
8391     }
8392
8393   ret = build_int_cst_type (etype, cval);
8394   var = build_fold_indirect_ref_loc (loc,
8395                                  fold_convert_loc (loc,
8396                                                    build_pointer_type (etype),
8397                                                    dest));
8398   ret = build2 (MODIFY_EXPR, etype, var, ret);
8399   if (ignore)
8400     return ret;
8401
8402   return omit_one_operand_loc (loc, type, dest, ret);
8403 }
8404
8405 /* Fold function call to builtin memset.  Return
8406    NULL_TREE if no simplification can be made.  */
8407
8408 static tree
8409 fold_builtin_bzero (location_t loc, tree dest, tree size, bool ignore)
8410 {
8411   if (! validate_arg (dest, POINTER_TYPE)
8412       || ! validate_arg (size, INTEGER_TYPE))
8413     return NULL_TREE;
8414
8415   if (!ignore)
8416     return NULL_TREE;
8417
8418   /* New argument list transforming bzero(ptr x, int y) to
8419      memset(ptr x, int 0, size_t y).   This is done this way
8420      so that if it isn't expanded inline, we fallback to
8421      calling bzero instead of memset.  */
8422
8423   return fold_builtin_memset (loc, dest, integer_zero_node,
8424                               fold_convert_loc (loc, sizetype, size),
8425                               void_type_node, ignore);
8426 }
8427
8428 /* Fold function call to builtin mem{{,p}cpy,move}.  Return
8429    NULL_TREE if no simplification can be made.
8430    If ENDP is 0, return DEST (like memcpy).
8431    If ENDP is 1, return DEST+LEN (like mempcpy).
8432    If ENDP is 2, return DEST+LEN-1 (like stpcpy).
8433    If ENDP is 3, return DEST, additionally *SRC and *DEST may overlap
8434    (memmove).   */
8435
8436 static tree
8437 fold_builtin_memory_op (location_t loc, tree dest, tree src,
8438                         tree len, tree type, bool ignore, int endp)
8439 {
8440   tree destvar, srcvar, expr;
8441
8442   if (! validate_arg (dest, POINTER_TYPE)
8443       || ! validate_arg (src, POINTER_TYPE)
8444       || ! validate_arg (len, INTEGER_TYPE))
8445     return NULL_TREE;
8446
8447   /* If the LEN parameter is zero, return DEST.  */
8448   if (integer_zerop (len))
8449     return omit_one_operand_loc (loc, type, dest, src);
8450
8451   /* If SRC and DEST are the same (and not volatile), return
8452      DEST{,+LEN,+LEN-1}.  */
8453   if (operand_equal_p (src, dest, 0))
8454     expr = len;
8455   else
8456     {
8457       tree srctype, desttype;
8458       unsigned int src_align, dest_align;
8459       tree off0;
8460
8461       if (endp == 3)
8462         {
8463           src_align = get_pointer_alignment (src, BIGGEST_ALIGNMENT);
8464           dest_align = get_pointer_alignment (dest, BIGGEST_ALIGNMENT);
8465
8466           /* Both DEST and SRC must be pointer types.
8467              ??? This is what old code did.  Is the testing for pointer types
8468              really mandatory?
8469
8470              If either SRC is readonly or length is 1, we can use memcpy.  */
8471           if (!dest_align || !src_align)
8472             return NULL_TREE;
8473           if (readonly_data_expr (src)
8474               || (host_integerp (len, 1)
8475                   && (MIN (src_align, dest_align) / BITS_PER_UNIT
8476                       >= (unsigned HOST_WIDE_INT) tree_low_cst (len, 1))))
8477             {
8478               tree fn = implicit_built_in_decls[BUILT_IN_MEMCPY];
8479               if (!fn)
8480                 return NULL_TREE;
8481               return build_call_expr_loc (loc, fn, 3, dest, src, len);
8482             }
8483
8484           /* If *src and *dest can't overlap, optimize into memcpy as well.  */
8485           if (TREE_CODE (src) == ADDR_EXPR
8486               && TREE_CODE (dest) == ADDR_EXPR)
8487             {
8488               tree src_base, dest_base, fn;
8489               HOST_WIDE_INT src_offset = 0, dest_offset = 0;
8490               HOST_WIDE_INT size = -1;
8491               HOST_WIDE_INT maxsize = -1;
8492
8493               srcvar = TREE_OPERAND (src, 0);
8494               src_base = get_ref_base_and_extent (srcvar, &src_offset,
8495                                                   &size, &maxsize);
8496               destvar = TREE_OPERAND (dest, 0);
8497               dest_base = get_ref_base_and_extent (destvar, &dest_offset,
8498                                                    &size, &maxsize);
8499               if (host_integerp (len, 1))
8500                 maxsize = tree_low_cst (len, 1);
8501               else
8502                 maxsize = -1;
8503               src_offset /= BITS_PER_UNIT;
8504               dest_offset /= BITS_PER_UNIT;
8505               if (SSA_VAR_P (src_base)
8506                   && SSA_VAR_P (dest_base))
8507                 {
8508                   if (operand_equal_p (src_base, dest_base, 0)
8509                       && ranges_overlap_p (src_offset, maxsize,
8510                                            dest_offset, maxsize))
8511                     return NULL_TREE;
8512                 }
8513               else if (TREE_CODE (src_base) == MEM_REF
8514                        && TREE_CODE (dest_base) == MEM_REF)
8515                 {
8516                   double_int off;
8517                   if (! operand_equal_p (TREE_OPERAND (src_base, 0),
8518                                          TREE_OPERAND (dest_base, 0), 0))
8519                     return NULL_TREE;
8520                   off = double_int_add (mem_ref_offset (src_base),
8521                                         shwi_to_double_int (src_offset));
8522                   if (!double_int_fits_in_shwi_p (off))
8523                     return NULL_TREE;
8524                   src_offset = off.low;
8525                   off = double_int_add (mem_ref_offset (dest_base),
8526                                         shwi_to_double_int (dest_offset));
8527                   if (!double_int_fits_in_shwi_p (off))
8528                     return NULL_TREE;
8529                   dest_offset = off.low;
8530                   if (ranges_overlap_p (src_offset, maxsize,
8531                                         dest_offset, maxsize))
8532                     return NULL_TREE;
8533                 }
8534               else
8535                 return NULL_TREE;
8536
8537               fn = implicit_built_in_decls[BUILT_IN_MEMCPY];
8538               if (!fn)
8539                 return NULL_TREE;
8540               return build_call_expr_loc (loc, fn, 3, dest, src, len);
8541             }
8542
8543           /* If the destination and source do not alias optimize into
8544              memcpy as well.  */
8545           if ((is_gimple_min_invariant (dest)
8546                || TREE_CODE (dest) == SSA_NAME)
8547               && (is_gimple_min_invariant (src)
8548                   || TREE_CODE (src) == SSA_NAME))
8549             {
8550               ao_ref destr, srcr;
8551               ao_ref_init_from_ptr_and_size (&destr, dest, len);
8552               ao_ref_init_from_ptr_and_size (&srcr, src, len);
8553               if (!refs_may_alias_p_1 (&destr, &srcr, false))
8554                 {
8555                   tree fn;
8556                   fn = implicit_built_in_decls[BUILT_IN_MEMCPY];
8557                   if (!fn)
8558                     return NULL_TREE;
8559                   return build_call_expr_loc (loc, fn, 3, dest, src, len);
8560                 }
8561             }
8562
8563           return NULL_TREE;
8564         }
8565
8566       if (!host_integerp (len, 0))
8567         return NULL_TREE;
8568       /* FIXME:
8569          This logic lose for arguments like (type *)malloc (sizeof (type)),
8570          since we strip the casts of up to VOID return value from malloc.
8571          Perhaps we ought to inherit type from non-VOID argument here?  */
8572       STRIP_NOPS (src);
8573       STRIP_NOPS (dest);
8574       /* As we fold (void *)(p + CST) to (void *)p + CST undo this here.  */
8575       if (TREE_CODE (src) == POINTER_PLUS_EXPR)
8576         {
8577           tree tem = TREE_OPERAND (src, 0);
8578           STRIP_NOPS (tem);
8579           if (tem != TREE_OPERAND (src, 0))
8580             src = build1 (NOP_EXPR, TREE_TYPE (tem), src);
8581         }
8582       if (TREE_CODE (dest) == POINTER_PLUS_EXPR)
8583         {
8584           tree tem = TREE_OPERAND (dest, 0);
8585           STRIP_NOPS (tem);
8586           if (tem != TREE_OPERAND (dest, 0))
8587             dest = build1 (NOP_EXPR, TREE_TYPE (tem), dest);
8588         }
8589       srctype = TREE_TYPE (TREE_TYPE (src));
8590       if (srctype
8591           && TREE_CODE (srctype) == ARRAY_TYPE
8592           && !tree_int_cst_equal (TYPE_SIZE_UNIT (srctype), len))
8593         {
8594           srctype = TREE_TYPE (srctype);
8595           STRIP_NOPS (src);
8596           src = build1 (NOP_EXPR, build_pointer_type (srctype), src);
8597         }
8598       desttype = TREE_TYPE (TREE_TYPE (dest));
8599       if (desttype
8600           && TREE_CODE (desttype) == ARRAY_TYPE
8601           && !tree_int_cst_equal (TYPE_SIZE_UNIT (desttype), len))
8602         {
8603           desttype = TREE_TYPE (desttype);
8604           STRIP_NOPS (dest);
8605           dest = build1 (NOP_EXPR, build_pointer_type (desttype), dest);
8606         }
8607       if (!srctype || !desttype
8608           || TREE_ADDRESSABLE (srctype)
8609           || TREE_ADDRESSABLE (desttype)
8610           || !TYPE_SIZE_UNIT (srctype)
8611           || !TYPE_SIZE_UNIT (desttype)
8612           || TREE_CODE (TYPE_SIZE_UNIT (srctype)) != INTEGER_CST
8613           || TREE_CODE (TYPE_SIZE_UNIT (desttype)) != INTEGER_CST)
8614         return NULL_TREE;
8615
8616       src_align = get_pointer_alignment (src, BIGGEST_ALIGNMENT);
8617       dest_align = get_pointer_alignment (dest, BIGGEST_ALIGNMENT);
8618       if (dest_align < TYPE_ALIGN (desttype)
8619           || src_align < TYPE_ALIGN (srctype))
8620         return NULL_TREE;
8621
8622       if (!ignore)
8623         dest = builtin_save_expr (dest);
8624
8625       /* Build accesses at offset zero with a ref-all character type.  */
8626       off0 = build_int_cst (build_pointer_type_for_mode (char_type_node,
8627                                                          ptr_mode, true), 0);
8628
8629       destvar = dest;
8630       STRIP_NOPS (destvar);
8631       if (TREE_CODE (destvar) == ADDR_EXPR
8632           && var_decl_component_p (TREE_OPERAND (destvar, 0))
8633           && tree_int_cst_equal (TYPE_SIZE_UNIT (desttype), len))
8634         destvar = fold_build2 (MEM_REF, desttype, destvar, off0);
8635       else
8636         destvar = NULL_TREE;
8637
8638       srcvar = src;
8639       STRIP_NOPS (srcvar);
8640       if (TREE_CODE (srcvar) == ADDR_EXPR
8641           && var_decl_component_p (TREE_OPERAND (srcvar, 0))
8642           && tree_int_cst_equal (TYPE_SIZE_UNIT (srctype), len))
8643         {
8644           if (!destvar
8645               || src_align >= TYPE_ALIGN (desttype))
8646             srcvar = fold_build2 (MEM_REF, destvar ? desttype : srctype,
8647                                   srcvar, off0);
8648           else if (!STRICT_ALIGNMENT)
8649             {
8650               srctype = build_aligned_type (TYPE_MAIN_VARIANT (desttype),
8651                                             src_align);
8652               srcvar = fold_build2 (MEM_REF, srctype, srcvar, off0);
8653             }
8654           else
8655             srcvar = NULL_TREE;
8656         }
8657       else
8658         srcvar = NULL_TREE;
8659
8660       if (srcvar == NULL_TREE && destvar == NULL_TREE)
8661         return NULL_TREE;
8662
8663       if (srcvar == NULL_TREE)
8664         {
8665           STRIP_NOPS (src);
8666           if (src_align >= TYPE_ALIGN (desttype))
8667             srcvar = fold_build2 (MEM_REF, desttype, src, off0);
8668           else
8669             {
8670               if (STRICT_ALIGNMENT)
8671                 return NULL_TREE;
8672               srctype = build_aligned_type (TYPE_MAIN_VARIANT (desttype),
8673                                             src_align);
8674               srcvar = fold_build2 (MEM_REF, srctype, src, off0);
8675             }
8676         }
8677       else if (destvar == NULL_TREE)
8678         {
8679           STRIP_NOPS (dest);
8680           if (dest_align >= TYPE_ALIGN (srctype))
8681             destvar = fold_build2 (MEM_REF, srctype, dest, off0);
8682           else
8683             {
8684               if (STRICT_ALIGNMENT)
8685                 return NULL_TREE;
8686               desttype = build_aligned_type (TYPE_MAIN_VARIANT (srctype),
8687                                              dest_align);
8688               destvar = fold_build2 (MEM_REF, desttype, dest, off0);
8689             }
8690         }
8691
8692       expr = build2 (MODIFY_EXPR, TREE_TYPE (destvar), destvar, srcvar);
8693     }
8694
8695   if (ignore)
8696     return expr;
8697
8698   if (endp == 0 || endp == 3)
8699     return omit_one_operand_loc (loc, type, dest, expr);
8700
8701   if (expr == len)
8702     expr = NULL_TREE;
8703
8704   if (endp == 2)
8705     len = fold_build2_loc (loc, MINUS_EXPR, TREE_TYPE (len), len,
8706                        ssize_int (1));
8707
8708   len = fold_convert_loc (loc, sizetype, len);
8709   dest = fold_build2_loc (loc, POINTER_PLUS_EXPR, TREE_TYPE (dest), dest, len);
8710   dest = fold_convert_loc (loc, type, dest);
8711   if (expr)
8712     dest = omit_one_operand_loc (loc, type, dest, expr);
8713   return dest;
8714 }
8715
8716 /* Fold function call to builtin strcpy with arguments DEST and SRC.
8717    If LEN is not NULL, it represents the length of the string to be
8718    copied.  Return NULL_TREE if no simplification can be made.  */
8719
8720 tree
8721 fold_builtin_strcpy (location_t loc, tree fndecl, tree dest, tree src, tree len)
8722 {
8723   tree fn;
8724
8725   if (!validate_arg (dest, POINTER_TYPE)
8726       || !validate_arg (src, POINTER_TYPE))
8727     return NULL_TREE;
8728
8729   /* If SRC and DEST are the same (and not volatile), return DEST.  */
8730   if (operand_equal_p (src, dest, 0))
8731     return fold_convert_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)), dest);
8732
8733   if (optimize_function_for_size_p (cfun))
8734     return NULL_TREE;
8735
8736   fn = implicit_built_in_decls[BUILT_IN_MEMCPY];
8737   if (!fn)
8738     return NULL_TREE;
8739
8740   if (!len)
8741     {
8742       len = c_strlen (src, 1);
8743       if (! len || TREE_SIDE_EFFECTS (len))
8744         return NULL_TREE;
8745     }
8746
8747   len = size_binop_loc (loc, PLUS_EXPR, len, ssize_int (1));
8748   return fold_convert_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)),
8749                            build_call_expr_loc (loc, fn, 3, dest, src, len));
8750 }
8751
8752 /* Fold function call to builtin stpcpy with arguments DEST and SRC.
8753    Return NULL_TREE if no simplification can be made.  */
8754
8755 static tree
8756 fold_builtin_stpcpy (location_t loc, tree fndecl, tree dest, tree src)
8757 {
8758   tree fn, len, lenp1, call, type;
8759
8760   if (!validate_arg (dest, POINTER_TYPE)
8761       || !validate_arg (src, POINTER_TYPE))
8762     return NULL_TREE;
8763
8764   len = c_strlen (src, 1);
8765   if (!len
8766       || TREE_CODE (len) != INTEGER_CST)
8767     return NULL_TREE;
8768
8769   if (optimize_function_for_size_p (cfun)
8770       /* If length is zero it's small enough.  */
8771       && !integer_zerop (len))
8772     return NULL_TREE;
8773
8774   fn = implicit_built_in_decls[BUILT_IN_MEMCPY];
8775   if (!fn)
8776     return NULL_TREE;
8777
8778   lenp1 = size_binop_loc (loc, PLUS_EXPR, len, ssize_int (1));
8779   /* We use dest twice in building our expression.  Save it from
8780      multiple expansions.  */
8781   dest = builtin_save_expr (dest);
8782   call = build_call_expr_loc (loc, fn, 3, dest, src, lenp1);
8783
8784   type = TREE_TYPE (TREE_TYPE (fndecl));
8785   len = fold_convert_loc (loc, sizetype, len);
8786   dest = fold_build2_loc (loc, POINTER_PLUS_EXPR, TREE_TYPE (dest), dest, len);
8787   dest = fold_convert_loc (loc, type, dest);
8788   dest = omit_one_operand_loc (loc, type, dest, call);
8789   return dest;
8790 }
8791
8792 /* Fold function call to builtin strncpy with arguments DEST, SRC, and LEN.
8793    If SLEN is not NULL, it represents the length of the source string.
8794    Return NULL_TREE if no simplification can be made.  */
8795
8796 tree
8797 fold_builtin_strncpy (location_t loc, tree fndecl, tree dest,
8798                       tree src, tree len, tree slen)
8799 {
8800   tree fn;
8801
8802   if (!validate_arg (dest, POINTER_TYPE)
8803       || !validate_arg (src, POINTER_TYPE)
8804       || !validate_arg (len, INTEGER_TYPE))
8805     return NULL_TREE;
8806
8807   /* If the LEN parameter is zero, return DEST.  */
8808   if (integer_zerop (len))
8809     return omit_one_operand_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)), dest, src);
8810
8811   /* We can't compare slen with len as constants below if len is not a
8812      constant.  */
8813   if (len == 0 || TREE_CODE (len) != INTEGER_CST)
8814     return NULL_TREE;
8815
8816   if (!slen)
8817     slen = c_strlen (src, 1);
8818
8819   /* Now, we must be passed a constant src ptr parameter.  */
8820   if (slen == 0 || TREE_CODE (slen) != INTEGER_CST)
8821     return NULL_TREE;
8822
8823   slen = size_binop_loc (loc, PLUS_EXPR, slen, ssize_int (1));
8824
8825   /* We do not support simplification of this case, though we do
8826      support it when expanding trees into RTL.  */
8827   /* FIXME: generate a call to __builtin_memset.  */
8828   if (tree_int_cst_lt (slen, len))
8829     return NULL_TREE;
8830
8831   /* OK transform into builtin memcpy.  */
8832   fn = implicit_built_in_decls[BUILT_IN_MEMCPY];
8833   if (!fn)
8834     return NULL_TREE;
8835   return fold_convert_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)),
8836                            build_call_expr_loc (loc, fn, 3, dest, src, len));
8837 }
8838
8839 /* Fold function call to builtin memchr.  ARG1, ARG2 and LEN are the
8840    arguments to the call, and TYPE is its return type.
8841    Return NULL_TREE if no simplification can be made.  */
8842
8843 static tree
8844 fold_builtin_memchr (location_t loc, tree arg1, tree arg2, tree len, tree type)
8845 {
8846   if (!validate_arg (arg1, POINTER_TYPE)
8847       || !validate_arg (arg2, INTEGER_TYPE)
8848       || !validate_arg (len, INTEGER_TYPE))
8849     return NULL_TREE;
8850   else
8851     {
8852       const char *p1;
8853
8854       if (TREE_CODE (arg2) != INTEGER_CST
8855           || !host_integerp (len, 1))
8856         return NULL_TREE;
8857
8858       p1 = c_getstr (arg1);
8859       if (p1 && compare_tree_int (len, strlen (p1) + 1) <= 0)
8860         {
8861           char c;
8862           const char *r;
8863           tree tem;
8864
8865           if (target_char_cast (arg2, &c))
8866             return NULL_TREE;
8867
8868           r = (char *) memchr (p1, c, tree_low_cst (len, 1));
8869
8870           if (r == NULL)
8871             return build_int_cst (TREE_TYPE (arg1), 0);
8872
8873           tem = fold_build2_loc (loc, POINTER_PLUS_EXPR, TREE_TYPE (arg1), arg1,
8874                              size_int (r - p1));
8875           return fold_convert_loc (loc, type, tem);
8876         }
8877       return NULL_TREE;
8878     }
8879 }
8880
8881 /* Fold function call to builtin memcmp with arguments ARG1 and ARG2.
8882    Return NULL_TREE if no simplification can be made.  */
8883
8884 static tree
8885 fold_builtin_memcmp (location_t loc, tree arg1, tree arg2, tree len)
8886 {
8887   const char *p1, *p2;
8888
8889   if (!validate_arg (arg1, POINTER_TYPE)
8890       || !validate_arg (arg2, POINTER_TYPE)
8891       || !validate_arg (len, INTEGER_TYPE))
8892     return NULL_TREE;
8893
8894   /* If the LEN parameter is zero, return zero.  */
8895   if (integer_zerop (len))
8896     return omit_two_operands_loc (loc, integer_type_node, integer_zero_node,
8897                               arg1, arg2);
8898
8899   /* If ARG1 and ARG2 are the same (and not volatile), return zero.  */
8900   if (operand_equal_p (arg1, arg2, 0))
8901     return omit_one_operand_loc (loc, integer_type_node, integer_zero_node, len);
8902
8903   p1 = c_getstr (arg1);
8904   p2 = c_getstr (arg2);
8905
8906   /* If all arguments are constant, and the value of len is not greater
8907      than the lengths of arg1 and arg2, evaluate at compile-time.  */
8908   if (host_integerp (len, 1) && p1 && p2
8909       && compare_tree_int (len, strlen (p1) + 1) <= 0
8910       && compare_tree_int (len, strlen (p2) + 1) <= 0)
8911     {
8912       const int r = memcmp (p1, p2, tree_low_cst (len, 1));
8913
8914       if (r > 0)
8915         return integer_one_node;
8916       else if (r < 0)
8917         return integer_minus_one_node;
8918       else
8919         return integer_zero_node;
8920     }
8921
8922   /* If len parameter is one, return an expression corresponding to
8923      (*(const unsigned char*)arg1 - (const unsigned char*)arg2).  */
8924   if (host_integerp (len, 1) && tree_low_cst (len, 1) == 1)
8925     {
8926       tree cst_uchar_node = build_type_variant (unsigned_char_type_node, 1, 0);
8927       tree cst_uchar_ptr_node
8928         = build_pointer_type_for_mode (cst_uchar_node, ptr_mode, true);
8929
8930       tree ind1
8931         = fold_convert_loc (loc, integer_type_node,
8932                             build1 (INDIRECT_REF, cst_uchar_node,
8933                                     fold_convert_loc (loc,
8934                                                       cst_uchar_ptr_node,
8935                                                       arg1)));
8936       tree ind2
8937         = fold_convert_loc (loc, integer_type_node,
8938                             build1 (INDIRECT_REF, cst_uchar_node,
8939                                     fold_convert_loc (loc,
8940                                                       cst_uchar_ptr_node,
8941                                                       arg2)));
8942       return fold_build2_loc (loc, MINUS_EXPR, integer_type_node, ind1, ind2);
8943     }
8944
8945   return NULL_TREE;
8946 }
8947
8948 /* Fold function call to builtin strcmp with arguments ARG1 and ARG2.
8949    Return NULL_TREE if no simplification can be made.  */
8950
8951 static tree
8952 fold_builtin_strcmp (location_t loc, tree arg1, tree arg2)
8953 {
8954   const char *p1, *p2;
8955
8956   if (!validate_arg (arg1, POINTER_TYPE)
8957       || !validate_arg (arg2, POINTER_TYPE))
8958     return NULL_TREE;
8959
8960   /* If ARG1 and ARG2 are the same (and not volatile), return zero.  */
8961   if (operand_equal_p (arg1, arg2, 0))
8962     return integer_zero_node;
8963
8964   p1 = c_getstr (arg1);
8965   p2 = c_getstr (arg2);
8966
8967   if (p1 && p2)
8968     {
8969       const int i = strcmp (p1, p2);
8970       if (i < 0)
8971         return integer_minus_one_node;
8972       else if (i > 0)
8973         return integer_one_node;
8974       else
8975         return integer_zero_node;
8976     }
8977
8978   /* If the second arg is "", return *(const unsigned char*)arg1.  */
8979   if (p2 && *p2 == '\0')
8980     {
8981       tree cst_uchar_node = build_type_variant (unsigned_char_type_node, 1, 0);
8982       tree cst_uchar_ptr_node
8983         = build_pointer_type_for_mode (cst_uchar_node, ptr_mode, true);
8984
8985       return fold_convert_loc (loc, integer_type_node,
8986                                build1 (INDIRECT_REF, cst_uchar_node,
8987                                        fold_convert_loc (loc,
8988                                                          cst_uchar_ptr_node,
8989                                                          arg1)));
8990     }
8991
8992   /* If the first arg is "", return -*(const unsigned char*)arg2.  */
8993   if (p1 && *p1 == '\0')
8994     {
8995       tree cst_uchar_node = build_type_variant (unsigned_char_type_node, 1, 0);
8996       tree cst_uchar_ptr_node
8997         = build_pointer_type_for_mode (cst_uchar_node, ptr_mode, true);
8998
8999       tree temp
9000         = fold_convert_loc (loc, integer_type_node,
9001                             build1 (INDIRECT_REF, cst_uchar_node,
9002                                     fold_convert_loc (loc,
9003                                                       cst_uchar_ptr_node,
9004                                                       arg2)));
9005       return fold_build1_loc (loc, NEGATE_EXPR, integer_type_node, temp);
9006     }
9007
9008   return NULL_TREE;
9009 }
9010
9011 /* Fold function call to builtin strncmp with arguments ARG1, ARG2, and LEN.
9012    Return NULL_TREE if no simplification can be made.  */
9013
9014 static tree
9015 fold_builtin_strncmp (location_t loc, tree arg1, tree arg2, tree len)
9016 {
9017   const char *p1, *p2;
9018
9019   if (!validate_arg (arg1, POINTER_TYPE)
9020       || !validate_arg (arg2, POINTER_TYPE)
9021       || !validate_arg (len, INTEGER_TYPE))
9022     return NULL_TREE;
9023
9024   /* If the LEN parameter is zero, return zero.  */
9025   if (integer_zerop (len))
9026     return omit_two_operands_loc (loc, integer_type_node, integer_zero_node,
9027                               arg1, arg2);
9028
9029   /* If ARG1 and ARG2 are the same (and not volatile), return zero.  */
9030   if (operand_equal_p (arg1, arg2, 0))
9031     return omit_one_operand_loc (loc, integer_type_node, integer_zero_node, len);
9032
9033   p1 = c_getstr (arg1);
9034   p2 = c_getstr (arg2);
9035
9036   if (host_integerp (len, 1) && p1 && p2)
9037     {
9038       const int i = strncmp (p1, p2, tree_low_cst (len, 1));
9039       if (i > 0)
9040         return integer_one_node;
9041       else if (i < 0)
9042         return integer_minus_one_node;
9043       else
9044         return integer_zero_node;
9045     }
9046
9047   /* If the second arg is "", and the length is greater than zero,
9048      return *(const unsigned char*)arg1.  */
9049   if (p2 && *p2 == '\0'
9050       && TREE_CODE (len) == INTEGER_CST
9051       && tree_int_cst_sgn (len) == 1)
9052     {
9053       tree cst_uchar_node = build_type_variant (unsigned_char_type_node, 1, 0);
9054       tree cst_uchar_ptr_node
9055         = build_pointer_type_for_mode (cst_uchar_node, ptr_mode, true);
9056
9057       return fold_convert_loc (loc, integer_type_node,
9058                                build1 (INDIRECT_REF, cst_uchar_node,
9059                                        fold_convert_loc (loc,
9060                                                          cst_uchar_ptr_node,
9061                                                          arg1)));
9062     }
9063
9064   /* If the first arg is "", and the length is greater than zero,
9065      return -*(const unsigned char*)arg2.  */
9066   if (p1 && *p1 == '\0'
9067       && TREE_CODE (len) == INTEGER_CST
9068       && tree_int_cst_sgn (len) == 1)
9069     {
9070       tree cst_uchar_node = build_type_variant (unsigned_char_type_node, 1, 0);
9071       tree cst_uchar_ptr_node
9072         = build_pointer_type_for_mode (cst_uchar_node, ptr_mode, true);
9073
9074       tree temp = fold_convert_loc (loc, integer_type_node,
9075                                     build1 (INDIRECT_REF, cst_uchar_node,
9076                                             fold_convert_loc (loc,
9077                                                               cst_uchar_ptr_node,
9078                                                               arg2)));
9079       return fold_build1_loc (loc, NEGATE_EXPR, integer_type_node, temp);
9080     }
9081
9082   /* If len parameter is one, return an expression corresponding to
9083      (*(const unsigned char*)arg1 - (const unsigned char*)arg2).  */
9084   if (host_integerp (len, 1) && tree_low_cst (len, 1) == 1)
9085     {
9086       tree cst_uchar_node = build_type_variant (unsigned_char_type_node, 1, 0);
9087       tree cst_uchar_ptr_node
9088         = build_pointer_type_for_mode (cst_uchar_node, ptr_mode, true);
9089
9090       tree ind1 = fold_convert_loc (loc, integer_type_node,
9091                                     build1 (INDIRECT_REF, cst_uchar_node,
9092                                             fold_convert_loc (loc,
9093                                                               cst_uchar_ptr_node,
9094                                                               arg1)));
9095       tree ind2 = fold_convert_loc (loc, integer_type_node,
9096                                     build1 (INDIRECT_REF, cst_uchar_node,
9097                                             fold_convert_loc (loc,
9098                                                               cst_uchar_ptr_node,
9099                                                               arg2)));
9100       return fold_build2_loc (loc, MINUS_EXPR, integer_type_node, ind1, ind2);
9101     }
9102
9103   return NULL_TREE;
9104 }
9105
9106 /* Fold function call to builtin signbit, signbitf or signbitl with argument
9107    ARG.  Return NULL_TREE if no simplification can be made.  */
9108
9109 static tree
9110 fold_builtin_signbit (location_t loc, tree arg, tree type)
9111 {
9112   if (!validate_arg (arg, REAL_TYPE))
9113     return NULL_TREE;
9114
9115   /* If ARG is a compile-time constant, determine the result.  */
9116   if (TREE_CODE (arg) == REAL_CST
9117       && !TREE_OVERFLOW (arg))
9118     {
9119       REAL_VALUE_TYPE c;
9120
9121       c = TREE_REAL_CST (arg);
9122       return (REAL_VALUE_NEGATIVE (c)
9123               ? build_one_cst (type)
9124               : build_zero_cst (type));
9125     }
9126
9127   /* If ARG is non-negative, the result is always zero.  */
9128   if (tree_expr_nonnegative_p (arg))
9129     return omit_one_operand_loc (loc, type, integer_zero_node, arg);
9130
9131   /* If ARG's format doesn't have signed zeros, return "arg < 0.0".  */
9132   if (!HONOR_SIGNED_ZEROS (TYPE_MODE (TREE_TYPE (arg))))
9133     return fold_build2_loc (loc, LT_EXPR, type, arg,
9134                         build_real (TREE_TYPE (arg), dconst0));
9135
9136   return NULL_TREE;
9137 }
9138
9139 /* Fold function call to builtin copysign, copysignf or copysignl with
9140    arguments ARG1 and ARG2.  Return NULL_TREE if no simplification can
9141    be made.  */
9142
9143 static tree
9144 fold_builtin_copysign (location_t loc, tree fndecl,
9145                        tree arg1, tree arg2, tree type)
9146 {
9147   tree tem;
9148
9149   if (!validate_arg (arg1, REAL_TYPE)
9150       || !validate_arg (arg2, REAL_TYPE))
9151     return NULL_TREE;
9152
9153   /* copysign(X,X) is X.  */
9154   if (operand_equal_p (arg1, arg2, 0))
9155     return fold_convert_loc (loc, type, arg1);
9156
9157   /* If ARG1 and ARG2 are compile-time constants, determine the result.  */
9158   if (TREE_CODE (arg1) == REAL_CST
9159       && TREE_CODE (arg2) == REAL_CST
9160       && !TREE_OVERFLOW (arg1)
9161       && !TREE_OVERFLOW (arg2))
9162     {
9163       REAL_VALUE_TYPE c1, c2;
9164
9165       c1 = TREE_REAL_CST (arg1);
9166       c2 = TREE_REAL_CST (arg2);
9167       /* c1.sign := c2.sign.  */
9168       real_copysign (&c1, &c2);
9169       return build_real (type, c1);
9170     }
9171
9172   /* copysign(X, Y) is fabs(X) when Y is always non-negative.
9173      Remember to evaluate Y for side-effects.  */
9174   if (tree_expr_nonnegative_p (arg2))
9175     return omit_one_operand_loc (loc, type,
9176                              fold_build1_loc (loc, ABS_EXPR, type, arg1),
9177                              arg2);
9178
9179   /* Strip sign changing operations for the first argument.  */
9180   tem = fold_strip_sign_ops (arg1);
9181   if (tem)
9182     return build_call_expr_loc (loc, fndecl, 2, tem, arg2);
9183
9184   return NULL_TREE;
9185 }
9186
9187 /* Fold a call to builtin isascii with argument ARG.  */
9188
9189 static tree
9190 fold_builtin_isascii (location_t loc, tree arg)
9191 {
9192   if (!validate_arg (arg, INTEGER_TYPE))
9193     return NULL_TREE;
9194   else
9195     {
9196       /* Transform isascii(c) -> ((c & ~0x7f) == 0).  */
9197       arg = fold_build2 (BIT_AND_EXPR, integer_type_node, arg,
9198                          build_int_cst (NULL_TREE,
9199                                         ~ (unsigned HOST_WIDE_INT) 0x7f));
9200       return fold_build2_loc (loc, EQ_EXPR, integer_type_node,
9201                           arg, integer_zero_node);
9202     }
9203 }
9204
9205 /* Fold a call to builtin toascii with argument ARG.  */
9206
9207 static tree
9208 fold_builtin_toascii (location_t loc, tree arg)
9209 {
9210   if (!validate_arg (arg, INTEGER_TYPE))
9211     return NULL_TREE;
9212
9213   /* Transform toascii(c) -> (c & 0x7f).  */
9214   return fold_build2_loc (loc, BIT_AND_EXPR, integer_type_node, arg,
9215                       build_int_cst (NULL_TREE, 0x7f));
9216 }
9217
9218 /* Fold a call to builtin isdigit with argument ARG.  */
9219
9220 static tree
9221 fold_builtin_isdigit (location_t loc, tree arg)
9222 {
9223   if (!validate_arg (arg, INTEGER_TYPE))
9224     return NULL_TREE;
9225   else
9226     {
9227       /* Transform isdigit(c) -> (unsigned)(c) - '0' <= 9.  */
9228       /* According to the C standard, isdigit is unaffected by locale.
9229          However, it definitely is affected by the target character set.  */
9230       unsigned HOST_WIDE_INT target_digit0
9231         = lang_hooks.to_target_charset ('0');
9232
9233       if (target_digit0 == 0)
9234         return NULL_TREE;
9235
9236       arg = fold_convert_loc (loc, unsigned_type_node, arg);
9237       arg = fold_build2 (MINUS_EXPR, unsigned_type_node, arg,
9238                          build_int_cst (unsigned_type_node, target_digit0));
9239       return fold_build2_loc (loc, LE_EXPR, integer_type_node, arg,
9240                           build_int_cst (unsigned_type_node, 9));
9241     }
9242 }
9243
9244 /* Fold a call to fabs, fabsf or fabsl with argument ARG.  */
9245
9246 static tree
9247 fold_builtin_fabs (location_t loc, tree arg, tree type)
9248 {
9249   if (!validate_arg (arg, REAL_TYPE))
9250     return NULL_TREE;
9251
9252   arg = fold_convert_loc (loc, type, arg);
9253   if (TREE_CODE (arg) == REAL_CST)
9254     return fold_abs_const (arg, type);
9255   return fold_build1_loc (loc, ABS_EXPR, type, arg);
9256 }
9257
9258 /* Fold a call to abs, labs, llabs or imaxabs with argument ARG.  */
9259
9260 static tree
9261 fold_builtin_abs (location_t loc, tree arg, tree type)
9262 {
9263   if (!validate_arg (arg, INTEGER_TYPE))
9264     return NULL_TREE;
9265
9266   arg = fold_convert_loc (loc, type, arg);
9267   if (TREE_CODE (arg) == INTEGER_CST)
9268     return fold_abs_const (arg, type);
9269   return fold_build1_loc (loc, ABS_EXPR, type, arg);
9270 }
9271
9272 /* Fold a fma operation with arguments ARG[012].  */
9273
9274 tree
9275 fold_fma (location_t loc ATTRIBUTE_UNUSED,
9276           tree type, tree arg0, tree arg1, tree arg2)
9277 {
9278   if (TREE_CODE (arg0) == REAL_CST
9279       && TREE_CODE (arg1) == REAL_CST
9280       && TREE_CODE (arg2) == REAL_CST)
9281     return do_mpfr_arg3 (arg0, arg1, arg2, type, mpfr_fma);
9282
9283   return NULL_TREE;
9284 }
9285
9286 /* Fold a call to fma, fmaf, or fmal with arguments ARG[012].  */
9287
9288 static tree
9289 fold_builtin_fma (location_t loc, tree arg0, tree arg1, tree arg2, tree type)
9290 {
9291   if (validate_arg (arg0, REAL_TYPE)
9292       && validate_arg(arg1, REAL_TYPE)
9293       && validate_arg(arg2, REAL_TYPE))
9294     {
9295       tree tem = fold_fma (loc, type, arg0, arg1, arg2);
9296       if (tem)
9297         return tem;
9298
9299       /* ??? Only expand to FMA_EXPR if it's directly supported.  */
9300       if (optab_handler (fma_optab, TYPE_MODE (type)) != CODE_FOR_nothing)
9301         return fold_build3_loc (loc, FMA_EXPR, type, arg0, arg1, arg2);
9302     }
9303   return NULL_TREE;
9304 }
9305
9306 /* Fold a call to builtin fmin or fmax.  */
9307
9308 static tree
9309 fold_builtin_fmin_fmax (location_t loc, tree arg0, tree arg1,
9310                         tree type, bool max)
9311 {
9312   if (validate_arg (arg0, REAL_TYPE) && validate_arg (arg1, REAL_TYPE))
9313     {
9314       /* Calculate the result when the argument is a constant.  */
9315       tree res = do_mpfr_arg2 (arg0, arg1, type, (max ? mpfr_max : mpfr_min));
9316
9317       if (res)
9318         return res;
9319
9320       /* If either argument is NaN, return the other one.  Avoid the
9321          transformation if we get (and honor) a signalling NaN.  Using
9322          omit_one_operand() ensures we create a non-lvalue.  */
9323       if (TREE_CODE (arg0) == REAL_CST
9324           && real_isnan (&TREE_REAL_CST (arg0))
9325           && (! HONOR_SNANS (TYPE_MODE (TREE_TYPE (arg0)))
9326               || ! TREE_REAL_CST (arg0).signalling))
9327         return omit_one_operand_loc (loc, type, arg1, arg0);
9328       if (TREE_CODE (arg1) == REAL_CST
9329           && real_isnan (&TREE_REAL_CST (arg1))
9330           && (! HONOR_SNANS (TYPE_MODE (TREE_TYPE (arg1)))
9331               || ! TREE_REAL_CST (arg1).signalling))
9332         return omit_one_operand_loc (loc, type, arg0, arg1);
9333
9334       /* Transform fmin/fmax(x,x) -> x.  */
9335       if (operand_equal_p (arg0, arg1, OEP_PURE_SAME))
9336         return omit_one_operand_loc (loc, type, arg0, arg1);
9337
9338       /* Convert fmin/fmax to MIN_EXPR/MAX_EXPR.  C99 requires these
9339          functions to return the numeric arg if the other one is NaN.
9340          These tree codes don't honor that, so only transform if
9341          -ffinite-math-only is set.  C99 doesn't require -0.0 to be
9342          handled, so we don't have to worry about it either.  */
9343       if (flag_finite_math_only)
9344         return fold_build2_loc (loc, (max ? MAX_EXPR : MIN_EXPR), type,
9345                             fold_convert_loc (loc, type, arg0),
9346                             fold_convert_loc (loc, type, arg1));
9347     }
9348   return NULL_TREE;
9349 }
9350
9351 /* Fold a call to builtin carg(a+bi) -> atan2(b,a).  */
9352
9353 static tree
9354 fold_builtin_carg (location_t loc, tree arg, tree type)
9355 {
9356   if (validate_arg (arg, COMPLEX_TYPE)
9357       && TREE_CODE (TREE_TYPE (TREE_TYPE (arg))) == REAL_TYPE)
9358     {
9359       tree atan2_fn = mathfn_built_in (type, BUILT_IN_ATAN2);
9360
9361       if (atan2_fn)
9362         {
9363           tree new_arg = builtin_save_expr (arg);
9364           tree r_arg = fold_build1_loc (loc, REALPART_EXPR, type, new_arg);
9365           tree i_arg = fold_build1_loc (loc, IMAGPART_EXPR, type, new_arg);
9366           return build_call_expr_loc (loc, atan2_fn, 2, i_arg, r_arg);
9367         }
9368     }
9369
9370   return NULL_TREE;
9371 }
9372
9373 /* Fold a call to builtin logb/ilogb.  */
9374
9375 static tree
9376 fold_builtin_logb (location_t loc, tree arg, tree rettype)
9377 {
9378   if (! validate_arg (arg, REAL_TYPE))
9379     return NULL_TREE;
9380
9381   STRIP_NOPS (arg);
9382
9383   if (TREE_CODE (arg) == REAL_CST && ! TREE_OVERFLOW (arg))
9384     {
9385       const REAL_VALUE_TYPE *const value = TREE_REAL_CST_PTR (arg);
9386
9387       switch (value->cl)
9388       {
9389       case rvc_nan:
9390       case rvc_inf:
9391         /* If arg is Inf or NaN and we're logb, return it.  */
9392         if (TREE_CODE (rettype) == REAL_TYPE)
9393           return fold_convert_loc (loc, rettype, arg);
9394         /* Fall through... */
9395       case rvc_zero:
9396         /* Zero may set errno and/or raise an exception for logb, also
9397            for ilogb we don't know FP_ILOGB0.  */
9398         return NULL_TREE;
9399       case rvc_normal:
9400         /* For normal numbers, proceed iff radix == 2.  In GCC,
9401            normalized significands are in the range [0.5, 1.0).  We
9402            want the exponent as if they were [1.0, 2.0) so get the
9403            exponent and subtract 1.  */
9404         if (REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (arg)))->b == 2)
9405           return fold_convert_loc (loc, rettype,
9406                                    build_int_cst (NULL_TREE,
9407                                                   REAL_EXP (value)-1));
9408         break;
9409       }
9410     }
9411
9412   return NULL_TREE;
9413 }
9414
9415 /* Fold a call to builtin significand, if radix == 2.  */
9416
9417 static tree
9418 fold_builtin_significand (location_t loc, tree arg, tree rettype)
9419 {
9420   if (! validate_arg (arg, REAL_TYPE))
9421     return NULL_TREE;
9422
9423   STRIP_NOPS (arg);
9424
9425   if (TREE_CODE (arg) == REAL_CST && ! TREE_OVERFLOW (arg))
9426     {
9427       const REAL_VALUE_TYPE *const value = TREE_REAL_CST_PTR (arg);
9428
9429       switch (value->cl)
9430       {
9431       case rvc_zero:
9432       case rvc_nan:
9433       case rvc_inf:
9434         /* If arg is +-0, +-Inf or +-NaN, then return it.  */
9435         return fold_convert_loc (loc, rettype, arg);
9436       case rvc_normal:
9437         /* For normal numbers, proceed iff radix == 2.  */
9438         if (REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (arg)))->b == 2)
9439           {
9440             REAL_VALUE_TYPE result = *value;
9441             /* In GCC, normalized significands are in the range [0.5,
9442                1.0).  We want them to be [1.0, 2.0) so set the
9443                exponent to 1.  */
9444             SET_REAL_EXP (&result, 1);
9445             return build_real (rettype, result);
9446           }
9447         break;
9448       }
9449     }
9450
9451   return NULL_TREE;
9452 }
9453
9454 /* Fold a call to builtin frexp, we can assume the base is 2.  */
9455
9456 static tree
9457 fold_builtin_frexp (location_t loc, tree arg0, tree arg1, tree rettype)
9458 {
9459   if (! validate_arg (arg0, REAL_TYPE) || ! validate_arg (arg1, POINTER_TYPE))
9460     return NULL_TREE;
9461
9462   STRIP_NOPS (arg0);
9463
9464   if (!(TREE_CODE (arg0) == REAL_CST && ! TREE_OVERFLOW (arg0)))
9465     return NULL_TREE;
9466
9467   arg1 = build_fold_indirect_ref_loc (loc, arg1);
9468
9469   /* Proceed if a valid pointer type was passed in.  */
9470   if (TYPE_MAIN_VARIANT (TREE_TYPE (arg1)) == integer_type_node)
9471     {
9472       const REAL_VALUE_TYPE *const value = TREE_REAL_CST_PTR (arg0);
9473       tree frac, exp;
9474
9475       switch (value->cl)
9476       {
9477       case rvc_zero:
9478         /* For +-0, return (*exp = 0, +-0).  */
9479         exp = integer_zero_node;
9480         frac = arg0;
9481         break;
9482       case rvc_nan:
9483       case rvc_inf:
9484         /* For +-NaN or +-Inf, *exp is unspecified, return arg0.  */
9485         return omit_one_operand_loc (loc, rettype, arg0, arg1);
9486       case rvc_normal:
9487         {
9488           /* Since the frexp function always expects base 2, and in
9489              GCC normalized significands are already in the range
9490              [0.5, 1.0), we have exactly what frexp wants.  */
9491           REAL_VALUE_TYPE frac_rvt = *value;
9492           SET_REAL_EXP (&frac_rvt, 0);
9493           frac = build_real (rettype, frac_rvt);
9494           exp = build_int_cst (NULL_TREE, REAL_EXP (value));
9495         }
9496         break;
9497       default:
9498         gcc_unreachable ();
9499       }
9500
9501       /* Create the COMPOUND_EXPR (*arg1 = trunc, frac). */
9502       arg1 = fold_build2_loc (loc, MODIFY_EXPR, rettype, arg1, exp);
9503       TREE_SIDE_EFFECTS (arg1) = 1;
9504       return fold_build2_loc (loc, COMPOUND_EXPR, rettype, arg1, frac);
9505     }
9506
9507   return NULL_TREE;
9508 }
9509
9510 /* Fold a call to builtin ldexp or scalbn/scalbln.  If LDEXP is true
9511    then we can assume the base is two.  If it's false, then we have to
9512    check the mode of the TYPE parameter in certain cases.  */
9513
9514 static tree
9515 fold_builtin_load_exponent (location_t loc, tree arg0, tree arg1,
9516                             tree type, bool ldexp)
9517 {
9518   if (validate_arg (arg0, REAL_TYPE) && validate_arg (arg1, INTEGER_TYPE))
9519     {
9520       STRIP_NOPS (arg0);
9521       STRIP_NOPS (arg1);
9522
9523       /* If arg0 is 0, Inf or NaN, or if arg1 is 0, then return arg0.  */
9524       if (real_zerop (arg0) || integer_zerop (arg1)
9525           || (TREE_CODE (arg0) == REAL_CST
9526               && !real_isfinite (&TREE_REAL_CST (arg0))))
9527         return omit_one_operand_loc (loc, type, arg0, arg1);
9528
9529       /* If both arguments are constant, then try to evaluate it.  */
9530       if ((ldexp || REAL_MODE_FORMAT (TYPE_MODE (type))->b == 2)
9531           && TREE_CODE (arg0) == REAL_CST && !TREE_OVERFLOW (arg0)
9532           && host_integerp (arg1, 0))
9533         {
9534           /* Bound the maximum adjustment to twice the range of the
9535              mode's valid exponents.  Use abs to ensure the range is
9536              positive as a sanity check.  */
9537           const long max_exp_adj = 2 *
9538             labs (REAL_MODE_FORMAT (TYPE_MODE (type))->emax
9539                  - REAL_MODE_FORMAT (TYPE_MODE (type))->emin);
9540
9541           /* Get the user-requested adjustment.  */
9542           const HOST_WIDE_INT req_exp_adj = tree_low_cst (arg1, 0);
9543
9544           /* The requested adjustment must be inside this range.  This
9545              is a preliminary cap to avoid things like overflow, we
9546              may still fail to compute the result for other reasons.  */
9547           if (-max_exp_adj < req_exp_adj && req_exp_adj < max_exp_adj)
9548             {
9549               REAL_VALUE_TYPE initial_result;
9550
9551               real_ldexp (&initial_result, &TREE_REAL_CST (arg0), req_exp_adj);
9552
9553               /* Ensure we didn't overflow.  */
9554               if (! real_isinf (&initial_result))
9555                 {
9556                   const REAL_VALUE_TYPE trunc_result
9557                     = real_value_truncate (TYPE_MODE (type), initial_result);
9558
9559                   /* Only proceed if the target mode can hold the
9560                      resulting value.  */
9561                   if (REAL_VALUES_EQUAL (initial_result, trunc_result))
9562                     return build_real (type, trunc_result);
9563                 }
9564             }
9565         }
9566     }
9567
9568   return NULL_TREE;
9569 }
9570
9571 /* Fold a call to builtin modf.  */
9572
9573 static tree
9574 fold_builtin_modf (location_t loc, tree arg0, tree arg1, tree rettype)
9575 {
9576   if (! validate_arg (arg0, REAL_TYPE) || ! validate_arg (arg1, POINTER_TYPE))
9577     return NULL_TREE;
9578
9579   STRIP_NOPS (arg0);
9580
9581   if (!(TREE_CODE (arg0) == REAL_CST && ! TREE_OVERFLOW (arg0)))
9582     return NULL_TREE;
9583
9584   arg1 = build_fold_indirect_ref_loc (loc, arg1);
9585
9586   /* Proceed if a valid pointer type was passed in.  */
9587   if (TYPE_MAIN_VARIANT (TREE_TYPE (arg1)) == TYPE_MAIN_VARIANT (rettype))
9588     {
9589       const REAL_VALUE_TYPE *const value = TREE_REAL_CST_PTR (arg0);
9590       REAL_VALUE_TYPE trunc, frac;
9591
9592       switch (value->cl)
9593       {
9594       case rvc_nan:
9595       case rvc_zero:
9596         /* For +-NaN or +-0, return (*arg1 = arg0, arg0).  */
9597         trunc = frac = *value;
9598         break;
9599       case rvc_inf:
9600         /* For +-Inf, return (*arg1 = arg0, +-0).  */
9601         frac = dconst0;
9602         frac.sign = value->sign;
9603         trunc = *value;
9604         break;
9605       case rvc_normal:
9606         /* Return (*arg1 = trunc(arg0), arg0-trunc(arg0)).  */
9607         real_trunc (&trunc, VOIDmode, value);
9608         real_arithmetic (&frac, MINUS_EXPR, value, &trunc);
9609         /* If the original number was negative and already
9610            integral, then the fractional part is -0.0.  */
9611         if (value->sign && frac.cl == rvc_zero)
9612           frac.sign = value->sign;
9613         break;
9614       }
9615
9616       /* Create the COMPOUND_EXPR (*arg1 = trunc, frac). */
9617       arg1 = fold_build2_loc (loc, MODIFY_EXPR, rettype, arg1,
9618                           build_real (rettype, trunc));
9619       TREE_SIDE_EFFECTS (arg1) = 1;
9620       return fold_build2_loc (loc, COMPOUND_EXPR, rettype, arg1,
9621                           build_real (rettype, frac));
9622     }
9623
9624   return NULL_TREE;
9625 }
9626
9627 /* Given a location LOC, an interclass builtin function decl FNDECL
9628    and its single argument ARG, return an folded expression computing
9629    the same, or NULL_TREE if we either couldn't or didn't want to fold
9630    (the latter happen if there's an RTL instruction available).  */
9631
9632 static tree
9633 fold_builtin_interclass_mathfn (location_t loc, tree fndecl, tree arg)
9634 {
9635   enum machine_mode mode;
9636
9637   if (!validate_arg (arg, REAL_TYPE))
9638     return NULL_TREE;
9639
9640   if (interclass_mathfn_icode (arg, fndecl) != CODE_FOR_nothing)
9641     return NULL_TREE;
9642
9643   mode = TYPE_MODE (TREE_TYPE (arg));
9644
9645   /* If there is no optab, try generic code.  */
9646   switch (DECL_FUNCTION_CODE (fndecl))
9647     {
9648       tree result;
9649
9650     CASE_FLT_FN (BUILT_IN_ISINF):
9651       {
9652         /* isinf(x) -> isgreater(fabs(x),DBL_MAX).  */
9653         tree const isgr_fn = built_in_decls[BUILT_IN_ISGREATER];
9654         tree const type = TREE_TYPE (arg);
9655         REAL_VALUE_TYPE r;
9656         char buf[128];
9657
9658         get_max_float (REAL_MODE_FORMAT (mode), buf, sizeof (buf));
9659         real_from_string (&r, buf);
9660         result = build_call_expr (isgr_fn, 2,
9661                                   fold_build1_loc (loc, ABS_EXPR, type, arg),
9662                                   build_real (type, r));
9663         return result;
9664       }
9665     CASE_FLT_FN (BUILT_IN_FINITE):
9666     case BUILT_IN_ISFINITE:
9667       {
9668         /* isfinite(x) -> islessequal(fabs(x),DBL_MAX).  */
9669         tree const isle_fn = built_in_decls[BUILT_IN_ISLESSEQUAL];
9670         tree const type = TREE_TYPE (arg);
9671         REAL_VALUE_TYPE r;
9672         char buf[128];
9673
9674         get_max_float (REAL_MODE_FORMAT (mode), buf, sizeof (buf));
9675         real_from_string (&r, buf);
9676         result = build_call_expr (isle_fn, 2,
9677                                   fold_build1_loc (loc, ABS_EXPR, type, arg),
9678                                   build_real (type, r));
9679         /*result = fold_build2_loc (loc, UNGT_EXPR,
9680                                   TREE_TYPE (TREE_TYPE (fndecl)),
9681                                   fold_build1_loc (loc, ABS_EXPR, type, arg),
9682                                   build_real (type, r));
9683         result = fold_build1_loc (loc, TRUTH_NOT_EXPR,
9684                                   TREE_TYPE (TREE_TYPE (fndecl)),
9685                                   result);*/
9686         return result;
9687       }
9688     case BUILT_IN_ISNORMAL:
9689       {
9690         /* isnormal(x) -> isgreaterequal(fabs(x),DBL_MIN) &
9691            islessequal(fabs(x),DBL_MAX).  */
9692         tree const isle_fn = built_in_decls[BUILT_IN_ISLESSEQUAL];
9693         tree const isge_fn = built_in_decls[BUILT_IN_ISGREATEREQUAL];
9694         tree const type = TREE_TYPE (arg);
9695         REAL_VALUE_TYPE rmax, rmin;
9696         char buf[128];
9697
9698         get_max_float (REAL_MODE_FORMAT (mode), buf, sizeof (buf));
9699         real_from_string (&rmax, buf);
9700         sprintf (buf, "0x1p%d", REAL_MODE_FORMAT (mode)->emin - 1);
9701         real_from_string (&rmin, buf);
9702         arg = builtin_save_expr (fold_build1_loc (loc, ABS_EXPR, type, arg));
9703         result = build_call_expr (isle_fn, 2, arg,
9704                                   build_real (type, rmax));
9705         result = fold_build2 (BIT_AND_EXPR, integer_type_node, result,
9706                               build_call_expr (isge_fn, 2, arg,
9707                                                build_real (type, rmin)));
9708         return result;
9709       }
9710     default:
9711       break;
9712     }
9713
9714   return NULL_TREE;
9715 }
9716
9717 /* Fold a call to __builtin_isnan(), __builtin_isinf, __builtin_finite.
9718    ARG is the argument for the call.  */
9719
9720 static tree
9721 fold_builtin_classify (location_t loc, tree fndecl, tree arg, int builtin_index)
9722 {
9723   tree type = TREE_TYPE (TREE_TYPE (fndecl));
9724   REAL_VALUE_TYPE r;
9725
9726   if (!validate_arg (arg, REAL_TYPE))
9727     return NULL_TREE;
9728
9729   switch (builtin_index)
9730     {
9731     case BUILT_IN_ISINF:
9732       if (!HONOR_INFINITIES (TYPE_MODE (TREE_TYPE (arg))))
9733         return omit_one_operand_loc (loc, type, integer_zero_node, arg);
9734
9735       if (TREE_CODE (arg) == REAL_CST)
9736         {
9737           r = TREE_REAL_CST (arg);
9738           if (real_isinf (&r))
9739             return real_compare (GT_EXPR, &r, &dconst0)
9740                    ? integer_one_node : integer_minus_one_node;
9741           else
9742             return integer_zero_node;
9743         }
9744
9745       return NULL_TREE;
9746
9747     case BUILT_IN_ISINF_SIGN:
9748       {
9749         /* isinf_sign(x) -> isinf(x) ? (signbit(x) ? -1 : 1) : 0 */
9750         /* In a boolean context, GCC will fold the inner COND_EXPR to
9751            1.  So e.g. "if (isinf_sign(x))" would be folded to just
9752            "if (isinf(x) ? 1 : 0)" which becomes "if (isinf(x))". */
9753         tree signbit_fn = mathfn_built_in_1 (TREE_TYPE (arg), BUILT_IN_SIGNBIT, 0);
9754         tree isinf_fn = built_in_decls[BUILT_IN_ISINF];
9755         tree tmp = NULL_TREE;
9756
9757         arg = builtin_save_expr (arg);
9758
9759         if (signbit_fn && isinf_fn)
9760           {
9761             tree signbit_call = build_call_expr_loc (loc, signbit_fn, 1, arg);
9762             tree isinf_call = build_call_expr_loc (loc, isinf_fn, 1, arg);
9763
9764             signbit_call = fold_build2_loc (loc, NE_EXPR, integer_type_node,
9765                                         signbit_call, integer_zero_node);
9766             isinf_call = fold_build2_loc (loc, NE_EXPR, integer_type_node,
9767                                       isinf_call, integer_zero_node);
9768
9769             tmp = fold_build3_loc (loc, COND_EXPR, integer_type_node, signbit_call,
9770                                integer_minus_one_node, integer_one_node);
9771             tmp = fold_build3_loc (loc, COND_EXPR, integer_type_node,
9772                                isinf_call, tmp,
9773                                integer_zero_node);
9774           }
9775
9776         return tmp;
9777       }
9778
9779     case BUILT_IN_ISFINITE:
9780       if (!HONOR_NANS (TYPE_MODE (TREE_TYPE (arg)))
9781           && !HONOR_INFINITIES (TYPE_MODE (TREE_TYPE (arg))))
9782         return omit_one_operand_loc (loc, type, integer_one_node, arg);
9783
9784       if (TREE_CODE (arg) == REAL_CST)
9785         {
9786           r = TREE_REAL_CST (arg);
9787           return real_isfinite (&r) ? integer_one_node : integer_zero_node;
9788         }
9789
9790       return NULL_TREE;
9791
9792     case BUILT_IN_ISNAN:
9793       if (!HONOR_NANS (TYPE_MODE (TREE_TYPE (arg))))
9794         return omit_one_operand_loc (loc, type, integer_zero_node, arg);
9795
9796       if (TREE_CODE (arg) == REAL_CST)
9797         {
9798           r = TREE_REAL_CST (arg);
9799           return real_isnan (&r) ? integer_one_node : integer_zero_node;
9800         }
9801
9802       arg = builtin_save_expr (arg);
9803       return fold_build2_loc (loc, UNORDERED_EXPR, type, arg, arg);
9804
9805     default:
9806       gcc_unreachable ();
9807     }
9808 }
9809
9810 /* Fold a call to __builtin_fpclassify(int, int, int, int, int, ...).
9811    This builtin will generate code to return the appropriate floating
9812    point classification depending on the value of the floating point
9813    number passed in.  The possible return values must be supplied as
9814    int arguments to the call in the following order: FP_NAN, FP_INFINITE,
9815    FP_NORMAL, FP_SUBNORMAL and FP_ZERO.  The ellipses is for exactly
9816    one floating point argument which is "type generic".  */
9817
9818 static tree
9819 fold_builtin_fpclassify (location_t loc, tree exp)
9820 {
9821   tree fp_nan, fp_infinite, fp_normal, fp_subnormal, fp_zero,
9822     arg, type, res, tmp;
9823   enum machine_mode mode;
9824   REAL_VALUE_TYPE r;
9825   char buf[128];
9826
9827   /* Verify the required arguments in the original call.  */
9828   if (!validate_arglist (exp, INTEGER_TYPE, INTEGER_TYPE,
9829                          INTEGER_TYPE, INTEGER_TYPE,
9830                          INTEGER_TYPE, REAL_TYPE, VOID_TYPE))
9831     return NULL_TREE;
9832
9833   fp_nan = CALL_EXPR_ARG (exp, 0);
9834   fp_infinite = CALL_EXPR_ARG (exp, 1);
9835   fp_normal = CALL_EXPR_ARG (exp, 2);
9836   fp_subnormal = CALL_EXPR_ARG (exp, 3);
9837   fp_zero = CALL_EXPR_ARG (exp, 4);
9838   arg = CALL_EXPR_ARG (exp, 5);
9839   type = TREE_TYPE (arg);
9840   mode = TYPE_MODE (type);
9841   arg = builtin_save_expr (fold_build1_loc (loc, ABS_EXPR, type, arg));
9842
9843   /* fpclassify(x) ->
9844        isnan(x) ? FP_NAN :
9845          (fabs(x) == Inf ? FP_INFINITE :
9846            (fabs(x) >= DBL_MIN ? FP_NORMAL :
9847              (x == 0 ? FP_ZERO : FP_SUBNORMAL))).  */
9848
9849   tmp = fold_build2_loc (loc, EQ_EXPR, integer_type_node, arg,
9850                      build_real (type, dconst0));
9851   res = fold_build3_loc (loc, COND_EXPR, integer_type_node,
9852                      tmp, fp_zero, fp_subnormal);
9853
9854   sprintf (buf, "0x1p%d", REAL_MODE_FORMAT (mode)->emin - 1);
9855   real_from_string (&r, buf);
9856   tmp = fold_build2_loc (loc, GE_EXPR, integer_type_node,
9857                      arg, build_real (type, r));
9858   res = fold_build3_loc (loc, COND_EXPR, integer_type_node, tmp, fp_normal, res);
9859
9860   if (HONOR_INFINITIES (mode))
9861     {
9862       real_inf (&r);
9863       tmp = fold_build2_loc (loc, EQ_EXPR, integer_type_node, arg,
9864                          build_real (type, r));
9865       res = fold_build3_loc (loc, COND_EXPR, integer_type_node, tmp,
9866                          fp_infinite, res);
9867     }
9868
9869   if (HONOR_NANS (mode))
9870     {
9871       tmp = fold_build2_loc (loc, ORDERED_EXPR, integer_type_node, arg, arg);
9872       res = fold_build3_loc (loc, COND_EXPR, integer_type_node, tmp, res, fp_nan);
9873     }
9874
9875   return res;
9876 }
9877
9878 /* Fold a call to an unordered comparison function such as
9879    __builtin_isgreater().  FNDECL is the FUNCTION_DECL for the function
9880    being called and ARG0 and ARG1 are the arguments for the call.
9881    UNORDERED_CODE and ORDERED_CODE are comparison codes that give
9882    the opposite of the desired result.  UNORDERED_CODE is used
9883    for modes that can hold NaNs and ORDERED_CODE is used for
9884    the rest.  */
9885
9886 static tree
9887 fold_builtin_unordered_cmp (location_t loc, tree fndecl, tree arg0, tree arg1,
9888                             enum tree_code unordered_code,
9889                             enum tree_code ordered_code)
9890 {
9891   tree type = TREE_TYPE (TREE_TYPE (fndecl));
9892   enum tree_code code;
9893   tree type0, type1;
9894   enum tree_code code0, code1;
9895   tree cmp_type = NULL_TREE;
9896
9897   type0 = TREE_TYPE (arg0);
9898   type1 = TREE_TYPE (arg1);
9899
9900   code0 = TREE_CODE (type0);
9901   code1 = TREE_CODE (type1);
9902
9903   if (code0 == REAL_TYPE && code1 == REAL_TYPE)
9904     /* Choose the wider of two real types.  */
9905     cmp_type = TYPE_PRECISION (type0) >= TYPE_PRECISION (type1)
9906       ? type0 : type1;
9907   else if (code0 == REAL_TYPE && code1 == INTEGER_TYPE)
9908     cmp_type = type0;
9909   else if (code0 == INTEGER_TYPE && code1 == REAL_TYPE)
9910     cmp_type = type1;
9911
9912   arg0 = fold_convert_loc (loc, cmp_type, arg0);
9913   arg1 = fold_convert_loc (loc, cmp_type, arg1);
9914
9915   if (unordered_code == UNORDERED_EXPR)
9916     {
9917       if (!HONOR_NANS (TYPE_MODE (TREE_TYPE (arg0))))
9918         return omit_two_operands_loc (loc, type, integer_zero_node, arg0, arg1);
9919       return fold_build2_loc (loc, UNORDERED_EXPR, type, arg0, arg1);
9920     }
9921
9922   code = HONOR_NANS (TYPE_MODE (TREE_TYPE (arg0))) ? unordered_code
9923                                                    : ordered_code;
9924   return fold_build1_loc (loc, TRUTH_NOT_EXPR, type,
9925                       fold_build2_loc (loc, code, type, arg0, arg1));
9926 }
9927
9928 /* Fold a call to built-in function FNDECL with 0 arguments.
9929    IGNORE is true if the result of the function call is ignored.  This
9930    function returns NULL_TREE if no simplification was possible.  */
9931
9932 static tree
9933 fold_builtin_0 (location_t loc, tree fndecl, bool ignore ATTRIBUTE_UNUSED)
9934 {
9935   tree type = TREE_TYPE (TREE_TYPE (fndecl));
9936   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
9937   switch (fcode)
9938     {
9939     CASE_FLT_FN (BUILT_IN_INF):
9940     case BUILT_IN_INFD32:
9941     case BUILT_IN_INFD64:
9942     case BUILT_IN_INFD128:
9943       return fold_builtin_inf (loc, type, true);
9944
9945     CASE_FLT_FN (BUILT_IN_HUGE_VAL):
9946       return fold_builtin_inf (loc, type, false);
9947
9948     case BUILT_IN_CLASSIFY_TYPE:
9949       return fold_builtin_classify_type (NULL_TREE);
9950
9951     default:
9952       break;
9953     }
9954   return NULL_TREE;
9955 }
9956
9957 /* Fold a call to built-in function FNDECL with 1 argument, ARG0.
9958    IGNORE is true if the result of the function call is ignored.  This
9959    function returns NULL_TREE if no simplification was possible.  */
9960
9961 static tree
9962 fold_builtin_1 (location_t loc, tree fndecl, tree arg0, bool ignore)
9963 {
9964   tree type = TREE_TYPE (TREE_TYPE (fndecl));
9965   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
9966   switch (fcode)
9967     {
9968     case BUILT_IN_CONSTANT_P:
9969       {
9970         tree val = fold_builtin_constant_p (arg0);
9971
9972         /* Gimplification will pull the CALL_EXPR for the builtin out of
9973            an if condition.  When not optimizing, we'll not CSE it back.
9974            To avoid link error types of regressions, return false now.  */
9975         if (!val && !optimize)
9976           val = integer_zero_node;
9977
9978         return val;
9979       }
9980
9981     case BUILT_IN_CLASSIFY_TYPE:
9982       return fold_builtin_classify_type (arg0);
9983
9984     case BUILT_IN_STRLEN:
9985       return fold_builtin_strlen (loc, type, arg0);
9986
9987     CASE_FLT_FN (BUILT_IN_FABS):
9988       return fold_builtin_fabs (loc, arg0, type);
9989
9990     case BUILT_IN_ABS:
9991     case BUILT_IN_LABS:
9992     case BUILT_IN_LLABS:
9993     case BUILT_IN_IMAXABS:
9994       return fold_builtin_abs (loc, arg0, type);
9995
9996     CASE_FLT_FN (BUILT_IN_CONJ):
9997       if (validate_arg (arg0, COMPLEX_TYPE)
9998         && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
9999         return fold_build1_loc (loc, CONJ_EXPR, type, arg0);
10000     break;
10001
10002     CASE_FLT_FN (BUILT_IN_CREAL):
10003       if (validate_arg (arg0, COMPLEX_TYPE)
10004         && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
10005         return non_lvalue_loc (loc, fold_build1_loc (loc, REALPART_EXPR, type, arg0));;
10006     break;
10007
10008     CASE_FLT_FN (BUILT_IN_CIMAG):
10009       if (validate_arg (arg0, COMPLEX_TYPE)
10010           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
10011         return non_lvalue_loc (loc, fold_build1_loc (loc, IMAGPART_EXPR, type, arg0));
10012     break;
10013
10014     CASE_FLT_FN (BUILT_IN_CCOS):
10015       return fold_builtin_ccos(loc, arg0, type, fndecl, /*hyper=*/ false);
10016
10017     CASE_FLT_FN (BUILT_IN_CCOSH):
10018       return fold_builtin_ccos(loc, arg0, type, fndecl, /*hyper=*/ true);
10019
10020     CASE_FLT_FN (BUILT_IN_CPROJ):
10021       return fold_builtin_cproj(loc, arg0, type);
10022
10023     CASE_FLT_FN (BUILT_IN_CSIN):
10024       if (validate_arg (arg0, COMPLEX_TYPE)
10025           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
10026         return do_mpc_arg1 (arg0, type, mpc_sin);
10027     break;
10028
10029     CASE_FLT_FN (BUILT_IN_CSINH):
10030       if (validate_arg (arg0, COMPLEX_TYPE)
10031           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
10032         return do_mpc_arg1 (arg0, type, mpc_sinh);
10033     break;
10034
10035     CASE_FLT_FN (BUILT_IN_CTAN):
10036       if (validate_arg (arg0, COMPLEX_TYPE)
10037           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
10038         return do_mpc_arg1 (arg0, type, mpc_tan);
10039     break;
10040
10041     CASE_FLT_FN (BUILT_IN_CTANH):
10042       if (validate_arg (arg0, COMPLEX_TYPE)
10043           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
10044         return do_mpc_arg1 (arg0, type, mpc_tanh);
10045     break;
10046
10047     CASE_FLT_FN (BUILT_IN_CLOG):
10048       if (validate_arg (arg0, COMPLEX_TYPE)
10049           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
10050         return do_mpc_arg1 (arg0, type, mpc_log);
10051     break;
10052
10053     CASE_FLT_FN (BUILT_IN_CSQRT):
10054       if (validate_arg (arg0, COMPLEX_TYPE)
10055           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
10056         return do_mpc_arg1 (arg0, type, mpc_sqrt);
10057     break;
10058
10059     CASE_FLT_FN (BUILT_IN_CASIN):
10060       if (validate_arg (arg0, COMPLEX_TYPE)
10061           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
10062         return do_mpc_arg1 (arg0, type, mpc_asin);
10063     break;
10064
10065     CASE_FLT_FN (BUILT_IN_CACOS):
10066       if (validate_arg (arg0, COMPLEX_TYPE)
10067           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
10068         return do_mpc_arg1 (arg0, type, mpc_acos);
10069     break;
10070
10071     CASE_FLT_FN (BUILT_IN_CATAN):
10072       if (validate_arg (arg0, COMPLEX_TYPE)
10073           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
10074         return do_mpc_arg1 (arg0, type, mpc_atan);
10075     break;
10076
10077     CASE_FLT_FN (BUILT_IN_CASINH):
10078       if (validate_arg (arg0, COMPLEX_TYPE)
10079           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
10080         return do_mpc_arg1 (arg0, type, mpc_asinh);
10081     break;
10082
10083     CASE_FLT_FN (BUILT_IN_CACOSH):
10084       if (validate_arg (arg0, COMPLEX_TYPE)
10085           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
10086         return do_mpc_arg1 (arg0, type, mpc_acosh);
10087     break;
10088
10089     CASE_FLT_FN (BUILT_IN_CATANH):
10090       if (validate_arg (arg0, COMPLEX_TYPE)
10091           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
10092         return do_mpc_arg1 (arg0, type, mpc_atanh);
10093     break;
10094
10095     CASE_FLT_FN (BUILT_IN_CABS):
10096       return fold_builtin_cabs (loc, arg0, type, fndecl);
10097
10098     CASE_FLT_FN (BUILT_IN_CARG):
10099       return fold_builtin_carg (loc, arg0, type);
10100
10101     CASE_FLT_FN (BUILT_IN_SQRT):
10102       return fold_builtin_sqrt (loc, arg0, type);
10103
10104     CASE_FLT_FN (BUILT_IN_CBRT):
10105       return fold_builtin_cbrt (loc, arg0, type);
10106
10107     CASE_FLT_FN (BUILT_IN_ASIN):
10108       if (validate_arg (arg0, REAL_TYPE))
10109         return do_mpfr_arg1 (arg0, type, mpfr_asin,
10110                              &dconstm1, &dconst1, true);
10111     break;
10112
10113     CASE_FLT_FN (BUILT_IN_ACOS):
10114       if (validate_arg (arg0, REAL_TYPE))
10115         return do_mpfr_arg1 (arg0, type, mpfr_acos,
10116                              &dconstm1, &dconst1, true);
10117     break;
10118
10119     CASE_FLT_FN (BUILT_IN_ATAN):
10120       if (validate_arg (arg0, REAL_TYPE))
10121         return do_mpfr_arg1 (arg0, type, mpfr_atan, NULL, NULL, 0);
10122     break;
10123
10124     CASE_FLT_FN (BUILT_IN_ASINH):
10125       if (validate_arg (arg0, REAL_TYPE))
10126         return do_mpfr_arg1 (arg0, type, mpfr_asinh, NULL, NULL, 0);
10127     break;
10128
10129     CASE_FLT_FN (BUILT_IN_ACOSH):
10130       if (validate_arg (arg0, REAL_TYPE))
10131         return do_mpfr_arg1 (arg0, type, mpfr_acosh,
10132                              &dconst1, NULL, true);
10133     break;
10134
10135     CASE_FLT_FN (BUILT_IN_ATANH):
10136       if (validate_arg (arg0, REAL_TYPE))
10137         return do_mpfr_arg1 (arg0, type, mpfr_atanh,
10138                              &dconstm1, &dconst1, false);
10139     break;
10140
10141     CASE_FLT_FN (BUILT_IN_SIN):
10142       if (validate_arg (arg0, REAL_TYPE))
10143         return do_mpfr_arg1 (arg0, type, mpfr_sin, NULL, NULL, 0);
10144     break;
10145
10146     CASE_FLT_FN (BUILT_IN_COS):
10147       return fold_builtin_cos (loc, arg0, type, fndecl);
10148
10149     CASE_FLT_FN (BUILT_IN_TAN):
10150       return fold_builtin_tan (arg0, type);
10151
10152     CASE_FLT_FN (BUILT_IN_CEXP):
10153       return fold_builtin_cexp (loc, arg0, type);
10154
10155     CASE_FLT_FN (BUILT_IN_CEXPI):
10156       if (validate_arg (arg0, REAL_TYPE))
10157         return do_mpfr_sincos (arg0, NULL_TREE, NULL_TREE);
10158     break;
10159
10160     CASE_FLT_FN (BUILT_IN_SINH):
10161       if (validate_arg (arg0, REAL_TYPE))
10162         return do_mpfr_arg1 (arg0, type, mpfr_sinh, NULL, NULL, 0);
10163     break;
10164
10165     CASE_FLT_FN (BUILT_IN_COSH):
10166       return fold_builtin_cosh (loc, arg0, type, fndecl);
10167
10168     CASE_FLT_FN (BUILT_IN_TANH):
10169       if (validate_arg (arg0, REAL_TYPE))
10170         return do_mpfr_arg1 (arg0, type, mpfr_tanh, NULL, NULL, 0);
10171     break;
10172
10173     CASE_FLT_FN (BUILT_IN_ERF):
10174       if (validate_arg (arg0, REAL_TYPE))
10175         return do_mpfr_arg1 (arg0, type, mpfr_erf, NULL, NULL, 0);
10176     break;
10177
10178     CASE_FLT_FN (BUILT_IN_ERFC):
10179       if (validate_arg (arg0, REAL_TYPE))
10180         return do_mpfr_arg1 (arg0, type, mpfr_erfc, NULL, NULL, 0);
10181     break;
10182
10183     CASE_FLT_FN (BUILT_IN_TGAMMA):
10184       if (validate_arg (arg0, REAL_TYPE))
10185         return do_mpfr_arg1 (arg0, type, mpfr_gamma, NULL, NULL, 0);
10186     break;
10187
10188     CASE_FLT_FN (BUILT_IN_EXP):
10189       return fold_builtin_exponent (loc, fndecl, arg0, mpfr_exp);
10190
10191     CASE_FLT_FN (BUILT_IN_EXP2):
10192       return fold_builtin_exponent (loc, fndecl, arg0, mpfr_exp2);
10193
10194     CASE_FLT_FN (BUILT_IN_EXP10):
10195     CASE_FLT_FN (BUILT_IN_POW10):
10196       return fold_builtin_exponent (loc, fndecl, arg0, mpfr_exp10);
10197
10198     CASE_FLT_FN (BUILT_IN_EXPM1):
10199       if (validate_arg (arg0, REAL_TYPE))
10200         return do_mpfr_arg1 (arg0, type, mpfr_expm1, NULL, NULL, 0);
10201     break;
10202
10203     CASE_FLT_FN (BUILT_IN_LOG):
10204     return fold_builtin_logarithm (loc, fndecl, arg0, mpfr_log);
10205
10206     CASE_FLT_FN (BUILT_IN_LOG2):
10207       return fold_builtin_logarithm (loc, fndecl, arg0, mpfr_log2);
10208
10209     CASE_FLT_FN (BUILT_IN_LOG10):
10210       return fold_builtin_logarithm (loc, fndecl, arg0, mpfr_log10);
10211
10212     CASE_FLT_FN (BUILT_IN_LOG1P):
10213       if (validate_arg (arg0, REAL_TYPE))
10214         return do_mpfr_arg1 (arg0, type, mpfr_log1p,
10215                              &dconstm1, NULL, false);
10216     break;
10217
10218     CASE_FLT_FN (BUILT_IN_J0):
10219       if (validate_arg (arg0, REAL_TYPE))
10220         return do_mpfr_arg1 (arg0, type, mpfr_j0,
10221                              NULL, NULL, 0);
10222     break;
10223
10224     CASE_FLT_FN (BUILT_IN_J1):
10225       if (validate_arg (arg0, REAL_TYPE))
10226         return do_mpfr_arg1 (arg0, type, mpfr_j1,
10227                              NULL, NULL, 0);
10228     break;
10229
10230     CASE_FLT_FN (BUILT_IN_Y0):
10231       if (validate_arg (arg0, REAL_TYPE))
10232         return do_mpfr_arg1 (arg0, type, mpfr_y0,
10233                              &dconst0, NULL, false);
10234     break;
10235
10236     CASE_FLT_FN (BUILT_IN_Y1):
10237       if (validate_arg (arg0, REAL_TYPE))
10238         return do_mpfr_arg1 (arg0, type, mpfr_y1,
10239                              &dconst0, NULL, false);
10240     break;
10241
10242     CASE_FLT_FN (BUILT_IN_NAN):
10243     case BUILT_IN_NAND32:
10244     case BUILT_IN_NAND64:
10245     case BUILT_IN_NAND128:
10246       return fold_builtin_nan (arg0, type, true);
10247
10248     CASE_FLT_FN (BUILT_IN_NANS):
10249       return fold_builtin_nan (arg0, type, false);
10250
10251     CASE_FLT_FN (BUILT_IN_FLOOR):
10252       return fold_builtin_floor (loc, fndecl, arg0);
10253
10254     CASE_FLT_FN (BUILT_IN_CEIL):
10255       return fold_builtin_ceil (loc, fndecl, arg0);
10256
10257     CASE_FLT_FN (BUILT_IN_TRUNC):
10258       return fold_builtin_trunc (loc, fndecl, arg0);
10259
10260     CASE_FLT_FN (BUILT_IN_ROUND):
10261       return fold_builtin_round (loc, fndecl, arg0);
10262
10263     CASE_FLT_FN (BUILT_IN_NEARBYINT):
10264     CASE_FLT_FN (BUILT_IN_RINT):
10265       return fold_trunc_transparent_mathfn (loc, fndecl, arg0);
10266
10267     CASE_FLT_FN (BUILT_IN_LCEIL):
10268     CASE_FLT_FN (BUILT_IN_LLCEIL):
10269     CASE_FLT_FN (BUILT_IN_LFLOOR):
10270     CASE_FLT_FN (BUILT_IN_LLFLOOR):
10271     CASE_FLT_FN (BUILT_IN_LROUND):
10272     CASE_FLT_FN (BUILT_IN_LLROUND):
10273       return fold_builtin_int_roundingfn (loc, fndecl, arg0);
10274
10275     CASE_FLT_FN (BUILT_IN_LRINT):
10276     CASE_FLT_FN (BUILT_IN_LLRINT):
10277       return fold_fixed_mathfn (loc, fndecl, arg0);
10278
10279     case BUILT_IN_BSWAP32:
10280     case BUILT_IN_BSWAP64:
10281       return fold_builtin_bswap (fndecl, arg0);
10282
10283     CASE_INT_FN (BUILT_IN_FFS):
10284     CASE_INT_FN (BUILT_IN_CLZ):
10285     CASE_INT_FN (BUILT_IN_CTZ):
10286     CASE_INT_FN (BUILT_IN_POPCOUNT):
10287     CASE_INT_FN (BUILT_IN_PARITY):
10288       return fold_builtin_bitop (fndecl, arg0);
10289
10290     CASE_FLT_FN (BUILT_IN_SIGNBIT):
10291       return fold_builtin_signbit (loc, arg0, type);
10292
10293     CASE_FLT_FN (BUILT_IN_SIGNIFICAND):
10294       return fold_builtin_significand (loc, arg0, type);
10295
10296     CASE_FLT_FN (BUILT_IN_ILOGB):
10297     CASE_FLT_FN (BUILT_IN_LOGB):
10298       return fold_builtin_logb (loc, arg0, type);
10299
10300     case BUILT_IN_ISASCII:
10301       return fold_builtin_isascii (loc, arg0);
10302
10303     case BUILT_IN_TOASCII:
10304       return fold_builtin_toascii (loc, arg0);
10305
10306     case BUILT_IN_ISDIGIT:
10307       return fold_builtin_isdigit (loc, arg0);
10308
10309     CASE_FLT_FN (BUILT_IN_FINITE):
10310     case BUILT_IN_FINITED32:
10311     case BUILT_IN_FINITED64:
10312     case BUILT_IN_FINITED128:
10313     case BUILT_IN_ISFINITE:
10314       {
10315         tree ret = fold_builtin_classify (loc, fndecl, arg0, BUILT_IN_ISFINITE);
10316         if (ret)
10317           return ret;
10318         return fold_builtin_interclass_mathfn (loc, fndecl, arg0);
10319       }
10320
10321     CASE_FLT_FN (BUILT_IN_ISINF):
10322     case BUILT_IN_ISINFD32:
10323     case BUILT_IN_ISINFD64:
10324     case BUILT_IN_ISINFD128:
10325       {
10326         tree ret = fold_builtin_classify (loc, fndecl, arg0, BUILT_IN_ISINF);
10327         if (ret)
10328           return ret;
10329         return fold_builtin_interclass_mathfn (loc, fndecl, arg0);
10330       }
10331
10332     case BUILT_IN_ISNORMAL:
10333       return fold_builtin_interclass_mathfn (loc, fndecl, arg0);
10334
10335     case BUILT_IN_ISINF_SIGN:
10336       return fold_builtin_classify (loc, fndecl, arg0, BUILT_IN_ISINF_SIGN);
10337
10338     CASE_FLT_FN (BUILT_IN_ISNAN):
10339     case BUILT_IN_ISNAND32:
10340     case BUILT_IN_ISNAND64:
10341     case BUILT_IN_ISNAND128:
10342       return fold_builtin_classify (loc, fndecl, arg0, BUILT_IN_ISNAN);
10343
10344     case BUILT_IN_PRINTF:
10345     case BUILT_IN_PRINTF_UNLOCKED:
10346     case BUILT_IN_VPRINTF:
10347       return fold_builtin_printf (loc, fndecl, arg0, NULL_TREE, ignore, fcode);
10348
10349     case BUILT_IN_FREE:
10350       if (integer_zerop (arg0))
10351         return build_empty_stmt (loc);
10352       break;
10353
10354     default:
10355       break;
10356     }
10357
10358   return NULL_TREE;
10359
10360 }
10361
10362 /* Fold a call to built-in function FNDECL with 2 arguments, ARG0 and ARG1.
10363    IGNORE is true if the result of the function call is ignored.  This
10364    function returns NULL_TREE if no simplification was possible.  */
10365
10366 static tree
10367 fold_builtin_2 (location_t loc, tree fndecl, tree arg0, tree arg1, bool ignore)
10368 {
10369   tree type = TREE_TYPE (TREE_TYPE (fndecl));
10370   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
10371
10372   switch (fcode)
10373     {
10374     CASE_FLT_FN (BUILT_IN_JN):
10375       if (validate_arg (arg0, INTEGER_TYPE)
10376           && validate_arg (arg1, REAL_TYPE))
10377         return do_mpfr_bessel_n (arg0, arg1, type, mpfr_jn, NULL, 0);
10378     break;
10379
10380     CASE_FLT_FN (BUILT_IN_YN):
10381       if (validate_arg (arg0, INTEGER_TYPE)
10382           && validate_arg (arg1, REAL_TYPE))
10383         return do_mpfr_bessel_n (arg0, arg1, type, mpfr_yn,
10384                                  &dconst0, false);
10385     break;
10386
10387     CASE_FLT_FN (BUILT_IN_DREM):
10388     CASE_FLT_FN (BUILT_IN_REMAINDER):
10389       if (validate_arg (arg0, REAL_TYPE)
10390           && validate_arg(arg1, REAL_TYPE))
10391         return do_mpfr_arg2 (arg0, arg1, type, mpfr_remainder);
10392     break;
10393
10394     CASE_FLT_FN_REENT (BUILT_IN_GAMMA): /* GAMMA_R */
10395     CASE_FLT_FN_REENT (BUILT_IN_LGAMMA): /* LGAMMA_R */
10396       if (validate_arg (arg0, REAL_TYPE)
10397           && validate_arg(arg1, POINTER_TYPE))
10398         return do_mpfr_lgamma_r (arg0, arg1, type);
10399     break;
10400
10401     CASE_FLT_FN (BUILT_IN_ATAN2):
10402       if (validate_arg (arg0, REAL_TYPE)
10403           && validate_arg(arg1, REAL_TYPE))
10404         return do_mpfr_arg2 (arg0, arg1, type, mpfr_atan2);
10405     break;
10406
10407     CASE_FLT_FN (BUILT_IN_FDIM):
10408       if (validate_arg (arg0, REAL_TYPE)
10409           && validate_arg(arg1, REAL_TYPE))
10410         return do_mpfr_arg2 (arg0, arg1, type, mpfr_dim);
10411     break;
10412
10413     CASE_FLT_FN (BUILT_IN_HYPOT):
10414       return fold_builtin_hypot (loc, fndecl, arg0, arg1, type);
10415
10416     CASE_FLT_FN (BUILT_IN_CPOW):
10417       if (validate_arg (arg0, COMPLEX_TYPE)
10418           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE
10419           && validate_arg (arg1, COMPLEX_TYPE)
10420           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg1))) == REAL_TYPE)
10421         return do_mpc_arg2 (arg0, arg1, type, /*do_nonfinite=*/ 0, mpc_pow);
10422     break;
10423
10424     CASE_FLT_FN (BUILT_IN_LDEXP):
10425       return fold_builtin_load_exponent (loc, arg0, arg1, type, /*ldexp=*/true);
10426     CASE_FLT_FN (BUILT_IN_SCALBN):
10427     CASE_FLT_FN (BUILT_IN_SCALBLN):
10428       return fold_builtin_load_exponent (loc, arg0, arg1,
10429                                          type, /*ldexp=*/false);
10430
10431     CASE_FLT_FN (BUILT_IN_FREXP):
10432       return fold_builtin_frexp (loc, arg0, arg1, type);
10433
10434     CASE_FLT_FN (BUILT_IN_MODF):
10435       return fold_builtin_modf (loc, arg0, arg1, type);
10436
10437     case BUILT_IN_BZERO:
10438       return fold_builtin_bzero (loc, arg0, arg1, ignore);
10439
10440     case BUILT_IN_FPUTS:
10441       return fold_builtin_fputs (loc, arg0, arg1, ignore, false, NULL_TREE);
10442
10443     case BUILT_IN_FPUTS_UNLOCKED:
10444       return fold_builtin_fputs (loc, arg0, arg1, ignore, true, NULL_TREE);
10445
10446     case BUILT_IN_STRSTR:
10447       return fold_builtin_strstr (loc, arg0, arg1, type);
10448
10449     case BUILT_IN_STRCAT:
10450       return fold_builtin_strcat (loc, arg0, arg1);
10451
10452     case BUILT_IN_STRSPN:
10453       return fold_builtin_strspn (loc, arg0, arg1);
10454
10455     case BUILT_IN_STRCSPN:
10456       return fold_builtin_strcspn (loc, arg0, arg1);
10457
10458     case BUILT_IN_STRCHR:
10459     case BUILT_IN_INDEX:
10460       return fold_builtin_strchr (loc, arg0, arg1, type);
10461
10462     case BUILT_IN_STRRCHR:
10463     case BUILT_IN_RINDEX:
10464       return fold_builtin_strrchr (loc, arg0, arg1, type);
10465
10466     case BUILT_IN_STRCPY:
10467       return fold_builtin_strcpy (loc, fndecl, arg0, arg1, NULL_TREE);
10468
10469     case BUILT_IN_STPCPY:
10470       if (ignore)
10471         {
10472           tree fn = implicit_built_in_decls[BUILT_IN_STRCPY];
10473           if (!fn)
10474             break;
10475
10476           return build_call_expr_loc (loc, fn, 2, arg0, arg1);
10477         }
10478       else
10479         return fold_builtin_stpcpy (loc, fndecl, arg0, arg1);
10480       break;
10481
10482     case BUILT_IN_STRCMP:
10483       return fold_builtin_strcmp (loc, arg0, arg1);
10484
10485     case BUILT_IN_STRPBRK:
10486       return fold_builtin_strpbrk (loc, arg0, arg1, type);
10487
10488     case BUILT_IN_EXPECT:
10489       return fold_builtin_expect (loc, arg0, arg1);
10490
10491     CASE_FLT_FN (BUILT_IN_POW):
10492       return fold_builtin_pow (loc, fndecl, arg0, arg1, type);
10493
10494     CASE_FLT_FN (BUILT_IN_POWI):
10495       return fold_builtin_powi (loc, fndecl, arg0, arg1, type);
10496
10497     CASE_FLT_FN (BUILT_IN_COPYSIGN):
10498       return fold_builtin_copysign (loc, fndecl, arg0, arg1, type);
10499
10500     CASE_FLT_FN (BUILT_IN_FMIN):
10501       return fold_builtin_fmin_fmax (loc, arg0, arg1, type, /*max=*/false);
10502
10503     CASE_FLT_FN (BUILT_IN_FMAX):
10504       return fold_builtin_fmin_fmax (loc, arg0, arg1, type, /*max=*/true);
10505
10506     case BUILT_IN_ISGREATER:
10507       return fold_builtin_unordered_cmp (loc, fndecl,
10508                                          arg0, arg1, UNLE_EXPR, LE_EXPR);
10509     case BUILT_IN_ISGREATEREQUAL:
10510       return fold_builtin_unordered_cmp (loc, fndecl,
10511                                          arg0, arg1, UNLT_EXPR, LT_EXPR);
10512     case BUILT_IN_ISLESS:
10513       return fold_builtin_unordered_cmp (loc, fndecl,
10514                                          arg0, arg1, UNGE_EXPR, GE_EXPR);
10515     case BUILT_IN_ISLESSEQUAL:
10516       return fold_builtin_unordered_cmp (loc, fndecl,
10517                                          arg0, arg1, UNGT_EXPR, GT_EXPR);
10518     case BUILT_IN_ISLESSGREATER:
10519       return fold_builtin_unordered_cmp (loc, fndecl,
10520                                          arg0, arg1, UNEQ_EXPR, EQ_EXPR);
10521     case BUILT_IN_ISUNORDERED:
10522       return fold_builtin_unordered_cmp (loc, fndecl,
10523                                          arg0, arg1, UNORDERED_EXPR,
10524                                          NOP_EXPR);
10525
10526       /* We do the folding for va_start in the expander.  */
10527     case BUILT_IN_VA_START:
10528       break;
10529
10530     case BUILT_IN_SPRINTF:
10531       return fold_builtin_sprintf (loc, arg0, arg1, NULL_TREE, ignore);
10532
10533     case BUILT_IN_OBJECT_SIZE:
10534       return fold_builtin_object_size (arg0, arg1);
10535
10536     case BUILT_IN_PRINTF:
10537     case BUILT_IN_PRINTF_UNLOCKED:
10538     case BUILT_IN_VPRINTF:
10539       return fold_builtin_printf (loc, fndecl, arg0, arg1, ignore, fcode);
10540
10541     case BUILT_IN_PRINTF_CHK:
10542     case BUILT_IN_VPRINTF_CHK:
10543       if (!validate_arg (arg0, INTEGER_TYPE)
10544           || TREE_SIDE_EFFECTS (arg0))
10545         return NULL_TREE;
10546       else
10547         return fold_builtin_printf (loc, fndecl,
10548                                     arg1, NULL_TREE, ignore, fcode);
10549     break;
10550
10551     case BUILT_IN_FPRINTF:
10552     case BUILT_IN_FPRINTF_UNLOCKED:
10553     case BUILT_IN_VFPRINTF:
10554       return fold_builtin_fprintf (loc, fndecl, arg0, arg1, NULL_TREE,
10555                                    ignore, fcode);
10556
10557     default:
10558       break;
10559     }
10560   return NULL_TREE;
10561 }
10562
10563 /* Fold a call to built-in function FNDECL with 3 arguments, ARG0, ARG1,
10564    and ARG2.  IGNORE is true if the result of the function call is ignored.
10565    This function returns NULL_TREE if no simplification was possible.  */
10566
10567 static tree
10568 fold_builtin_3 (location_t loc, tree fndecl,
10569                 tree arg0, tree arg1, tree arg2, bool ignore)
10570 {
10571   tree type = TREE_TYPE (TREE_TYPE (fndecl));
10572   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
10573   switch (fcode)
10574     {
10575
10576     CASE_FLT_FN (BUILT_IN_SINCOS):
10577       return fold_builtin_sincos (loc, arg0, arg1, arg2);
10578
10579     CASE_FLT_FN (BUILT_IN_FMA):
10580       return fold_builtin_fma (loc, arg0, arg1, arg2, type);
10581     break;
10582
10583     CASE_FLT_FN (BUILT_IN_REMQUO):
10584       if (validate_arg (arg0, REAL_TYPE)
10585           && validate_arg(arg1, REAL_TYPE)
10586           && validate_arg(arg2, POINTER_TYPE))
10587         return do_mpfr_remquo (arg0, arg1, arg2);
10588     break;
10589
10590     case BUILT_IN_MEMSET:
10591       return fold_builtin_memset (loc, arg0, arg1, arg2, type, ignore);
10592
10593     case BUILT_IN_BCOPY:
10594       return fold_builtin_memory_op (loc, arg1, arg0, arg2,
10595                                      void_type_node, true, /*endp=*/3);
10596
10597     case BUILT_IN_MEMCPY:
10598       return fold_builtin_memory_op (loc, arg0, arg1, arg2,
10599                                      type, ignore, /*endp=*/0);
10600
10601     case BUILT_IN_MEMPCPY:
10602       return fold_builtin_memory_op (loc, arg0, arg1, arg2,
10603                                      type, ignore, /*endp=*/1);
10604
10605     case BUILT_IN_MEMMOVE:
10606       return fold_builtin_memory_op (loc, arg0, arg1, arg2,
10607                                      type, ignore, /*endp=*/3);
10608
10609     case BUILT_IN_STRNCAT:
10610       return fold_builtin_strncat (loc, arg0, arg1, arg2);
10611
10612     case BUILT_IN_STRNCPY:
10613       return fold_builtin_strncpy (loc, fndecl, arg0, arg1, arg2, NULL_TREE);
10614
10615     case BUILT_IN_STRNCMP:
10616       return fold_builtin_strncmp (loc, arg0, arg1, arg2);
10617
10618     case BUILT_IN_MEMCHR:
10619       return fold_builtin_memchr (loc, arg0, arg1, arg2, type);
10620
10621     case BUILT_IN_BCMP:
10622     case BUILT_IN_MEMCMP:
10623       return fold_builtin_memcmp (loc, arg0, arg1, arg2);;
10624
10625     case BUILT_IN_SPRINTF:
10626       return fold_builtin_sprintf (loc, arg0, arg1, arg2, ignore);
10627
10628     case BUILT_IN_STRCPY_CHK:
10629     case BUILT_IN_STPCPY_CHK:
10630       return fold_builtin_stxcpy_chk (loc, fndecl, arg0, arg1, arg2, NULL_TREE,
10631                                       ignore, fcode);
10632
10633     case BUILT_IN_STRCAT_CHK:
10634       return fold_builtin_strcat_chk (loc, fndecl, arg0, arg1, arg2);
10635
10636     case BUILT_IN_PRINTF_CHK:
10637     case BUILT_IN_VPRINTF_CHK:
10638       if (!validate_arg (arg0, INTEGER_TYPE)
10639           || TREE_SIDE_EFFECTS (arg0))
10640         return NULL_TREE;
10641       else
10642         return fold_builtin_printf (loc, fndecl, arg1, arg2, ignore, fcode);
10643     break;
10644
10645     case BUILT_IN_FPRINTF:
10646     case BUILT_IN_FPRINTF_UNLOCKED:
10647     case BUILT_IN_VFPRINTF:
10648       return fold_builtin_fprintf (loc, fndecl, arg0, arg1, arg2,
10649                                    ignore, fcode);
10650
10651     case BUILT_IN_FPRINTF_CHK:
10652     case BUILT_IN_VFPRINTF_CHK:
10653       if (!validate_arg (arg1, INTEGER_TYPE)
10654           || TREE_SIDE_EFFECTS (arg1))
10655         return NULL_TREE;
10656       else
10657         return fold_builtin_fprintf (loc, fndecl, arg0, arg2, NULL_TREE,
10658                                      ignore, fcode);
10659
10660     default:
10661       break;
10662     }
10663   return NULL_TREE;
10664 }
10665
10666 /* Fold a call to built-in function FNDECL with 4 arguments, ARG0, ARG1,
10667    ARG2, and ARG3.  IGNORE is true if the result of the function call is
10668    ignored.  This function returns NULL_TREE if no simplification was
10669    possible.  */
10670
10671 static tree
10672 fold_builtin_4 (location_t loc, tree fndecl,
10673                 tree arg0, tree arg1, tree arg2, tree arg3, bool ignore)
10674 {
10675   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
10676
10677   switch (fcode)
10678     {
10679     case BUILT_IN_MEMCPY_CHK:
10680     case BUILT_IN_MEMPCPY_CHK:
10681     case BUILT_IN_MEMMOVE_CHK:
10682     case BUILT_IN_MEMSET_CHK:
10683       return fold_builtin_memory_chk (loc, fndecl, arg0, arg1, arg2, arg3,
10684                                       NULL_TREE, ignore,
10685                                       DECL_FUNCTION_CODE (fndecl));
10686
10687     case BUILT_IN_STRNCPY_CHK:
10688       return fold_builtin_strncpy_chk (loc, arg0, arg1, arg2, arg3, NULL_TREE);
10689
10690     case BUILT_IN_STRNCAT_CHK:
10691       return fold_builtin_strncat_chk (loc, fndecl, arg0, arg1, arg2, arg3);
10692
10693     case BUILT_IN_FPRINTF_CHK:
10694     case BUILT_IN_VFPRINTF_CHK:
10695       if (!validate_arg (arg1, INTEGER_TYPE)
10696           || TREE_SIDE_EFFECTS (arg1))
10697         return NULL_TREE;
10698       else
10699         return fold_builtin_fprintf (loc, fndecl, arg0, arg2, arg3,
10700                                      ignore, fcode);
10701     break;
10702
10703     default:
10704       break;
10705     }
10706   return NULL_TREE;
10707 }
10708
10709 /* Fold a call to built-in function FNDECL.  ARGS is an array of NARGS
10710     arguments, where NARGS <= 4.  IGNORE is true if the result of the
10711     function call is ignored.  This function returns NULL_TREE if no
10712     simplification was possible.  Note that this only folds builtins with
10713     fixed argument patterns.  Foldings that do varargs-to-varargs
10714     transformations, or that match calls with more than 4 arguments,
10715     need to be handled with fold_builtin_varargs instead.  */
10716
10717 #define MAX_ARGS_TO_FOLD_BUILTIN 4
10718
10719 static tree
10720 fold_builtin_n (location_t loc, tree fndecl, tree *args, int nargs, bool ignore)
10721 {
10722   tree ret = NULL_TREE;
10723
10724   switch (nargs)
10725     {
10726     case 0:
10727       ret = fold_builtin_0 (loc, fndecl, ignore);
10728       break;
10729     case 1:
10730       ret = fold_builtin_1 (loc, fndecl, args[0], ignore);
10731       break;
10732     case 2:
10733       ret = fold_builtin_2 (loc, fndecl, args[0], args[1], ignore);
10734       break;
10735     case 3:
10736       ret = fold_builtin_3 (loc, fndecl, args[0], args[1], args[2], ignore);
10737       break;
10738     case 4:
10739       ret = fold_builtin_4 (loc, fndecl, args[0], args[1], args[2], args[3],
10740                             ignore);
10741       break;
10742     default:
10743       break;
10744     }
10745   if (ret)
10746     {
10747       ret = build1 (NOP_EXPR, TREE_TYPE (ret), ret);
10748       SET_EXPR_LOCATION (ret, loc);
10749       TREE_NO_WARNING (ret) = 1;
10750       return ret;
10751     }
10752   return NULL_TREE;
10753 }
10754
10755 /* Builtins with folding operations that operate on "..." arguments
10756    need special handling; we need to store the arguments in a convenient
10757    data structure before attempting any folding.  Fortunately there are
10758    only a few builtins that fall into this category.  FNDECL is the
10759    function, EXP is the CALL_EXPR for the call, and IGNORE is true if the
10760    result of the function call is ignored.  */
10761
10762 static tree
10763 fold_builtin_varargs (location_t loc, tree fndecl, tree exp,
10764                       bool ignore ATTRIBUTE_UNUSED)
10765 {
10766   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
10767   tree ret = NULL_TREE;
10768
10769   switch (fcode)
10770     {
10771     case BUILT_IN_SPRINTF_CHK:
10772     case BUILT_IN_VSPRINTF_CHK:
10773       ret = fold_builtin_sprintf_chk (loc, exp, fcode);
10774       break;
10775
10776     case BUILT_IN_SNPRINTF_CHK:
10777     case BUILT_IN_VSNPRINTF_CHK:
10778       ret = fold_builtin_snprintf_chk (loc, exp, NULL_TREE, fcode);
10779       break;
10780
10781     case BUILT_IN_FPCLASSIFY:
10782       ret = fold_builtin_fpclassify (loc, exp);
10783       break;
10784
10785     default:
10786       break;
10787     }
10788   if (ret)
10789     {
10790       ret = build1 (NOP_EXPR, TREE_TYPE (ret), ret);
10791       SET_EXPR_LOCATION (ret, loc);
10792       TREE_NO_WARNING (ret) = 1;
10793       return ret;
10794     }
10795   return NULL_TREE;
10796 }
10797
10798 /* Return true if FNDECL shouldn't be folded right now.
10799    If a built-in function has an inline attribute always_inline
10800    wrapper, defer folding it after always_inline functions have
10801    been inlined, otherwise e.g. -D_FORTIFY_SOURCE checking
10802    might not be performed.  */
10803
10804 static bool
10805 avoid_folding_inline_builtin (tree fndecl)
10806 {
10807   return (DECL_DECLARED_INLINE_P (fndecl)
10808           && DECL_DISREGARD_INLINE_LIMITS (fndecl)
10809           && cfun
10810           && !cfun->always_inline_functions_inlined
10811           && lookup_attribute ("always_inline", DECL_ATTRIBUTES (fndecl)));
10812 }
10813
10814 /* A wrapper function for builtin folding that prevents warnings for
10815    "statement without effect" and the like, caused by removing the
10816    call node earlier than the warning is generated.  */
10817
10818 tree
10819 fold_call_expr (location_t loc, tree exp, bool ignore)
10820 {
10821   tree ret = NULL_TREE;
10822   tree fndecl = get_callee_fndecl (exp);
10823   if (fndecl
10824       && TREE_CODE (fndecl) == FUNCTION_DECL
10825       && DECL_BUILT_IN (fndecl)
10826       /* If CALL_EXPR_VA_ARG_PACK is set, the arguments aren't finalized
10827          yet.  Defer folding until we see all the arguments
10828          (after inlining).  */
10829       && !CALL_EXPR_VA_ARG_PACK (exp))
10830     {
10831       int nargs = call_expr_nargs (exp);
10832
10833       /* Before gimplification CALL_EXPR_VA_ARG_PACK is not set, but
10834          instead last argument is __builtin_va_arg_pack ().  Defer folding
10835          even in that case, until arguments are finalized.  */
10836       if (nargs && TREE_CODE (CALL_EXPR_ARG (exp, nargs - 1)) == CALL_EXPR)
10837         {
10838           tree fndecl2 = get_callee_fndecl (CALL_EXPR_ARG (exp, nargs - 1));
10839           if (fndecl2
10840               && TREE_CODE (fndecl2) == FUNCTION_DECL
10841               && DECL_BUILT_IN_CLASS (fndecl2) == BUILT_IN_NORMAL
10842               && DECL_FUNCTION_CODE (fndecl2) == BUILT_IN_VA_ARG_PACK)
10843             return NULL_TREE;
10844         }
10845
10846       if (avoid_folding_inline_builtin (fndecl))
10847         return NULL_TREE;
10848
10849       if (DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_MD)
10850         return targetm.fold_builtin (fndecl, call_expr_nargs (exp),
10851                                      CALL_EXPR_ARGP (exp), ignore);
10852       else
10853         {
10854           if (nargs <= MAX_ARGS_TO_FOLD_BUILTIN)
10855             {
10856               tree *args = CALL_EXPR_ARGP (exp);
10857               ret = fold_builtin_n (loc, fndecl, args, nargs, ignore);
10858             }
10859           if (!ret)
10860             ret = fold_builtin_varargs (loc, fndecl, exp, ignore);
10861           if (ret)
10862             return ret;
10863         }
10864     }
10865   return NULL_TREE;
10866 }
10867
10868 /* Conveniently construct a function call expression.  FNDECL names the
10869    function to be called and N arguments are passed in the array
10870    ARGARRAY.  */
10871
10872 tree
10873 build_call_expr_loc_array (location_t loc, tree fndecl, int n, tree *argarray)
10874 {
10875   tree fntype = TREE_TYPE (fndecl);
10876   tree fn = build1 (ADDR_EXPR, build_pointer_type (fntype), fndecl);
10877  
10878   return fold_builtin_call_array (loc, TREE_TYPE (fntype), fn, n, argarray);
10879 }
10880
10881 /* Conveniently construct a function call expression.  FNDECL names the
10882    function to be called and the arguments are passed in the vector
10883    VEC.  */
10884
10885 tree
10886 build_call_expr_loc_vec (location_t loc, tree fndecl, VEC(tree,gc) *vec)
10887 {
10888   return build_call_expr_loc_array (loc, fndecl, VEC_length (tree, vec),
10889                                     VEC_address (tree, vec));
10890 }
10891
10892
10893 /* Conveniently construct a function call expression.  FNDECL names the
10894    function to be called, N is the number of arguments, and the "..."
10895    parameters are the argument expressions.  */
10896
10897 tree
10898 build_call_expr_loc (location_t loc, tree fndecl, int n, ...)
10899 {
10900   va_list ap;
10901   tree *argarray = XALLOCAVEC (tree, n);
10902   int i;
10903
10904   va_start (ap, n);
10905   for (i = 0; i < n; i++)
10906     argarray[i] = va_arg (ap, tree);
10907   va_end (ap);
10908   return build_call_expr_loc_array (loc, fndecl, n, argarray);
10909 }
10910
10911 /* Like build_call_expr_loc (UNKNOWN_LOCATION, ...).  Duplicated because
10912    varargs macros aren't supported by all bootstrap compilers.  */
10913
10914 tree
10915 build_call_expr (tree fndecl, int n, ...)
10916 {
10917   va_list ap;
10918   tree *argarray = XALLOCAVEC (tree, n);
10919   int i;
10920
10921   va_start (ap, n);
10922   for (i = 0; i < n; i++)
10923     argarray[i] = va_arg (ap, tree);
10924   va_end (ap);
10925   return build_call_expr_loc_array (UNKNOWN_LOCATION, fndecl, n, argarray);
10926 }
10927
10928 /* Construct a CALL_EXPR with type TYPE with FN as the function expression.
10929    N arguments are passed in the array ARGARRAY.  */
10930
10931 tree
10932 fold_builtin_call_array (location_t loc, tree type,
10933                          tree fn,
10934                          int n,
10935                          tree *argarray)
10936 {
10937   tree ret = NULL_TREE;
10938    tree exp;
10939
10940   if (TREE_CODE (fn) == ADDR_EXPR)
10941   {
10942     tree fndecl = TREE_OPERAND (fn, 0);
10943     if (TREE_CODE (fndecl) == FUNCTION_DECL
10944         && DECL_BUILT_IN (fndecl))
10945       {
10946         /* If last argument is __builtin_va_arg_pack (), arguments to this
10947            function are not finalized yet.  Defer folding until they are.  */
10948         if (n && TREE_CODE (argarray[n - 1]) == CALL_EXPR)
10949           {
10950             tree fndecl2 = get_callee_fndecl (argarray[n - 1]);
10951             if (fndecl2
10952                 && TREE_CODE (fndecl2) == FUNCTION_DECL
10953                 && DECL_BUILT_IN_CLASS (fndecl2) == BUILT_IN_NORMAL
10954                 && DECL_FUNCTION_CODE (fndecl2) == BUILT_IN_VA_ARG_PACK)
10955               return build_call_array_loc (loc, type, fn, n, argarray);
10956           }
10957         if (avoid_folding_inline_builtin (fndecl))
10958           return build_call_array_loc (loc, type, fn, n, argarray);
10959         if (DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_MD)
10960           {
10961             ret = targetm.fold_builtin (fndecl, n, argarray, false);
10962             if (ret)
10963               return ret;
10964
10965             return build_call_array_loc (loc, type, fn, n, argarray);
10966           }
10967         else if (n <= MAX_ARGS_TO_FOLD_BUILTIN)
10968           {
10969             /* First try the transformations that don't require consing up
10970                an exp.  */
10971             ret = fold_builtin_n (loc, fndecl, argarray, n, false);
10972             if (ret)
10973               return ret;
10974           }
10975
10976         /* If we got this far, we need to build an exp.  */
10977         exp = build_call_array_loc (loc, type, fn, n, argarray);
10978         ret = fold_builtin_varargs (loc, fndecl, exp, false);
10979         return ret ? ret : exp;
10980       }
10981   }
10982
10983   return build_call_array_loc (loc, type, fn, n, argarray);
10984 }
10985
10986 /* Construct a new CALL_EXPR to FNDECL using the tail of the argument
10987    list ARGS along with N new arguments in NEWARGS.  SKIP is the number
10988    of arguments in ARGS to be omitted.  OLDNARGS is the number of
10989    elements in ARGS.  */
10990
10991 static tree
10992 rewrite_call_expr_valist (location_t loc, int oldnargs, tree *args,
10993                           int skip, tree fndecl, int n, va_list newargs)
10994 {
10995   int nargs = oldnargs - skip + n;
10996   tree *buffer;
10997
10998   if (n > 0)
10999     {
11000       int i, j;
11001
11002       buffer = XALLOCAVEC (tree, nargs);
11003       for (i = 0; i < n; i++)
11004         buffer[i] = va_arg (newargs, tree);
11005       for (j = skip; j < oldnargs; j++, i++)
11006         buffer[i] = args[j];
11007     }
11008   else
11009     buffer = args + skip;
11010
11011   return build_call_expr_loc_array (loc, fndecl, nargs, buffer);
11012 }
11013
11014 /* Construct a new CALL_EXPR to FNDECL using the tail of the argument
11015    list ARGS along with N new arguments specified as the "..."
11016    parameters.  SKIP is the number of arguments in ARGS to be omitted.
11017    OLDNARGS is the number of elements in ARGS.  */
11018
11019 static tree
11020 rewrite_call_expr_array (location_t loc, int oldnargs, tree *args,
11021                          int skip, tree fndecl, int n, ...)
11022 {
11023   va_list ap;
11024   tree t;
11025
11026   va_start (ap, n);
11027   t = rewrite_call_expr_valist (loc, oldnargs, args, skip, fndecl, n, ap);
11028   va_end (ap);
11029
11030   return t;
11031 }
11032
11033 /* Construct a new CALL_EXPR using the tail of the argument list of EXP
11034    along with N new arguments specified as the "..." parameters.  SKIP
11035    is the number of arguments in EXP to be omitted.  This function is used
11036    to do varargs-to-varargs transformations.  */
11037
11038 static tree
11039 rewrite_call_expr (location_t loc, tree exp, int skip, tree fndecl, int n, ...)
11040 {
11041   va_list ap;
11042   tree t;
11043
11044   va_start (ap, n);
11045   t = rewrite_call_expr_valist (loc, call_expr_nargs (exp),
11046                                 CALL_EXPR_ARGP (exp), skip, fndecl, n, ap);
11047   va_end (ap);
11048
11049   return t;
11050 }
11051
11052 /* Validate a single argument ARG against a tree code CODE representing
11053    a type.  */
11054
11055 static bool
11056 validate_arg (const_tree arg, enum tree_code code)
11057 {
11058   if (!arg)
11059     return false;
11060   else if (code == POINTER_TYPE)
11061     return POINTER_TYPE_P (TREE_TYPE (arg));
11062   else if (code == INTEGER_TYPE)
11063     return INTEGRAL_TYPE_P (TREE_TYPE (arg));
11064   return code == TREE_CODE (TREE_TYPE (arg));
11065 }
11066
11067 /* This function validates the types of a function call argument list
11068    against a specified list of tree_codes.  If the last specifier is a 0,
11069    that represents an ellipses, otherwise the last specifier must be a
11070    VOID_TYPE.
11071
11072    This is the GIMPLE version of validate_arglist.  Eventually we want to
11073    completely convert builtins.c to work from GIMPLEs and the tree based
11074    validate_arglist will then be removed.  */
11075
11076 bool
11077 validate_gimple_arglist (const_gimple call, ...)
11078 {
11079   enum tree_code code;
11080   bool res = 0;
11081   va_list ap;
11082   const_tree arg;
11083   size_t i;
11084
11085   va_start (ap, call);
11086   i = 0;
11087
11088   do
11089     {
11090       code = (enum tree_code) va_arg (ap, int);
11091       switch (code)
11092         {
11093         case 0:
11094           /* This signifies an ellipses, any further arguments are all ok.  */
11095           res = true;
11096           goto end;
11097         case VOID_TYPE:
11098           /* This signifies an endlink, if no arguments remain, return
11099              true, otherwise return false.  */
11100           res = (i == gimple_call_num_args (call));
11101           goto end;
11102         default:
11103           /* If no parameters remain or the parameter's code does not
11104              match the specified code, return false.  Otherwise continue
11105              checking any remaining arguments.  */
11106           arg = gimple_call_arg (call, i++);
11107           if (!validate_arg (arg, code))
11108             goto end;
11109           break;
11110         }
11111     }
11112   while (1);
11113
11114   /* We need gotos here since we can only have one VA_CLOSE in a
11115      function.  */
11116  end: ;
11117   va_end (ap);
11118
11119   return res;
11120 }
11121
11122 /* This function validates the types of a function call argument list
11123    against a specified list of tree_codes.  If the last specifier is a 0,
11124    that represents an ellipses, otherwise the last specifier must be a
11125    VOID_TYPE.  */
11126
11127 bool
11128 validate_arglist (const_tree callexpr, ...)
11129 {
11130   enum tree_code code;
11131   bool res = 0;
11132   va_list ap;
11133   const_call_expr_arg_iterator iter;
11134   const_tree arg;
11135
11136   va_start (ap, callexpr);
11137   init_const_call_expr_arg_iterator (callexpr, &iter);
11138
11139   do
11140     {
11141       code = (enum tree_code) va_arg (ap, int);
11142       switch (code)
11143         {
11144         case 0:
11145           /* This signifies an ellipses, any further arguments are all ok.  */
11146           res = true;
11147           goto end;
11148         case VOID_TYPE:
11149           /* This signifies an endlink, if no arguments remain, return
11150              true, otherwise return false.  */
11151           res = !more_const_call_expr_args_p (&iter);
11152           goto end;
11153         default:
11154           /* If no parameters remain or the parameter's code does not
11155              match the specified code, return false.  Otherwise continue
11156              checking any remaining arguments.  */
11157           arg = next_const_call_expr_arg (&iter);
11158           if (!validate_arg (arg, code))
11159             goto end;
11160           break;
11161         }
11162     }
11163   while (1);
11164
11165   /* We need gotos here since we can only have one VA_CLOSE in a
11166      function.  */
11167  end: ;
11168   va_end (ap);
11169
11170   return res;
11171 }
11172
11173 /* Default target-specific builtin expander that does nothing.  */
11174
11175 rtx
11176 default_expand_builtin (tree exp ATTRIBUTE_UNUSED,
11177                         rtx target ATTRIBUTE_UNUSED,
11178                         rtx subtarget ATTRIBUTE_UNUSED,
11179                         enum machine_mode mode ATTRIBUTE_UNUSED,
11180                         int ignore ATTRIBUTE_UNUSED)
11181 {
11182   return NULL_RTX;
11183 }
11184
11185 /* Returns true is EXP represents data that would potentially reside
11186    in a readonly section.  */
11187
11188 static bool
11189 readonly_data_expr (tree exp)
11190 {
11191   STRIP_NOPS (exp);
11192
11193   if (TREE_CODE (exp) != ADDR_EXPR)
11194     return false;
11195
11196   exp = get_base_address (TREE_OPERAND (exp, 0));
11197   if (!exp)
11198     return false;
11199
11200   /* Make sure we call decl_readonly_section only for trees it
11201      can handle (since it returns true for everything it doesn't
11202      understand).  */
11203   if (TREE_CODE (exp) == STRING_CST
11204       || TREE_CODE (exp) == CONSTRUCTOR
11205       || (TREE_CODE (exp) == VAR_DECL && TREE_STATIC (exp)))
11206     return decl_readonly_section (exp, 0);
11207   else
11208     return false;
11209 }
11210
11211 /* Simplify a call to the strstr builtin.  S1 and S2 are the arguments
11212    to the call, and TYPE is its return type.
11213
11214    Return NULL_TREE if no simplification was possible, otherwise return the
11215    simplified form of the call as a tree.
11216
11217    The simplified form may be a constant or other expression which
11218    computes the same value, but in a more efficient manner (including
11219    calls to other builtin functions).
11220
11221    The call may contain arguments which need to be evaluated, but
11222    which are not useful to determine the result of the call.  In
11223    this case we return a chain of COMPOUND_EXPRs.  The LHS of each
11224    COMPOUND_EXPR will be an argument which must be evaluated.
11225    COMPOUND_EXPRs are chained through their RHS.  The RHS of the last
11226    COMPOUND_EXPR in the chain will contain the tree for the simplified
11227    form of the builtin function call.  */
11228
11229 static tree
11230 fold_builtin_strstr (location_t loc, tree s1, tree s2, tree type)
11231 {
11232   if (!validate_arg (s1, POINTER_TYPE)
11233       || !validate_arg (s2, POINTER_TYPE))
11234     return NULL_TREE;
11235   else
11236     {
11237       tree fn;
11238       const char *p1, *p2;
11239
11240       p2 = c_getstr (s2);
11241       if (p2 == NULL)
11242         return NULL_TREE;
11243
11244       p1 = c_getstr (s1);
11245       if (p1 != NULL)
11246         {
11247           const char *r = strstr (p1, p2);
11248           tree tem;
11249
11250           if (r == NULL)
11251             return build_int_cst (TREE_TYPE (s1), 0);
11252
11253           /* Return an offset into the constant string argument.  */
11254           tem = fold_build2_loc (loc, POINTER_PLUS_EXPR, TREE_TYPE (s1),
11255                              s1, size_int (r - p1));
11256           return fold_convert_loc (loc, type, tem);
11257         }
11258
11259       /* The argument is const char *, and the result is char *, so we need
11260          a type conversion here to avoid a warning.  */
11261       if (p2[0] == '\0')
11262         return fold_convert_loc (loc, type, s1);
11263
11264       if (p2[1] != '\0')
11265         return NULL_TREE;
11266
11267       fn = implicit_built_in_decls[BUILT_IN_STRCHR];
11268       if (!fn)
11269         return NULL_TREE;
11270
11271       /* New argument list transforming strstr(s1, s2) to
11272          strchr(s1, s2[0]).  */
11273       return build_call_expr_loc (loc, fn, 2, s1, build_int_cst (NULL_TREE, p2[0]));
11274     }
11275 }
11276
11277 /* Simplify a call to the strchr builtin.  S1 and S2 are the arguments to
11278    the call, and TYPE is its return type.
11279
11280    Return NULL_TREE if no simplification was possible, otherwise return the
11281    simplified form of the call as a tree.
11282
11283    The simplified form may be a constant or other expression which
11284    computes the same value, but in a more efficient manner (including
11285    calls to other builtin functions).
11286
11287    The call may contain arguments which need to be evaluated, but
11288    which are not useful to determine the result of the call.  In
11289    this case we return a chain of COMPOUND_EXPRs.  The LHS of each
11290    COMPOUND_EXPR will be an argument which must be evaluated.
11291    COMPOUND_EXPRs are chained through their RHS.  The RHS of the last
11292    COMPOUND_EXPR in the chain will contain the tree for the simplified
11293    form of the builtin function call.  */
11294
11295 static tree
11296 fold_builtin_strchr (location_t loc, tree s1, tree s2, tree type)
11297 {
11298   if (!validate_arg (s1, POINTER_TYPE)
11299       || !validate_arg (s2, INTEGER_TYPE))
11300     return NULL_TREE;
11301   else
11302     {
11303       const char *p1;
11304
11305       if (TREE_CODE (s2) != INTEGER_CST)
11306         return NULL_TREE;
11307
11308       p1 = c_getstr (s1);
11309       if (p1 != NULL)
11310         {
11311           char c;
11312           const char *r;
11313           tree tem;
11314
11315           if (target_char_cast (s2, &c))
11316             return NULL_TREE;
11317
11318           r = strchr (p1, c);
11319
11320           if (r == NULL)
11321             return build_int_cst (TREE_TYPE (s1), 0);
11322
11323           /* Return an offset into the constant string argument.  */
11324           tem = fold_build2_loc (loc, POINTER_PLUS_EXPR, TREE_TYPE (s1),
11325                              s1, size_int (r - p1));
11326           return fold_convert_loc (loc, type, tem);
11327         }
11328       return NULL_TREE;
11329     }
11330 }
11331
11332 /* Simplify a call to the strrchr builtin.  S1 and S2 are the arguments to
11333    the call, and TYPE is its return type.
11334
11335    Return NULL_TREE if no simplification was possible, otherwise return the
11336    simplified form of the call as a tree.
11337
11338    The simplified form may be a constant or other expression which
11339    computes the same value, but in a more efficient manner (including
11340    calls to other builtin functions).
11341
11342    The call may contain arguments which need to be evaluated, but
11343    which are not useful to determine the result of the call.  In
11344    this case we return a chain of COMPOUND_EXPRs.  The LHS of each
11345    COMPOUND_EXPR will be an argument which must be evaluated.
11346    COMPOUND_EXPRs are chained through their RHS.  The RHS of the last
11347    COMPOUND_EXPR in the chain will contain the tree for the simplified
11348    form of the builtin function call.  */
11349
11350 static tree
11351 fold_builtin_strrchr (location_t loc, tree s1, tree s2, tree type)
11352 {
11353   if (!validate_arg (s1, POINTER_TYPE)
11354       || !validate_arg (s2, INTEGER_TYPE))
11355     return NULL_TREE;
11356   else
11357     {
11358       tree fn;
11359       const char *p1;
11360
11361       if (TREE_CODE (s2) != INTEGER_CST)
11362         return NULL_TREE;
11363
11364       p1 = c_getstr (s1);
11365       if (p1 != NULL)
11366         {
11367           char c;
11368           const char *r;
11369           tree tem;
11370
11371           if (target_char_cast (s2, &c))
11372             return NULL_TREE;
11373
11374           r = strrchr (p1, c);
11375
11376           if (r == NULL)
11377             return build_int_cst (TREE_TYPE (s1), 0);
11378
11379           /* Return an offset into the constant string argument.  */
11380           tem = fold_build2_loc (loc, POINTER_PLUS_EXPR, TREE_TYPE (s1),
11381                              s1, size_int (r - p1));
11382           return fold_convert_loc (loc, type, tem);
11383         }
11384
11385       if (! integer_zerop (s2))
11386         return NULL_TREE;
11387
11388       fn = implicit_built_in_decls[BUILT_IN_STRCHR];
11389       if (!fn)
11390         return NULL_TREE;
11391
11392       /* Transform strrchr(s1, '\0') to strchr(s1, '\0').  */
11393       return build_call_expr_loc (loc, fn, 2, s1, s2);
11394     }
11395 }
11396
11397 /* Simplify a call to the strpbrk builtin.  S1 and S2 are the arguments
11398    to the call, and TYPE is its return type.
11399
11400    Return NULL_TREE if no simplification was possible, otherwise return the
11401    simplified form of the call as a tree.
11402
11403    The simplified form may be a constant or other expression which
11404    computes the same value, but in a more efficient manner (including
11405    calls to other builtin functions).
11406
11407    The call may contain arguments which need to be evaluated, but
11408    which are not useful to determine the result of the call.  In
11409    this case we return a chain of COMPOUND_EXPRs.  The LHS of each
11410    COMPOUND_EXPR will be an argument which must be evaluated.
11411    COMPOUND_EXPRs are chained through their RHS.  The RHS of the last
11412    COMPOUND_EXPR in the chain will contain the tree for the simplified
11413    form of the builtin function call.  */
11414
11415 static tree
11416 fold_builtin_strpbrk (location_t loc, tree s1, tree s2, tree type)
11417 {
11418   if (!validate_arg (s1, POINTER_TYPE)
11419       || !validate_arg (s2, POINTER_TYPE))
11420     return NULL_TREE;
11421   else
11422     {
11423       tree fn;
11424       const char *p1, *p2;
11425
11426       p2 = c_getstr (s2);
11427       if (p2 == NULL)
11428         return NULL_TREE;
11429
11430       p1 = c_getstr (s1);
11431       if (p1 != NULL)
11432         {
11433           const char *r = strpbrk (p1, p2);
11434           tree tem;
11435
11436           if (r == NULL)
11437             return build_int_cst (TREE_TYPE (s1), 0);
11438
11439           /* Return an offset into the constant string argument.  */
11440           tem = fold_build2_loc (loc, POINTER_PLUS_EXPR, TREE_TYPE (s1),
11441                              s1, size_int (r - p1));
11442           return fold_convert_loc (loc, type, tem);
11443         }
11444
11445       if (p2[0] == '\0')
11446         /* strpbrk(x, "") == NULL.
11447            Evaluate and ignore s1 in case it had side-effects.  */
11448         return omit_one_operand_loc (loc, TREE_TYPE (s1), integer_zero_node, s1);
11449
11450       if (p2[1] != '\0')
11451         return NULL_TREE;  /* Really call strpbrk.  */
11452
11453       fn = implicit_built_in_decls[BUILT_IN_STRCHR];
11454       if (!fn)
11455         return NULL_TREE;
11456
11457       /* New argument list transforming strpbrk(s1, s2) to
11458          strchr(s1, s2[0]).  */
11459       return build_call_expr_loc (loc, fn, 2, s1, build_int_cst (NULL_TREE, p2[0]));
11460     }
11461 }
11462
11463 /* Simplify a call to the strcat builtin.  DST and SRC are the arguments
11464    to the call.
11465
11466    Return NULL_TREE if no simplification was possible, otherwise return the
11467    simplified form of the call as a tree.
11468
11469    The simplified form may be a constant or other expression which
11470    computes the same value, but in a more efficient manner (including
11471    calls to other builtin functions).
11472
11473    The call may contain arguments which need to be evaluated, but
11474    which are not useful to determine the result of the call.  In
11475    this case we return a chain of COMPOUND_EXPRs.  The LHS of each
11476    COMPOUND_EXPR will be an argument which must be evaluated.
11477    COMPOUND_EXPRs are chained through their RHS.  The RHS of the last
11478    COMPOUND_EXPR in the chain will contain the tree for the simplified
11479    form of the builtin function call.  */
11480
11481 static tree
11482 fold_builtin_strcat (location_t loc ATTRIBUTE_UNUSED, tree dst, tree src)
11483 {
11484   if (!validate_arg (dst, POINTER_TYPE)
11485       || !validate_arg (src, POINTER_TYPE))
11486     return NULL_TREE;
11487   else
11488     {
11489       const char *p = c_getstr (src);
11490
11491       /* If the string length is zero, return the dst parameter.  */
11492       if (p && *p == '\0')
11493         return dst;
11494
11495       if (optimize_insn_for_speed_p ())
11496         {
11497           /* See if we can store by pieces into (dst + strlen(dst)).  */
11498           tree newdst, call;
11499           tree strlen_fn = implicit_built_in_decls[BUILT_IN_STRLEN];
11500           tree strcpy_fn = implicit_built_in_decls[BUILT_IN_STRCPY];
11501
11502           if (!strlen_fn || !strcpy_fn)
11503             return NULL_TREE;
11504
11505           /* If we don't have a movstr we don't want to emit an strcpy
11506              call.  We have to do that if the length of the source string
11507              isn't computable (in that case we can use memcpy probably
11508              later expanding to a sequence of mov instructions).  If we
11509              have movstr instructions we can emit strcpy calls.  */
11510           if (!HAVE_movstr)
11511             {
11512               tree len = c_strlen (src, 1);
11513               if (! len || TREE_SIDE_EFFECTS (len))
11514                 return NULL_TREE;
11515             }
11516
11517           /* Stabilize the argument list.  */
11518           dst = builtin_save_expr (dst);
11519
11520           /* Create strlen (dst).  */
11521           newdst = build_call_expr_loc (loc, strlen_fn, 1, dst);
11522           /* Create (dst p+ strlen (dst)).  */
11523
11524           newdst = fold_build2_loc (loc, POINTER_PLUS_EXPR,
11525                                 TREE_TYPE (dst), dst, newdst);
11526           newdst = builtin_save_expr (newdst);
11527
11528           call = build_call_expr_loc (loc, strcpy_fn, 2, newdst, src);
11529           return build2 (COMPOUND_EXPR, TREE_TYPE (dst), call, dst);
11530         }
11531       return NULL_TREE;
11532     }
11533 }
11534
11535 /* Simplify a call to the strncat builtin.  DST, SRC, and LEN are the
11536    arguments to the call.
11537
11538    Return NULL_TREE if no simplification was possible, otherwise return the
11539    simplified form of the call as a tree.
11540
11541    The simplified form may be a constant or other expression which
11542    computes the same value, but in a more efficient manner (including
11543    calls to other builtin functions).
11544
11545    The call may contain arguments which need to be evaluated, but
11546    which are not useful to determine the result of the call.  In
11547    this case we return a chain of COMPOUND_EXPRs.  The LHS of each
11548    COMPOUND_EXPR will be an argument which must be evaluated.
11549    COMPOUND_EXPRs are chained through their RHS.  The RHS of the last
11550    COMPOUND_EXPR in the chain will contain the tree for the simplified
11551    form of the builtin function call.  */
11552
11553 static tree
11554 fold_builtin_strncat (location_t loc, tree dst, tree src, tree len)
11555 {
11556   if (!validate_arg (dst, POINTER_TYPE)
11557       || !validate_arg (src, POINTER_TYPE)
11558       || !validate_arg (len, INTEGER_TYPE))
11559     return NULL_TREE;
11560   else
11561     {
11562       const char *p = c_getstr (src);
11563
11564       /* If the requested length is zero, or the src parameter string
11565          length is zero, return the dst parameter.  */
11566       if (integer_zerop (len) || (p && *p == '\0'))
11567         return omit_two_operands_loc (loc, TREE_TYPE (dst), dst, src, len);
11568
11569       /* If the requested len is greater than or equal to the string
11570          length, call strcat.  */
11571       if (TREE_CODE (len) == INTEGER_CST && p
11572           && compare_tree_int (len, strlen (p)) >= 0)
11573         {
11574           tree fn = implicit_built_in_decls[BUILT_IN_STRCAT];
11575
11576           /* If the replacement _DECL isn't initialized, don't do the
11577              transformation.  */
11578           if (!fn)
11579             return NULL_TREE;
11580
11581           return build_call_expr_loc (loc, fn, 2, dst, src);
11582         }
11583       return NULL_TREE;
11584     }
11585 }
11586
11587 /* Simplify a call to the strspn builtin.  S1 and S2 are the arguments
11588    to the call.
11589
11590    Return NULL_TREE if no simplification was possible, otherwise return the
11591    simplified form of the call as a tree.
11592
11593    The simplified form may be a constant or other expression which
11594    computes the same value, but in a more efficient manner (including
11595    calls to other builtin functions).
11596
11597    The call may contain arguments which need to be evaluated, but
11598    which are not useful to determine the result of the call.  In
11599    this case we return a chain of COMPOUND_EXPRs.  The LHS of each
11600    COMPOUND_EXPR will be an argument which must be evaluated.
11601    COMPOUND_EXPRs are chained through their RHS.  The RHS of the last
11602    COMPOUND_EXPR in the chain will contain the tree for the simplified
11603    form of the builtin function call.  */
11604
11605 static tree
11606 fold_builtin_strspn (location_t loc, tree s1, tree s2)
11607 {
11608   if (!validate_arg (s1, POINTER_TYPE)
11609       || !validate_arg (s2, POINTER_TYPE))
11610     return NULL_TREE;
11611   else
11612     {
11613       const char *p1 = c_getstr (s1), *p2 = c_getstr (s2);
11614
11615       /* If both arguments are constants, evaluate at compile-time.  */
11616       if (p1 && p2)
11617         {
11618           const size_t r = strspn (p1, p2);
11619           return size_int (r);
11620         }
11621
11622       /* If either argument is "", return NULL_TREE.  */
11623       if ((p1 && *p1 == '\0') || (p2 && *p2 == '\0'))
11624         /* Evaluate and ignore both arguments in case either one has
11625            side-effects.  */
11626         return omit_two_operands_loc (loc, size_type_node, size_zero_node,
11627                                   s1, s2);
11628       return NULL_TREE;
11629     }
11630 }
11631
11632 /* Simplify a call to the strcspn builtin.  S1 and S2 are the arguments
11633    to the call.
11634
11635    Return NULL_TREE if no simplification was possible, otherwise return the
11636    simplified form of the call as a tree.
11637
11638    The simplified form may be a constant or other expression which
11639    computes the same value, but in a more efficient manner (including
11640    calls to other builtin functions).
11641
11642    The call may contain arguments which need to be evaluated, but
11643    which are not useful to determine the result of the call.  In
11644    this case we return a chain of COMPOUND_EXPRs.  The LHS of each
11645    COMPOUND_EXPR will be an argument which must be evaluated.
11646    COMPOUND_EXPRs are chained through their RHS.  The RHS of the last
11647    COMPOUND_EXPR in the chain will contain the tree for the simplified
11648    form of the builtin function call.  */
11649
11650 static tree
11651 fold_builtin_strcspn (location_t loc, tree s1, tree s2)
11652 {
11653   if (!validate_arg (s1, POINTER_TYPE)
11654       || !validate_arg (s2, POINTER_TYPE))
11655     return NULL_TREE;
11656   else
11657     {
11658       const char *p1 = c_getstr (s1), *p2 = c_getstr (s2);
11659
11660       /* If both arguments are constants, evaluate at compile-time.  */
11661       if (p1 && p2)
11662         {
11663           const size_t r = strcspn (p1, p2);
11664           return size_int (r);
11665         }
11666
11667       /* If the first argument is "", return NULL_TREE.  */
11668       if (p1 && *p1 == '\0')
11669         {
11670           /* Evaluate and ignore argument s2 in case it has
11671              side-effects.  */
11672           return omit_one_operand_loc (loc, size_type_node,
11673                                    size_zero_node, s2);
11674         }
11675
11676       /* If the second argument is "", return __builtin_strlen(s1).  */
11677       if (p2 && *p2 == '\0')
11678         {
11679           tree fn = implicit_built_in_decls[BUILT_IN_STRLEN];
11680
11681           /* If the replacement _DECL isn't initialized, don't do the
11682              transformation.  */
11683           if (!fn)
11684             return NULL_TREE;
11685
11686           return build_call_expr_loc (loc, fn, 1, s1);
11687         }
11688       return NULL_TREE;
11689     }
11690 }
11691
11692 /* Fold a call to the fputs builtin.  ARG0 and ARG1 are the arguments
11693    to the call.  IGNORE is true if the value returned
11694    by the builtin will be ignored.  UNLOCKED is true is true if this
11695    actually a call to fputs_unlocked.  If LEN in non-NULL, it represents
11696    the known length of the string.  Return NULL_TREE if no simplification
11697    was possible.  */
11698
11699 tree
11700 fold_builtin_fputs (location_t loc, tree arg0, tree arg1,
11701                     bool ignore, bool unlocked, tree len)
11702 {
11703   /* If we're using an unlocked function, assume the other unlocked
11704      functions exist explicitly.  */
11705   tree const fn_fputc = unlocked ? built_in_decls[BUILT_IN_FPUTC_UNLOCKED]
11706     : implicit_built_in_decls[BUILT_IN_FPUTC];
11707   tree const fn_fwrite = unlocked ? built_in_decls[BUILT_IN_FWRITE_UNLOCKED]
11708     : implicit_built_in_decls[BUILT_IN_FWRITE];
11709
11710   /* If the return value is used, don't do the transformation.  */
11711   if (!ignore)
11712     return NULL_TREE;
11713
11714   /* Verify the arguments in the original call.  */
11715   if (!validate_arg (arg0, POINTER_TYPE)
11716       || !validate_arg (arg1, POINTER_TYPE))
11717     return NULL_TREE;
11718
11719   if (! len)
11720     len = c_strlen (arg0, 0);
11721
11722   /* Get the length of the string passed to fputs.  If the length
11723      can't be determined, punt.  */
11724   if (!len
11725       || TREE_CODE (len) != INTEGER_CST)
11726     return NULL_TREE;
11727
11728   switch (compare_tree_int (len, 1))
11729     {
11730     case -1: /* length is 0, delete the call entirely .  */
11731       return omit_one_operand_loc (loc, integer_type_node,
11732                                integer_zero_node, arg1);;
11733
11734     case 0: /* length is 1, call fputc.  */
11735       {
11736         const char *p = c_getstr (arg0);
11737
11738         if (p != NULL)
11739           {
11740             if (fn_fputc)
11741               return build_call_expr_loc (loc, fn_fputc, 2,
11742                                       build_int_cst (NULL_TREE, p[0]), arg1);
11743             else
11744               return NULL_TREE;
11745           }
11746       }
11747       /* FALLTHROUGH */
11748     case 1: /* length is greater than 1, call fwrite.  */
11749       {
11750         /* If optimizing for size keep fputs.  */
11751         if (optimize_function_for_size_p (cfun))
11752           return NULL_TREE;
11753         /* New argument list transforming fputs(string, stream) to
11754            fwrite(string, 1, len, stream).  */
11755         if (fn_fwrite)
11756           return build_call_expr_loc (loc, fn_fwrite, 4, arg0,
11757                                   size_one_node, len, arg1);
11758         else
11759           return NULL_TREE;
11760       }
11761     default:
11762       gcc_unreachable ();
11763     }
11764   return NULL_TREE;
11765 }
11766
11767 /* Fold the next_arg or va_start call EXP. Returns true if there was an error
11768    produced.  False otherwise.  This is done so that we don't output the error
11769    or warning twice or three times.  */
11770
11771 bool
11772 fold_builtin_next_arg (tree exp, bool va_start_p)
11773 {
11774   tree fntype = TREE_TYPE (current_function_decl);
11775   int nargs = call_expr_nargs (exp);
11776   tree arg;
11777
11778   if (!stdarg_p (fntype))
11779     {
11780       error ("%<va_start%> used in function with fixed args");
11781       return true;
11782     }
11783
11784   if (va_start_p)
11785     {
11786       if (va_start_p && (nargs != 2))
11787         {
11788           error ("wrong number of arguments to function %<va_start%>");
11789           return true;
11790         }
11791       arg = CALL_EXPR_ARG (exp, 1);
11792     }
11793   /* We use __builtin_va_start (ap, 0, 0) or __builtin_next_arg (0, 0)
11794      when we checked the arguments and if needed issued a warning.  */
11795   else
11796     {
11797       if (nargs == 0)
11798         {
11799           /* Evidently an out of date version of <stdarg.h>; can't validate
11800              va_start's second argument, but can still work as intended.  */
11801           warning (0, "%<__builtin_next_arg%> called without an argument");
11802           return true;
11803         }
11804       else if (nargs > 1)
11805         {
11806           error ("wrong number of arguments to function %<__builtin_next_arg%>");
11807           return true;
11808         }
11809       arg = CALL_EXPR_ARG (exp, 0);
11810     }
11811
11812   if (TREE_CODE (arg) == SSA_NAME)
11813     arg = SSA_NAME_VAR (arg);
11814
11815   /* We destructively modify the call to be __builtin_va_start (ap, 0)
11816      or __builtin_next_arg (0) the first time we see it, after checking
11817      the arguments and if needed issuing a warning.  */
11818   if (!integer_zerop (arg))
11819     {
11820       tree last_parm = tree_last (DECL_ARGUMENTS (current_function_decl));
11821
11822       /* Strip off all nops for the sake of the comparison.  This
11823          is not quite the same as STRIP_NOPS.  It does more.
11824          We must also strip off INDIRECT_EXPR for C++ reference
11825          parameters.  */
11826       while (CONVERT_EXPR_P (arg)
11827              || TREE_CODE (arg) == INDIRECT_REF)
11828         arg = TREE_OPERAND (arg, 0);
11829       if (arg != last_parm)
11830         {
11831           /* FIXME: Sometimes with the tree optimizers we can get the
11832              not the last argument even though the user used the last
11833              argument.  We just warn and set the arg to be the last
11834              argument so that we will get wrong-code because of
11835              it.  */
11836           warning (0, "second parameter of %<va_start%> not last named argument");
11837         }
11838
11839       /* Undefined by C99 7.15.1.4p4 (va_start):
11840          "If the parameter parmN is declared with the register storage
11841          class, with a function or array type, or with a type that is
11842          not compatible with the type that results after application of
11843          the default argument promotions, the behavior is undefined."
11844       */
11845       else if (DECL_REGISTER (arg))
11846         warning (0, "undefined behaviour when second parameter of "
11847                  "%<va_start%> is declared with %<register%> storage");
11848
11849       /* We want to verify the second parameter just once before the tree
11850          optimizers are run and then avoid keeping it in the tree,
11851          as otherwise we could warn even for correct code like:
11852          void foo (int i, ...)
11853          { va_list ap; i++; va_start (ap, i); va_end (ap); }  */
11854       if (va_start_p)
11855         CALL_EXPR_ARG (exp, 1) = integer_zero_node;
11856       else
11857         CALL_EXPR_ARG (exp, 0) = integer_zero_node;
11858     }
11859   return false;
11860 }
11861
11862
11863 /* Simplify a call to the sprintf builtin with arguments DEST, FMT, and ORIG.
11864    ORIG may be null if this is a 2-argument call.  We don't attempt to
11865    simplify calls with more than 3 arguments.
11866
11867    Return NULL_TREE if no simplification was possible, otherwise return the
11868    simplified form of the call as a tree.  If IGNORED is true, it means that
11869    the caller does not use the returned value of the function.  */
11870
11871 static tree
11872 fold_builtin_sprintf (location_t loc, tree dest, tree fmt,
11873                       tree orig, int ignored)
11874 {
11875   tree call, retval;
11876   const char *fmt_str = NULL;
11877
11878   /* Verify the required arguments in the original call.  We deal with two
11879      types of sprintf() calls: 'sprintf (str, fmt)' and
11880      'sprintf (dest, "%s", orig)'.  */
11881   if (!validate_arg (dest, POINTER_TYPE)
11882       || !validate_arg (fmt, POINTER_TYPE))
11883     return NULL_TREE;
11884   if (orig && !validate_arg (orig, POINTER_TYPE))
11885     return NULL_TREE;
11886
11887   /* Check whether the format is a literal string constant.  */
11888   fmt_str = c_getstr (fmt);
11889   if (fmt_str == NULL)
11890     return NULL_TREE;
11891
11892   call = NULL_TREE;
11893   retval = NULL_TREE;
11894
11895   if (!init_target_chars ())
11896     return NULL_TREE;
11897
11898   /* If the format doesn't contain % args or %%, use strcpy.  */
11899   if (strchr (fmt_str, target_percent) == NULL)
11900     {
11901       tree fn = implicit_built_in_decls[BUILT_IN_STRCPY];
11902
11903       if (!fn)
11904         return NULL_TREE;
11905
11906       /* Don't optimize sprintf (buf, "abc", ptr++).  */
11907       if (orig)
11908         return NULL_TREE;
11909
11910       /* Convert sprintf (str, fmt) into strcpy (str, fmt) when
11911          'format' is known to contain no % formats.  */
11912       call = build_call_expr_loc (loc, fn, 2, dest, fmt);
11913       if (!ignored)
11914         retval = build_int_cst (NULL_TREE, strlen (fmt_str));
11915     }
11916
11917   /* If the format is "%s", use strcpy if the result isn't used.  */
11918   else if (fmt_str && strcmp (fmt_str, target_percent_s) == 0)
11919     {
11920       tree fn;
11921       fn = implicit_built_in_decls[BUILT_IN_STRCPY];
11922
11923       if (!fn)
11924         return NULL_TREE;
11925
11926       /* Don't crash on sprintf (str1, "%s").  */
11927       if (!orig)
11928         return NULL_TREE;
11929
11930       /* Convert sprintf (str1, "%s", str2) into strcpy (str1, str2).  */
11931       if (!ignored)
11932         {
11933           retval = c_strlen (orig, 1);
11934           if (!retval || TREE_CODE (retval) != INTEGER_CST)
11935             return NULL_TREE;
11936         }
11937       call = build_call_expr_loc (loc, fn, 2, dest, orig);
11938     }
11939
11940   if (call && retval)
11941     {
11942       retval = fold_convert_loc
11943         (loc, TREE_TYPE (TREE_TYPE (implicit_built_in_decls[BUILT_IN_SPRINTF])),
11944          retval);
11945       return build2 (COMPOUND_EXPR, TREE_TYPE (retval), call, retval);
11946     }
11947   else
11948     return call;
11949 }
11950
11951 /* Expand a call EXP to __builtin_object_size.  */
11952
11953 rtx
11954 expand_builtin_object_size (tree exp)
11955 {
11956   tree ost;
11957   int object_size_type;
11958   tree fndecl = get_callee_fndecl (exp);
11959
11960   if (!validate_arglist (exp, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
11961     {
11962       error ("%Kfirst argument of %D must be a pointer, second integer constant",
11963              exp, fndecl);
11964       expand_builtin_trap ();
11965       return const0_rtx;
11966     }
11967
11968   ost = CALL_EXPR_ARG (exp, 1);
11969   STRIP_NOPS (ost);
11970
11971   if (TREE_CODE (ost) != INTEGER_CST
11972       || tree_int_cst_sgn (ost) < 0
11973       || compare_tree_int (ost, 3) > 0)
11974     {
11975       error ("%Klast argument of %D is not integer constant between 0 and 3",
11976              exp, fndecl);
11977       expand_builtin_trap ();
11978       return const0_rtx;
11979     }
11980
11981   object_size_type = tree_low_cst (ost, 0);
11982
11983   return object_size_type < 2 ? constm1_rtx : const0_rtx;
11984 }
11985
11986 /* Expand EXP, a call to the __mem{cpy,pcpy,move,set}_chk builtin.
11987    FCODE is the BUILT_IN_* to use.
11988    Return NULL_RTX if we failed; the caller should emit a normal call,
11989    otherwise try to get the result in TARGET, if convenient (and in
11990    mode MODE if that's convenient).  */
11991
11992 static rtx
11993 expand_builtin_memory_chk (tree exp, rtx target, enum machine_mode mode,
11994                            enum built_in_function fcode)
11995 {
11996   tree dest, src, len, size;
11997
11998   if (!validate_arglist (exp,
11999                          POINTER_TYPE,
12000                          fcode == BUILT_IN_MEMSET_CHK
12001                          ? INTEGER_TYPE : POINTER_TYPE,
12002                          INTEGER_TYPE, INTEGER_TYPE, VOID_TYPE))
12003     return NULL_RTX;
12004
12005   dest = CALL_EXPR_ARG (exp, 0);
12006   src = CALL_EXPR_ARG (exp, 1);
12007   len = CALL_EXPR_ARG (exp, 2);
12008   size = CALL_EXPR_ARG (exp, 3);
12009
12010   if (! host_integerp (size, 1))
12011     return NULL_RTX;
12012
12013   if (host_integerp (len, 1) || integer_all_onesp (size))
12014     {
12015       tree fn;
12016
12017       if (! integer_all_onesp (size) && tree_int_cst_lt (size, len))
12018         {
12019           warning_at (tree_nonartificial_location (exp),
12020                       0, "%Kcall to %D will always overflow destination buffer",
12021                       exp, get_callee_fndecl (exp));
12022           return NULL_RTX;
12023         }
12024
12025       fn = NULL_TREE;
12026       /* If __builtin_mem{cpy,pcpy,move,set}_chk is used, assume
12027          mem{cpy,pcpy,move,set} is available.  */
12028       switch (fcode)
12029         {
12030         case BUILT_IN_MEMCPY_CHK:
12031           fn = built_in_decls[BUILT_IN_MEMCPY];
12032           break;
12033         case BUILT_IN_MEMPCPY_CHK:
12034           fn = built_in_decls[BUILT_IN_MEMPCPY];
12035           break;
12036         case BUILT_IN_MEMMOVE_CHK:
12037           fn = built_in_decls[BUILT_IN_MEMMOVE];
12038           break;
12039         case BUILT_IN_MEMSET_CHK:
12040           fn = built_in_decls[BUILT_IN_MEMSET];
12041           break;
12042         default:
12043           break;
12044         }
12045
12046       if (! fn)
12047         return NULL_RTX;
12048
12049       fn = build_call_nofold_loc (EXPR_LOCATION (exp), fn, 3, dest, src, len);
12050       gcc_assert (TREE_CODE (fn) == CALL_EXPR);
12051       CALL_EXPR_TAILCALL (fn) = CALL_EXPR_TAILCALL (exp);
12052       return expand_expr (fn, target, mode, EXPAND_NORMAL);
12053     }
12054   else if (fcode == BUILT_IN_MEMSET_CHK)
12055     return NULL_RTX;
12056   else
12057     {
12058       unsigned int dest_align
12059         = get_pointer_alignment (dest, BIGGEST_ALIGNMENT);
12060
12061       /* If DEST is not a pointer type, call the normal function.  */
12062       if (dest_align == 0)
12063         return NULL_RTX;
12064
12065       /* If SRC and DEST are the same (and not volatile), do nothing.  */
12066       if (operand_equal_p (src, dest, 0))
12067         {
12068           tree expr;
12069
12070           if (fcode != BUILT_IN_MEMPCPY_CHK)
12071             {
12072               /* Evaluate and ignore LEN in case it has side-effects.  */
12073               expand_expr (len, const0_rtx, VOIDmode, EXPAND_NORMAL);
12074               return expand_expr (dest, target, mode, EXPAND_NORMAL);
12075             }
12076
12077           expr = fold_build2 (POINTER_PLUS_EXPR, TREE_TYPE (dest), dest, len);
12078           return expand_expr (expr, target, mode, EXPAND_NORMAL);
12079         }
12080
12081       /* __memmove_chk special case.  */
12082       if (fcode == BUILT_IN_MEMMOVE_CHK)
12083         {
12084           unsigned int src_align
12085             = get_pointer_alignment (src, BIGGEST_ALIGNMENT);
12086
12087           if (src_align == 0)
12088             return NULL_RTX;
12089
12090           /* If src is categorized for a readonly section we can use
12091              normal __memcpy_chk.  */
12092           if (readonly_data_expr (src))
12093             {
12094               tree fn = built_in_decls[BUILT_IN_MEMCPY_CHK];
12095               if (!fn)
12096                 return NULL_RTX;
12097               fn = build_call_nofold_loc (EXPR_LOCATION (exp), fn, 4,
12098                                           dest, src, len, size);
12099               gcc_assert (TREE_CODE (fn) == CALL_EXPR);
12100               CALL_EXPR_TAILCALL (fn) = CALL_EXPR_TAILCALL (exp);
12101               return expand_expr (fn, target, mode, EXPAND_NORMAL);
12102             }
12103         }
12104       return NULL_RTX;
12105     }
12106 }
12107
12108 /* Emit warning if a buffer overflow is detected at compile time.  */
12109
12110 static void
12111 maybe_emit_chk_warning (tree exp, enum built_in_function fcode)
12112 {
12113   int is_strlen = 0;
12114   tree len, size;
12115   location_t loc = tree_nonartificial_location (exp);
12116
12117   switch (fcode)
12118     {
12119     case BUILT_IN_STRCPY_CHK:
12120     case BUILT_IN_STPCPY_CHK:
12121     /* For __strcat_chk the warning will be emitted only if overflowing
12122        by at least strlen (dest) + 1 bytes.  */
12123     case BUILT_IN_STRCAT_CHK:
12124       len = CALL_EXPR_ARG (exp, 1);
12125       size = CALL_EXPR_ARG (exp, 2);
12126       is_strlen = 1;
12127       break;
12128     case BUILT_IN_STRNCAT_CHK:
12129     case BUILT_IN_STRNCPY_CHK:
12130       len = CALL_EXPR_ARG (exp, 2);
12131       size = CALL_EXPR_ARG (exp, 3);
12132       break;
12133     case BUILT_IN_SNPRINTF_CHK:
12134     case BUILT_IN_VSNPRINTF_CHK:
12135       len = CALL_EXPR_ARG (exp, 1);
12136       size = CALL_EXPR_ARG (exp, 3);
12137       break;
12138     default:
12139       gcc_unreachable ();
12140     }
12141
12142   if (!len || !size)
12143     return;
12144
12145   if (! host_integerp (size, 1) || integer_all_onesp (size))
12146     return;
12147
12148   if (is_strlen)
12149     {
12150       len = c_strlen (len, 1);
12151       if (! len || ! host_integerp (len, 1) || tree_int_cst_lt (len, size))
12152         return;
12153     }
12154   else if (fcode == BUILT_IN_STRNCAT_CHK)
12155     {
12156       tree src = CALL_EXPR_ARG (exp, 1);
12157       if (! src || ! host_integerp (len, 1) || tree_int_cst_lt (len, size))
12158         return;
12159       src = c_strlen (src, 1);
12160       if (! src || ! host_integerp (src, 1))
12161         {
12162           warning_at (loc, 0, "%Kcall to %D might overflow destination buffer",
12163                       exp, get_callee_fndecl (exp));
12164           return;
12165         }
12166       else if (tree_int_cst_lt (src, size))
12167         return;
12168     }
12169   else if (! host_integerp (len, 1) || ! tree_int_cst_lt (size, len))
12170     return;
12171
12172   warning_at (loc, 0, "%Kcall to %D will always overflow destination buffer",
12173               exp, get_callee_fndecl (exp));
12174 }
12175
12176 /* Emit warning if a buffer overflow is detected at compile time
12177    in __sprintf_chk/__vsprintf_chk calls.  */
12178
12179 static void
12180 maybe_emit_sprintf_chk_warning (tree exp, enum built_in_function fcode)
12181 {
12182   tree size, len, fmt;
12183   const char *fmt_str;
12184   int nargs = call_expr_nargs (exp);
12185
12186   /* Verify the required arguments in the original call.  */
12187
12188   if (nargs < 4)
12189     return;
12190   size = CALL_EXPR_ARG (exp, 2);
12191   fmt = CALL_EXPR_ARG (exp, 3);
12192
12193   if (! host_integerp (size, 1) || integer_all_onesp (size))
12194     return;
12195
12196   /* Check whether the format is a literal string constant.  */
12197   fmt_str = c_getstr (fmt);
12198   if (fmt_str == NULL)
12199     return;
12200
12201   if (!init_target_chars ())
12202     return;
12203
12204   /* If the format doesn't contain % args or %%, we know its size.  */
12205   if (strchr (fmt_str, target_percent) == 0)
12206     len = build_int_cstu (size_type_node, strlen (fmt_str));
12207   /* If the format is "%s" and first ... argument is a string literal,
12208      we know it too.  */
12209   else if (fcode == BUILT_IN_SPRINTF_CHK
12210            && strcmp (fmt_str, target_percent_s) == 0)
12211     {
12212       tree arg;
12213
12214       if (nargs < 5)
12215         return;
12216       arg = CALL_EXPR_ARG (exp, 4);
12217       if (! POINTER_TYPE_P (TREE_TYPE (arg)))
12218         return;
12219
12220       len = c_strlen (arg, 1);
12221       if (!len || ! host_integerp (len, 1))
12222         return;
12223     }
12224   else
12225     return;
12226
12227   if (! tree_int_cst_lt (len, size))
12228     warning_at (tree_nonartificial_location (exp),
12229                 0, "%Kcall to %D will always overflow destination buffer",
12230                 exp, get_callee_fndecl (exp));
12231 }
12232
12233 /* Emit warning if a free is called with address of a variable.  */
12234
12235 static void
12236 maybe_emit_free_warning (tree exp)
12237 {
12238   tree arg = CALL_EXPR_ARG (exp, 0);
12239
12240   STRIP_NOPS (arg);
12241   if (TREE_CODE (arg) != ADDR_EXPR)
12242     return;
12243
12244   arg = get_base_address (TREE_OPERAND (arg, 0));
12245   if (arg == NULL || INDIRECT_REF_P (arg) || TREE_CODE (arg) == MEM_REF)
12246     return;
12247
12248   if (SSA_VAR_P (arg))
12249     warning_at (tree_nonartificial_location (exp),
12250                 0, "%Kattempt to free a non-heap object %qD", exp, arg);
12251   else
12252     warning_at (tree_nonartificial_location (exp),
12253                 0, "%Kattempt to free a non-heap object", exp);
12254 }
12255
12256 /* Fold a call to __builtin_object_size with arguments PTR and OST,
12257    if possible.  */
12258
12259 tree
12260 fold_builtin_object_size (tree ptr, tree ost)
12261 {
12262   unsigned HOST_WIDE_INT bytes;
12263   int object_size_type;
12264
12265   if (!validate_arg (ptr, POINTER_TYPE)
12266       || !validate_arg (ost, INTEGER_TYPE))
12267     return NULL_TREE;
12268
12269   STRIP_NOPS (ost);
12270
12271   if (TREE_CODE (ost) != INTEGER_CST
12272       || tree_int_cst_sgn (ost) < 0
12273       || compare_tree_int (ost, 3) > 0)
12274     return NULL_TREE;
12275
12276   object_size_type = tree_low_cst (ost, 0);
12277
12278   /* __builtin_object_size doesn't evaluate side-effects in its arguments;
12279      if there are any side-effects, it returns (size_t) -1 for types 0 and 1
12280      and (size_t) 0 for types 2 and 3.  */
12281   if (TREE_SIDE_EFFECTS (ptr))
12282     return build_int_cst_type (size_type_node, object_size_type < 2 ? -1 : 0);
12283
12284   if (TREE_CODE (ptr) == ADDR_EXPR)
12285     {
12286       bytes = compute_builtin_object_size (ptr, object_size_type);
12287       if (double_int_fits_to_tree_p (size_type_node,
12288                                      uhwi_to_double_int (bytes)))
12289         return build_int_cstu (size_type_node, bytes);
12290     }
12291   else if (TREE_CODE (ptr) == SSA_NAME)
12292     {
12293       /* If object size is not known yet, delay folding until
12294        later.  Maybe subsequent passes will help determining
12295        it.  */
12296       bytes = compute_builtin_object_size (ptr, object_size_type);
12297       if (bytes != (unsigned HOST_WIDE_INT) (object_size_type < 2 ? -1 : 0)
12298           && double_int_fits_to_tree_p (size_type_node,
12299                                         uhwi_to_double_int (bytes)))
12300         return build_int_cstu (size_type_node, bytes);
12301     }
12302
12303   return NULL_TREE;
12304 }
12305
12306 /* Fold a call to the __mem{cpy,pcpy,move,set}_chk builtin.
12307    DEST, SRC, LEN, and SIZE are the arguments to the call.
12308    IGNORE is true, if return value can be ignored.  FCODE is the BUILT_IN_*
12309    code of the builtin.  If MAXLEN is not NULL, it is maximum length
12310    passed as third argument.  */
12311
12312 tree
12313 fold_builtin_memory_chk (location_t loc, tree fndecl,
12314                          tree dest, tree src, tree len, tree size,
12315                          tree maxlen, bool ignore,
12316                          enum built_in_function fcode)
12317 {
12318   tree fn;
12319
12320   if (!validate_arg (dest, POINTER_TYPE)
12321       || !validate_arg (src,
12322                         (fcode == BUILT_IN_MEMSET_CHK
12323                          ? INTEGER_TYPE : POINTER_TYPE))
12324       || !validate_arg (len, INTEGER_TYPE)
12325       || !validate_arg (size, INTEGER_TYPE))
12326     return NULL_TREE;
12327
12328   /* If SRC and DEST are the same (and not volatile), return DEST
12329      (resp. DEST+LEN for __mempcpy_chk).  */
12330   if (fcode != BUILT_IN_MEMSET_CHK && operand_equal_p (src, dest, 0))
12331     {
12332       if (fcode != BUILT_IN_MEMPCPY_CHK)
12333         return omit_one_operand_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)),
12334                                  dest, len);
12335       else
12336         {
12337           tree temp = fold_build2_loc (loc, POINTER_PLUS_EXPR, TREE_TYPE (dest),
12338                                    dest, len);
12339           return fold_convert_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)), temp);
12340         }
12341     }
12342
12343   if (! host_integerp (size, 1))
12344     return NULL_TREE;
12345
12346   if (! integer_all_onesp (size))
12347     {
12348       if (! host_integerp (len, 1))
12349         {
12350           /* If LEN is not constant, try MAXLEN too.
12351              For MAXLEN only allow optimizing into non-_ocs function
12352              if SIZE is >= MAXLEN, never convert to __ocs_fail ().  */
12353           if (maxlen == NULL_TREE || ! host_integerp (maxlen, 1))
12354             {
12355               if (fcode == BUILT_IN_MEMPCPY_CHK && ignore)
12356                 {
12357                   /* (void) __mempcpy_chk () can be optimized into
12358                      (void) __memcpy_chk ().  */
12359                   fn = built_in_decls[BUILT_IN_MEMCPY_CHK];
12360                   if (!fn)
12361                     return NULL_TREE;
12362
12363                   return build_call_expr_loc (loc, fn, 4, dest, src, len, size);
12364                 }
12365               return NULL_TREE;
12366             }
12367         }
12368       else
12369         maxlen = len;
12370
12371       if (tree_int_cst_lt (size, maxlen))
12372         return NULL_TREE;
12373     }
12374
12375   fn = NULL_TREE;
12376   /* If __builtin_mem{cpy,pcpy,move,set}_chk is used, assume
12377      mem{cpy,pcpy,move,set} is available.  */
12378   switch (fcode)
12379     {
12380     case BUILT_IN_MEMCPY_CHK:
12381       fn = built_in_decls[BUILT_IN_MEMCPY];
12382       break;
12383     case BUILT_IN_MEMPCPY_CHK:
12384       fn = built_in_decls[BUILT_IN_MEMPCPY];
12385       break;
12386     case BUILT_IN_MEMMOVE_CHK:
12387       fn = built_in_decls[BUILT_IN_MEMMOVE];
12388       break;
12389     case BUILT_IN_MEMSET_CHK:
12390       fn = built_in_decls[BUILT_IN_MEMSET];
12391       break;
12392     default:
12393       break;
12394     }
12395
12396   if (!fn)
12397     return NULL_TREE;
12398
12399   return build_call_expr_loc (loc, fn, 3, dest, src, len);
12400 }
12401
12402 /* Fold a call to the __st[rp]cpy_chk builtin.
12403    DEST, SRC, and SIZE are the arguments to the call.
12404    IGNORE is true if return value can be ignored.  FCODE is the BUILT_IN_*
12405    code of the builtin.  If MAXLEN is not NULL, it is maximum length of
12406    strings passed as second argument.  */
12407
12408 tree
12409 fold_builtin_stxcpy_chk (location_t loc, tree fndecl, tree dest,
12410                          tree src, tree size,
12411                          tree maxlen, bool ignore,
12412                          enum built_in_function fcode)
12413 {
12414   tree len, fn;
12415
12416   if (!validate_arg (dest, POINTER_TYPE)
12417       || !validate_arg (src, POINTER_TYPE)
12418       || !validate_arg (size, INTEGER_TYPE))
12419     return NULL_TREE;
12420
12421   /* If SRC and DEST are the same (and not volatile), return DEST.  */
12422   if (fcode == BUILT_IN_STRCPY_CHK && operand_equal_p (src, dest, 0))
12423     return fold_convert_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)), dest);
12424
12425   if (! host_integerp (size, 1))
12426     return NULL_TREE;
12427
12428   if (! integer_all_onesp (size))
12429     {
12430       len = c_strlen (src, 1);
12431       if (! len || ! host_integerp (len, 1))
12432         {
12433           /* If LEN is not constant, try MAXLEN too.
12434              For MAXLEN only allow optimizing into non-_ocs function
12435              if SIZE is >= MAXLEN, never convert to __ocs_fail ().  */
12436           if (maxlen == NULL_TREE || ! host_integerp (maxlen, 1))
12437             {
12438               if (fcode == BUILT_IN_STPCPY_CHK)
12439                 {
12440                   if (! ignore)
12441                     return NULL_TREE;
12442
12443                   /* If return value of __stpcpy_chk is ignored,
12444                      optimize into __strcpy_chk.  */
12445                   fn = built_in_decls[BUILT_IN_STRCPY_CHK];
12446                   if (!fn)
12447                     return NULL_TREE;
12448
12449                   return build_call_expr_loc (loc, fn, 3, dest, src, size);
12450                 }
12451
12452               if (! len || TREE_SIDE_EFFECTS (len))
12453                 return NULL_TREE;
12454
12455               /* If c_strlen returned something, but not a constant,
12456                  transform __strcpy_chk into __memcpy_chk.  */
12457               fn = built_in_decls[BUILT_IN_MEMCPY_CHK];
12458               if (!fn)
12459                 return NULL_TREE;
12460
12461               len = size_binop_loc (loc, PLUS_EXPR, len, ssize_int (1));
12462               return fold_convert_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)),
12463                                        build_call_expr_loc (loc, fn, 4,
12464                                                         dest, src, len, size));
12465             }
12466         }
12467       else
12468         maxlen = len;
12469
12470       if (! tree_int_cst_lt (maxlen, size))
12471         return NULL_TREE;
12472     }
12473
12474   /* If __builtin_st{r,p}cpy_chk is used, assume st{r,p}cpy is available.  */
12475   fn = built_in_decls[fcode == BUILT_IN_STPCPY_CHK
12476                       ? BUILT_IN_STPCPY : BUILT_IN_STRCPY];
12477   if (!fn)
12478     return NULL_TREE;
12479
12480   return build_call_expr_loc (loc, fn, 2, dest, src);
12481 }
12482
12483 /* Fold a call to the __strncpy_chk builtin.  DEST, SRC, LEN, and SIZE
12484    are the arguments to the call.  If MAXLEN is not NULL, it is maximum
12485    length passed as third argument.  */
12486
12487 tree
12488 fold_builtin_strncpy_chk (location_t loc, tree dest, tree src,
12489                           tree len, tree size, tree maxlen)
12490 {
12491   tree fn;
12492
12493   if (!validate_arg (dest, POINTER_TYPE)
12494       || !validate_arg (src, POINTER_TYPE)
12495       || !validate_arg (len, INTEGER_TYPE)
12496       || !validate_arg (size, INTEGER_TYPE))
12497     return NULL_TREE;
12498
12499   if (! host_integerp (size, 1))
12500     return NULL_TREE;
12501
12502   if (! integer_all_onesp (size))
12503     {
12504       if (! host_integerp (len, 1))
12505         {
12506           /* If LEN is not constant, try MAXLEN too.
12507              For MAXLEN only allow optimizing into non-_ocs function
12508              if SIZE is >= MAXLEN, never convert to __ocs_fail ().  */
12509           if (maxlen == NULL_TREE || ! host_integerp (maxlen, 1))
12510             return NULL_TREE;
12511         }
12512       else
12513         maxlen = len;
12514
12515       if (tree_int_cst_lt (size, maxlen))
12516         return NULL_TREE;
12517     }
12518
12519   /* If __builtin_strncpy_chk is used, assume strncpy is available.  */
12520   fn = built_in_decls[BUILT_IN_STRNCPY];
12521   if (!fn)
12522     return NULL_TREE;
12523
12524   return build_call_expr_loc (loc, fn, 3, dest, src, len);
12525 }
12526
12527 /* Fold a call to the __strcat_chk builtin FNDECL.  DEST, SRC, and SIZE
12528    are the arguments to the call.  */
12529
12530 static tree
12531 fold_builtin_strcat_chk (location_t loc, tree fndecl, tree dest,
12532                          tree src, tree size)
12533 {
12534   tree fn;
12535   const char *p;
12536
12537   if (!validate_arg (dest, POINTER_TYPE)
12538       || !validate_arg (src, POINTER_TYPE)
12539       || !validate_arg (size, INTEGER_TYPE))
12540     return NULL_TREE;
12541
12542   p = c_getstr (src);
12543   /* If the SRC parameter is "", return DEST.  */
12544   if (p && *p == '\0')
12545     return omit_one_operand_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)), dest, src);
12546
12547   if (! host_integerp (size, 1) || ! integer_all_onesp (size))
12548     return NULL_TREE;
12549
12550   /* If __builtin_strcat_chk is used, assume strcat is available.  */
12551   fn = built_in_decls[BUILT_IN_STRCAT];
12552   if (!fn)
12553     return NULL_TREE;
12554
12555   return build_call_expr_loc (loc, fn, 2, dest, src);
12556 }
12557
12558 /* Fold a call to the __strncat_chk builtin with arguments DEST, SRC,
12559    LEN, and SIZE.  */
12560
12561 static tree
12562 fold_builtin_strncat_chk (location_t loc, tree fndecl,
12563                           tree dest, tree src, tree len, tree size)
12564 {
12565   tree fn;
12566   const char *p;
12567
12568   if (!validate_arg (dest, POINTER_TYPE)
12569       || !validate_arg (src, POINTER_TYPE)
12570       || !validate_arg (size, INTEGER_TYPE)
12571       || !validate_arg (size, INTEGER_TYPE))
12572     return NULL_TREE;
12573
12574   p = c_getstr (src);
12575   /* If the SRC parameter is "" or if LEN is 0, return DEST.  */
12576   if (p && *p == '\0')
12577     return omit_one_operand_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)), dest, len);
12578   else if (integer_zerop (len))
12579     return omit_one_operand_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)), dest, src);
12580
12581   if (! host_integerp (size, 1))
12582     return NULL_TREE;
12583
12584   if (! integer_all_onesp (size))
12585     {
12586       tree src_len = c_strlen (src, 1);
12587       if (src_len
12588           && host_integerp (src_len, 1)
12589           && host_integerp (len, 1)
12590           && ! tree_int_cst_lt (len, src_len))
12591         {
12592           /* If LEN >= strlen (SRC), optimize into __strcat_chk.  */
12593           fn = built_in_decls[BUILT_IN_STRCAT_CHK];
12594           if (!fn)
12595             return NULL_TREE;
12596
12597           return build_call_expr_loc (loc, fn, 3, dest, src, size);
12598         }
12599       return NULL_TREE;
12600     }
12601
12602   /* If __builtin_strncat_chk is used, assume strncat is available.  */
12603   fn = built_in_decls[BUILT_IN_STRNCAT];
12604   if (!fn)
12605     return NULL_TREE;
12606
12607   return build_call_expr_loc (loc, fn, 3, dest, src, len);
12608 }
12609
12610 /* Fold a call EXP to __{,v}sprintf_chk having NARGS passed as ARGS.
12611    Return NULL_TREE if a normal call should be emitted rather than
12612    expanding the function inline.  FCODE is either BUILT_IN_SPRINTF_CHK
12613    or BUILT_IN_VSPRINTF_CHK.  */
12614
12615 static tree
12616 fold_builtin_sprintf_chk_1 (location_t loc, int nargs, tree *args,
12617                             enum built_in_function fcode)
12618 {
12619   tree dest, size, len, fn, fmt, flag;
12620   const char *fmt_str;
12621
12622   /* Verify the required arguments in the original call.  */
12623   if (nargs < 4)
12624     return NULL_TREE;
12625   dest = args[0];
12626   if (!validate_arg (dest, POINTER_TYPE))
12627     return NULL_TREE;
12628   flag = args[1];
12629   if (!validate_arg (flag, INTEGER_TYPE))
12630     return NULL_TREE;
12631   size = args[2];
12632   if (!validate_arg (size, INTEGER_TYPE))
12633     return NULL_TREE;
12634   fmt = args[3];
12635   if (!validate_arg (fmt, POINTER_TYPE))
12636     return NULL_TREE;
12637
12638   if (! host_integerp (size, 1))
12639     return NULL_TREE;
12640
12641   len = NULL_TREE;
12642
12643   if (!init_target_chars ())
12644     return NULL_TREE;
12645
12646   /* Check whether the format is a literal string constant.  */
12647   fmt_str = c_getstr (fmt);
12648   if (fmt_str != NULL)
12649     {
12650       /* If the format doesn't contain % args or %%, we know the size.  */
12651       if (strchr (fmt_str, target_percent) == 0)
12652         {
12653           if (fcode != BUILT_IN_SPRINTF_CHK || nargs == 4)
12654             len = build_int_cstu (size_type_node, strlen (fmt_str));
12655         }
12656       /* If the format is "%s" and first ... argument is a string literal,
12657          we know the size too.  */
12658       else if (fcode == BUILT_IN_SPRINTF_CHK
12659                && strcmp (fmt_str, target_percent_s) == 0)
12660         {
12661           tree arg;
12662
12663           if (nargs == 5)
12664             {
12665               arg = args[4];
12666               if (validate_arg (arg, POINTER_TYPE))
12667                 {
12668                   len = c_strlen (arg, 1);
12669                   if (! len || ! host_integerp (len, 1))
12670                     len = NULL_TREE;
12671                 }
12672             }
12673         }
12674     }
12675
12676   if (! integer_all_onesp (size))
12677     {
12678       if (! len || ! tree_int_cst_lt (len, size))
12679         return NULL_TREE;
12680     }
12681
12682   /* Only convert __{,v}sprintf_chk to {,v}sprintf if flag is 0
12683      or if format doesn't contain % chars or is "%s".  */
12684   if (! integer_zerop (flag))
12685     {
12686       if (fmt_str == NULL)
12687         return NULL_TREE;
12688       if (strchr (fmt_str, target_percent) != NULL
12689           && strcmp (fmt_str, target_percent_s))
12690         return NULL_TREE;
12691     }
12692
12693   /* If __builtin_{,v}sprintf_chk is used, assume {,v}sprintf is available.  */
12694   fn = built_in_decls[fcode == BUILT_IN_VSPRINTF_CHK
12695                       ? BUILT_IN_VSPRINTF : BUILT_IN_SPRINTF];
12696   if (!fn)
12697     return NULL_TREE;
12698
12699   return rewrite_call_expr_array (loc, nargs, args, 4, fn, 2, dest, fmt);
12700 }
12701
12702 /* Fold a call EXP to __{,v}sprintf_chk.  Return NULL_TREE if
12703    a normal call should be emitted rather than expanding the function
12704    inline.  FCODE is either BUILT_IN_SPRINTF_CHK or BUILT_IN_VSPRINTF_CHK.  */
12705
12706 static tree
12707 fold_builtin_sprintf_chk (location_t loc, tree exp,
12708                           enum built_in_function fcode)
12709 {
12710   return fold_builtin_sprintf_chk_1 (loc, call_expr_nargs (exp),
12711                                      CALL_EXPR_ARGP (exp), fcode);
12712 }
12713
12714 /* Fold a call EXP to {,v}snprintf having NARGS passed as ARGS.  Return
12715    NULL_TREE if a normal call should be emitted rather than expanding
12716    the function inline.  FCODE is either BUILT_IN_SNPRINTF_CHK or
12717    BUILT_IN_VSNPRINTF_CHK.  If MAXLEN is not NULL, it is maximum length
12718    passed as second argument.  */
12719
12720 static tree
12721 fold_builtin_snprintf_chk_1 (location_t loc, int nargs, tree *args,
12722                              tree maxlen, enum built_in_function fcode)
12723 {
12724   tree dest, size, len, fn, fmt, flag;
12725   const char *fmt_str;
12726
12727   /* Verify the required arguments in the original call.  */
12728   if (nargs < 5)
12729     return NULL_TREE;
12730   dest = args[0];
12731   if (!validate_arg (dest, POINTER_TYPE))
12732     return NULL_TREE;
12733   len = args[1];
12734   if (!validate_arg (len, INTEGER_TYPE))
12735     return NULL_TREE;
12736   flag = args[2];
12737   if (!validate_arg (flag, INTEGER_TYPE))
12738     return NULL_TREE;
12739   size = args[3];
12740   if (!validate_arg (size, INTEGER_TYPE))
12741     return NULL_TREE;
12742   fmt = args[4];
12743   if (!validate_arg (fmt, POINTER_TYPE))
12744     return NULL_TREE;
12745
12746   if (! host_integerp (size, 1))
12747     return NULL_TREE;
12748
12749   if (! integer_all_onesp (size))
12750     {
12751       if (! host_integerp (len, 1))
12752         {
12753           /* If LEN is not constant, try MAXLEN too.
12754              For MAXLEN only allow optimizing into non-_ocs function
12755              if SIZE is >= MAXLEN, never convert to __ocs_fail ().  */
12756           if (maxlen == NULL_TREE || ! host_integerp (maxlen, 1))
12757             return NULL_TREE;
12758         }
12759       else
12760         maxlen = len;
12761
12762       if (tree_int_cst_lt (size, maxlen))
12763         return NULL_TREE;
12764     }
12765
12766   if (!init_target_chars ())
12767     return NULL_TREE;
12768
12769   /* Only convert __{,v}snprintf_chk to {,v}snprintf if flag is 0
12770      or if format doesn't contain % chars or is "%s".  */
12771   if (! integer_zerop (flag))
12772     {
12773       fmt_str = c_getstr (fmt);
12774       if (fmt_str == NULL)
12775         return NULL_TREE;
12776       if (strchr (fmt_str, target_percent) != NULL
12777           && strcmp (fmt_str, target_percent_s))
12778         return NULL_TREE;
12779     }
12780
12781   /* If __builtin_{,v}snprintf_chk is used, assume {,v}snprintf is
12782      available.  */
12783   fn = built_in_decls[fcode == BUILT_IN_VSNPRINTF_CHK
12784                       ? BUILT_IN_VSNPRINTF : BUILT_IN_SNPRINTF];
12785   if (!fn)
12786     return NULL_TREE;
12787
12788   return rewrite_call_expr_array (loc, nargs, args, 5, fn, 3, dest, len, fmt);
12789 }
12790
12791 /* Fold a call EXP to {,v}snprintf.  Return NULL_TREE if
12792    a normal call should be emitted rather than expanding the function
12793    inline.  FCODE is either BUILT_IN_SNPRINTF_CHK or
12794    BUILT_IN_VSNPRINTF_CHK.  If MAXLEN is not NULL, it is maximum length
12795    passed as second argument.  */
12796
12797 tree
12798 fold_builtin_snprintf_chk (location_t loc, tree exp, tree maxlen,
12799                            enum built_in_function fcode)
12800 {
12801   return fold_builtin_snprintf_chk_1 (loc, call_expr_nargs (exp),
12802                                       CALL_EXPR_ARGP (exp), maxlen, fcode);
12803 }
12804
12805 /* Fold a call to the {,v}printf{,_unlocked} and __{,v}printf_chk builtins.
12806    FMT and ARG are the arguments to the call; we don't fold cases with
12807    more than 2 arguments, and ARG may be null if this is a 1-argument case.
12808
12809    Return NULL_TREE if no simplification was possible, otherwise return the
12810    simplified form of the call as a tree.  FCODE is the BUILT_IN_*
12811    code of the function to be simplified.  */
12812
12813 static tree
12814 fold_builtin_printf (location_t loc, tree fndecl, tree fmt,
12815                      tree arg, bool ignore,
12816                      enum built_in_function fcode)
12817 {
12818   tree fn_putchar, fn_puts, newarg, call = NULL_TREE;
12819   const char *fmt_str = NULL;
12820
12821   /* If the return value is used, don't do the transformation.  */
12822   if (! ignore)
12823     return NULL_TREE;
12824
12825   /* Verify the required arguments in the original call.  */
12826   if (!validate_arg (fmt, POINTER_TYPE))
12827     return NULL_TREE;
12828
12829   /* Check whether the format is a literal string constant.  */
12830   fmt_str = c_getstr (fmt);
12831   if (fmt_str == NULL)
12832     return NULL_TREE;
12833
12834   if (fcode == BUILT_IN_PRINTF_UNLOCKED)
12835     {
12836       /* If we're using an unlocked function, assume the other
12837          unlocked functions exist explicitly.  */
12838       fn_putchar = built_in_decls[BUILT_IN_PUTCHAR_UNLOCKED];
12839       fn_puts = built_in_decls[BUILT_IN_PUTS_UNLOCKED];
12840     }
12841   else
12842     {
12843       fn_putchar = implicit_built_in_decls[BUILT_IN_PUTCHAR];
12844       fn_puts = implicit_built_in_decls[BUILT_IN_PUTS];
12845     }
12846
12847   if (!init_target_chars ())
12848     return NULL_TREE;
12849
12850   if (strcmp (fmt_str, target_percent_s) == 0
12851       || strchr (fmt_str, target_percent) == NULL)
12852     {
12853       const char *str;
12854
12855       if (strcmp (fmt_str, target_percent_s) == 0)
12856         {
12857           if (fcode == BUILT_IN_VPRINTF || fcode == BUILT_IN_VPRINTF_CHK)
12858             return NULL_TREE;
12859
12860           if (!arg || !validate_arg (arg, POINTER_TYPE))
12861             return NULL_TREE;
12862
12863           str = c_getstr (arg);
12864           if (str == NULL)
12865             return NULL_TREE;
12866         }
12867       else
12868         {
12869           /* The format specifier doesn't contain any '%' characters.  */
12870           if (fcode != BUILT_IN_VPRINTF && fcode != BUILT_IN_VPRINTF_CHK
12871               && arg)
12872             return NULL_TREE;
12873           str = fmt_str;
12874         }
12875
12876       /* If the string was "", printf does nothing.  */
12877       if (str[0] == '\0')
12878         return build_int_cst (TREE_TYPE (TREE_TYPE (fndecl)), 0);
12879
12880       /* If the string has length of 1, call putchar.  */
12881       if (str[1] == '\0')
12882         {
12883           /* Given printf("c"), (where c is any one character,)
12884              convert "c"[0] to an int and pass that to the replacement
12885              function.  */
12886           newarg = build_int_cst (NULL_TREE, str[0]);
12887           if (fn_putchar)
12888             call = build_call_expr_loc (loc, fn_putchar, 1, newarg);
12889         }
12890       else
12891         {
12892           /* If the string was "string\n", call puts("string").  */
12893           size_t len = strlen (str);
12894           if ((unsigned char)str[len - 1] == target_newline
12895               && (size_t) (int) len == len
12896               && (int) len > 0)
12897             {
12898               char *newstr;
12899               tree offset_node, string_cst;
12900
12901               /* Create a NUL-terminated string that's one char shorter
12902                  than the original, stripping off the trailing '\n'.  */
12903               newarg = build_string_literal (len, str);
12904               string_cst = string_constant (newarg, &offset_node);
12905               gcc_checking_assert (string_cst
12906                                    && (TREE_STRING_LENGTH (string_cst)
12907                                        == (int) len)
12908                                    && integer_zerop (offset_node)
12909                                    && (unsigned char)
12910                                       TREE_STRING_POINTER (string_cst)[len - 1]
12911                                       == target_newline);
12912               /* build_string_literal creates a new STRING_CST,
12913                  modify it in place to avoid double copying.  */
12914               newstr = CONST_CAST (char *, TREE_STRING_POINTER (string_cst));
12915               newstr[len - 1] = '\0';
12916               if (fn_puts)
12917                 call = build_call_expr_loc (loc, fn_puts, 1, newarg);
12918             }
12919           else
12920             /* We'd like to arrange to call fputs(string,stdout) here,
12921                but we need stdout and don't have a way to get it yet.  */
12922             return NULL_TREE;
12923         }
12924     }
12925
12926   /* The other optimizations can be done only on the non-va_list variants.  */
12927   else if (fcode == BUILT_IN_VPRINTF || fcode == BUILT_IN_VPRINTF_CHK)
12928     return NULL_TREE;
12929
12930   /* If the format specifier was "%s\n", call __builtin_puts(arg).  */
12931   else if (strcmp (fmt_str, target_percent_s_newline) == 0)
12932     {
12933       if (!arg || !validate_arg (arg, POINTER_TYPE))
12934         return NULL_TREE;
12935       if (fn_puts)
12936         call = build_call_expr_loc (loc, fn_puts, 1, arg);
12937     }
12938
12939   /* If the format specifier was "%c", call __builtin_putchar(arg).  */
12940   else if (strcmp (fmt_str, target_percent_c) == 0)
12941     {
12942       if (!arg || !validate_arg (arg, INTEGER_TYPE))
12943         return NULL_TREE;
12944       if (fn_putchar)
12945         call = build_call_expr_loc (loc, fn_putchar, 1, arg);
12946     }
12947
12948   if (!call)
12949     return NULL_TREE;
12950
12951   return fold_convert_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)), call);
12952 }
12953
12954 /* Fold a call to the {,v}fprintf{,_unlocked} and __{,v}printf_chk builtins.
12955    FP, FMT, and ARG are the arguments to the call.  We don't fold calls with
12956    more than 3 arguments, and ARG may be null in the 2-argument case.
12957
12958    Return NULL_TREE if no simplification was possible, otherwise return the
12959    simplified form of the call as a tree.  FCODE is the BUILT_IN_*
12960    code of the function to be simplified.  */
12961
12962 static tree
12963 fold_builtin_fprintf (location_t loc, tree fndecl, tree fp,
12964                       tree fmt, tree arg, bool ignore,
12965                       enum built_in_function fcode)
12966 {
12967   tree fn_fputc, fn_fputs, call = NULL_TREE;
12968   const char *fmt_str = NULL;
12969
12970   /* If the return value is used, don't do the transformation.  */
12971   if (! ignore)
12972     return NULL_TREE;
12973
12974   /* Verify the required arguments in the original call.  */
12975   if (!validate_arg (fp, POINTER_TYPE))
12976     return NULL_TREE;
12977   if (!validate_arg (fmt, POINTER_TYPE))
12978     return NULL_TREE;
12979
12980   /* Check whether the format is a literal string constant.  */
12981   fmt_str = c_getstr (fmt);
12982   if (fmt_str == NULL)
12983     return NULL_TREE;
12984
12985   if (fcode == BUILT_IN_FPRINTF_UNLOCKED)
12986     {
12987       /* If we're using an unlocked function, assume the other
12988          unlocked functions exist explicitly.  */
12989       fn_fputc = built_in_decls[BUILT_IN_FPUTC_UNLOCKED];
12990       fn_fputs = built_in_decls[BUILT_IN_FPUTS_UNLOCKED];
12991     }
12992   else
12993     {
12994       fn_fputc = implicit_built_in_decls[BUILT_IN_FPUTC];
12995       fn_fputs = implicit_built_in_decls[BUILT_IN_FPUTS];
12996     }
12997
12998   if (!init_target_chars ())
12999     return NULL_TREE;
13000
13001   /* If the format doesn't contain % args or %%, use strcpy.  */
13002   if (strchr (fmt_str, target_percent) == NULL)
13003     {
13004       if (fcode != BUILT_IN_VFPRINTF && fcode != BUILT_IN_VFPRINTF_CHK
13005           && arg)
13006         return NULL_TREE;
13007
13008       /* If the format specifier was "", fprintf does nothing.  */
13009       if (fmt_str[0] == '\0')
13010         {
13011           /* If FP has side-effects, just wait until gimplification is
13012              done.  */
13013           if (TREE_SIDE_EFFECTS (fp))
13014             return NULL_TREE;
13015
13016           return build_int_cst (TREE_TYPE (TREE_TYPE (fndecl)), 0);
13017         }
13018
13019       /* When "string" doesn't contain %, replace all cases of
13020          fprintf (fp, string) with fputs (string, fp).  The fputs
13021          builtin will take care of special cases like length == 1.  */
13022       if (fn_fputs)
13023         call = build_call_expr_loc (loc, fn_fputs, 2, fmt, fp);
13024     }
13025
13026   /* The other optimizations can be done only on the non-va_list variants.  */
13027   else if (fcode == BUILT_IN_VFPRINTF || fcode == BUILT_IN_VFPRINTF_CHK)
13028     return NULL_TREE;
13029
13030   /* If the format specifier was "%s", call __builtin_fputs (arg, fp).  */
13031   else if (strcmp (fmt_str, target_percent_s) == 0)
13032     {
13033       if (!arg || !validate_arg (arg, POINTER_TYPE))
13034         return NULL_TREE;
13035       if (fn_fputs)
13036         call = build_call_expr_loc (loc, fn_fputs, 2, arg, fp);
13037     }
13038
13039   /* If the format specifier was "%c", call __builtin_fputc (arg, fp).  */
13040   else if (strcmp (fmt_str, target_percent_c) == 0)
13041     {
13042       if (!arg || !validate_arg (arg, INTEGER_TYPE))
13043         return NULL_TREE;
13044       if (fn_fputc)
13045         call = build_call_expr_loc (loc, fn_fputc, 2, arg, fp);
13046     }
13047
13048   if (!call)
13049     return NULL_TREE;
13050   return fold_convert_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)), call);
13051 }
13052
13053 /* Initialize format string characters in the target charset.  */
13054
13055 static bool
13056 init_target_chars (void)
13057 {
13058   static bool init;
13059   if (!init)
13060     {
13061       target_newline = lang_hooks.to_target_charset ('\n');
13062       target_percent = lang_hooks.to_target_charset ('%');
13063       target_c = lang_hooks.to_target_charset ('c');
13064       target_s = lang_hooks.to_target_charset ('s');
13065       if (target_newline == 0 || target_percent == 0 || target_c == 0
13066           || target_s == 0)
13067         return false;
13068
13069       target_percent_c[0] = target_percent;
13070       target_percent_c[1] = target_c;
13071       target_percent_c[2] = '\0';
13072
13073       target_percent_s[0] = target_percent;
13074       target_percent_s[1] = target_s;
13075       target_percent_s[2] = '\0';
13076
13077       target_percent_s_newline[0] = target_percent;
13078       target_percent_s_newline[1] = target_s;
13079       target_percent_s_newline[2] = target_newline;
13080       target_percent_s_newline[3] = '\0';
13081
13082       init = true;
13083     }
13084   return true;
13085 }
13086
13087 /* Helper function for do_mpfr_arg*().  Ensure M is a normal number
13088    and no overflow/underflow occurred.  INEXACT is true if M was not
13089    exactly calculated.  TYPE is the tree type for the result.  This
13090    function assumes that you cleared the MPFR flags and then
13091    calculated M to see if anything subsequently set a flag prior to
13092    entering this function.  Return NULL_TREE if any checks fail.  */
13093
13094 static tree
13095 do_mpfr_ckconv (mpfr_srcptr m, tree type, int inexact)
13096 {
13097   /* Proceed iff we get a normal number, i.e. not NaN or Inf and no
13098      overflow/underflow occurred.  If -frounding-math, proceed iff the
13099      result of calling FUNC was exact.  */
13100   if (mpfr_number_p (m) && !mpfr_overflow_p () && !mpfr_underflow_p ()
13101       && (!flag_rounding_math || !inexact))
13102     {
13103       REAL_VALUE_TYPE rr;
13104
13105       real_from_mpfr (&rr, m, type, GMP_RNDN);
13106       /* Proceed iff GCC's REAL_VALUE_TYPE can hold the MPFR value,
13107          check for overflow/underflow.  If the REAL_VALUE_TYPE is zero
13108          but the mpft_t is not, then we underflowed in the
13109          conversion.  */
13110       if (real_isfinite (&rr)
13111           && (rr.cl == rvc_zero) == (mpfr_zero_p (m) != 0))
13112         {
13113           REAL_VALUE_TYPE rmode;
13114
13115           real_convert (&rmode, TYPE_MODE (type), &rr);
13116           /* Proceed iff the specified mode can hold the value.  */
13117           if (real_identical (&rmode, &rr))
13118             return build_real (type, rmode);
13119         }
13120     }
13121   return NULL_TREE;
13122 }
13123
13124 /* Helper function for do_mpc_arg*().  Ensure M is a normal complex
13125    number and no overflow/underflow occurred.  INEXACT is true if M
13126    was not exactly calculated.  TYPE is the tree type for the result.
13127    This function assumes that you cleared the MPFR flags and then
13128    calculated M to see if anything subsequently set a flag prior to
13129    entering this function.  Return NULL_TREE if any checks fail, if
13130    FORCE_CONVERT is true, then bypass the checks.  */
13131
13132 static tree
13133 do_mpc_ckconv (mpc_srcptr m, tree type, int inexact, int force_convert)
13134 {
13135   /* Proceed iff we get a normal number, i.e. not NaN or Inf and no
13136      overflow/underflow occurred.  If -frounding-math, proceed iff the
13137      result of calling FUNC was exact.  */
13138   if (force_convert
13139       || (mpfr_number_p (mpc_realref (m)) && mpfr_number_p (mpc_imagref (m))
13140           && !mpfr_overflow_p () && !mpfr_underflow_p ()
13141           && (!flag_rounding_math || !inexact)))
13142     {
13143       REAL_VALUE_TYPE re, im;
13144
13145       real_from_mpfr (&re, mpc_realref (m), TREE_TYPE (type), GMP_RNDN);
13146       real_from_mpfr (&im, mpc_imagref (m), TREE_TYPE (type), GMP_RNDN);
13147       /* Proceed iff GCC's REAL_VALUE_TYPE can hold the MPFR values,
13148          check for overflow/underflow.  If the REAL_VALUE_TYPE is zero
13149          but the mpft_t is not, then we underflowed in the
13150          conversion.  */
13151       if (force_convert
13152           || (real_isfinite (&re) && real_isfinite (&im)
13153               && (re.cl == rvc_zero) == (mpfr_zero_p (mpc_realref (m)) != 0)
13154               && (im.cl == rvc_zero) == (mpfr_zero_p (mpc_imagref (m)) != 0)))
13155         {
13156           REAL_VALUE_TYPE re_mode, im_mode;
13157
13158           real_convert (&re_mode, TYPE_MODE (TREE_TYPE (type)), &re);
13159           real_convert (&im_mode, TYPE_MODE (TREE_TYPE (type)), &im);
13160           /* Proceed iff the specified mode can hold the value.  */
13161           if (force_convert
13162               || (real_identical (&re_mode, &re)
13163                   && real_identical (&im_mode, &im)))
13164             return build_complex (type, build_real (TREE_TYPE (type), re_mode),
13165                                   build_real (TREE_TYPE (type), im_mode));
13166         }
13167     }
13168   return NULL_TREE;
13169 }
13170
13171 /* If argument ARG is a REAL_CST, call the one-argument mpfr function
13172    FUNC on it and return the resulting value as a tree with type TYPE.
13173    If MIN and/or MAX are not NULL, then the supplied ARG must be
13174    within those bounds.  If INCLUSIVE is true, then MIN/MAX are
13175    acceptable values, otherwise they are not.  The mpfr precision is
13176    set to the precision of TYPE.  We assume that function FUNC returns
13177    zero if the result could be calculated exactly within the requested
13178    precision.  */
13179
13180 static tree
13181 do_mpfr_arg1 (tree arg, tree type, int (*func)(mpfr_ptr, mpfr_srcptr, mp_rnd_t),
13182               const REAL_VALUE_TYPE *min, const REAL_VALUE_TYPE *max,
13183               bool inclusive)
13184 {
13185   tree result = NULL_TREE;
13186
13187   STRIP_NOPS (arg);
13188
13189   /* To proceed, MPFR must exactly represent the target floating point
13190      format, which only happens when the target base equals two.  */
13191   if (REAL_MODE_FORMAT (TYPE_MODE (type))->b == 2
13192       && TREE_CODE (arg) == REAL_CST && !TREE_OVERFLOW (arg))
13193     {
13194       const REAL_VALUE_TYPE *const ra = &TREE_REAL_CST (arg);
13195
13196       if (real_isfinite (ra)
13197           && (!min || real_compare (inclusive ? GE_EXPR: GT_EXPR , ra, min))
13198           && (!max || real_compare (inclusive ? LE_EXPR: LT_EXPR , ra, max)))
13199         {
13200           const struct real_format *fmt = REAL_MODE_FORMAT (TYPE_MODE (type));
13201           const int prec = fmt->p;
13202           const mp_rnd_t rnd = fmt->round_towards_zero? GMP_RNDZ : GMP_RNDN;
13203           int inexact;
13204           mpfr_t m;
13205
13206           mpfr_init2 (m, prec);
13207           mpfr_from_real (m, ra, GMP_RNDN);
13208           mpfr_clear_flags ();
13209           inexact = func (m, m, rnd);
13210           result = do_mpfr_ckconv (m, type, inexact);
13211           mpfr_clear (m);
13212         }
13213     }
13214
13215   return result;
13216 }
13217
13218 /* If argument ARG is a REAL_CST, call the two-argument mpfr function
13219    FUNC on it and return the resulting value as a tree with type TYPE.
13220    The mpfr precision is set to the precision of TYPE.  We assume that
13221    function FUNC returns zero if the result could be calculated
13222    exactly within the requested precision.  */
13223
13224 static tree
13225 do_mpfr_arg2 (tree arg1, tree arg2, tree type,
13226               int (*func)(mpfr_ptr, mpfr_srcptr, mpfr_srcptr, mp_rnd_t))
13227 {
13228   tree result = NULL_TREE;
13229
13230   STRIP_NOPS (arg1);
13231   STRIP_NOPS (arg2);
13232
13233   /* To proceed, MPFR must exactly represent the target floating point
13234      format, which only happens when the target base equals two.  */
13235   if (REAL_MODE_FORMAT (TYPE_MODE (type))->b == 2
13236       && TREE_CODE (arg1) == REAL_CST && !TREE_OVERFLOW (arg1)
13237       && TREE_CODE (arg2) == REAL_CST && !TREE_OVERFLOW (arg2))
13238     {
13239       const REAL_VALUE_TYPE *const ra1 = &TREE_REAL_CST (arg1);
13240       const REAL_VALUE_TYPE *const ra2 = &TREE_REAL_CST (arg2);
13241
13242       if (real_isfinite (ra1) && real_isfinite (ra2))
13243         {
13244           const struct real_format *fmt = REAL_MODE_FORMAT (TYPE_MODE (type));
13245           const int prec = fmt->p;
13246           const mp_rnd_t rnd = fmt->round_towards_zero? GMP_RNDZ : GMP_RNDN;
13247           int inexact;
13248           mpfr_t m1, m2;
13249
13250           mpfr_inits2 (prec, m1, m2, NULL);
13251           mpfr_from_real (m1, ra1, GMP_RNDN);
13252           mpfr_from_real (m2, ra2, GMP_RNDN);
13253           mpfr_clear_flags ();
13254           inexact = func (m1, m1, m2, rnd);
13255           result = do_mpfr_ckconv (m1, type, inexact);
13256           mpfr_clears (m1, m2, NULL);
13257         }
13258     }
13259
13260   return result;
13261 }
13262
13263 /* If argument ARG is a REAL_CST, call the three-argument mpfr function
13264    FUNC on it and return the resulting value as a tree with type TYPE.
13265    The mpfr precision is set to the precision of TYPE.  We assume that
13266    function FUNC returns zero if the result could be calculated
13267    exactly within the requested precision.  */
13268
13269 static tree
13270 do_mpfr_arg3 (tree arg1, tree arg2, tree arg3, tree type,
13271               int (*func)(mpfr_ptr, mpfr_srcptr, mpfr_srcptr, mpfr_srcptr, mp_rnd_t))
13272 {
13273   tree result = NULL_TREE;
13274
13275   STRIP_NOPS (arg1);
13276   STRIP_NOPS (arg2);
13277   STRIP_NOPS (arg3);
13278
13279   /* To proceed, MPFR must exactly represent the target floating point
13280      format, which only happens when the target base equals two.  */
13281   if (REAL_MODE_FORMAT (TYPE_MODE (type))->b == 2
13282       && TREE_CODE (arg1) == REAL_CST && !TREE_OVERFLOW (arg1)
13283       && TREE_CODE (arg2) == REAL_CST && !TREE_OVERFLOW (arg2)
13284       && TREE_CODE (arg3) == REAL_CST && !TREE_OVERFLOW (arg3))
13285     {
13286       const REAL_VALUE_TYPE *const ra1 = &TREE_REAL_CST (arg1);
13287       const REAL_VALUE_TYPE *const ra2 = &TREE_REAL_CST (arg2);
13288       const REAL_VALUE_TYPE *const ra3 = &TREE_REAL_CST (arg3);
13289
13290       if (real_isfinite (ra1) && real_isfinite (ra2) && real_isfinite (ra3))
13291         {
13292           const struct real_format *fmt = REAL_MODE_FORMAT (TYPE_MODE (type));
13293           const int prec = fmt->p;
13294           const mp_rnd_t rnd = fmt->round_towards_zero? GMP_RNDZ : GMP_RNDN;
13295           int inexact;
13296           mpfr_t m1, m2, m3;
13297
13298           mpfr_inits2 (prec, m1, m2, m3, NULL);
13299           mpfr_from_real (m1, ra1, GMP_RNDN);
13300           mpfr_from_real (m2, ra2, GMP_RNDN);
13301           mpfr_from_real (m3, ra3, GMP_RNDN);
13302           mpfr_clear_flags ();
13303           inexact = func (m1, m1, m2, m3, rnd);
13304           result = do_mpfr_ckconv (m1, type, inexact);
13305           mpfr_clears (m1, m2, m3, NULL);
13306         }
13307     }
13308
13309   return result;
13310 }
13311
13312 /* If argument ARG is a REAL_CST, call mpfr_sin_cos() on it and set
13313    the pointers *(ARG_SINP) and *(ARG_COSP) to the resulting values.
13314    If ARG_SINP and ARG_COSP are NULL then the result is returned
13315    as a complex value.
13316    The type is taken from the type of ARG and is used for setting the
13317    precision of the calculation and results.  */
13318
13319 static tree
13320 do_mpfr_sincos (tree arg, tree arg_sinp, tree arg_cosp)
13321 {
13322   tree const type = TREE_TYPE (arg);
13323   tree result = NULL_TREE;
13324
13325   STRIP_NOPS (arg);
13326
13327   /* To proceed, MPFR must exactly represent the target floating point
13328      format, which only happens when the target base equals two.  */
13329   if (REAL_MODE_FORMAT (TYPE_MODE (type))->b == 2
13330       && TREE_CODE (arg) == REAL_CST
13331       && !TREE_OVERFLOW (arg))
13332     {
13333       const REAL_VALUE_TYPE *const ra = &TREE_REAL_CST (arg);
13334
13335       if (real_isfinite (ra))
13336         {
13337           const struct real_format *fmt = REAL_MODE_FORMAT (TYPE_MODE (type));
13338           const int prec = fmt->p;
13339           const mp_rnd_t rnd = fmt->round_towards_zero? GMP_RNDZ : GMP_RNDN;
13340           tree result_s, result_c;
13341           int inexact;
13342           mpfr_t m, ms, mc;
13343
13344           mpfr_inits2 (prec, m, ms, mc, NULL);
13345           mpfr_from_real (m, ra, GMP_RNDN);
13346           mpfr_clear_flags ();
13347           inexact = mpfr_sin_cos (ms, mc, m, rnd);
13348           result_s = do_mpfr_ckconv (ms, type, inexact);
13349           result_c = do_mpfr_ckconv (mc, type, inexact);
13350           mpfr_clears (m, ms, mc, NULL);
13351           if (result_s && result_c)
13352             {
13353               /* If we are to return in a complex value do so.  */
13354               if (!arg_sinp && !arg_cosp)
13355                 return build_complex (build_complex_type (type),
13356                                       result_c, result_s);
13357
13358               /* Dereference the sin/cos pointer arguments.  */
13359               arg_sinp = build_fold_indirect_ref (arg_sinp);
13360               arg_cosp = build_fold_indirect_ref (arg_cosp);
13361               /* Proceed if valid pointer type were passed in.  */
13362               if (TYPE_MAIN_VARIANT (TREE_TYPE (arg_sinp)) == TYPE_MAIN_VARIANT (type)
13363                   && TYPE_MAIN_VARIANT (TREE_TYPE (arg_cosp)) == TYPE_MAIN_VARIANT (type))
13364                 {
13365                   /* Set the values. */
13366                   result_s = fold_build2 (MODIFY_EXPR, type, arg_sinp,
13367                                           result_s);
13368                   TREE_SIDE_EFFECTS (result_s) = 1;
13369                   result_c = fold_build2 (MODIFY_EXPR, type, arg_cosp,
13370                                           result_c);
13371                   TREE_SIDE_EFFECTS (result_c) = 1;
13372                   /* Combine the assignments into a compound expr.  */
13373                   result = non_lvalue (fold_build2 (COMPOUND_EXPR, type,
13374                                                     result_s, result_c));
13375                 }
13376             }
13377         }
13378     }
13379   return result;
13380 }
13381
13382 /* If argument ARG1 is an INTEGER_CST and ARG2 is a REAL_CST, call the
13383    two-argument mpfr order N Bessel function FUNC on them and return
13384    the resulting value as a tree with type TYPE.  The mpfr precision
13385    is set to the precision of TYPE.  We assume that function FUNC
13386    returns zero if the result could be calculated exactly within the
13387    requested precision.  */
13388 static tree
13389 do_mpfr_bessel_n (tree arg1, tree arg2, tree type,
13390                   int (*func)(mpfr_ptr, long, mpfr_srcptr, mp_rnd_t),
13391                   const REAL_VALUE_TYPE *min, bool inclusive)
13392 {
13393   tree result = NULL_TREE;
13394
13395   STRIP_NOPS (arg1);
13396   STRIP_NOPS (arg2);
13397
13398   /* To proceed, MPFR must exactly represent the target floating point
13399      format, which only happens when the target base equals two.  */
13400   if (REAL_MODE_FORMAT (TYPE_MODE (type))->b == 2
13401       && host_integerp (arg1, 0)
13402       && TREE_CODE (arg2) == REAL_CST && !TREE_OVERFLOW (arg2))
13403     {
13404       const HOST_WIDE_INT n = tree_low_cst(arg1, 0);
13405       const REAL_VALUE_TYPE *const ra = &TREE_REAL_CST (arg2);
13406
13407       if (n == (long)n
13408           && real_isfinite (ra)
13409           && (!min || real_compare (inclusive ? GE_EXPR: GT_EXPR , ra, min)))
13410         {
13411           const struct real_format *fmt = REAL_MODE_FORMAT (TYPE_MODE (type));
13412           const int prec = fmt->p;
13413           const mp_rnd_t rnd = fmt->round_towards_zero? GMP_RNDZ : GMP_RNDN;
13414           int inexact;
13415           mpfr_t m;
13416
13417           mpfr_init2 (m, prec);
13418           mpfr_from_real (m, ra, GMP_RNDN);
13419           mpfr_clear_flags ();
13420           inexact = func (m, n, m, rnd);
13421           result = do_mpfr_ckconv (m, type, inexact);
13422           mpfr_clear (m);
13423         }
13424     }
13425
13426   return result;
13427 }
13428
13429 /* If arguments ARG0 and ARG1 are REAL_CSTs, call mpfr_remquo() to set
13430    the pointer *(ARG_QUO) and return the result.  The type is taken
13431    from the type of ARG0 and is used for setting the precision of the
13432    calculation and results.  */
13433
13434 static tree
13435 do_mpfr_remquo (tree arg0, tree arg1, tree arg_quo)
13436 {
13437   tree const type = TREE_TYPE (arg0);
13438   tree result = NULL_TREE;
13439
13440   STRIP_NOPS (arg0);
13441   STRIP_NOPS (arg1);
13442
13443   /* To proceed, MPFR must exactly represent the target floating point
13444      format, which only happens when the target base equals two.  */
13445   if (REAL_MODE_FORMAT (TYPE_MODE (type))->b == 2
13446       && TREE_CODE (arg0) == REAL_CST && !TREE_OVERFLOW (arg0)
13447       && TREE_CODE (arg1) == REAL_CST && !TREE_OVERFLOW (arg1))
13448     {
13449       const REAL_VALUE_TYPE *const ra0 = TREE_REAL_CST_PTR (arg0);
13450       const REAL_VALUE_TYPE *const ra1 = TREE_REAL_CST_PTR (arg1);
13451
13452       if (real_isfinite (ra0) && real_isfinite (ra1))
13453         {
13454           const struct real_format *fmt = REAL_MODE_FORMAT (TYPE_MODE (type));
13455           const int prec = fmt->p;
13456           const mp_rnd_t rnd = fmt->round_towards_zero? GMP_RNDZ : GMP_RNDN;
13457           tree result_rem;
13458           long integer_quo;
13459           mpfr_t m0, m1;
13460
13461           mpfr_inits2 (prec, m0, m1, NULL);
13462           mpfr_from_real (m0, ra0, GMP_RNDN);
13463           mpfr_from_real (m1, ra1, GMP_RNDN);
13464           mpfr_clear_flags ();
13465           mpfr_remquo (m0, &integer_quo, m0, m1, rnd);
13466           /* Remquo is independent of the rounding mode, so pass
13467              inexact=0 to do_mpfr_ckconv().  */
13468           result_rem = do_mpfr_ckconv (m0, type, /*inexact=*/ 0);
13469           mpfr_clears (m0, m1, NULL);
13470           if (result_rem)
13471             {
13472               /* MPFR calculates quo in the host's long so it may
13473                  return more bits in quo than the target int can hold
13474                  if sizeof(host long) > sizeof(target int).  This can
13475                  happen even for native compilers in LP64 mode.  In
13476                  these cases, modulo the quo value with the largest
13477                  number that the target int can hold while leaving one
13478                  bit for the sign.  */
13479               if (sizeof (integer_quo) * CHAR_BIT > INT_TYPE_SIZE)
13480                 integer_quo %= (long)(1UL << (INT_TYPE_SIZE - 1));
13481
13482               /* Dereference the quo pointer argument.  */
13483               arg_quo = build_fold_indirect_ref (arg_quo);
13484               /* Proceed iff a valid pointer type was passed in.  */
13485               if (TYPE_MAIN_VARIANT (TREE_TYPE (arg_quo)) == integer_type_node)
13486                 {
13487                   /* Set the value. */
13488                   tree result_quo = fold_build2 (MODIFY_EXPR,
13489                                                  TREE_TYPE (arg_quo), arg_quo,
13490                                                  build_int_cst (NULL, integer_quo));
13491                   TREE_SIDE_EFFECTS (result_quo) = 1;
13492                   /* Combine the quo assignment with the rem.  */
13493                   result = non_lvalue (fold_build2 (COMPOUND_EXPR, type,
13494                                                     result_quo, result_rem));
13495                 }
13496             }
13497         }
13498     }
13499   return result;
13500 }
13501
13502 /* If ARG is a REAL_CST, call mpfr_lgamma() on it and return the
13503    resulting value as a tree with type TYPE.  The mpfr precision is
13504    set to the precision of TYPE.  We assume that this mpfr function
13505    returns zero if the result could be calculated exactly within the
13506    requested precision.  In addition, the integer pointer represented
13507    by ARG_SG will be dereferenced and set to the appropriate signgam
13508    (-1,1) value.  */
13509
13510 static tree
13511 do_mpfr_lgamma_r (tree arg, tree arg_sg, tree type)
13512 {
13513   tree result = NULL_TREE;
13514
13515   STRIP_NOPS (arg);
13516
13517   /* To proceed, MPFR must exactly represent the target floating point
13518      format, which only happens when the target base equals two.  Also
13519      verify ARG is a constant and that ARG_SG is an int pointer.  */
13520   if (REAL_MODE_FORMAT (TYPE_MODE (type))->b == 2
13521       && TREE_CODE (arg) == REAL_CST && !TREE_OVERFLOW (arg)
13522       && TREE_CODE (TREE_TYPE (arg_sg)) == POINTER_TYPE
13523       && TYPE_MAIN_VARIANT (TREE_TYPE (TREE_TYPE (arg_sg))) == integer_type_node)
13524     {
13525       const REAL_VALUE_TYPE *const ra = TREE_REAL_CST_PTR (arg);
13526
13527       /* In addition to NaN and Inf, the argument cannot be zero or a
13528          negative integer.  */
13529       if (real_isfinite (ra)
13530           && ra->cl != rvc_zero
13531           && !(real_isneg(ra) && real_isinteger(ra, TYPE_MODE (type))))
13532         {
13533           const struct real_format *fmt = REAL_MODE_FORMAT (TYPE_MODE (type));
13534           const int prec = fmt->p;
13535           const mp_rnd_t rnd = fmt->round_towards_zero? GMP_RNDZ : GMP_RNDN;
13536           int inexact, sg;
13537           mpfr_t m;
13538           tree result_lg;
13539
13540           mpfr_init2 (m, prec);
13541           mpfr_from_real (m, ra, GMP_RNDN);
13542           mpfr_clear_flags ();
13543           inexact = mpfr_lgamma (m, &sg, m, rnd);
13544           result_lg = do_mpfr_ckconv (m, type, inexact);
13545           mpfr_clear (m);
13546           if (result_lg)
13547             {
13548               tree result_sg;
13549
13550               /* Dereference the arg_sg pointer argument.  */
13551               arg_sg = build_fold_indirect_ref (arg_sg);
13552               /* Assign the signgam value into *arg_sg. */
13553               result_sg = fold_build2 (MODIFY_EXPR,
13554                                        TREE_TYPE (arg_sg), arg_sg,
13555                                        build_int_cst (NULL, sg));
13556               TREE_SIDE_EFFECTS (result_sg) = 1;
13557               /* Combine the signgam assignment with the lgamma result.  */
13558               result = non_lvalue (fold_build2 (COMPOUND_EXPR, type,
13559                                                 result_sg, result_lg));
13560             }
13561         }
13562     }
13563
13564   return result;
13565 }
13566
13567 /* If argument ARG is a COMPLEX_CST, call the one-argument mpc
13568    function FUNC on it and return the resulting value as a tree with
13569    type TYPE.  The mpfr precision is set to the precision of TYPE.  We
13570    assume that function FUNC returns zero if the result could be
13571    calculated exactly within the requested precision.  */
13572
13573 static tree
13574 do_mpc_arg1 (tree arg, tree type, int (*func)(mpc_ptr, mpc_srcptr, mpc_rnd_t))
13575 {
13576   tree result = NULL_TREE;
13577
13578   STRIP_NOPS (arg);
13579
13580   /* To proceed, MPFR must exactly represent the target floating point
13581      format, which only happens when the target base equals two.  */
13582   if (TREE_CODE (arg) == COMPLEX_CST && !TREE_OVERFLOW (arg)
13583       && TREE_CODE (TREE_TYPE (TREE_TYPE (arg))) == REAL_TYPE
13584       && REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (TREE_TYPE (arg))))->b == 2)
13585     {
13586       const REAL_VALUE_TYPE *const re = TREE_REAL_CST_PTR (TREE_REALPART (arg));
13587       const REAL_VALUE_TYPE *const im = TREE_REAL_CST_PTR (TREE_IMAGPART (arg));
13588
13589       if (real_isfinite (re) && real_isfinite (im))
13590         {
13591           const struct real_format *const fmt =
13592             REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (type)));
13593           const int prec = fmt->p;
13594           const mp_rnd_t rnd = fmt->round_towards_zero ? GMP_RNDZ : GMP_RNDN;
13595           const mpc_rnd_t crnd = fmt->round_towards_zero ? MPC_RNDZZ : MPC_RNDNN;
13596           int inexact;
13597           mpc_t m;
13598
13599           mpc_init2 (m, prec);
13600           mpfr_from_real (mpc_realref(m), re, rnd);
13601           mpfr_from_real (mpc_imagref(m), im, rnd);
13602           mpfr_clear_flags ();
13603           inexact = func (m, m, crnd);
13604           result = do_mpc_ckconv (m, type, inexact, /*force_convert=*/ 0);
13605           mpc_clear (m);
13606         }
13607     }
13608
13609   return result;
13610 }
13611
13612 /* If arguments ARG0 and ARG1 are a COMPLEX_CST, call the two-argument
13613    mpc function FUNC on it and return the resulting value as a tree
13614    with type TYPE.  The mpfr precision is set to the precision of
13615    TYPE.  We assume that function FUNC returns zero if the result
13616    could be calculated exactly within the requested precision.  If
13617    DO_NONFINITE is true, then fold expressions containing Inf or NaN
13618    in the arguments and/or results.  */
13619
13620 tree
13621 do_mpc_arg2 (tree arg0, tree arg1, tree type, int do_nonfinite,
13622              int (*func)(mpc_ptr, mpc_srcptr, mpc_srcptr, mpc_rnd_t))
13623 {
13624   tree result = NULL_TREE;
13625
13626   STRIP_NOPS (arg0);
13627   STRIP_NOPS (arg1);
13628
13629   /* To proceed, MPFR must exactly represent the target floating point
13630      format, which only happens when the target base equals two.  */
13631   if (TREE_CODE (arg0) == COMPLEX_CST && !TREE_OVERFLOW (arg0)
13632       && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE
13633       && TREE_CODE (arg1) == COMPLEX_CST && !TREE_OVERFLOW (arg1)
13634       && TREE_CODE (TREE_TYPE (TREE_TYPE (arg1))) == REAL_TYPE
13635       && REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (TREE_TYPE (arg0))))->b == 2)
13636     {
13637       const REAL_VALUE_TYPE *const re0 = TREE_REAL_CST_PTR (TREE_REALPART (arg0));
13638       const REAL_VALUE_TYPE *const im0 = TREE_REAL_CST_PTR (TREE_IMAGPART (arg0));
13639       const REAL_VALUE_TYPE *const re1 = TREE_REAL_CST_PTR (TREE_REALPART (arg1));
13640       const REAL_VALUE_TYPE *const im1 = TREE_REAL_CST_PTR (TREE_IMAGPART (arg1));
13641
13642       if (do_nonfinite
13643           || (real_isfinite (re0) && real_isfinite (im0)
13644               && real_isfinite (re1) && real_isfinite (im1)))
13645         {
13646           const struct real_format *const fmt =
13647             REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (type)));
13648           const int prec = fmt->p;
13649           const mp_rnd_t rnd = fmt->round_towards_zero ? GMP_RNDZ : GMP_RNDN;
13650           const mpc_rnd_t crnd = fmt->round_towards_zero ? MPC_RNDZZ : MPC_RNDNN;
13651           int inexact;
13652           mpc_t m0, m1;
13653
13654           mpc_init2 (m0, prec);
13655           mpc_init2 (m1, prec);
13656           mpfr_from_real (mpc_realref(m0), re0, rnd);
13657           mpfr_from_real (mpc_imagref(m0), im0, rnd);
13658           mpfr_from_real (mpc_realref(m1), re1, rnd);
13659           mpfr_from_real (mpc_imagref(m1), im1, rnd);
13660           mpfr_clear_flags ();
13661           inexact = func (m0, m0, m1, crnd);
13662           result = do_mpc_ckconv (m0, type, inexact, do_nonfinite);
13663           mpc_clear (m0);
13664           mpc_clear (m1);
13665         }
13666     }
13667
13668   return result;
13669 }
13670
13671 /* Fold a call STMT to __{,v}sprintf_chk.  Return NULL_TREE if
13672    a normal call should be emitted rather than expanding the function
13673    inline.  FCODE is either BUILT_IN_SPRINTF_CHK or BUILT_IN_VSPRINTF_CHK.  */
13674
13675 static tree
13676 gimple_fold_builtin_sprintf_chk (gimple stmt, enum built_in_function fcode)
13677 {
13678   int nargs = gimple_call_num_args (stmt);
13679
13680   return fold_builtin_sprintf_chk_1 (gimple_location (stmt), nargs,
13681                                      (nargs > 0
13682                                       ? gimple_call_arg_ptr (stmt, 0)
13683                                       : &error_mark_node), fcode);
13684 }
13685
13686 /* Fold a call STMT to {,v}snprintf.  Return NULL_TREE if
13687    a normal call should be emitted rather than expanding the function
13688    inline.  FCODE is either BUILT_IN_SNPRINTF_CHK or
13689    BUILT_IN_VSNPRINTF_CHK.  If MAXLEN is not NULL, it is maximum length
13690    passed as second argument.  */
13691
13692 tree
13693 gimple_fold_builtin_snprintf_chk (gimple stmt, tree maxlen,
13694                                   enum built_in_function fcode)
13695 {
13696   int nargs = gimple_call_num_args (stmt);
13697
13698   return fold_builtin_snprintf_chk_1 (gimple_location (stmt), nargs,
13699                                       (nargs > 0
13700                                        ? gimple_call_arg_ptr (stmt, 0)
13701                                        : &error_mark_node), maxlen, fcode);
13702 }
13703
13704 /* Builtins with folding operations that operate on "..." arguments
13705    need special handling; we need to store the arguments in a convenient
13706    data structure before attempting any folding.  Fortunately there are
13707    only a few builtins that fall into this category.  FNDECL is the
13708    function, EXP is the CALL_EXPR for the call, and IGNORE is true if the
13709    result of the function call is ignored.  */
13710
13711 static tree
13712 gimple_fold_builtin_varargs (tree fndecl, gimple stmt,
13713                              bool ignore ATTRIBUTE_UNUSED)
13714 {
13715   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
13716   tree ret = NULL_TREE;
13717
13718   switch (fcode)
13719     {
13720     case BUILT_IN_SPRINTF_CHK:
13721     case BUILT_IN_VSPRINTF_CHK:
13722       ret = gimple_fold_builtin_sprintf_chk (stmt, fcode);
13723       break;
13724
13725     case BUILT_IN_SNPRINTF_CHK:
13726     case BUILT_IN_VSNPRINTF_CHK:
13727       ret = gimple_fold_builtin_snprintf_chk (stmt, NULL_TREE, fcode);
13728
13729     default:
13730       break;
13731     }
13732   if (ret)
13733     {
13734       ret = build1 (NOP_EXPR, TREE_TYPE (ret), ret);
13735       TREE_NO_WARNING (ret) = 1;
13736       return ret;
13737     }
13738   return NULL_TREE;
13739 }
13740
13741 /* A wrapper function for builtin folding that prevents warnings for
13742    "statement without effect" and the like, caused by removing the
13743    call node earlier than the warning is generated.  */
13744
13745 tree
13746 fold_call_stmt (gimple stmt, bool ignore)
13747 {
13748   tree ret = NULL_TREE;
13749   tree fndecl = gimple_call_fndecl (stmt);
13750   location_t loc = gimple_location (stmt);
13751   if (fndecl
13752       && TREE_CODE (fndecl) == FUNCTION_DECL
13753       && DECL_BUILT_IN (fndecl)
13754       && !gimple_call_va_arg_pack_p (stmt))
13755     {
13756       int nargs = gimple_call_num_args (stmt);
13757       tree *args = (nargs > 0
13758                     ? gimple_call_arg_ptr (stmt, 0)
13759                     : &error_mark_node);
13760
13761       if (avoid_folding_inline_builtin (fndecl))
13762         return NULL_TREE;
13763       if (DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_MD)
13764         {
13765           return targetm.fold_builtin (fndecl, nargs, args, ignore);
13766         }
13767       else
13768         {
13769           if (nargs <= MAX_ARGS_TO_FOLD_BUILTIN)
13770             ret = fold_builtin_n (loc, fndecl, args, nargs, ignore);
13771           if (!ret)
13772             ret = gimple_fold_builtin_varargs (fndecl, stmt, ignore);
13773           if (ret)
13774             {
13775               /* Propagate location information from original call to
13776                  expansion of builtin.  Otherwise things like
13777                  maybe_emit_chk_warning, that operate on the expansion
13778                  of a builtin, will use the wrong location information.  */
13779               if (gimple_has_location (stmt))
13780                 {
13781                   tree realret = ret;
13782                   if (TREE_CODE (ret) == NOP_EXPR)
13783                     realret = TREE_OPERAND (ret, 0);
13784                   if (CAN_HAVE_LOCATION_P (realret)
13785                       && !EXPR_HAS_LOCATION (realret))
13786                     SET_EXPR_LOCATION (realret, loc);
13787                   return realret;
13788                 }
13789               return ret;
13790             }
13791         }
13792     }
13793   return NULL_TREE;
13794 }
13795
13796 /* Look up the function in built_in_decls that corresponds to DECL
13797    and set ASMSPEC as its user assembler name.  DECL must be a
13798    function decl that declares a builtin.  */
13799
13800 void
13801 set_builtin_user_assembler_name (tree decl, const char *asmspec)
13802 {
13803   tree builtin;
13804   gcc_assert (TREE_CODE (decl) == FUNCTION_DECL
13805               && DECL_BUILT_IN_CLASS (decl) == BUILT_IN_NORMAL
13806               && asmspec != 0);
13807
13808   builtin = built_in_decls [DECL_FUNCTION_CODE (decl)];
13809   set_user_assembler_name (builtin, asmspec);
13810   switch (DECL_FUNCTION_CODE (decl))
13811     {
13812     case BUILT_IN_MEMCPY:
13813       init_block_move_fn (asmspec);
13814       memcpy_libfunc = set_user_assembler_libfunc ("memcpy", asmspec);
13815       break;
13816     case BUILT_IN_MEMSET:
13817       init_block_clear_fn (asmspec);
13818       memset_libfunc = set_user_assembler_libfunc ("memset", asmspec);
13819       break;
13820     case BUILT_IN_MEMMOVE:
13821       memmove_libfunc = set_user_assembler_libfunc ("memmove", asmspec);
13822       break;
13823     case BUILT_IN_MEMCMP:
13824       memcmp_libfunc = set_user_assembler_libfunc ("memcmp", asmspec);
13825       break;
13826     case BUILT_IN_ABORT:
13827       abort_libfunc = set_user_assembler_libfunc ("abort", asmspec);
13828       break;
13829     case BUILT_IN_FFS:
13830       if (INT_TYPE_SIZE < BITS_PER_WORD)
13831         {
13832           set_user_assembler_libfunc ("ffs", asmspec);
13833           set_optab_libfunc (ffs_optab, mode_for_size (INT_TYPE_SIZE,
13834                                                        MODE_INT, 0), "ffs");
13835         }
13836       break;
13837     default:
13838       break;
13839     }
13840 }
13841
13842 /* Return true if DECL is a builtin that expands to a constant or similarly
13843    simple code.  */
13844 bool
13845 is_simple_builtin (tree decl)
13846 {
13847   if (decl && DECL_BUILT_IN_CLASS (decl) == BUILT_IN_NORMAL)
13848     switch (DECL_FUNCTION_CODE (decl))
13849       {
13850         /* Builtins that expand to constants.  */
13851       case BUILT_IN_CONSTANT_P:
13852       case BUILT_IN_EXPECT:
13853       case BUILT_IN_OBJECT_SIZE:
13854       case BUILT_IN_UNREACHABLE:
13855         /* Simple register moves or loads from stack.  */
13856       case BUILT_IN_RETURN_ADDRESS:
13857       case BUILT_IN_EXTRACT_RETURN_ADDR:
13858       case BUILT_IN_FROB_RETURN_ADDR:
13859       case BUILT_IN_RETURN:
13860       case BUILT_IN_AGGREGATE_INCOMING_ADDRESS:
13861       case BUILT_IN_FRAME_ADDRESS:
13862       case BUILT_IN_VA_END:
13863       case BUILT_IN_STACK_SAVE:
13864       case BUILT_IN_STACK_RESTORE:
13865         /* Exception state returns or moves registers around.  */
13866       case BUILT_IN_EH_FILTER:
13867       case BUILT_IN_EH_POINTER:
13868       case BUILT_IN_EH_COPY_VALUES:
13869         return true;
13870
13871       default:
13872         return false;
13873       }
13874
13875   return false;
13876 }
13877
13878 /* Return true if DECL is a builtin that is not expensive, i.e., they are
13879    most probably expanded inline into reasonably simple code.  This is a
13880    superset of is_simple_builtin.  */
13881 bool
13882 is_inexpensive_builtin (tree decl)
13883 {
13884   if (!decl)
13885     return false;
13886   else if (DECL_BUILT_IN_CLASS (decl) == BUILT_IN_MD)
13887     return true;
13888   else if (DECL_BUILT_IN_CLASS (decl) == BUILT_IN_NORMAL)
13889     switch (DECL_FUNCTION_CODE (decl))
13890       {
13891       case BUILT_IN_ABS:
13892       case BUILT_IN_ALLOCA:
13893       case BUILT_IN_BSWAP32:
13894       case BUILT_IN_BSWAP64:
13895       case BUILT_IN_CLZ:
13896       case BUILT_IN_CLZIMAX:
13897       case BUILT_IN_CLZL:
13898       case BUILT_IN_CLZLL:
13899       case BUILT_IN_CTZ:
13900       case BUILT_IN_CTZIMAX:
13901       case BUILT_IN_CTZL:
13902       case BUILT_IN_CTZLL:
13903       case BUILT_IN_FFS:
13904       case BUILT_IN_FFSIMAX:
13905       case BUILT_IN_FFSL:
13906       case BUILT_IN_FFSLL:
13907       case BUILT_IN_IMAXABS:
13908       case BUILT_IN_FINITE:
13909       case BUILT_IN_FINITEF:
13910       case BUILT_IN_FINITEL:
13911       case BUILT_IN_FINITED32:
13912       case BUILT_IN_FINITED64:
13913       case BUILT_IN_FINITED128:
13914       case BUILT_IN_FPCLASSIFY:
13915       case BUILT_IN_ISFINITE:
13916       case BUILT_IN_ISINF_SIGN:
13917       case BUILT_IN_ISINF:
13918       case BUILT_IN_ISINFF:
13919       case BUILT_IN_ISINFL:
13920       case BUILT_IN_ISINFD32:
13921       case BUILT_IN_ISINFD64:
13922       case BUILT_IN_ISINFD128:
13923       case BUILT_IN_ISNAN:
13924       case BUILT_IN_ISNANF:
13925       case BUILT_IN_ISNANL:
13926       case BUILT_IN_ISNAND32:
13927       case BUILT_IN_ISNAND64:
13928       case BUILT_IN_ISNAND128:
13929       case BUILT_IN_ISNORMAL:
13930       case BUILT_IN_ISGREATER:
13931       case BUILT_IN_ISGREATEREQUAL:
13932       case BUILT_IN_ISLESS:
13933       case BUILT_IN_ISLESSEQUAL:
13934       case BUILT_IN_ISLESSGREATER:
13935       case BUILT_IN_ISUNORDERED:
13936       case BUILT_IN_VA_ARG_PACK:
13937       case BUILT_IN_VA_ARG_PACK_LEN:
13938       case BUILT_IN_VA_COPY:
13939       case BUILT_IN_TRAP:
13940       case BUILT_IN_SAVEREGS:
13941       case BUILT_IN_POPCOUNTL:
13942       case BUILT_IN_POPCOUNTLL:
13943       case BUILT_IN_POPCOUNTIMAX:
13944       case BUILT_IN_POPCOUNT:
13945       case BUILT_IN_PARITYL:
13946       case BUILT_IN_PARITYLL:
13947       case BUILT_IN_PARITYIMAX:
13948       case BUILT_IN_PARITY:
13949       case BUILT_IN_LABS:
13950       case BUILT_IN_LLABS:
13951       case BUILT_IN_PREFETCH:
13952         return true;
13953
13954       default:
13955         return is_simple_builtin (decl);
13956       }
13957
13958   return false;
13959 }