OSDN Git Service

31a869bf1f61991eb77fe2821a3161a04eb03fe8
[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 "toplev.h"
44 #include "predict.h"
45 #include "tm_p.h"
46 #include "target.h"
47 #include "langhooks.h"
48 #include "basic-block.h"
49 #include "tree-mudflap.h"
50 #include "tree-flow.h"
51 #include "value-prof.h"
52 #include "diagnostic-core.h"
53 #include "builtins.h"
54
55 #ifndef SLOW_UNALIGNED_ACCESS
56 #define SLOW_UNALIGNED_ACCESS(MODE, ALIGN) STRICT_ALIGNMENT
57 #endif
58
59 #ifndef PAD_VARARGS_DOWN
60 #define PAD_VARARGS_DOWN BYTES_BIG_ENDIAN
61 #endif
62 static tree do_mpc_arg1 (tree, tree, int (*)(mpc_ptr, mpc_srcptr, mpc_rnd_t));
63
64 struct target_builtins default_target_builtins;
65 #if SWITCHABLE_TARGET
66 struct target_builtins *this_target_builtins = &default_target_builtins;
67 #endif
68
69 /* Define the names of the builtin function types and codes.  */
70 const char *const built_in_class_names[4]
71   = {"NOT_BUILT_IN", "BUILT_IN_FRONTEND", "BUILT_IN_MD", "BUILT_IN_NORMAL"};
72
73 #define DEF_BUILTIN(X, N, C, T, LT, B, F, NA, AT, IM, COND) #X,
74 const char * built_in_names[(int) END_BUILTINS] =
75 {
76 #include "builtins.def"
77 };
78 #undef DEF_BUILTIN
79
80 /* Setup an array of _DECL trees, make sure each element is
81    initialized to NULL_TREE.  */
82 tree built_in_decls[(int) END_BUILTINS];
83 /* Declarations used when constructing the builtin implicitly in the compiler.
84    It may be NULL_TREE when this is invalid (for instance runtime is not
85    required to implement the function call in all cases).  */
86 tree implicit_built_in_decls[(int) END_BUILTINS];
87
88 static const char *c_getstr (tree);
89 static rtx c_readstr (const char *, enum machine_mode);
90 static int target_char_cast (tree, char *);
91 static rtx get_memory_rtx (tree, tree);
92 static int apply_args_size (void);
93 static int apply_result_size (void);
94 #if defined (HAVE_untyped_call) || defined (HAVE_untyped_return)
95 static rtx result_vector (int, rtx);
96 #endif
97 static void expand_builtin_update_setjmp_buf (rtx);
98 static void expand_builtin_prefetch (tree);
99 static rtx expand_builtin_apply_args (void);
100 static rtx expand_builtin_apply_args_1 (void);
101 static rtx expand_builtin_apply (rtx, rtx, rtx);
102 static void expand_builtin_return (rtx);
103 static enum type_class type_to_class (tree);
104 static rtx expand_builtin_classify_type (tree);
105 static void expand_errno_check (tree, rtx);
106 static rtx expand_builtin_mathfn (tree, rtx, rtx);
107 static rtx expand_builtin_mathfn_2 (tree, rtx, rtx);
108 static rtx expand_builtin_mathfn_3 (tree, rtx, rtx);
109 static rtx expand_builtin_mathfn_ternary (tree, rtx, rtx);
110 static rtx expand_builtin_interclass_mathfn (tree, rtx);
111 static rtx expand_builtin_sincos (tree);
112 static rtx expand_builtin_cexpi (tree, rtx);
113 static rtx expand_builtin_int_roundingfn (tree, rtx);
114 static rtx expand_builtin_int_roundingfn_2 (tree, rtx);
115 static rtx expand_builtin_next_arg (void);
116 static rtx expand_builtin_va_start (tree);
117 static rtx expand_builtin_va_end (tree);
118 static rtx expand_builtin_va_copy (tree);
119 static rtx expand_builtin_memcmp (tree, rtx, enum machine_mode);
120 static rtx expand_builtin_strcmp (tree, rtx);
121 static rtx expand_builtin_strncmp (tree, rtx, enum machine_mode);
122 static rtx builtin_memcpy_read_str (void *, HOST_WIDE_INT, enum machine_mode);
123 static rtx expand_builtin_memcpy (tree, rtx);
124 static rtx expand_builtin_mempcpy (tree, rtx, enum machine_mode);
125 static rtx expand_builtin_mempcpy_args (tree, tree, tree, rtx,
126                                         enum machine_mode, int);
127 static rtx expand_builtin_strcpy (tree, rtx);
128 static rtx expand_builtin_strcpy_args (tree, tree, rtx);
129 static rtx expand_builtin_stpcpy (tree, rtx, enum machine_mode);
130 static rtx expand_builtin_strncpy (tree, rtx);
131 static rtx builtin_memset_gen_str (void *, HOST_WIDE_INT, enum machine_mode);
132 static rtx expand_builtin_memset (tree, rtx, enum machine_mode);
133 static rtx expand_builtin_memset_args (tree, tree, tree, rtx, enum machine_mode, tree);
134 static rtx expand_builtin_bzero (tree);
135 static rtx expand_builtin_strlen (tree, rtx, enum machine_mode);
136 static rtx expand_builtin_alloca (tree, bool);
137 static rtx expand_builtin_unop (enum machine_mode, tree, rtx, rtx, optab);
138 static rtx expand_builtin_frame_address (tree, tree);
139 static tree stabilize_va_list_loc (location_t, tree, int);
140 static rtx expand_builtin_expect (tree, rtx);
141 static tree fold_builtin_constant_p (tree);
142 static tree fold_builtin_expect (location_t, tree, tree);
143 static tree fold_builtin_classify_type (tree);
144 static tree fold_builtin_strlen (location_t, tree, tree);
145 static tree fold_builtin_inf (location_t, tree, int);
146 static tree fold_builtin_nan (tree, tree, int);
147 static tree rewrite_call_expr (location_t, tree, int, tree, int, ...);
148 static bool validate_arg (const_tree, enum tree_code code);
149 static bool integer_valued_real_p (tree);
150 static tree fold_trunc_transparent_mathfn (location_t, tree, tree);
151 static bool readonly_data_expr (tree);
152 static rtx expand_builtin_fabs (tree, rtx, rtx);
153 static rtx expand_builtin_signbit (tree, rtx);
154 static tree fold_builtin_sqrt (location_t, tree, tree);
155 static tree fold_builtin_cbrt (location_t, tree, tree);
156 static tree fold_builtin_pow (location_t, tree, tree, tree, tree);
157 static tree fold_builtin_powi (location_t, tree, tree, tree, tree);
158 static tree fold_builtin_cos (location_t, tree, tree, tree);
159 static tree fold_builtin_cosh (location_t, tree, tree, tree);
160 static tree fold_builtin_tan (tree, tree);
161 static tree fold_builtin_trunc (location_t, tree, tree);
162 static tree fold_builtin_floor (location_t, tree, tree);
163 static tree fold_builtin_ceil (location_t, tree, tree);
164 static tree fold_builtin_round (location_t, tree, tree);
165 static tree fold_builtin_int_roundingfn (location_t, tree, tree);
166 static tree fold_builtin_bitop (tree, tree);
167 static tree fold_builtin_memory_op (location_t, tree, tree, tree, tree, bool, int);
168 static tree fold_builtin_strchr (location_t, tree, tree, tree);
169 static tree fold_builtin_memchr (location_t, tree, tree, tree, tree);
170 static tree fold_builtin_memcmp (location_t, tree, tree, tree);
171 static tree fold_builtin_strcmp (location_t, tree, tree);
172 static tree fold_builtin_strncmp (location_t, tree, tree, tree);
173 static tree fold_builtin_signbit (location_t, tree, tree);
174 static tree fold_builtin_copysign (location_t, tree, tree, tree, tree);
175 static tree fold_builtin_isascii (location_t, tree);
176 static tree fold_builtin_toascii (location_t, tree);
177 static tree fold_builtin_isdigit (location_t, tree);
178 static tree fold_builtin_fabs (location_t, tree, tree);
179 static tree fold_builtin_abs (location_t, tree, tree);
180 static tree fold_builtin_unordered_cmp (location_t, tree, tree, tree, enum tree_code,
181                                         enum tree_code);
182 static tree fold_builtin_n (location_t, tree, tree *, int, bool);
183 static tree fold_builtin_0 (location_t, tree, bool);
184 static tree fold_builtin_1 (location_t, tree, tree, bool);
185 static tree fold_builtin_2 (location_t, tree, tree, tree, bool);
186 static tree fold_builtin_3 (location_t, tree, tree, tree, tree, bool);
187 static tree fold_builtin_4 (location_t, tree, tree, tree, tree, tree, bool);
188 static tree fold_builtin_varargs (location_t, tree, tree, bool);
189
190 static tree fold_builtin_strpbrk (location_t, tree, tree, tree);
191 static tree fold_builtin_strstr (location_t, tree, tree, tree);
192 static tree fold_builtin_strrchr (location_t, tree, tree, tree);
193 static tree fold_builtin_strcat (location_t, tree, tree);
194 static tree fold_builtin_strncat (location_t, tree, tree, tree);
195 static tree fold_builtin_strspn (location_t, tree, tree);
196 static tree fold_builtin_strcspn (location_t, tree, tree);
197 static tree fold_builtin_sprintf (location_t, tree, tree, tree, int);
198
199 static rtx expand_builtin_object_size (tree);
200 static rtx expand_builtin_memory_chk (tree, rtx, enum machine_mode,
201                                       enum built_in_function);
202 static void maybe_emit_chk_warning (tree, enum built_in_function);
203 static void maybe_emit_sprintf_chk_warning (tree, enum built_in_function);
204 static void maybe_emit_free_warning (tree);
205 static tree fold_builtin_object_size (tree, tree);
206 static tree fold_builtin_strcat_chk (location_t, tree, tree, tree, tree);
207 static tree fold_builtin_strncat_chk (location_t, tree, tree, tree, tree, tree);
208 static tree fold_builtin_sprintf_chk (location_t, tree, enum built_in_function);
209 static tree fold_builtin_printf (location_t, tree, tree, tree, bool, enum built_in_function);
210 static tree fold_builtin_fprintf (location_t, tree, tree, tree, tree, bool,
211                                   enum built_in_function);
212 static bool init_target_chars (void);
213
214 static unsigned HOST_WIDE_INT target_newline;
215 static unsigned HOST_WIDE_INT target_percent;
216 static unsigned HOST_WIDE_INT target_c;
217 static unsigned HOST_WIDE_INT target_s;
218 static char target_percent_c[3];
219 static char target_percent_s[3];
220 static char target_percent_s_newline[4];
221 static tree do_mpfr_arg1 (tree, tree, int (*)(mpfr_ptr, mpfr_srcptr, mp_rnd_t),
222                           const REAL_VALUE_TYPE *, const REAL_VALUE_TYPE *, bool);
223 static tree do_mpfr_arg2 (tree, tree, tree,
224                           int (*)(mpfr_ptr, mpfr_srcptr, mpfr_srcptr, mp_rnd_t));
225 static tree do_mpfr_arg3 (tree, tree, tree, tree,
226                           int (*)(mpfr_ptr, mpfr_srcptr, mpfr_srcptr, mpfr_srcptr, mp_rnd_t));
227 static tree do_mpfr_sincos (tree, tree, tree);
228 static tree do_mpfr_bessel_n (tree, tree, tree,
229                               int (*)(mpfr_ptr, long, mpfr_srcptr, mp_rnd_t),
230                               const REAL_VALUE_TYPE *, bool);
231 static tree do_mpfr_remquo (tree, tree, tree);
232 static tree do_mpfr_lgamma_r (tree, tree, tree);
233
234 /* Return true if NAME starts with __builtin_ or __sync_.  */
235
236 bool
237 is_builtin_name (const char *name)
238 {
239   if (strncmp (name, "__builtin_", 10) == 0)
240     return true;
241   if (strncmp (name, "__sync_", 7) == 0)
242     return true;
243   return false;
244 }
245
246
247 /* Return true if DECL is a function symbol representing a built-in.  */
248
249 bool
250 is_builtin_fn (tree decl)
251 {
252   return TREE_CODE (decl) == FUNCTION_DECL && DECL_BUILT_IN (decl);
253 }
254
255
256 /* Return true if NODE should be considered for inline expansion regardless
257    of the optimization level.  This means whenever a function is invoked with
258    its "internal" name, which normally contains the prefix "__builtin".  */
259
260 static bool
261 called_as_built_in (tree node)
262 {
263   /* Note that we must use DECL_NAME, not DECL_ASSEMBLER_NAME_SET_P since
264      we want the name used to call the function, not the name it
265      will have. */
266   const char *name = IDENTIFIER_POINTER (DECL_NAME (node));
267   return is_builtin_name (name);
268 }
269
270 /* Return the alignment in bits of EXP, an object.
271    Don't return more than MAX_ALIGN no matter what.  */
272
273 unsigned int
274 get_object_alignment (tree exp, unsigned int max_align)
275 {
276   HOST_WIDE_INT bitsize, bitpos;
277   tree offset;
278   enum machine_mode mode;
279   int unsignedp, volatilep;
280   unsigned int align, inner;
281
282   /* Get the innermost object and the constant (bitpos) and possibly
283      variable (offset) offset of the access.  */
284   exp = get_inner_reference (exp, &bitsize, &bitpos, &offset,
285                              &mode, &unsignedp, &volatilep, true);
286
287   /* Extract alignment information from the innermost object and
288      possibly adjust bitpos and offset.  */
289   if (TREE_CODE (exp) == CONST_DECL)
290     exp = DECL_INITIAL (exp);
291   if (DECL_P (exp)
292       && TREE_CODE (exp) != LABEL_DECL)
293     align = DECL_ALIGN (exp);
294   else if (CONSTANT_CLASS_P (exp))
295     {
296       align = TYPE_ALIGN (TREE_TYPE (exp));
297 #ifdef CONSTANT_ALIGNMENT
298       align = (unsigned)CONSTANT_ALIGNMENT (exp, align);
299 #endif
300     }
301   else if (TREE_CODE (exp) == VIEW_CONVERT_EXPR)
302     align = TYPE_ALIGN (TREE_TYPE (exp));
303   else if (TREE_CODE (exp) == INDIRECT_REF)
304     align = TYPE_ALIGN (TREE_TYPE (exp));
305   else if (TREE_CODE (exp) == MEM_REF)
306     {
307       tree addr = TREE_OPERAND (exp, 0);
308       struct ptr_info_def *pi;
309       if (TREE_CODE (addr) == BIT_AND_EXPR
310           && TREE_CODE (TREE_OPERAND (addr, 1)) == INTEGER_CST)
311         {
312           align = (TREE_INT_CST_LOW (TREE_OPERAND (addr, 1))
313                     & -TREE_INT_CST_LOW (TREE_OPERAND (addr, 1)));
314           align *= BITS_PER_UNIT;
315           addr = TREE_OPERAND (addr, 0);
316         }
317       else
318         align = BITS_PER_UNIT;
319       if (TREE_CODE (addr) == SSA_NAME
320           && (pi = SSA_NAME_PTR_INFO (addr)))
321         {
322           bitpos += (pi->misalign * BITS_PER_UNIT) & ~(align - 1);
323           align = MAX (pi->align * BITS_PER_UNIT, align);
324         }
325       else if (TREE_CODE (addr) == ADDR_EXPR)
326         align = MAX (align, get_object_alignment (TREE_OPERAND (addr, 0),
327                                                   max_align));
328       bitpos += mem_ref_offset (exp).low * BITS_PER_UNIT;
329     }
330   else if (TREE_CODE (exp) == TARGET_MEM_REF)
331     {
332       struct ptr_info_def *pi;
333       tree addr = TMR_BASE (exp);
334       if (TREE_CODE (addr) == BIT_AND_EXPR
335           && TREE_CODE (TREE_OPERAND (addr, 1)) == INTEGER_CST)
336         {
337           align = (TREE_INT_CST_LOW (TREE_OPERAND (addr, 1))
338                    & -TREE_INT_CST_LOW (TREE_OPERAND (addr, 1)));
339           align *= BITS_PER_UNIT;
340           addr = TREE_OPERAND (addr, 0);
341         }
342       else
343         align = BITS_PER_UNIT;
344       if (TREE_CODE (addr) == SSA_NAME
345           && (pi = SSA_NAME_PTR_INFO (addr)))
346         {
347           bitpos += (pi->misalign * BITS_PER_UNIT) & ~(align - 1);
348           align = MAX (pi->align * BITS_PER_UNIT, align);
349         }
350       else if (TREE_CODE (addr) == ADDR_EXPR)
351         align = MAX (align, get_object_alignment (TREE_OPERAND (addr, 0),
352                                                   max_align));
353       if (TMR_OFFSET (exp))
354         bitpos += TREE_INT_CST_LOW (TMR_OFFSET (exp)) * BITS_PER_UNIT;
355       if (TMR_INDEX (exp) && TMR_STEP (exp))
356         {
357           unsigned HOST_WIDE_INT step = TREE_INT_CST_LOW (TMR_STEP (exp));
358           align = MIN (align, (step & -step) * BITS_PER_UNIT);
359         }
360       else if (TMR_INDEX (exp))
361         align = BITS_PER_UNIT;
362       if (TMR_INDEX2 (exp))
363         align = BITS_PER_UNIT;
364     }
365   else
366     align = BITS_PER_UNIT;
367
368   /* If there is a non-constant offset part extract the maximum
369      alignment that can prevail.  */
370   inner = max_align;
371   while (offset)
372     {
373       tree next_offset;
374
375       if (TREE_CODE (offset) == PLUS_EXPR)
376         {
377           next_offset = TREE_OPERAND (offset, 0);
378           offset = TREE_OPERAND (offset, 1);
379         }
380       else
381         next_offset = NULL;
382       if (host_integerp (offset, 1))
383         {
384           /* Any overflow in calculating offset_bits won't change
385              the alignment.  */
386           unsigned offset_bits
387             = ((unsigned) tree_low_cst (offset, 1) * BITS_PER_UNIT);
388
389           if (offset_bits)
390             inner = MIN (inner, (offset_bits & -offset_bits));
391         }
392       else if (TREE_CODE (offset) == MULT_EXPR
393                && host_integerp (TREE_OPERAND (offset, 1), 1))
394         {
395           /* Any overflow in calculating offset_factor won't change
396              the alignment.  */
397           unsigned offset_factor
398             = ((unsigned) tree_low_cst (TREE_OPERAND (offset, 1), 1)
399                * BITS_PER_UNIT);
400
401           if (offset_factor)
402             inner = MIN (inner, (offset_factor & -offset_factor));
403         }
404       else
405         {
406           inner = MIN (inner, BITS_PER_UNIT);
407           break;
408         }
409       offset = next_offset;
410     }
411
412   /* Alignment is innermost object alignment adjusted by the constant
413      and non-constant offset parts.  */
414   align = MIN (align, inner);
415   bitpos = bitpos & (align - 1);
416
417   /* align and bitpos now specify known low bits of the pointer.
418      ptr & (align - 1) == bitpos.  */
419
420   if (bitpos != 0)
421     align = (bitpos & -bitpos);
422
423   return MIN (align, max_align);
424 }
425
426 /* Returns true iff we can trust that alignment information has been
427    calculated properly.  */
428
429 bool
430 can_trust_pointer_alignment (void)
431 {
432   /* We rely on TER to compute accurate alignment information.  */
433   return (optimize && flag_tree_ter);
434 }
435
436 /* Return the alignment in bits of EXP, a pointer valued expression.
437    But don't return more than MAX_ALIGN no matter what.
438    The alignment returned is, by default, the alignment of the thing that
439    EXP points to.  If it is not a POINTER_TYPE, 0 is returned.
440
441    Otherwise, look at the expression to see if we can do better, i.e., if the
442    expression is actually pointing at an object whose alignment is tighter.  */
443
444 unsigned int
445 get_pointer_alignment (tree exp, unsigned int max_align)
446 {
447   STRIP_NOPS (exp);
448
449   if (TREE_CODE (exp) == ADDR_EXPR)
450     return get_object_alignment (TREE_OPERAND (exp, 0), max_align);
451   else if (TREE_CODE (exp) == SSA_NAME
452            && POINTER_TYPE_P (TREE_TYPE (exp)))
453     {
454       struct ptr_info_def *pi = SSA_NAME_PTR_INFO (exp);
455       unsigned align;
456       if (!pi)
457         return BITS_PER_UNIT;
458       if (pi->misalign != 0)
459         align = (pi->misalign & -pi->misalign);
460       else
461         align = pi->align;
462       return MIN (max_align, align * BITS_PER_UNIT);
463     }
464
465   return POINTER_TYPE_P (TREE_TYPE (exp)) ? BITS_PER_UNIT : 0;
466 }
467
468 /* Compute the length of a C string.  TREE_STRING_LENGTH is not the right
469    way, because it could contain a zero byte in the middle.
470    TREE_STRING_LENGTH is the size of the character array, not the string.
471
472    ONLY_VALUE should be nonzero if the result is not going to be emitted
473    into the instruction stream and zero if it is going to be expanded.
474    E.g. with i++ ? "foo" : "bar", if ONLY_VALUE is nonzero, constant 3
475    is returned, otherwise NULL, since
476    len = c_strlen (src, 1); if (len) expand_expr (len, ...); would not
477    evaluate the side-effects.
478
479    The value returned is of type `ssizetype'.
480
481    Unfortunately, string_constant can't access the values of const char
482    arrays with initializers, so neither can we do so here.  */
483
484 tree
485 c_strlen (tree src, int only_value)
486 {
487   tree offset_node;
488   HOST_WIDE_INT offset;
489   int max;
490   const char *ptr;
491   location_t loc;
492
493   STRIP_NOPS (src);
494   if (TREE_CODE (src) == COND_EXPR
495       && (only_value || !TREE_SIDE_EFFECTS (TREE_OPERAND (src, 0))))
496     {
497       tree len1, len2;
498
499       len1 = c_strlen (TREE_OPERAND (src, 1), only_value);
500       len2 = c_strlen (TREE_OPERAND (src, 2), only_value);
501       if (tree_int_cst_equal (len1, len2))
502         return len1;
503     }
504
505   if (TREE_CODE (src) == COMPOUND_EXPR
506       && (only_value || !TREE_SIDE_EFFECTS (TREE_OPERAND (src, 0))))
507     return c_strlen (TREE_OPERAND (src, 1), only_value);
508
509   loc = EXPR_LOC_OR_HERE (src);
510
511   src = string_constant (src, &offset_node);
512   if (src == 0)
513     return NULL_TREE;
514
515   max = TREE_STRING_LENGTH (src) - 1;
516   ptr = TREE_STRING_POINTER (src);
517
518   if (offset_node && TREE_CODE (offset_node) != INTEGER_CST)
519     {
520       /* If the string has an internal zero byte (e.g., "foo\0bar"), we can't
521          compute the offset to the following null if we don't know where to
522          start searching for it.  */
523       int i;
524
525       for (i = 0; i < max; i++)
526         if (ptr[i] == 0)
527           return NULL_TREE;
528
529       /* We don't know the starting offset, but we do know that the string
530          has no internal zero bytes.  We can assume that the offset falls
531          within the bounds of the string; otherwise, the programmer deserves
532          what he gets.  Subtract the offset from the length of the string,
533          and return that.  This would perhaps not be valid if we were dealing
534          with named arrays in addition to literal string constants.  */
535
536       return size_diffop_loc (loc, size_int (max), offset_node);
537     }
538
539   /* We have a known offset into the string.  Start searching there for
540      a null character if we can represent it as a single HOST_WIDE_INT.  */
541   if (offset_node == 0)
542     offset = 0;
543   else if (! host_integerp (offset_node, 0))
544     offset = -1;
545   else
546     offset = tree_low_cst (offset_node, 0);
547
548   /* If the offset is known to be out of bounds, warn, and call strlen at
549      runtime.  */
550   if (offset < 0 || offset > max)
551     {
552      /* Suppress multiple warnings for propagated constant strings.  */
553       if (! TREE_NO_WARNING (src))
554         {
555           warning_at (loc, 0, "offset outside bounds of constant string");
556           TREE_NO_WARNING (src) = 1;
557         }
558       return NULL_TREE;
559     }
560
561   /* Use strlen to search for the first zero byte.  Since any strings
562      constructed with build_string will have nulls appended, we win even
563      if we get handed something like (char[4])"abcd".
564
565      Since OFFSET is our starting index into the string, no further
566      calculation is needed.  */
567   return ssize_int (strlen (ptr + offset));
568 }
569
570 /* Return a char pointer for a C string if it is a string constant
571    or sum of string constant and integer constant.  */
572
573 static const char *
574 c_getstr (tree src)
575 {
576   tree offset_node;
577
578   src = string_constant (src, &offset_node);
579   if (src == 0)
580     return 0;
581
582   if (offset_node == 0)
583     return TREE_STRING_POINTER (src);
584   else if (!host_integerp (offset_node, 1)
585            || compare_tree_int (offset_node, TREE_STRING_LENGTH (src) - 1) > 0)
586     return 0;
587
588   return TREE_STRING_POINTER (src) + tree_low_cst (offset_node, 1);
589 }
590
591 /* Return a CONST_INT or CONST_DOUBLE corresponding to target reading
592    GET_MODE_BITSIZE (MODE) bits from string constant STR.  */
593
594 static rtx
595 c_readstr (const char *str, enum machine_mode mode)
596 {
597   HOST_WIDE_INT c[2];
598   HOST_WIDE_INT ch;
599   unsigned int i, j;
600
601   gcc_assert (GET_MODE_CLASS (mode) == MODE_INT);
602
603   c[0] = 0;
604   c[1] = 0;
605   ch = 1;
606   for (i = 0; i < GET_MODE_SIZE (mode); i++)
607     {
608       j = i;
609       if (WORDS_BIG_ENDIAN)
610         j = GET_MODE_SIZE (mode) - i - 1;
611       if (BYTES_BIG_ENDIAN != WORDS_BIG_ENDIAN
612           && GET_MODE_SIZE (mode) > UNITS_PER_WORD)
613         j = j + UNITS_PER_WORD - 2 * (j % UNITS_PER_WORD) - 1;
614       j *= BITS_PER_UNIT;
615       gcc_assert (j < 2 * HOST_BITS_PER_WIDE_INT);
616
617       if (ch)
618         ch = (unsigned char) str[i];
619       c[j / HOST_BITS_PER_WIDE_INT] |= ch << (j % HOST_BITS_PER_WIDE_INT);
620     }
621   return immed_double_const (c[0], c[1], mode);
622 }
623
624 /* Cast a target constant CST to target CHAR and if that value fits into
625    host char type, return zero and put that value into variable pointed to by
626    P.  */
627
628 static int
629 target_char_cast (tree cst, char *p)
630 {
631   unsigned HOST_WIDE_INT val, hostval;
632
633   if (!host_integerp (cst, 1)
634       || CHAR_TYPE_SIZE > HOST_BITS_PER_WIDE_INT)
635     return 1;
636
637   val = tree_low_cst (cst, 1);
638   if (CHAR_TYPE_SIZE < HOST_BITS_PER_WIDE_INT)
639     val &= (((unsigned HOST_WIDE_INT) 1) << CHAR_TYPE_SIZE) - 1;
640
641   hostval = val;
642   if (HOST_BITS_PER_CHAR < HOST_BITS_PER_WIDE_INT)
643     hostval &= (((unsigned HOST_WIDE_INT) 1) << HOST_BITS_PER_CHAR) - 1;
644
645   if (val != hostval)
646     return 1;
647
648   *p = hostval;
649   return 0;
650 }
651
652 /* Similar to save_expr, but assumes that arbitrary code is not executed
653    in between the multiple evaluations.  In particular, we assume that a
654    non-addressable local variable will not be modified.  */
655
656 static tree
657 builtin_save_expr (tree exp)
658 {
659   if (TREE_ADDRESSABLE (exp) == 0
660       && (TREE_CODE (exp) == PARM_DECL
661           || (TREE_CODE (exp) == VAR_DECL && !TREE_STATIC (exp))))
662     return exp;
663
664   return save_expr (exp);
665 }
666
667 /* Given TEM, a pointer to a stack frame, follow the dynamic chain COUNT
668    times to get the address of either a higher stack frame, or a return
669    address located within it (depending on FNDECL_CODE).  */
670
671 static rtx
672 expand_builtin_return_addr (enum built_in_function fndecl_code, int count)
673 {
674   int i;
675
676 #ifdef INITIAL_FRAME_ADDRESS_RTX
677   rtx tem = INITIAL_FRAME_ADDRESS_RTX;
678 #else
679   rtx tem;
680
681   /* For a zero count with __builtin_return_address, we don't care what
682      frame address we return, because target-specific definitions will
683      override us.  Therefore frame pointer elimination is OK, and using
684      the soft frame pointer is OK.
685
686      For a nonzero count, or a zero count with __builtin_frame_address,
687      we require a stable offset from the current frame pointer to the
688      previous one, so we must use the hard frame pointer, and
689      we must disable frame pointer elimination.  */
690   if (count == 0 && fndecl_code == BUILT_IN_RETURN_ADDRESS)
691     tem = frame_pointer_rtx;
692   else
693     {
694       tem = hard_frame_pointer_rtx;
695
696       /* Tell reload not to eliminate the frame pointer.  */
697       crtl->accesses_prior_frames = 1;
698     }
699 #endif
700
701   /* Some machines need special handling before we can access
702      arbitrary frames.  For example, on the SPARC, we must first flush
703      all register windows to the stack.  */
704 #ifdef SETUP_FRAME_ADDRESSES
705   if (count > 0)
706     SETUP_FRAME_ADDRESSES ();
707 #endif
708
709   /* On the SPARC, the return address is not in the frame, it is in a
710      register.  There is no way to access it off of the current frame
711      pointer, but it can be accessed off the previous frame pointer by
712      reading the value from the register window save area.  */
713 #ifdef RETURN_ADDR_IN_PREVIOUS_FRAME
714   if (fndecl_code == BUILT_IN_RETURN_ADDRESS)
715     count--;
716 #endif
717
718   /* Scan back COUNT frames to the specified frame.  */
719   for (i = 0; i < count; i++)
720     {
721       /* Assume the dynamic chain pointer is in the word that the
722          frame address points to, unless otherwise specified.  */
723 #ifdef DYNAMIC_CHAIN_ADDRESS
724       tem = DYNAMIC_CHAIN_ADDRESS (tem);
725 #endif
726       tem = memory_address (Pmode, tem);
727       tem = gen_frame_mem (Pmode, tem);
728       tem = copy_to_reg (tem);
729     }
730
731   /* For __builtin_frame_address, return what we've got.  But, on
732      the SPARC for example, we may have to add a bias.  */
733   if (fndecl_code == BUILT_IN_FRAME_ADDRESS)
734 #ifdef FRAME_ADDR_RTX
735     return FRAME_ADDR_RTX (tem);
736 #else
737     return tem;
738 #endif
739
740   /* For __builtin_return_address, get the return address from that frame.  */
741 #ifdef RETURN_ADDR_RTX
742   tem = RETURN_ADDR_RTX (count, tem);
743 #else
744   tem = memory_address (Pmode,
745                         plus_constant (tem, GET_MODE_SIZE (Pmode)));
746   tem = gen_frame_mem (Pmode, tem);
747 #endif
748   return tem;
749 }
750
751 /* Alias set used for setjmp buffer.  */
752 static alias_set_type setjmp_alias_set = -1;
753
754 /* Construct the leading half of a __builtin_setjmp call.  Control will
755    return to RECEIVER_LABEL.  This is also called directly by the SJLJ
756    exception handling code.  */
757
758 void
759 expand_builtin_setjmp_setup (rtx buf_addr, rtx receiver_label)
760 {
761   enum machine_mode sa_mode = STACK_SAVEAREA_MODE (SAVE_NONLOCAL);
762   rtx stack_save;
763   rtx mem;
764
765   if (setjmp_alias_set == -1)
766     setjmp_alias_set = new_alias_set ();
767
768   buf_addr = convert_memory_address (Pmode, buf_addr);
769
770   buf_addr = force_reg (Pmode, force_operand (buf_addr, NULL_RTX));
771
772   /* We store the frame pointer and the address of receiver_label in
773      the buffer and use the rest of it for the stack save area, which
774      is machine-dependent.  */
775
776   mem = gen_rtx_MEM (Pmode, buf_addr);
777   set_mem_alias_set (mem, setjmp_alias_set);
778   emit_move_insn (mem, targetm.builtin_setjmp_frame_value ());
779
780   mem = gen_rtx_MEM (Pmode, plus_constant (buf_addr, GET_MODE_SIZE (Pmode))),
781   set_mem_alias_set (mem, setjmp_alias_set);
782
783   emit_move_insn (validize_mem (mem),
784                   force_reg (Pmode, gen_rtx_LABEL_REF (Pmode, receiver_label)));
785
786   stack_save = gen_rtx_MEM (sa_mode,
787                             plus_constant (buf_addr,
788                                            2 * GET_MODE_SIZE (Pmode)));
789   set_mem_alias_set (stack_save, setjmp_alias_set);
790   emit_stack_save (SAVE_NONLOCAL, &stack_save, NULL_RTX);
791
792   /* If there is further processing to do, do it.  */
793 #ifdef HAVE_builtin_setjmp_setup
794   if (HAVE_builtin_setjmp_setup)
795     emit_insn (gen_builtin_setjmp_setup (buf_addr));
796 #endif
797
798   /* Tell optimize_save_area_alloca that extra work is going to
799      need to go on during alloca.  */
800   cfun->calls_setjmp = 1;
801
802   /* We have a nonlocal label.   */
803   cfun->has_nonlocal_label = 1;
804 }
805
806 /* Construct the trailing part of a __builtin_setjmp call.  This is
807    also called directly by the SJLJ exception handling code.  */
808
809 void
810 expand_builtin_setjmp_receiver (rtx receiver_label ATTRIBUTE_UNUSED)
811 {
812   rtx chain;
813
814   /* Clobber the FP when we get here, so we have to make sure it's
815      marked as used by this function.  */
816   emit_use (hard_frame_pointer_rtx);
817
818   /* Mark the static chain as clobbered here so life information
819      doesn't get messed up for it.  */
820   chain = targetm.calls.static_chain (current_function_decl, true);
821   if (chain && REG_P (chain))
822     emit_clobber (chain);
823
824   /* Now put in the code to restore the frame pointer, and argument
825      pointer, if needed.  */
826 #ifdef HAVE_nonlocal_goto
827   if (! HAVE_nonlocal_goto)
828 #endif
829     {
830       emit_move_insn (virtual_stack_vars_rtx, hard_frame_pointer_rtx);
831       /* This might change the hard frame pointer in ways that aren't
832          apparent to early optimization passes, so force a clobber.  */
833       emit_clobber (hard_frame_pointer_rtx);
834     }
835
836 #if !HARD_FRAME_POINTER_IS_ARG_POINTER
837   if (fixed_regs[ARG_POINTER_REGNUM])
838     {
839 #ifdef ELIMINABLE_REGS
840       size_t i;
841       static const struct elims {const int from, to;} elim_regs[] = ELIMINABLE_REGS;
842
843       for (i = 0; i < ARRAY_SIZE (elim_regs); i++)
844         if (elim_regs[i].from == ARG_POINTER_REGNUM
845             && elim_regs[i].to == HARD_FRAME_POINTER_REGNUM)
846           break;
847
848       if (i == ARRAY_SIZE (elim_regs))
849 #endif
850         {
851           /* Now restore our arg pointer from the address at which it
852              was saved in our stack frame.  */
853           emit_move_insn (crtl->args.internal_arg_pointer,
854                           copy_to_reg (get_arg_pointer_save_area ()));
855         }
856     }
857 #endif
858
859 #ifdef HAVE_builtin_setjmp_receiver
860   if (HAVE_builtin_setjmp_receiver)
861     emit_insn (gen_builtin_setjmp_receiver (receiver_label));
862   else
863 #endif
864 #ifdef HAVE_nonlocal_goto_receiver
865     if (HAVE_nonlocal_goto_receiver)
866       emit_insn (gen_nonlocal_goto_receiver ());
867     else
868 #endif
869       { /* Nothing */ }
870
871   /* We must not allow the code we just generated to be reordered by
872      scheduling.  Specifically, the update of the frame pointer must
873      happen immediately, not later.  */
874   emit_insn (gen_blockage ());
875 }
876
877 /* __builtin_longjmp is passed a pointer to an array of five words (not
878    all will be used on all machines).  It operates similarly to the C
879    library function of the same name, but is more efficient.  Much of
880    the code below is copied from the handling of non-local gotos.  */
881
882 static void
883 expand_builtin_longjmp (rtx buf_addr, rtx value)
884 {
885   rtx fp, lab, stack, insn, last;
886   enum machine_mode sa_mode = STACK_SAVEAREA_MODE (SAVE_NONLOCAL);
887
888   /* DRAP is needed for stack realign if longjmp is expanded to current
889      function  */
890   if (SUPPORTS_STACK_ALIGNMENT)
891     crtl->need_drap = true;
892
893   if (setjmp_alias_set == -1)
894     setjmp_alias_set = new_alias_set ();
895
896   buf_addr = convert_memory_address (Pmode, buf_addr);
897
898   buf_addr = force_reg (Pmode, buf_addr);
899
900   /* We require that the user must pass a second argument of 1, because
901      that is what builtin_setjmp will return.  */
902   gcc_assert (value == const1_rtx);
903
904   last = get_last_insn ();
905 #ifdef HAVE_builtin_longjmp
906   if (HAVE_builtin_longjmp)
907     emit_insn (gen_builtin_longjmp (buf_addr));
908   else
909 #endif
910     {
911       fp = gen_rtx_MEM (Pmode, buf_addr);
912       lab = gen_rtx_MEM (Pmode, plus_constant (buf_addr,
913                                                GET_MODE_SIZE (Pmode)));
914
915       stack = gen_rtx_MEM (sa_mode, plus_constant (buf_addr,
916                                                    2 * GET_MODE_SIZE (Pmode)));
917       set_mem_alias_set (fp, setjmp_alias_set);
918       set_mem_alias_set (lab, setjmp_alias_set);
919       set_mem_alias_set (stack, setjmp_alias_set);
920
921       /* Pick up FP, label, and SP from the block and jump.  This code is
922          from expand_goto in stmt.c; see there for detailed comments.  */
923 #ifdef HAVE_nonlocal_goto
924       if (HAVE_nonlocal_goto)
925         /* We have to pass a value to the nonlocal_goto pattern that will
926            get copied into the static_chain pointer, but it does not matter
927            what that value is, because builtin_setjmp does not use it.  */
928         emit_insn (gen_nonlocal_goto (value, lab, stack, fp));
929       else
930 #endif
931         {
932           lab = copy_to_reg (lab);
933
934           emit_clobber (gen_rtx_MEM (BLKmode, gen_rtx_SCRATCH (VOIDmode)));
935           emit_clobber (gen_rtx_MEM (BLKmode, hard_frame_pointer_rtx));
936
937           emit_move_insn (hard_frame_pointer_rtx, fp);
938           emit_stack_restore (SAVE_NONLOCAL, stack, NULL_RTX);
939
940           emit_use (hard_frame_pointer_rtx);
941           emit_use (stack_pointer_rtx);
942           emit_indirect_jump (lab);
943         }
944     }
945
946   /* Search backwards and mark the jump insn as a non-local goto.
947      Note that this precludes the use of __builtin_longjmp to a
948      __builtin_setjmp target in the same function.  However, we've
949      already cautioned the user that these functions are for
950      internal exception handling use only.  */
951   for (insn = get_last_insn (); insn; insn = PREV_INSN (insn))
952     {
953       gcc_assert (insn != last);
954
955       if (JUMP_P (insn))
956         {
957           add_reg_note (insn, REG_NON_LOCAL_GOTO, const0_rtx);
958           break;
959         }
960       else if (CALL_P (insn))
961         break;
962     }
963 }
964
965 /* Expand a call to __builtin_nonlocal_goto.  We're passed the target label
966    and the address of the save area.  */
967
968 static rtx
969 expand_builtin_nonlocal_goto (tree exp)
970 {
971   tree t_label, t_save_area;
972   rtx r_label, r_save_area, r_fp, r_sp, insn;
973
974   if (!validate_arglist (exp, POINTER_TYPE, POINTER_TYPE, VOID_TYPE))
975     return NULL_RTX;
976
977   t_label = CALL_EXPR_ARG (exp, 0);
978   t_save_area = CALL_EXPR_ARG (exp, 1);
979
980   r_label = expand_normal (t_label);
981   r_label = convert_memory_address (Pmode, r_label);
982   r_save_area = expand_normal (t_save_area);
983   r_save_area = convert_memory_address (Pmode, r_save_area);
984   /* Copy the address of the save location to a register just in case it was based
985     on the frame pointer.   */
986   r_save_area = copy_to_reg (r_save_area);
987   r_fp = gen_rtx_MEM (Pmode, r_save_area);
988   r_sp = gen_rtx_MEM (STACK_SAVEAREA_MODE (SAVE_NONLOCAL),
989                       plus_constant (r_save_area, GET_MODE_SIZE (Pmode)));
990
991   crtl->has_nonlocal_goto = 1;
992
993 #ifdef HAVE_nonlocal_goto
994   /* ??? We no longer need to pass the static chain value, afaik.  */
995   if (HAVE_nonlocal_goto)
996     emit_insn (gen_nonlocal_goto (const0_rtx, r_label, r_sp, r_fp));
997   else
998 #endif
999     {
1000       r_label = copy_to_reg (r_label);
1001
1002       emit_clobber (gen_rtx_MEM (BLKmode, gen_rtx_SCRATCH (VOIDmode)));
1003       emit_clobber (gen_rtx_MEM (BLKmode, hard_frame_pointer_rtx));
1004
1005       /* Restore frame pointer for containing function.
1006          This sets the actual hard register used for the frame pointer
1007          to the location of the function's incoming static chain info.
1008          The non-local goto handler will then adjust it to contain the
1009          proper value and reload the argument pointer, if needed.  */
1010       emit_move_insn (hard_frame_pointer_rtx, r_fp);
1011       emit_stack_restore (SAVE_NONLOCAL, r_sp, NULL_RTX);
1012
1013       /* USE of hard_frame_pointer_rtx added for consistency;
1014          not clear if really needed.  */
1015       emit_use (hard_frame_pointer_rtx);
1016       emit_use (stack_pointer_rtx);
1017
1018       /* If the architecture is using a GP register, we must
1019          conservatively assume that the target function makes use of it.
1020          The prologue of functions with nonlocal gotos must therefore
1021          initialize the GP register to the appropriate value, and we
1022          must then make sure that this value is live at the point
1023          of the jump.  (Note that this doesn't necessarily apply
1024          to targets with a nonlocal_goto pattern; they are free
1025          to implement it in their own way.  Note also that this is
1026          a no-op if the GP register is a global invariant.)  */
1027       if ((unsigned) PIC_OFFSET_TABLE_REGNUM != INVALID_REGNUM
1028           && fixed_regs[PIC_OFFSET_TABLE_REGNUM])
1029         emit_use (pic_offset_table_rtx);
1030
1031       emit_indirect_jump (r_label);
1032     }
1033
1034   /* Search backwards to the jump insn and mark it as a
1035      non-local goto.  */
1036   for (insn = get_last_insn (); insn; insn = PREV_INSN (insn))
1037     {
1038       if (JUMP_P (insn))
1039         {
1040           add_reg_note (insn, REG_NON_LOCAL_GOTO, const0_rtx);
1041           break;
1042         }
1043       else if (CALL_P (insn))
1044         break;
1045     }
1046
1047   return const0_rtx;
1048 }
1049
1050 /* __builtin_update_setjmp_buf is passed a pointer to an array of five words
1051    (not all will be used on all machines) that was passed to __builtin_setjmp.
1052    It updates the stack pointer in that block to correspond to the current
1053    stack pointer.  */
1054
1055 static void
1056 expand_builtin_update_setjmp_buf (rtx buf_addr)
1057 {
1058   enum machine_mode sa_mode = Pmode;
1059   rtx stack_save;
1060
1061
1062 #ifdef HAVE_save_stack_nonlocal
1063   if (HAVE_save_stack_nonlocal)
1064     sa_mode = insn_data[(int) CODE_FOR_save_stack_nonlocal].operand[0].mode;
1065 #endif
1066 #ifdef STACK_SAVEAREA_MODE
1067   sa_mode = STACK_SAVEAREA_MODE (SAVE_NONLOCAL);
1068 #endif
1069
1070   stack_save
1071     = gen_rtx_MEM (sa_mode,
1072                    memory_address
1073                    (sa_mode,
1074                     plus_constant (buf_addr, 2 * GET_MODE_SIZE (Pmode))));
1075
1076 #ifdef HAVE_setjmp
1077   if (HAVE_setjmp)
1078     emit_insn (gen_setjmp ());
1079 #endif
1080
1081   emit_stack_save (SAVE_NONLOCAL, &stack_save, NULL_RTX);
1082 }
1083
1084 /* Expand a call to __builtin_prefetch.  For a target that does not support
1085    data prefetch, evaluate the memory address argument in case it has side
1086    effects.  */
1087
1088 static void
1089 expand_builtin_prefetch (tree exp)
1090 {
1091   tree arg0, arg1, arg2;
1092   int nargs;
1093   rtx op0, op1, op2;
1094
1095   if (!validate_arglist (exp, POINTER_TYPE, 0))
1096     return;
1097
1098   arg0 = CALL_EXPR_ARG (exp, 0);
1099
1100   /* Arguments 1 and 2 are optional; argument 1 (read/write) defaults to
1101      zero (read) and argument 2 (locality) defaults to 3 (high degree of
1102      locality).  */
1103   nargs = call_expr_nargs (exp);
1104   if (nargs > 1)
1105     arg1 = CALL_EXPR_ARG (exp, 1);
1106   else
1107     arg1 = integer_zero_node;
1108   if (nargs > 2)
1109     arg2 = CALL_EXPR_ARG (exp, 2);
1110   else
1111     arg2 = integer_three_node;
1112
1113   /* Argument 0 is an address.  */
1114   op0 = expand_expr (arg0, NULL_RTX, Pmode, EXPAND_NORMAL);
1115
1116   /* Argument 1 (read/write flag) must be a compile-time constant int.  */
1117   if (TREE_CODE (arg1) != INTEGER_CST)
1118     {
1119       error ("second argument to %<__builtin_prefetch%> must be a constant");
1120       arg1 = integer_zero_node;
1121     }
1122   op1 = expand_normal (arg1);
1123   /* Argument 1 must be either zero or one.  */
1124   if (INTVAL (op1) != 0 && INTVAL (op1) != 1)
1125     {
1126       warning (0, "invalid second argument to %<__builtin_prefetch%>;"
1127                " using zero");
1128       op1 = const0_rtx;
1129     }
1130
1131   /* Argument 2 (locality) must be a compile-time constant int.  */
1132   if (TREE_CODE (arg2) != INTEGER_CST)
1133     {
1134       error ("third argument to %<__builtin_prefetch%> must be a constant");
1135       arg2 = integer_zero_node;
1136     }
1137   op2 = expand_normal (arg2);
1138   /* Argument 2 must be 0, 1, 2, or 3.  */
1139   if (INTVAL (op2) < 0 || INTVAL (op2) > 3)
1140     {
1141       warning (0, "invalid third argument to %<__builtin_prefetch%>; using zero");
1142       op2 = const0_rtx;
1143     }
1144
1145 #ifdef HAVE_prefetch
1146   if (HAVE_prefetch)
1147     {
1148       if ((! (*insn_data[(int) CODE_FOR_prefetch].operand[0].predicate)
1149              (op0,
1150               insn_data[(int) CODE_FOR_prefetch].operand[0].mode))
1151           || (GET_MODE (op0) != Pmode))
1152         {
1153           op0 = convert_memory_address (Pmode, op0);
1154           op0 = force_reg (Pmode, op0);
1155         }
1156       emit_insn (gen_prefetch (op0, op1, op2));
1157     }
1158 #endif
1159
1160   /* Don't do anything with direct references to volatile memory, but
1161      generate code to handle other side effects.  */
1162   if (!MEM_P (op0) && side_effects_p (op0))
1163     emit_insn (op0);
1164 }
1165
1166 /* Get a MEM rtx for expression EXP which is the address of an operand
1167    to be used in a string instruction (cmpstrsi, movmemsi, ..).  LEN is
1168    the maximum length of the block of memory that might be accessed or
1169    NULL if unknown.  */
1170
1171 static rtx
1172 get_memory_rtx (tree exp, tree len)
1173 {
1174   tree orig_exp = exp;
1175   rtx addr, mem;
1176   HOST_WIDE_INT off;
1177
1178   /* When EXP is not resolved SAVE_EXPR, MEM_ATTRS can be still derived
1179      from its expression, for expr->a.b only <variable>.a.b is recorded.  */
1180   if (TREE_CODE (exp) == SAVE_EXPR && !SAVE_EXPR_RESOLVED_P (exp))
1181     exp = TREE_OPERAND (exp, 0);
1182
1183   addr = expand_expr (orig_exp, NULL_RTX, ptr_mode, EXPAND_NORMAL);
1184   mem = gen_rtx_MEM (BLKmode, memory_address (BLKmode, addr));
1185
1186   /* Get an expression we can use to find the attributes to assign to MEM.
1187      If it is an ADDR_EXPR, use the operand.  Otherwise, dereference it if
1188      we can.  First remove any nops.  */
1189   while (CONVERT_EXPR_P (exp)
1190          && POINTER_TYPE_P (TREE_TYPE (TREE_OPERAND (exp, 0))))
1191     exp = TREE_OPERAND (exp, 0);
1192
1193   off = 0;
1194   if (TREE_CODE (exp) == POINTER_PLUS_EXPR
1195       && TREE_CODE (TREE_OPERAND (exp, 0)) == ADDR_EXPR
1196       && host_integerp (TREE_OPERAND (exp, 1), 0)
1197       && (off = tree_low_cst (TREE_OPERAND (exp, 1), 0)) > 0)
1198     exp = TREE_OPERAND (TREE_OPERAND (exp, 0), 0);
1199   else if (TREE_CODE (exp) == ADDR_EXPR)
1200     exp = TREE_OPERAND (exp, 0);
1201   else if (POINTER_TYPE_P (TREE_TYPE (exp)))
1202     exp = build1 (INDIRECT_REF, TREE_TYPE (TREE_TYPE (exp)), exp);
1203   else
1204     exp = NULL;
1205
1206   /* Honor attributes derived from exp, except for the alias set
1207      (as builtin stringops may alias with anything) and the size
1208      (as stringops may access multiple array elements).  */
1209   if (exp)
1210     {
1211       set_mem_attributes (mem, exp, 0);
1212
1213       if (off)
1214         mem = adjust_automodify_address_nv (mem, BLKmode, NULL, off);
1215
1216       /* Allow the string and memory builtins to overflow from one
1217          field into another, see http://gcc.gnu.org/PR23561.
1218          Thus avoid COMPONENT_REFs in MEM_EXPR unless we know the whole
1219          memory accessed by the string or memory builtin will fit
1220          within the field.  */
1221       if (MEM_EXPR (mem) && TREE_CODE (MEM_EXPR (mem)) == COMPONENT_REF)
1222         {
1223           tree mem_expr = MEM_EXPR (mem);
1224           HOST_WIDE_INT offset = -1, length = -1;
1225           tree inner = exp;
1226
1227           while (TREE_CODE (inner) == ARRAY_REF
1228                  || CONVERT_EXPR_P (inner)
1229                  || TREE_CODE (inner) == VIEW_CONVERT_EXPR
1230                  || TREE_CODE (inner) == SAVE_EXPR)
1231             inner = TREE_OPERAND (inner, 0);
1232
1233           gcc_assert (TREE_CODE (inner) == COMPONENT_REF);
1234
1235           if (MEM_OFFSET (mem)
1236               && CONST_INT_P (MEM_OFFSET (mem)))
1237             offset = INTVAL (MEM_OFFSET (mem));
1238
1239           if (offset >= 0 && len && host_integerp (len, 0))
1240             length = tree_low_cst (len, 0);
1241
1242           while (TREE_CODE (inner) == COMPONENT_REF)
1243             {
1244               tree field = TREE_OPERAND (inner, 1);
1245               gcc_assert (TREE_CODE (mem_expr) == COMPONENT_REF);
1246               gcc_assert (field == TREE_OPERAND (mem_expr, 1));
1247
1248               /* Bitfields are generally not byte-addressable.  */
1249               gcc_assert (!DECL_BIT_FIELD (field)
1250                           || ((tree_low_cst (DECL_FIELD_BIT_OFFSET (field), 1)
1251                                % BITS_PER_UNIT) == 0
1252                               && host_integerp (DECL_SIZE (field), 0)
1253                               && (TREE_INT_CST_LOW (DECL_SIZE (field))
1254                                   % BITS_PER_UNIT) == 0));
1255
1256               /* If we can prove that the memory starting at XEXP (mem, 0) and
1257                  ending at XEXP (mem, 0) + LENGTH will fit into this field, we
1258                  can keep the COMPONENT_REF in MEM_EXPR.  But be careful with
1259                  fields without DECL_SIZE_UNIT like flexible array members.  */
1260               if (length >= 0
1261                   && DECL_SIZE_UNIT (field)
1262                   && host_integerp (DECL_SIZE_UNIT (field), 0))
1263                 {
1264                   HOST_WIDE_INT size
1265                     = TREE_INT_CST_LOW (DECL_SIZE_UNIT (field));
1266                   if (offset <= size
1267                       && length <= size
1268                       && offset + length <= size)
1269                     break;
1270                 }
1271
1272               if (offset >= 0
1273                   && host_integerp (DECL_FIELD_OFFSET (field), 0))
1274                 offset += TREE_INT_CST_LOW (DECL_FIELD_OFFSET (field))
1275                           + tree_low_cst (DECL_FIELD_BIT_OFFSET (field), 1)
1276                             / BITS_PER_UNIT;
1277               else
1278                 {
1279                   offset = -1;
1280                   length = -1;
1281                 }
1282
1283               mem_expr = TREE_OPERAND (mem_expr, 0);
1284               inner = TREE_OPERAND (inner, 0);
1285             }
1286
1287           if (mem_expr == NULL)
1288             offset = -1;
1289           if (mem_expr != MEM_EXPR (mem))
1290             {
1291               set_mem_expr (mem, mem_expr);
1292               set_mem_offset (mem, offset >= 0 ? GEN_INT (offset) : NULL_RTX);
1293             }
1294         }
1295       set_mem_alias_set (mem, 0);
1296       set_mem_size (mem, NULL_RTX);
1297     }
1298
1299   return mem;
1300 }
1301 \f
1302 /* Built-in functions to perform an untyped call and return.  */
1303
1304 #define apply_args_mode \
1305   (this_target_builtins->x_apply_args_mode)
1306 #define apply_result_mode \
1307   (this_target_builtins->x_apply_result_mode)
1308
1309 /* Return the size required for the block returned by __builtin_apply_args,
1310    and initialize apply_args_mode.  */
1311
1312 static int
1313 apply_args_size (void)
1314 {
1315   static int size = -1;
1316   int align;
1317   unsigned int regno;
1318   enum machine_mode mode;
1319
1320   /* The values computed by this function never change.  */
1321   if (size < 0)
1322     {
1323       /* The first value is the incoming arg-pointer.  */
1324       size = GET_MODE_SIZE (Pmode);
1325
1326       /* The second value is the structure value address unless this is
1327          passed as an "invisible" first argument.  */
1328       if (targetm.calls.struct_value_rtx (cfun ? TREE_TYPE (cfun->decl) : 0, 0))
1329         size += GET_MODE_SIZE (Pmode);
1330
1331       for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
1332         if (FUNCTION_ARG_REGNO_P (regno))
1333           {
1334             mode = targetm.calls.get_raw_arg_mode (regno);
1335
1336             gcc_assert (mode != VOIDmode);
1337
1338             align = GET_MODE_ALIGNMENT (mode) / BITS_PER_UNIT;
1339             if (size % align != 0)
1340               size = CEIL (size, align) * align;
1341             size += GET_MODE_SIZE (mode);
1342             apply_args_mode[regno] = mode;
1343           }
1344         else
1345           {
1346             apply_args_mode[regno] = VOIDmode;
1347           }
1348     }
1349   return size;
1350 }
1351
1352 /* Return the size required for the block returned by __builtin_apply,
1353    and initialize apply_result_mode.  */
1354
1355 static int
1356 apply_result_size (void)
1357 {
1358   static int size = -1;
1359   int align, regno;
1360   enum machine_mode mode;
1361
1362   /* The values computed by this function never change.  */
1363   if (size < 0)
1364     {
1365       size = 0;
1366
1367       for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
1368         if (targetm.calls.function_value_regno_p (regno))
1369           {
1370             mode = targetm.calls.get_raw_result_mode (regno);
1371
1372             gcc_assert (mode != VOIDmode);
1373
1374             align = GET_MODE_ALIGNMENT (mode) / BITS_PER_UNIT;
1375             if (size % align != 0)
1376               size = CEIL (size, align) * align;
1377             size += GET_MODE_SIZE (mode);
1378             apply_result_mode[regno] = mode;
1379           }
1380         else
1381           apply_result_mode[regno] = VOIDmode;
1382
1383       /* Allow targets that use untyped_call and untyped_return to override
1384          the size so that machine-specific information can be stored here.  */
1385 #ifdef APPLY_RESULT_SIZE
1386       size = APPLY_RESULT_SIZE;
1387 #endif
1388     }
1389   return size;
1390 }
1391
1392 #if defined (HAVE_untyped_call) || defined (HAVE_untyped_return)
1393 /* Create a vector describing the result block RESULT.  If SAVEP is true,
1394    the result block is used to save the values; otherwise it is used to
1395    restore the values.  */
1396
1397 static rtx
1398 result_vector (int savep, rtx result)
1399 {
1400   int regno, size, align, nelts;
1401   enum machine_mode mode;
1402   rtx reg, mem;
1403   rtx *savevec = XALLOCAVEC (rtx, FIRST_PSEUDO_REGISTER);
1404
1405   size = nelts = 0;
1406   for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
1407     if ((mode = apply_result_mode[regno]) != VOIDmode)
1408       {
1409         align = GET_MODE_ALIGNMENT (mode) / BITS_PER_UNIT;
1410         if (size % align != 0)
1411           size = CEIL (size, align) * align;
1412         reg = gen_rtx_REG (mode, savep ? regno : INCOMING_REGNO (regno));
1413         mem = adjust_address (result, mode, size);
1414         savevec[nelts++] = (savep
1415                             ? gen_rtx_SET (VOIDmode, mem, reg)
1416                             : gen_rtx_SET (VOIDmode, reg, mem));
1417         size += GET_MODE_SIZE (mode);
1418       }
1419   return gen_rtx_PARALLEL (VOIDmode, gen_rtvec_v (nelts, savevec));
1420 }
1421 #endif /* HAVE_untyped_call or HAVE_untyped_return */
1422
1423 /* Save the state required to perform an untyped call with the same
1424    arguments as were passed to the current function.  */
1425
1426 static rtx
1427 expand_builtin_apply_args_1 (void)
1428 {
1429   rtx registers, tem;
1430   int size, align, regno;
1431   enum machine_mode mode;
1432   rtx struct_incoming_value = targetm.calls.struct_value_rtx (cfun ? TREE_TYPE (cfun->decl) : 0, 1);
1433
1434   /* Create a block where the arg-pointer, structure value address,
1435      and argument registers can be saved.  */
1436   registers = assign_stack_local (BLKmode, apply_args_size (), -1);
1437
1438   /* Walk past the arg-pointer and structure value address.  */
1439   size = GET_MODE_SIZE (Pmode);
1440   if (targetm.calls.struct_value_rtx (cfun ? TREE_TYPE (cfun->decl) : 0, 0))
1441     size += GET_MODE_SIZE (Pmode);
1442
1443   /* Save each register used in calling a function to the block.  */
1444   for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
1445     if ((mode = apply_args_mode[regno]) != VOIDmode)
1446       {
1447         align = GET_MODE_ALIGNMENT (mode) / BITS_PER_UNIT;
1448         if (size % align != 0)
1449           size = CEIL (size, align) * align;
1450
1451         tem = gen_rtx_REG (mode, INCOMING_REGNO (regno));
1452
1453         emit_move_insn (adjust_address (registers, mode, size), tem);
1454         size += GET_MODE_SIZE (mode);
1455       }
1456
1457   /* Save the arg pointer to the block.  */
1458   tem = copy_to_reg (crtl->args.internal_arg_pointer);
1459 #ifdef STACK_GROWS_DOWNWARD
1460   /* We need the pointer as the caller actually passed them to us, not
1461      as we might have pretended they were passed.  Make sure it's a valid
1462      operand, as emit_move_insn isn't expected to handle a PLUS.  */
1463   tem
1464     = force_operand (plus_constant (tem, crtl->args.pretend_args_size),
1465                      NULL_RTX);
1466 #endif
1467   emit_move_insn (adjust_address (registers, Pmode, 0), tem);
1468
1469   size = GET_MODE_SIZE (Pmode);
1470
1471   /* Save the structure value address unless this is passed as an
1472      "invisible" first argument.  */
1473   if (struct_incoming_value)
1474     {
1475       emit_move_insn (adjust_address (registers, Pmode, size),
1476                       copy_to_reg (struct_incoming_value));
1477       size += GET_MODE_SIZE (Pmode);
1478     }
1479
1480   /* Return the address of the block.  */
1481   return copy_addr_to_reg (XEXP (registers, 0));
1482 }
1483
1484 /* __builtin_apply_args returns block of memory allocated on
1485    the stack into which is stored the arg pointer, structure
1486    value address, static chain, and all the registers that might
1487    possibly be used in performing a function call.  The code is
1488    moved to the start of the function so the incoming values are
1489    saved.  */
1490
1491 static rtx
1492 expand_builtin_apply_args (void)
1493 {
1494   /* Don't do __builtin_apply_args more than once in a function.
1495      Save the result of the first call and reuse it.  */
1496   if (apply_args_value != 0)
1497     return apply_args_value;
1498   {
1499     /* When this function is called, it means that registers must be
1500        saved on entry to this function.  So we migrate the
1501        call to the first insn of this function.  */
1502     rtx temp;
1503     rtx seq;
1504
1505     start_sequence ();
1506     temp = expand_builtin_apply_args_1 ();
1507     seq = get_insns ();
1508     end_sequence ();
1509
1510     apply_args_value = temp;
1511
1512     /* Put the insns after the NOTE that starts the function.
1513        If this is inside a start_sequence, make the outer-level insn
1514        chain current, so the code is placed at the start of the
1515        function.  If internal_arg_pointer is a non-virtual pseudo,
1516        it needs to be placed after the function that initializes
1517        that pseudo.  */
1518     push_topmost_sequence ();
1519     if (REG_P (crtl->args.internal_arg_pointer)
1520         && REGNO (crtl->args.internal_arg_pointer) > LAST_VIRTUAL_REGISTER)
1521       emit_insn_before (seq, parm_birth_insn);
1522     else
1523       emit_insn_before (seq, NEXT_INSN (entry_of_function ()));
1524     pop_topmost_sequence ();
1525     return temp;
1526   }
1527 }
1528
1529 /* Perform an untyped call and save the state required to perform an
1530    untyped return of whatever value was returned by the given function.  */
1531
1532 static rtx
1533 expand_builtin_apply (rtx function, rtx arguments, rtx argsize)
1534 {
1535   int size, align, regno;
1536   enum machine_mode mode;
1537   rtx incoming_args, result, reg, dest, src, call_insn;
1538   rtx old_stack_level = 0;
1539   rtx call_fusage = 0;
1540   rtx struct_value = targetm.calls.struct_value_rtx (cfun ? TREE_TYPE (cfun->decl) : 0, 0);
1541
1542   arguments = convert_memory_address (Pmode, arguments);
1543
1544   /* Create a block where the return registers can be saved.  */
1545   result = assign_stack_local (BLKmode, apply_result_size (), -1);
1546
1547   /* Fetch the arg pointer from the ARGUMENTS block.  */
1548   incoming_args = gen_reg_rtx (Pmode);
1549   emit_move_insn (incoming_args, gen_rtx_MEM (Pmode, arguments));
1550 #ifndef STACK_GROWS_DOWNWARD
1551   incoming_args = expand_simple_binop (Pmode, MINUS, incoming_args, argsize,
1552                                        incoming_args, 0, OPTAB_LIB_WIDEN);
1553 #endif
1554
1555   /* Push a new argument block and copy the arguments.  Do not allow
1556      the (potential) memcpy call below to interfere with our stack
1557      manipulations.  */
1558   do_pending_stack_adjust ();
1559   NO_DEFER_POP;
1560
1561   /* Save the stack with nonlocal if available.  */
1562 #ifdef HAVE_save_stack_nonlocal
1563   if (HAVE_save_stack_nonlocal)
1564     emit_stack_save (SAVE_NONLOCAL, &old_stack_level, NULL_RTX);
1565   else
1566 #endif
1567     emit_stack_save (SAVE_BLOCK, &old_stack_level, NULL_RTX);
1568
1569   /* Allocate a block of memory onto the stack and copy the memory
1570      arguments to the outgoing arguments address.  We can pass TRUE
1571      as the 4th argument because we just saved the stack pointer
1572      and will restore it right after the call.  */
1573   allocate_dynamic_stack_space (argsize, 0, BIGGEST_ALIGNMENT, true);
1574
1575   /* Set DRAP flag to true, even though allocate_dynamic_stack_space
1576      may have already set current_function_calls_alloca to true.
1577      current_function_calls_alloca won't be set if argsize is zero,
1578      so we have to guarantee need_drap is true here.  */
1579   if (SUPPORTS_STACK_ALIGNMENT)
1580     crtl->need_drap = true;
1581
1582   dest = virtual_outgoing_args_rtx;
1583 #ifndef STACK_GROWS_DOWNWARD
1584   if (CONST_INT_P (argsize))
1585     dest = plus_constant (dest, -INTVAL (argsize));
1586   else
1587     dest = gen_rtx_PLUS (Pmode, dest, negate_rtx (Pmode, argsize));
1588 #endif
1589   dest = gen_rtx_MEM (BLKmode, dest);
1590   set_mem_align (dest, PARM_BOUNDARY);
1591   src = gen_rtx_MEM (BLKmode, incoming_args);
1592   set_mem_align (src, PARM_BOUNDARY);
1593   emit_block_move (dest, src, argsize, BLOCK_OP_NORMAL);
1594
1595   /* Refer to the argument block.  */
1596   apply_args_size ();
1597   arguments = gen_rtx_MEM (BLKmode, arguments);
1598   set_mem_align (arguments, PARM_BOUNDARY);
1599
1600   /* Walk past the arg-pointer and structure value address.  */
1601   size = GET_MODE_SIZE (Pmode);
1602   if (struct_value)
1603     size += GET_MODE_SIZE (Pmode);
1604
1605   /* Restore each of the registers previously saved.  Make USE insns
1606      for each of these registers for use in making the call.  */
1607   for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
1608     if ((mode = apply_args_mode[regno]) != VOIDmode)
1609       {
1610         align = GET_MODE_ALIGNMENT (mode) / BITS_PER_UNIT;
1611         if (size % align != 0)
1612           size = CEIL (size, align) * align;
1613         reg = gen_rtx_REG (mode, regno);
1614         emit_move_insn (reg, adjust_address (arguments, mode, size));
1615         use_reg (&call_fusage, reg);
1616         size += GET_MODE_SIZE (mode);
1617       }
1618
1619   /* Restore the structure value address unless this is passed as an
1620      "invisible" first argument.  */
1621   size = GET_MODE_SIZE (Pmode);
1622   if (struct_value)
1623     {
1624       rtx value = gen_reg_rtx (Pmode);
1625       emit_move_insn (value, adjust_address (arguments, Pmode, size));
1626       emit_move_insn (struct_value, value);
1627       if (REG_P (struct_value))
1628         use_reg (&call_fusage, struct_value);
1629       size += GET_MODE_SIZE (Pmode);
1630     }
1631
1632   /* All arguments and registers used for the call are set up by now!  */
1633   function = prepare_call_address (NULL, function, NULL, &call_fusage, 0, 0);
1634
1635   /* Ensure address is valid.  SYMBOL_REF is already valid, so no need,
1636      and we don't want to load it into a register as an optimization,
1637      because prepare_call_address already did it if it should be done.  */
1638   if (GET_CODE (function) != SYMBOL_REF)
1639     function = memory_address (FUNCTION_MODE, function);
1640
1641   /* Generate the actual call instruction and save the return value.  */
1642 #ifdef HAVE_untyped_call
1643   if (HAVE_untyped_call)
1644     emit_call_insn (gen_untyped_call (gen_rtx_MEM (FUNCTION_MODE, function),
1645                                       result, result_vector (1, result)));
1646   else
1647 #endif
1648 #ifdef HAVE_call_value
1649   if (HAVE_call_value)
1650     {
1651       rtx valreg = 0;
1652
1653       /* Locate the unique return register.  It is not possible to
1654          express a call that sets more than one return register using
1655          call_value; use untyped_call for that.  In fact, untyped_call
1656          only needs to save the return registers in the given block.  */
1657       for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
1658         if ((mode = apply_result_mode[regno]) != VOIDmode)
1659           {
1660             gcc_assert (!valreg); /* HAVE_untyped_call required.  */
1661
1662             valreg = gen_rtx_REG (mode, regno);
1663           }
1664
1665       emit_call_insn (GEN_CALL_VALUE (valreg,
1666                                       gen_rtx_MEM (FUNCTION_MODE, function),
1667                                       const0_rtx, NULL_RTX, const0_rtx));
1668
1669       emit_move_insn (adjust_address (result, GET_MODE (valreg), 0), valreg);
1670     }
1671   else
1672 #endif
1673     gcc_unreachable ();
1674
1675   /* Find the CALL insn we just emitted, and attach the register usage
1676      information.  */
1677   call_insn = last_call_insn ();
1678   add_function_usage_to (call_insn, call_fusage);
1679
1680   /* Restore the stack.  */
1681 #ifdef HAVE_save_stack_nonlocal
1682   if (HAVE_save_stack_nonlocal)
1683     emit_stack_restore (SAVE_NONLOCAL, old_stack_level, NULL_RTX);
1684   else
1685 #endif
1686     emit_stack_restore (SAVE_BLOCK, old_stack_level, NULL_RTX);
1687
1688   OK_DEFER_POP;
1689
1690   /* Return the address of the result block.  */
1691   result = copy_addr_to_reg (XEXP (result, 0));
1692   return convert_memory_address (ptr_mode, result);
1693 }
1694
1695 /* Perform an untyped return.  */
1696
1697 static void
1698 expand_builtin_return (rtx result)
1699 {
1700   int size, align, regno;
1701   enum machine_mode mode;
1702   rtx reg;
1703   rtx call_fusage = 0;
1704
1705   result = convert_memory_address (Pmode, result);
1706
1707   apply_result_size ();
1708   result = gen_rtx_MEM (BLKmode, result);
1709
1710 #ifdef HAVE_untyped_return
1711   if (HAVE_untyped_return)
1712     {
1713       emit_jump_insn (gen_untyped_return (result, result_vector (0, result)));
1714       emit_barrier ();
1715       return;
1716     }
1717 #endif
1718
1719   /* Restore the return value and note that each value is used.  */
1720   size = 0;
1721   for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
1722     if ((mode = apply_result_mode[regno]) != VOIDmode)
1723       {
1724         align = GET_MODE_ALIGNMENT (mode) / BITS_PER_UNIT;
1725         if (size % align != 0)
1726           size = CEIL (size, align) * align;
1727         reg = gen_rtx_REG (mode, INCOMING_REGNO (regno));
1728         emit_move_insn (reg, adjust_address (result, mode, size));
1729
1730         push_to_sequence (call_fusage);
1731         emit_use (reg);
1732         call_fusage = get_insns ();
1733         end_sequence ();
1734         size += GET_MODE_SIZE (mode);
1735       }
1736
1737   /* Put the USE insns before the return.  */
1738   emit_insn (call_fusage);
1739
1740   /* Return whatever values was restored by jumping directly to the end
1741      of the function.  */
1742   expand_naked_return ();
1743 }
1744
1745 /* Used by expand_builtin_classify_type and fold_builtin_classify_type.  */
1746
1747 static enum type_class
1748 type_to_class (tree type)
1749 {
1750   switch (TREE_CODE (type))
1751     {
1752     case VOID_TYPE:        return void_type_class;
1753     case INTEGER_TYPE:     return integer_type_class;
1754     case ENUMERAL_TYPE:    return enumeral_type_class;
1755     case BOOLEAN_TYPE:     return boolean_type_class;
1756     case POINTER_TYPE:     return pointer_type_class;
1757     case REFERENCE_TYPE:   return reference_type_class;
1758     case OFFSET_TYPE:      return offset_type_class;
1759     case REAL_TYPE:        return real_type_class;
1760     case COMPLEX_TYPE:     return complex_type_class;
1761     case FUNCTION_TYPE:    return function_type_class;
1762     case METHOD_TYPE:      return method_type_class;
1763     case RECORD_TYPE:      return record_type_class;
1764     case UNION_TYPE:
1765     case QUAL_UNION_TYPE:  return union_type_class;
1766     case ARRAY_TYPE:       return (TYPE_STRING_FLAG (type)
1767                                    ? string_type_class : array_type_class);
1768     case LANG_TYPE:        return lang_type_class;
1769     default:               return no_type_class;
1770     }
1771 }
1772
1773 /* Expand a call EXP to __builtin_classify_type.  */
1774
1775 static rtx
1776 expand_builtin_classify_type (tree exp)
1777 {
1778   if (call_expr_nargs (exp))
1779     return GEN_INT (type_to_class (TREE_TYPE (CALL_EXPR_ARG (exp, 0))));
1780   return GEN_INT (no_type_class);
1781 }
1782
1783 /* This helper macro, meant to be used in mathfn_built_in below,
1784    determines which among a set of three builtin math functions is
1785    appropriate for a given type mode.  The `F' and `L' cases are
1786    automatically generated from the `double' case.  */
1787 #define CASE_MATHFN(BUILT_IN_MATHFN) \
1788   case BUILT_IN_MATHFN: case BUILT_IN_MATHFN##F: case BUILT_IN_MATHFN##L: \
1789   fcode = BUILT_IN_MATHFN; fcodef = BUILT_IN_MATHFN##F ; \
1790   fcodel = BUILT_IN_MATHFN##L ; break;
1791 /* Similar to above, but appends _R after any F/L suffix.  */
1792 #define CASE_MATHFN_REENT(BUILT_IN_MATHFN) \
1793   case BUILT_IN_MATHFN##_R: case BUILT_IN_MATHFN##F_R: case BUILT_IN_MATHFN##L_R: \
1794   fcode = BUILT_IN_MATHFN##_R; fcodef = BUILT_IN_MATHFN##F_R ; \
1795   fcodel = BUILT_IN_MATHFN##L_R ; break;
1796
1797 /* Return mathematic function equivalent to FN but operating directly
1798    on TYPE, if available.  If IMPLICIT is true find the function in
1799    implicit_built_in_decls[], otherwise use built_in_decls[].  If we
1800    can't do the conversion, return zero.  */
1801
1802 static tree
1803 mathfn_built_in_1 (tree type, enum built_in_function fn, bool implicit)
1804 {
1805   tree const *const fn_arr
1806     = implicit ? implicit_built_in_decls : built_in_decls;
1807   enum built_in_function fcode, fcodef, fcodel;
1808
1809   switch (fn)
1810     {
1811       CASE_MATHFN (BUILT_IN_ACOS)
1812       CASE_MATHFN (BUILT_IN_ACOSH)
1813       CASE_MATHFN (BUILT_IN_ASIN)
1814       CASE_MATHFN (BUILT_IN_ASINH)
1815       CASE_MATHFN (BUILT_IN_ATAN)
1816       CASE_MATHFN (BUILT_IN_ATAN2)
1817       CASE_MATHFN (BUILT_IN_ATANH)
1818       CASE_MATHFN (BUILT_IN_CBRT)
1819       CASE_MATHFN (BUILT_IN_CEIL)
1820       CASE_MATHFN (BUILT_IN_CEXPI)
1821       CASE_MATHFN (BUILT_IN_COPYSIGN)
1822       CASE_MATHFN (BUILT_IN_COS)
1823       CASE_MATHFN (BUILT_IN_COSH)
1824       CASE_MATHFN (BUILT_IN_DREM)
1825       CASE_MATHFN (BUILT_IN_ERF)
1826       CASE_MATHFN (BUILT_IN_ERFC)
1827       CASE_MATHFN (BUILT_IN_EXP)
1828       CASE_MATHFN (BUILT_IN_EXP10)
1829       CASE_MATHFN (BUILT_IN_EXP2)
1830       CASE_MATHFN (BUILT_IN_EXPM1)
1831       CASE_MATHFN (BUILT_IN_FABS)
1832       CASE_MATHFN (BUILT_IN_FDIM)
1833       CASE_MATHFN (BUILT_IN_FLOOR)
1834       CASE_MATHFN (BUILT_IN_FMA)
1835       CASE_MATHFN (BUILT_IN_FMAX)
1836       CASE_MATHFN (BUILT_IN_FMIN)
1837       CASE_MATHFN (BUILT_IN_FMOD)
1838       CASE_MATHFN (BUILT_IN_FREXP)
1839       CASE_MATHFN (BUILT_IN_GAMMA)
1840       CASE_MATHFN_REENT (BUILT_IN_GAMMA) /* GAMMA_R */
1841       CASE_MATHFN (BUILT_IN_HUGE_VAL)
1842       CASE_MATHFN (BUILT_IN_HYPOT)
1843       CASE_MATHFN (BUILT_IN_ILOGB)
1844       CASE_MATHFN (BUILT_IN_INF)
1845       CASE_MATHFN (BUILT_IN_ISINF)
1846       CASE_MATHFN (BUILT_IN_J0)
1847       CASE_MATHFN (BUILT_IN_J1)
1848       CASE_MATHFN (BUILT_IN_JN)
1849       CASE_MATHFN (BUILT_IN_LCEIL)
1850       CASE_MATHFN (BUILT_IN_LDEXP)
1851       CASE_MATHFN (BUILT_IN_LFLOOR)
1852       CASE_MATHFN (BUILT_IN_LGAMMA)
1853       CASE_MATHFN_REENT (BUILT_IN_LGAMMA) /* LGAMMA_R */
1854       CASE_MATHFN (BUILT_IN_LLCEIL)
1855       CASE_MATHFN (BUILT_IN_LLFLOOR)
1856       CASE_MATHFN (BUILT_IN_LLRINT)
1857       CASE_MATHFN (BUILT_IN_LLROUND)
1858       CASE_MATHFN (BUILT_IN_LOG)
1859       CASE_MATHFN (BUILT_IN_LOG10)
1860       CASE_MATHFN (BUILT_IN_LOG1P)
1861       CASE_MATHFN (BUILT_IN_LOG2)
1862       CASE_MATHFN (BUILT_IN_LOGB)
1863       CASE_MATHFN (BUILT_IN_LRINT)
1864       CASE_MATHFN (BUILT_IN_LROUND)
1865       CASE_MATHFN (BUILT_IN_MODF)
1866       CASE_MATHFN (BUILT_IN_NAN)
1867       CASE_MATHFN (BUILT_IN_NANS)
1868       CASE_MATHFN (BUILT_IN_NEARBYINT)
1869       CASE_MATHFN (BUILT_IN_NEXTAFTER)
1870       CASE_MATHFN (BUILT_IN_NEXTTOWARD)
1871       CASE_MATHFN (BUILT_IN_POW)
1872       CASE_MATHFN (BUILT_IN_POWI)
1873       CASE_MATHFN (BUILT_IN_POW10)
1874       CASE_MATHFN (BUILT_IN_REMAINDER)
1875       CASE_MATHFN (BUILT_IN_REMQUO)
1876       CASE_MATHFN (BUILT_IN_RINT)
1877       CASE_MATHFN (BUILT_IN_ROUND)
1878       CASE_MATHFN (BUILT_IN_SCALB)
1879       CASE_MATHFN (BUILT_IN_SCALBLN)
1880       CASE_MATHFN (BUILT_IN_SCALBN)
1881       CASE_MATHFN (BUILT_IN_SIGNBIT)
1882       CASE_MATHFN (BUILT_IN_SIGNIFICAND)
1883       CASE_MATHFN (BUILT_IN_SIN)
1884       CASE_MATHFN (BUILT_IN_SINCOS)
1885       CASE_MATHFN (BUILT_IN_SINH)
1886       CASE_MATHFN (BUILT_IN_SQRT)
1887       CASE_MATHFN (BUILT_IN_TAN)
1888       CASE_MATHFN (BUILT_IN_TANH)
1889       CASE_MATHFN (BUILT_IN_TGAMMA)
1890       CASE_MATHFN (BUILT_IN_TRUNC)
1891       CASE_MATHFN (BUILT_IN_Y0)
1892       CASE_MATHFN (BUILT_IN_Y1)
1893       CASE_MATHFN (BUILT_IN_YN)
1894
1895       default:
1896         return NULL_TREE;
1897       }
1898
1899   if (TYPE_MAIN_VARIANT (type) == double_type_node)
1900     return fn_arr[fcode];
1901   else if (TYPE_MAIN_VARIANT (type) == float_type_node)
1902     return fn_arr[fcodef];
1903   else if (TYPE_MAIN_VARIANT (type) == long_double_type_node)
1904     return fn_arr[fcodel];
1905   else
1906     return NULL_TREE;
1907 }
1908
1909 /* Like mathfn_built_in_1(), but always use the implicit array.  */
1910
1911 tree
1912 mathfn_built_in (tree type, enum built_in_function fn)
1913 {
1914   return mathfn_built_in_1 (type, fn, /*implicit=*/ 1);
1915 }
1916
1917 /* If errno must be maintained, expand the RTL to check if the result,
1918    TARGET, of a built-in function call, EXP, is NaN, and if so set
1919    errno to EDOM.  */
1920
1921 static void
1922 expand_errno_check (tree exp, rtx target)
1923 {
1924   rtx lab = gen_label_rtx ();
1925
1926   /* Test the result; if it is NaN, set errno=EDOM because
1927      the argument was not in the domain.  */
1928   do_compare_rtx_and_jump (target, target, EQ, 0, GET_MODE (target),
1929                            NULL_RTX, NULL_RTX, lab,
1930                            /* The jump is very likely.  */
1931                            REG_BR_PROB_BASE - (REG_BR_PROB_BASE / 2000 - 1));
1932
1933 #ifdef TARGET_EDOM
1934   /* If this built-in doesn't throw an exception, set errno directly.  */
1935   if (TREE_NOTHROW (TREE_OPERAND (CALL_EXPR_FN (exp), 0)))
1936     {
1937 #ifdef GEN_ERRNO_RTX
1938       rtx errno_rtx = GEN_ERRNO_RTX;
1939 #else
1940       rtx errno_rtx
1941           = gen_rtx_MEM (word_mode, gen_rtx_SYMBOL_REF (Pmode, "errno"));
1942 #endif
1943       emit_move_insn (errno_rtx, GEN_INT (TARGET_EDOM));
1944       emit_label (lab);
1945       return;
1946     }
1947 #endif
1948
1949   /* Make sure the library call isn't expanded as a tail call.  */
1950   CALL_EXPR_TAILCALL (exp) = 0;
1951
1952   /* We can't set errno=EDOM directly; let the library call do it.
1953      Pop the arguments right away in case the call gets deleted.  */
1954   NO_DEFER_POP;
1955   expand_call (exp, target, 0);
1956   OK_DEFER_POP;
1957   emit_label (lab);
1958 }
1959
1960 /* Expand a call to one of the builtin math functions (sqrt, exp, or log).
1961    Return NULL_RTX if a normal call should be emitted rather than expanding
1962    the function in-line.  EXP is the expression that is a call to the builtin
1963    function; if convenient, the result should be placed in TARGET.
1964    SUBTARGET may be used as the target for computing one of EXP's operands.  */
1965
1966 static rtx
1967 expand_builtin_mathfn (tree exp, rtx target, rtx subtarget)
1968 {
1969   optab builtin_optab;
1970   rtx op0, insns;
1971   tree fndecl = get_callee_fndecl (exp);
1972   enum machine_mode mode;
1973   bool errno_set = false;
1974   tree arg;
1975
1976   if (!validate_arglist (exp, REAL_TYPE, VOID_TYPE))
1977     return NULL_RTX;
1978
1979   arg = CALL_EXPR_ARG (exp, 0);
1980
1981   switch (DECL_FUNCTION_CODE (fndecl))
1982     {
1983     CASE_FLT_FN (BUILT_IN_SQRT):
1984       errno_set = ! tree_expr_nonnegative_p (arg);
1985       builtin_optab = sqrt_optab;
1986       break;
1987     CASE_FLT_FN (BUILT_IN_EXP):
1988       errno_set = true; builtin_optab = exp_optab; break;
1989     CASE_FLT_FN (BUILT_IN_EXP10):
1990     CASE_FLT_FN (BUILT_IN_POW10):
1991       errno_set = true; builtin_optab = exp10_optab; break;
1992     CASE_FLT_FN (BUILT_IN_EXP2):
1993       errno_set = true; builtin_optab = exp2_optab; break;
1994     CASE_FLT_FN (BUILT_IN_EXPM1):
1995       errno_set = true; builtin_optab = expm1_optab; break;
1996     CASE_FLT_FN (BUILT_IN_LOGB):
1997       errno_set = true; builtin_optab = logb_optab; break;
1998     CASE_FLT_FN (BUILT_IN_LOG):
1999       errno_set = true; builtin_optab = log_optab; break;
2000     CASE_FLT_FN (BUILT_IN_LOG10):
2001       errno_set = true; builtin_optab = log10_optab; break;
2002     CASE_FLT_FN (BUILT_IN_LOG2):
2003       errno_set = true; builtin_optab = log2_optab; break;
2004     CASE_FLT_FN (BUILT_IN_LOG1P):
2005       errno_set = true; builtin_optab = log1p_optab; break;
2006     CASE_FLT_FN (BUILT_IN_ASIN):
2007       builtin_optab = asin_optab; break;
2008     CASE_FLT_FN (BUILT_IN_ACOS):
2009       builtin_optab = acos_optab; break;
2010     CASE_FLT_FN (BUILT_IN_TAN):
2011       builtin_optab = tan_optab; break;
2012     CASE_FLT_FN (BUILT_IN_ATAN):
2013       builtin_optab = atan_optab; break;
2014     CASE_FLT_FN (BUILT_IN_FLOOR):
2015       builtin_optab = floor_optab; break;
2016     CASE_FLT_FN (BUILT_IN_CEIL):
2017       builtin_optab = ceil_optab; break;
2018     CASE_FLT_FN (BUILT_IN_TRUNC):
2019       builtin_optab = btrunc_optab; break;
2020     CASE_FLT_FN (BUILT_IN_ROUND):
2021       builtin_optab = round_optab; break;
2022     CASE_FLT_FN (BUILT_IN_NEARBYINT):
2023       builtin_optab = nearbyint_optab;
2024       if (flag_trapping_math)
2025         break;
2026       /* Else fallthrough and expand as rint.  */
2027     CASE_FLT_FN (BUILT_IN_RINT):
2028       builtin_optab = rint_optab; break;
2029     CASE_FLT_FN (BUILT_IN_SIGNIFICAND):
2030       builtin_optab = significand_optab; break;
2031     default:
2032       gcc_unreachable ();
2033     }
2034
2035   /* Make a suitable register to place result in.  */
2036   mode = TYPE_MODE (TREE_TYPE (exp));
2037
2038   if (! flag_errno_math || ! HONOR_NANS (mode))
2039     errno_set = false;
2040
2041   /* Before working hard, check whether the instruction is available.  */
2042   if (optab_handler (builtin_optab, mode) != CODE_FOR_nothing)
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   /* Always stabilize the argument list.  */
2153   CALL_EXPR_ARG (exp, 0) = arg0 = builtin_save_expr (arg0);
2154   CALL_EXPR_ARG (exp, 1) = arg1 = builtin_save_expr (arg1);
2155
2156   op0 = expand_expr (arg0, subtarget, VOIDmode, EXPAND_NORMAL);
2157   op1 = expand_normal (arg1);
2158
2159   start_sequence ();
2160
2161   /* Compute into TARGET.
2162      Set TARGET to wherever the result comes back.  */
2163   target = expand_binop (mode, builtin_optab, op0, op1,
2164                          target, 0, OPTAB_DIRECT);
2165
2166   /* If we were unable to expand via the builtin, stop the sequence
2167      (without outputting the insns) and call to the library function
2168      with the stabilized argument list.  */
2169   if (target == 0)
2170     {
2171       end_sequence ();
2172       return expand_call (exp, target, target == const0_rtx);
2173     }
2174
2175   if (errno_set)
2176     expand_errno_check (exp, target);
2177
2178   /* Output the entire sequence.  */
2179   insns = get_insns ();
2180   end_sequence ();
2181   emit_insn (insns);
2182
2183   return target;
2184 }
2185
2186 /* Expand a call to the builtin trinary math functions (fma).
2187    Return NULL_RTX if a normal call should be emitted rather than expanding the
2188    function in-line.  EXP is the expression that is a call to the builtin
2189    function; if convenient, the result should be placed in TARGET.
2190    SUBTARGET may be used as the target for computing one of EXP's
2191    operands.  */
2192
2193 static rtx
2194 expand_builtin_mathfn_ternary (tree exp, rtx target, rtx subtarget)
2195 {
2196   optab builtin_optab;
2197   rtx op0, op1, op2, insns;
2198   tree fndecl = get_callee_fndecl (exp);
2199   tree arg0, arg1, arg2;
2200   enum machine_mode mode;
2201
2202   if (!validate_arglist (exp, REAL_TYPE, REAL_TYPE, REAL_TYPE, VOID_TYPE))
2203     return NULL_RTX;
2204
2205   arg0 = CALL_EXPR_ARG (exp, 0);
2206   arg1 = CALL_EXPR_ARG (exp, 1);
2207   arg2 = CALL_EXPR_ARG (exp, 2);
2208
2209   switch (DECL_FUNCTION_CODE (fndecl))
2210     {
2211     CASE_FLT_FN (BUILT_IN_FMA):
2212       builtin_optab = fma_optab; break;
2213     default:
2214       gcc_unreachable ();
2215     }
2216
2217   /* Make a suitable register to place result in.  */
2218   mode = TYPE_MODE (TREE_TYPE (exp));
2219
2220   /* Before working hard, check whether the instruction is available.  */
2221   if (optab_handler (builtin_optab, mode) == CODE_FOR_nothing)
2222     return NULL_RTX;
2223
2224   target = gen_reg_rtx (mode);
2225
2226   /* Always stabilize the argument list.  */
2227   CALL_EXPR_ARG (exp, 0) = arg0 = builtin_save_expr (arg0);
2228   CALL_EXPR_ARG (exp, 1) = arg1 = builtin_save_expr (arg1);
2229   CALL_EXPR_ARG (exp, 2) = arg2 = builtin_save_expr (arg2);
2230
2231   op0 = expand_expr (arg0, subtarget, VOIDmode, EXPAND_NORMAL);
2232   op1 = expand_normal (arg1);
2233   op2 = expand_normal (arg2);
2234
2235   start_sequence ();
2236
2237   /* Compute into TARGET.
2238      Set TARGET to wherever the result comes back.  */
2239   target = expand_ternary_op (mode, builtin_optab, op0, op1, op2,
2240                               target, 0);
2241
2242   /* If we were unable to expand via the builtin, stop the sequence
2243      (without outputting the insns) and call to the library function
2244      with the stabilized argument list.  */
2245   if (target == 0)
2246     {
2247       end_sequence ();
2248       return expand_call (exp, target, target == const0_rtx);
2249     }
2250
2251   /* Output the entire sequence.  */
2252   insns = get_insns ();
2253   end_sequence ();
2254   emit_insn (insns);
2255
2256   return target;
2257 }
2258
2259 /* Expand a call to the builtin sin and cos math functions.
2260    Return NULL_RTX if a normal call should be emitted rather than expanding the
2261    function in-line.  EXP is the expression that is a call to the builtin
2262    function; if convenient, the result should be placed in TARGET.
2263    SUBTARGET may be used as the target for computing one of EXP's
2264    operands.  */
2265
2266 static rtx
2267 expand_builtin_mathfn_3 (tree exp, rtx target, rtx subtarget)
2268 {
2269   optab builtin_optab;
2270   rtx op0, insns;
2271   tree fndecl = get_callee_fndecl (exp);
2272   enum machine_mode mode;
2273   tree arg;
2274
2275   if (!validate_arglist (exp, REAL_TYPE, VOID_TYPE))
2276     return NULL_RTX;
2277
2278   arg = CALL_EXPR_ARG (exp, 0);
2279
2280   switch (DECL_FUNCTION_CODE (fndecl))
2281     {
2282     CASE_FLT_FN (BUILT_IN_SIN):
2283     CASE_FLT_FN (BUILT_IN_COS):
2284       builtin_optab = sincos_optab; break;
2285     default:
2286       gcc_unreachable ();
2287     }
2288
2289   /* Make a suitable register to place result in.  */
2290   mode = TYPE_MODE (TREE_TYPE (exp));
2291
2292   /* Check if sincos insn is available, otherwise fallback
2293      to sin or cos insn.  */
2294   if (optab_handler (builtin_optab, mode) == CODE_FOR_nothing)
2295     switch (DECL_FUNCTION_CODE (fndecl))
2296       {
2297       CASE_FLT_FN (BUILT_IN_SIN):
2298         builtin_optab = sin_optab; break;
2299       CASE_FLT_FN (BUILT_IN_COS):
2300         builtin_optab = cos_optab; break;
2301       default:
2302         gcc_unreachable ();
2303       }
2304
2305   /* Before working hard, check whether the instruction is available.  */
2306   if (optab_handler (builtin_optab, mode) != CODE_FOR_nothing)
2307     {
2308       target = gen_reg_rtx (mode);
2309
2310       /* Wrap the computation of the argument in a SAVE_EXPR, as we may
2311          need to expand the argument again.  This way, we will not perform
2312          side-effects more the once.  */
2313       CALL_EXPR_ARG (exp, 0) = arg = builtin_save_expr (arg);
2314
2315       op0 = expand_expr (arg, subtarget, VOIDmode, EXPAND_NORMAL);
2316
2317       start_sequence ();
2318
2319       /* Compute into TARGET.
2320          Set TARGET to wherever the result comes back.  */
2321       if (builtin_optab == sincos_optab)
2322         {
2323           int result;
2324
2325           switch (DECL_FUNCTION_CODE (fndecl))
2326             {
2327             CASE_FLT_FN (BUILT_IN_SIN):
2328               result = expand_twoval_unop (builtin_optab, op0, 0, target, 0);
2329               break;
2330             CASE_FLT_FN (BUILT_IN_COS):
2331               result = expand_twoval_unop (builtin_optab, op0, target, 0, 0);
2332               break;
2333             default:
2334               gcc_unreachable ();
2335             }
2336           gcc_assert (result);
2337         }
2338       else
2339         {
2340           target = expand_unop (mode, builtin_optab, op0, target, 0);
2341         }
2342
2343       if (target != 0)
2344         {
2345           /* Output the entire sequence.  */
2346           insns = get_insns ();
2347           end_sequence ();
2348           emit_insn (insns);
2349           return target;
2350         }
2351
2352       /* If we were unable to expand via the builtin, stop the sequence
2353          (without outputting the insns) and call to the library function
2354          with the stabilized argument list.  */
2355       end_sequence ();
2356     }
2357
2358   target = expand_call (exp, target, target == const0_rtx);
2359
2360   return target;
2361 }
2362
2363 /* Given an interclass math builtin decl FNDECL and it's argument ARG
2364    return an RTL instruction code that implements the functionality.
2365    If that isn't possible or available return CODE_FOR_nothing.  */
2366
2367 static enum insn_code
2368 interclass_mathfn_icode (tree arg, tree fndecl)
2369 {
2370   bool errno_set = false;
2371   optab builtin_optab = 0;
2372   enum machine_mode mode;
2373
2374   switch (DECL_FUNCTION_CODE (fndecl))
2375     {
2376     CASE_FLT_FN (BUILT_IN_ILOGB):
2377       errno_set = true; builtin_optab = ilogb_optab; break;
2378     CASE_FLT_FN (BUILT_IN_ISINF):
2379       builtin_optab = isinf_optab; break;
2380     case BUILT_IN_ISNORMAL:
2381     case BUILT_IN_ISFINITE:
2382     CASE_FLT_FN (BUILT_IN_FINITE):
2383     case BUILT_IN_FINITED32:
2384     case BUILT_IN_FINITED64:
2385     case BUILT_IN_FINITED128:
2386     case BUILT_IN_ISINFD32:
2387     case BUILT_IN_ISINFD64:
2388     case BUILT_IN_ISINFD128:
2389       /* These builtins have no optabs (yet).  */
2390       break;
2391     default:
2392       gcc_unreachable ();
2393     }
2394
2395   /* There's no easy way to detect the case we need to set EDOM.  */
2396   if (flag_errno_math && errno_set)
2397     return CODE_FOR_nothing;
2398
2399   /* Optab mode depends on the mode of the input argument.  */
2400   mode = TYPE_MODE (TREE_TYPE (arg));
2401
2402   if (builtin_optab)
2403     return optab_handler (builtin_optab, mode);
2404   return CODE_FOR_nothing;
2405 }
2406
2407 /* Expand a call to one of the builtin math functions that operate on
2408    floating point argument and output an integer result (ilogb, isinf,
2409    isnan, etc).
2410    Return 0 if a normal call should be emitted rather than expanding the
2411    function in-line.  EXP is the expression that is a call to the builtin
2412    function; if convenient, the result should be placed in TARGET.  */
2413
2414 static rtx
2415 expand_builtin_interclass_mathfn (tree exp, rtx target)
2416 {
2417   enum insn_code icode = CODE_FOR_nothing;
2418   rtx op0;
2419   tree fndecl = get_callee_fndecl (exp);
2420   enum machine_mode mode;
2421   tree arg;
2422
2423   if (!validate_arglist (exp, REAL_TYPE, VOID_TYPE))
2424     return NULL_RTX;
2425
2426   arg = CALL_EXPR_ARG (exp, 0);
2427   icode = interclass_mathfn_icode (arg, fndecl);
2428   mode = TYPE_MODE (TREE_TYPE (arg));
2429
2430   if (icode != CODE_FOR_nothing)
2431     {
2432       rtx last = get_last_insn ();
2433       tree orig_arg = arg;
2434       /* Make a suitable register to place result in.  */
2435       if (!target
2436           || GET_MODE (target) != TYPE_MODE (TREE_TYPE (exp))
2437           || !insn_data[icode].operand[0].predicate (target, GET_MODE (target)))
2438          target = gen_reg_rtx (TYPE_MODE (TREE_TYPE (exp)));
2439
2440       gcc_assert (insn_data[icode].operand[0].predicate
2441                   (target, GET_MODE (target)));
2442
2443       /* Wrap the computation of the argument in a SAVE_EXPR, as we may
2444          need to expand the argument again.  This way, we will not perform
2445          side-effects more the once.  */
2446       CALL_EXPR_ARG (exp, 0) = arg = builtin_save_expr (arg);
2447
2448       op0 = expand_expr (arg, NULL_RTX, VOIDmode, EXPAND_NORMAL);
2449
2450       if (mode != GET_MODE (op0))
2451         op0 = convert_to_mode (mode, op0, 0);
2452
2453       /* Compute into TARGET.
2454          Set TARGET to wherever the result comes back.  */
2455       if (maybe_emit_unop_insn (icode, target, op0, UNKNOWN))
2456         return target;
2457       delete_insns_since (last);
2458       CALL_EXPR_ARG (exp, 0) = orig_arg;
2459     }
2460
2461   return NULL_RTX;
2462 }
2463
2464 /* Expand a call to the builtin sincos math function.
2465    Return NULL_RTX if a normal call should be emitted rather than expanding the
2466    function in-line.  EXP is the expression that is a call to the builtin
2467    function.  */
2468
2469 static rtx
2470 expand_builtin_sincos (tree exp)
2471 {
2472   rtx op0, op1, op2, target1, target2;
2473   enum machine_mode mode;
2474   tree arg, sinp, cosp;
2475   int result;
2476   location_t loc = EXPR_LOCATION (exp);
2477   tree alias_type, alias_off;
2478
2479   if (!validate_arglist (exp, REAL_TYPE,
2480                          POINTER_TYPE, POINTER_TYPE, VOID_TYPE))
2481     return NULL_RTX;
2482
2483   arg = CALL_EXPR_ARG (exp, 0);
2484   sinp = CALL_EXPR_ARG (exp, 1);
2485   cosp = CALL_EXPR_ARG (exp, 2);
2486
2487   /* Make a suitable register to place result in.  */
2488   mode = TYPE_MODE (TREE_TYPE (arg));
2489
2490   /* Check if sincos insn is available, otherwise emit the call.  */
2491   if (optab_handler (sincos_optab, mode) == CODE_FOR_nothing)
2492     return NULL_RTX;
2493
2494   target1 = gen_reg_rtx (mode);
2495   target2 = gen_reg_rtx (mode);
2496
2497   op0 = expand_normal (arg);
2498   alias_type = build_pointer_type_for_mode (TREE_TYPE (arg), ptr_mode, true);
2499   alias_off = build_int_cst (alias_type, 0);
2500   op1 = expand_normal (fold_build2_loc (loc, MEM_REF, TREE_TYPE (arg),
2501                                         sinp, alias_off));
2502   op2 = expand_normal (fold_build2_loc (loc, MEM_REF, TREE_TYPE (arg),
2503                                         cosp, alias_off));
2504
2505   /* Compute into target1 and target2.
2506      Set TARGET to wherever the result comes back.  */
2507   result = expand_twoval_unop (sincos_optab, op0, target2, target1, 0);
2508   gcc_assert (result);
2509
2510   /* Move target1 and target2 to the memory locations indicated
2511      by op1 and op2.  */
2512   emit_move_insn (op1, target1);
2513   emit_move_insn (op2, target2);
2514
2515   return const0_rtx;
2516 }
2517
2518 /* Expand a call to the internal cexpi builtin to the sincos math function.
2519    EXP is the expression that is a call to the builtin function; if convenient,
2520    the result should be placed in TARGET.  */
2521
2522 static rtx
2523 expand_builtin_cexpi (tree exp, rtx target)
2524 {
2525   tree fndecl = get_callee_fndecl (exp);
2526   tree arg, type;
2527   enum machine_mode mode;
2528   rtx op0, op1, op2;
2529   location_t loc = EXPR_LOCATION (exp);
2530
2531   if (!validate_arglist (exp, REAL_TYPE, VOID_TYPE))
2532     return NULL_RTX;
2533
2534   arg = CALL_EXPR_ARG (exp, 0);
2535   type = TREE_TYPE (arg);
2536   mode = TYPE_MODE (TREE_TYPE (arg));
2537
2538   /* Try expanding via a sincos optab, fall back to emitting a libcall
2539      to sincos or cexp.  We are sure we have sincos or cexp because cexpi
2540      is only generated from sincos, cexp or if we have either of them.  */
2541   if (optab_handler (sincos_optab, mode) != CODE_FOR_nothing)
2542     {
2543       op1 = gen_reg_rtx (mode);
2544       op2 = gen_reg_rtx (mode);
2545
2546       op0 = expand_expr (arg, NULL_RTX, VOIDmode, EXPAND_NORMAL);
2547
2548       /* Compute into op1 and op2.  */
2549       expand_twoval_unop (sincos_optab, op0, op2, op1, 0);
2550     }
2551   else if (TARGET_HAS_SINCOS)
2552     {
2553       tree call, fn = NULL_TREE;
2554       tree top1, top2;
2555       rtx op1a, op2a;
2556
2557       if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPIF)
2558         fn = built_in_decls[BUILT_IN_SINCOSF];
2559       else if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPI)
2560         fn = built_in_decls[BUILT_IN_SINCOS];
2561       else if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPIL)
2562         fn = built_in_decls[BUILT_IN_SINCOSL];
2563       else
2564         gcc_unreachable ();
2565
2566       op1 = assign_temp (TREE_TYPE (arg), 0, 1, 1);
2567       op2 = assign_temp (TREE_TYPE (arg), 0, 1, 1);
2568       op1a = copy_to_mode_reg (Pmode, XEXP (op1, 0));
2569       op2a = copy_to_mode_reg (Pmode, XEXP (op2, 0));
2570       top1 = make_tree (build_pointer_type (TREE_TYPE (arg)), op1a);
2571       top2 = make_tree (build_pointer_type (TREE_TYPE (arg)), op2a);
2572
2573       /* Make sure not to fold the sincos call again.  */
2574       call = build1 (ADDR_EXPR, build_pointer_type (TREE_TYPE (fn)), fn);
2575       expand_normal (build_call_nary (TREE_TYPE (TREE_TYPE (fn)),
2576                                       call, 3, arg, top1, top2));
2577     }
2578   else
2579     {
2580       tree call, fn = NULL_TREE, narg;
2581       tree ctype = build_complex_type (type);
2582
2583       if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPIF)
2584         fn = built_in_decls[BUILT_IN_CEXPF];
2585       else if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPI)
2586         fn = built_in_decls[BUILT_IN_CEXP];
2587       else if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPIL)
2588         fn = built_in_decls[BUILT_IN_CEXPL];
2589       else
2590         gcc_unreachable ();
2591
2592       /* If we don't have a decl for cexp create one.  This is the
2593          friendliest fallback if the user calls __builtin_cexpi
2594          without full target C99 function support.  */
2595       if (fn == NULL_TREE)
2596         {
2597           tree fntype;
2598           const char *name = NULL;
2599
2600           if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPIF)
2601             name = "cexpf";
2602           else if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPI)
2603             name = "cexp";
2604           else if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPIL)
2605             name = "cexpl";
2606
2607           fntype = build_function_type_list (ctype, ctype, NULL_TREE);
2608           fn = build_fn_decl (name, fntype);
2609         }
2610
2611       narg = fold_build2_loc (loc, COMPLEX_EXPR, ctype,
2612                           build_real (type, dconst0), arg);
2613
2614       /* Make sure not to fold the cexp call again.  */
2615       call = build1 (ADDR_EXPR, build_pointer_type (TREE_TYPE (fn)), fn);
2616       return expand_expr (build_call_nary (ctype, call, 1, narg),
2617                           target, VOIDmode, EXPAND_NORMAL);
2618     }
2619
2620   /* Now build the proper return type.  */
2621   return expand_expr (build2 (COMPLEX_EXPR, build_complex_type (type),
2622                               make_tree (TREE_TYPE (arg), op2),
2623                               make_tree (TREE_TYPE (arg), op1)),
2624                       target, VOIDmode, EXPAND_NORMAL);
2625 }
2626
2627 /* Conveniently construct a function call expression.  FNDECL names the
2628    function to be called, N is the number of arguments, and the "..."
2629    parameters are the argument expressions.  Unlike build_call_exr
2630    this doesn't fold the call, hence it will always return a CALL_EXPR.  */
2631
2632 static tree
2633 build_call_nofold_loc (location_t loc, tree fndecl, int n, ...)
2634 {
2635   va_list ap;
2636   tree fntype = TREE_TYPE (fndecl);
2637   tree fn = build1 (ADDR_EXPR, build_pointer_type (fntype), fndecl);
2638
2639   va_start (ap, n);
2640   fn = build_call_valist (TREE_TYPE (fntype), fn, n, ap);
2641   va_end (ap);
2642   SET_EXPR_LOCATION (fn, loc);
2643   return fn;
2644 }
2645
2646 /* Expand a call to one of the builtin rounding functions gcc defines
2647    as an extension (lfloor and lceil).  As these are gcc extensions we
2648    do not need to worry about setting errno to EDOM.
2649    If expanding via optab fails, lower expression to (int)(floor(x)).
2650    EXP is the expression that is a call to the builtin function;
2651    if convenient, the result should be placed in TARGET.  */
2652
2653 static rtx
2654 expand_builtin_int_roundingfn (tree exp, rtx target)
2655 {
2656   convert_optab builtin_optab;
2657   rtx op0, insns, tmp;
2658   tree fndecl = get_callee_fndecl (exp);
2659   enum built_in_function fallback_fn;
2660   tree fallback_fndecl;
2661   enum machine_mode mode;
2662   tree arg;
2663
2664   if (!validate_arglist (exp, REAL_TYPE, VOID_TYPE))
2665     gcc_unreachable ();
2666
2667   arg = CALL_EXPR_ARG (exp, 0);
2668
2669   switch (DECL_FUNCTION_CODE (fndecl))
2670     {
2671     CASE_FLT_FN (BUILT_IN_LCEIL):
2672     CASE_FLT_FN (BUILT_IN_LLCEIL):
2673       builtin_optab = lceil_optab;
2674       fallback_fn = BUILT_IN_CEIL;
2675       break;
2676
2677     CASE_FLT_FN (BUILT_IN_LFLOOR):
2678     CASE_FLT_FN (BUILT_IN_LLFLOOR):
2679       builtin_optab = lfloor_optab;
2680       fallback_fn = BUILT_IN_FLOOR;
2681       break;
2682
2683     default:
2684       gcc_unreachable ();
2685     }
2686
2687   /* Make a suitable register to place result in.  */
2688   mode = TYPE_MODE (TREE_TYPE (exp));
2689
2690   target = gen_reg_rtx (mode);
2691
2692   /* Wrap the computation of the argument in a SAVE_EXPR, as we may
2693      need to expand the argument again.  This way, we will not perform
2694      side-effects more the once.  */
2695   CALL_EXPR_ARG (exp, 0) = arg = builtin_save_expr (arg);
2696
2697   op0 = expand_expr (arg, NULL, VOIDmode, EXPAND_NORMAL);
2698
2699   start_sequence ();
2700
2701   /* Compute into TARGET.  */
2702   if (expand_sfix_optab (target, op0, builtin_optab))
2703     {
2704       /* Output the entire sequence.  */
2705       insns = get_insns ();
2706       end_sequence ();
2707       emit_insn (insns);
2708       return target;
2709     }
2710
2711   /* If we were unable to expand via the builtin, stop the sequence
2712      (without outputting the insns).  */
2713   end_sequence ();
2714
2715   /* Fall back to floating point rounding optab.  */
2716   fallback_fndecl = mathfn_built_in (TREE_TYPE (arg), fallback_fn);
2717
2718   /* For non-C99 targets we may end up without a fallback fndecl here
2719      if the user called __builtin_lfloor directly.  In this case emit
2720      a call to the floor/ceil variants nevertheless.  This should result
2721      in the best user experience for not full C99 targets.  */
2722   if (fallback_fndecl == NULL_TREE)
2723     {
2724       tree fntype;
2725       const char *name = NULL;
2726
2727       switch (DECL_FUNCTION_CODE (fndecl))
2728         {
2729         case BUILT_IN_LCEIL:
2730         case BUILT_IN_LLCEIL:
2731           name = "ceil";
2732           break;
2733         case BUILT_IN_LCEILF:
2734         case BUILT_IN_LLCEILF:
2735           name = "ceilf";
2736           break;
2737         case BUILT_IN_LCEILL:
2738         case BUILT_IN_LLCEILL:
2739           name = "ceill";
2740           break;
2741         case BUILT_IN_LFLOOR:
2742         case BUILT_IN_LLFLOOR:
2743           name = "floor";
2744           break;
2745         case BUILT_IN_LFLOORF:
2746         case BUILT_IN_LLFLOORF:
2747           name = "floorf";
2748           break;
2749         case BUILT_IN_LFLOORL:
2750         case BUILT_IN_LLFLOORL:
2751           name = "floorl";
2752           break;
2753         default:
2754           gcc_unreachable ();
2755         }
2756
2757       fntype = build_function_type_list (TREE_TYPE (arg),
2758                                          TREE_TYPE (arg), NULL_TREE);
2759       fallback_fndecl = build_fn_decl (name, fntype);
2760     }
2761
2762   exp = build_call_nofold_loc (EXPR_LOCATION (exp), fallback_fndecl, 1, arg);
2763
2764   tmp = expand_normal (exp);
2765
2766   /* Truncate the result of floating point optab to integer
2767      via expand_fix ().  */
2768   target = gen_reg_rtx (mode);
2769   expand_fix (target, tmp, 0);
2770
2771   return target;
2772 }
2773
2774 /* Expand a call to one of the builtin math functions doing integer
2775    conversion (lrint).
2776    Return 0 if a normal call should be emitted rather than expanding the
2777    function in-line.  EXP is the expression that is a call to the builtin
2778    function; if convenient, the result should be placed in TARGET.  */
2779
2780 static rtx
2781 expand_builtin_int_roundingfn_2 (tree exp, rtx target)
2782 {
2783   convert_optab builtin_optab;
2784   rtx op0, insns;
2785   tree fndecl = get_callee_fndecl (exp);
2786   tree arg;
2787   enum machine_mode mode;
2788
2789   /* There's no easy way to detect the case we need to set EDOM.  */
2790   if (flag_errno_math)
2791     return NULL_RTX;
2792
2793   if (!validate_arglist (exp, REAL_TYPE, VOID_TYPE))
2794      gcc_unreachable ();
2795
2796   arg = CALL_EXPR_ARG (exp, 0);
2797
2798   switch (DECL_FUNCTION_CODE (fndecl))
2799     {
2800     CASE_FLT_FN (BUILT_IN_LRINT):
2801     CASE_FLT_FN (BUILT_IN_LLRINT):
2802       builtin_optab = lrint_optab; break;
2803     CASE_FLT_FN (BUILT_IN_LROUND):
2804     CASE_FLT_FN (BUILT_IN_LLROUND):
2805       builtin_optab = lround_optab; break;
2806     default:
2807       gcc_unreachable ();
2808     }
2809
2810   /* Make a suitable register to place result in.  */
2811   mode = TYPE_MODE (TREE_TYPE (exp));
2812
2813   target = gen_reg_rtx (mode);
2814
2815   /* Wrap the computation of the argument in a SAVE_EXPR, as we may
2816      need to expand the argument again.  This way, we will not perform
2817      side-effects more the once.  */
2818   CALL_EXPR_ARG (exp, 0) = arg = builtin_save_expr (arg);
2819
2820   op0 = expand_expr (arg, NULL, VOIDmode, EXPAND_NORMAL);
2821
2822   start_sequence ();
2823
2824   if (expand_sfix_optab (target, op0, builtin_optab))
2825     {
2826       /* Output the entire sequence.  */
2827       insns = get_insns ();
2828       end_sequence ();
2829       emit_insn (insns);
2830       return target;
2831     }
2832
2833   /* If we were unable to expand via the builtin, stop the sequence
2834      (without outputting the insns) and call to the library function
2835      with the stabilized argument list.  */
2836   end_sequence ();
2837
2838   target = expand_call (exp, target, target == const0_rtx);
2839
2840   return target;
2841 }
2842
2843 /* To evaluate powi(x,n), the floating point value x raised to the
2844    constant integer exponent n, we use a hybrid algorithm that
2845    combines the "window method" with look-up tables.  For an
2846    introduction to exponentiation algorithms and "addition chains",
2847    see section 4.6.3, "Evaluation of Powers" of Donald E. Knuth,
2848    "Seminumerical Algorithms", Vol. 2, "The Art of Computer Programming",
2849    3rd Edition, 1998, and Daniel M. Gordon, "A Survey of Fast Exponentiation
2850    Methods", Journal of Algorithms, Vol. 27, pp. 129-146, 1998.  */
2851
2852 /* Provide a default value for POWI_MAX_MULTS, the maximum number of
2853    multiplications to inline before calling the system library's pow
2854    function.  powi(x,n) requires at worst 2*bits(n)-2 multiplications,
2855    so this default never requires calling pow, powf or powl.  */
2856
2857 #ifndef POWI_MAX_MULTS
2858 #define POWI_MAX_MULTS  (2*HOST_BITS_PER_WIDE_INT-2)
2859 #endif
2860
2861 /* The size of the "optimal power tree" lookup table.  All
2862    exponents less than this value are simply looked up in the
2863    powi_table below.  This threshold is also used to size the
2864    cache of pseudo registers that hold intermediate results.  */
2865 #define POWI_TABLE_SIZE 256
2866
2867 /* The size, in bits of the window, used in the "window method"
2868    exponentiation algorithm.  This is equivalent to a radix of
2869    (1<<POWI_WINDOW_SIZE) in the corresponding "m-ary method".  */
2870 #define POWI_WINDOW_SIZE 3
2871
2872 /* The following table is an efficient representation of an
2873    "optimal power tree".  For each value, i, the corresponding
2874    value, j, in the table states than an optimal evaluation
2875    sequence for calculating pow(x,i) can be found by evaluating
2876    pow(x,j)*pow(x,i-j).  An optimal power tree for the first
2877    100 integers is given in Knuth's "Seminumerical algorithms".  */
2878
2879 static const unsigned char powi_table[POWI_TABLE_SIZE] =
2880   {
2881       0,   1,   1,   2,   2,   3,   3,   4,  /*   0 -   7 */
2882       4,   6,   5,   6,   6,  10,   7,   9,  /*   8 -  15 */
2883       8,  16,   9,  16,  10,  12,  11,  13,  /*  16 -  23 */
2884      12,  17,  13,  18,  14,  24,  15,  26,  /*  24 -  31 */
2885      16,  17,  17,  19,  18,  33,  19,  26,  /*  32 -  39 */
2886      20,  25,  21,  40,  22,  27,  23,  44,  /*  40 -  47 */
2887      24,  32,  25,  34,  26,  29,  27,  44,  /*  48 -  55 */
2888      28,  31,  29,  34,  30,  60,  31,  36,  /*  56 -  63 */
2889      32,  64,  33,  34,  34,  46,  35,  37,  /*  64 -  71 */
2890      36,  65,  37,  50,  38,  48,  39,  69,  /*  72 -  79 */
2891      40,  49,  41,  43,  42,  51,  43,  58,  /*  80 -  87 */
2892      44,  64,  45,  47,  46,  59,  47,  76,  /*  88 -  95 */
2893      48,  65,  49,  66,  50,  67,  51,  66,  /*  96 - 103 */
2894      52,  70,  53,  74,  54, 104,  55,  74,  /* 104 - 111 */
2895      56,  64,  57,  69,  58,  78,  59,  68,  /* 112 - 119 */
2896      60,  61,  61,  80,  62,  75,  63,  68,  /* 120 - 127 */
2897      64,  65,  65, 128,  66, 129,  67,  90,  /* 128 - 135 */
2898      68,  73,  69, 131,  70,  94,  71,  88,  /* 136 - 143 */
2899      72, 128,  73,  98,  74, 132,  75, 121,  /* 144 - 151 */
2900      76, 102,  77, 124,  78, 132,  79, 106,  /* 152 - 159 */
2901      80,  97,  81, 160,  82,  99,  83, 134,  /* 160 - 167 */
2902      84,  86,  85,  95,  86, 160,  87, 100,  /* 168 - 175 */
2903      88, 113,  89,  98,  90, 107,  91, 122,  /* 176 - 183 */
2904      92, 111,  93, 102,  94, 126,  95, 150,  /* 184 - 191 */
2905      96, 128,  97, 130,  98, 133,  99, 195,  /* 192 - 199 */
2906     100, 128, 101, 123, 102, 164, 103, 138,  /* 200 - 207 */
2907     104, 145, 105, 146, 106, 109, 107, 149,  /* 208 - 215 */
2908     108, 200, 109, 146, 110, 170, 111, 157,  /* 216 - 223 */
2909     112, 128, 113, 130, 114, 182, 115, 132,  /* 224 - 231 */
2910     116, 200, 117, 132, 118, 158, 119, 206,  /* 232 - 239 */
2911     120, 240, 121, 162, 122, 147, 123, 152,  /* 240 - 247 */
2912     124, 166, 125, 214, 126, 138, 127, 153,  /* 248 - 255 */
2913   };
2914
2915
2916 /* Return the number of multiplications required to calculate
2917    powi(x,n) where n is less than POWI_TABLE_SIZE.  This is a
2918    subroutine of powi_cost.  CACHE is an array indicating
2919    which exponents have already been calculated.  */
2920
2921 static int
2922 powi_lookup_cost (unsigned HOST_WIDE_INT n, bool *cache)
2923 {
2924   /* If we've already calculated this exponent, then this evaluation
2925      doesn't require any additional multiplications.  */
2926   if (cache[n])
2927     return 0;
2928
2929   cache[n] = true;
2930   return powi_lookup_cost (n - powi_table[n], cache)
2931          + powi_lookup_cost (powi_table[n], cache) + 1;
2932 }
2933
2934 /* Return the number of multiplications required to calculate
2935    powi(x,n) for an arbitrary x, given the exponent N.  This
2936    function needs to be kept in sync with expand_powi below.  */
2937
2938 static int
2939 powi_cost (HOST_WIDE_INT n)
2940 {
2941   bool cache[POWI_TABLE_SIZE];
2942   unsigned HOST_WIDE_INT digit;
2943   unsigned HOST_WIDE_INT val;
2944   int result;
2945
2946   if (n == 0)
2947     return 0;
2948
2949   /* Ignore the reciprocal when calculating the cost.  */
2950   val = (n < 0) ? -n : n;
2951
2952   /* Initialize the exponent cache.  */
2953   memset (cache, 0, POWI_TABLE_SIZE * sizeof (bool));
2954   cache[1] = true;
2955
2956   result = 0;
2957
2958   while (val >= POWI_TABLE_SIZE)
2959     {
2960       if (val & 1)
2961         {
2962           digit = val & ((1 << POWI_WINDOW_SIZE) - 1);
2963           result += powi_lookup_cost (digit, cache)
2964                     + POWI_WINDOW_SIZE + 1;
2965           val >>= POWI_WINDOW_SIZE;
2966         }
2967       else
2968         {
2969           val >>= 1;
2970           result++;
2971         }
2972     }
2973
2974   return result + powi_lookup_cost (val, cache);
2975 }
2976
2977 /* Recursive subroutine of expand_powi.  This function takes the array,
2978    CACHE, of already calculated exponents and an exponent N and returns
2979    an RTX that corresponds to CACHE[1]**N, as calculated in mode MODE.  */
2980
2981 static rtx
2982 expand_powi_1 (enum machine_mode mode, unsigned HOST_WIDE_INT n, rtx *cache)
2983 {
2984   unsigned HOST_WIDE_INT digit;
2985   rtx target, result;
2986   rtx op0, op1;
2987
2988   if (n < POWI_TABLE_SIZE)
2989     {
2990       if (cache[n])
2991         return cache[n];
2992
2993       target = gen_reg_rtx (mode);
2994       cache[n] = target;
2995
2996       op0 = expand_powi_1 (mode, n - powi_table[n], cache);
2997       op1 = expand_powi_1 (mode, powi_table[n], cache);
2998     }
2999   else if (n & 1)
3000     {
3001       target = gen_reg_rtx (mode);
3002       digit = n & ((1 << POWI_WINDOW_SIZE) - 1);
3003       op0 = expand_powi_1 (mode, n - digit, cache);
3004       op1 = expand_powi_1 (mode, digit, cache);
3005     }
3006   else
3007     {
3008       target = gen_reg_rtx (mode);
3009       op0 = expand_powi_1 (mode, n >> 1, cache);
3010       op1 = op0;
3011     }
3012
3013   result = expand_mult (mode, op0, op1, target, 0);
3014   if (result != target)
3015     emit_move_insn (target, result);
3016   return target;
3017 }
3018
3019 /* Expand the RTL to evaluate powi(x,n) in mode MODE.  X is the
3020    floating point operand in mode MODE, and N is the exponent.  This
3021    function needs to be kept in sync with powi_cost above.  */
3022
3023 static rtx
3024 expand_powi (rtx x, enum machine_mode mode, HOST_WIDE_INT n)
3025 {
3026   rtx cache[POWI_TABLE_SIZE];
3027   rtx result;
3028
3029   if (n == 0)
3030     return CONST1_RTX (mode);
3031
3032   memset (cache, 0, sizeof (cache));
3033   cache[1] = x;
3034
3035   result = expand_powi_1 (mode, (n < 0) ? -n : n, cache);
3036
3037   /* If the original exponent was negative, reciprocate the result.  */
3038   if (n < 0)
3039     result = expand_binop (mode, sdiv_optab, CONST1_RTX (mode),
3040                            result, NULL_RTX, 0, OPTAB_LIB_WIDEN);
3041
3042   return result;
3043 }
3044
3045 /* Fold a builtin function call to pow, powf, or powl into a series of sqrts or
3046    cbrts.  Return NULL_RTX if no simplification can be made or expand the tree
3047    if we can simplify it.  */
3048 static rtx
3049 expand_builtin_pow_root (location_t loc, tree arg0, tree arg1, tree type,
3050                          rtx subtarget)
3051 {
3052   if (TREE_CODE (arg1) == REAL_CST
3053       && !TREE_OVERFLOW (arg1)
3054       && flag_unsafe_math_optimizations)
3055     {
3056       enum machine_mode mode = TYPE_MODE (type);
3057       tree sqrtfn = mathfn_built_in (type, BUILT_IN_SQRT);
3058       tree cbrtfn = mathfn_built_in (type, BUILT_IN_CBRT);
3059       REAL_VALUE_TYPE c = TREE_REAL_CST (arg1);
3060       tree op = NULL_TREE;
3061
3062       if (sqrtfn)
3063         {
3064           /* Optimize pow (x, 0.5) into sqrt.  */
3065           if (REAL_VALUES_EQUAL (c, dconsthalf))
3066             op = build_call_nofold_loc (loc, sqrtfn, 1, arg0);
3067
3068           else
3069             {
3070               REAL_VALUE_TYPE dconst1_4 = dconst1;
3071               REAL_VALUE_TYPE dconst3_4;
3072               SET_REAL_EXP (&dconst1_4, REAL_EXP (&dconst1_4) - 2);
3073
3074               real_from_integer (&dconst3_4, VOIDmode, 3, 0, 0);
3075               SET_REAL_EXP (&dconst3_4, REAL_EXP (&dconst3_4) - 2);
3076
3077               /* Optimize pow (x, 0.25) into sqrt (sqrt (x)).  Assume on most
3078                  machines that a builtin sqrt instruction is smaller than a
3079                  call to pow with 0.25, so do this optimization even if
3080                  -Os.  */
3081               if (REAL_VALUES_EQUAL (c, dconst1_4))
3082                 {
3083                   op = build_call_nofold_loc (loc, sqrtfn, 1, arg0);
3084                   op = build_call_nofold_loc (loc, sqrtfn, 1, op);
3085                 }
3086
3087               /* Optimize pow (x, 0.75) = sqrt (x) * sqrt (sqrt (x)) unless we
3088                  are optimizing for space.  */
3089               else if (optimize_insn_for_speed_p ()
3090                        && !TREE_SIDE_EFFECTS (arg0)
3091                        && REAL_VALUES_EQUAL (c, dconst3_4))
3092                 {
3093                   tree sqrt1 = build_call_expr_loc (loc, sqrtfn, 1, arg0);
3094                   tree sqrt2 = builtin_save_expr (sqrt1);
3095                   tree sqrt3 = build_call_expr_loc (loc, sqrtfn, 1, sqrt1);
3096                   op = fold_build2_loc (loc, MULT_EXPR, type, sqrt2, sqrt3);
3097                 }
3098             }
3099         }
3100
3101       /* Check whether we can do cbrt insstead of pow (x, 1./3.) and
3102          cbrt/sqrts instead of pow (x, 1./6.).  */
3103       if (cbrtfn && ! op
3104           && (tree_expr_nonnegative_p (arg0) || !HONOR_NANS (mode)))
3105         {
3106           /* First try 1/3.  */
3107           REAL_VALUE_TYPE dconst1_3
3108             = real_value_truncate (mode, dconst_third ());
3109
3110           if (REAL_VALUES_EQUAL (c, dconst1_3))
3111             op = build_call_nofold_loc (loc, cbrtfn, 1, arg0);
3112
3113               /* Now try 1/6.  */
3114           else if (optimize_insn_for_speed_p ())
3115             {
3116               REAL_VALUE_TYPE dconst1_6 = dconst1_3;
3117               SET_REAL_EXP (&dconst1_6, REAL_EXP (&dconst1_6) - 1);
3118
3119               if (REAL_VALUES_EQUAL (c, dconst1_6))
3120                 {
3121                   op = build_call_nofold_loc (loc, sqrtfn, 1, arg0);
3122                   op = build_call_nofold_loc (loc, cbrtfn, 1, op);
3123                 }
3124             }
3125         }
3126
3127       if (op)
3128         return expand_expr (op, subtarget, mode, EXPAND_NORMAL);
3129     }
3130
3131   return NULL_RTX;
3132 }
3133
3134 /* Expand a call to the pow built-in mathematical function.  Return NULL_RTX if
3135    a normal call should be emitted rather than expanding the function
3136    in-line.  EXP is the expression that is a call to the builtin
3137    function; if convenient, the result should be placed in TARGET.  */
3138
3139 static rtx
3140 expand_builtin_pow (tree exp, rtx target, rtx subtarget)
3141 {
3142   tree arg0, arg1;
3143   tree fn, narg0;
3144   tree type = TREE_TYPE (exp);
3145   REAL_VALUE_TYPE cint, c, c2;
3146   HOST_WIDE_INT n;
3147   rtx op, op2;
3148   enum machine_mode mode = TYPE_MODE (type);
3149
3150   if (! validate_arglist (exp, REAL_TYPE, REAL_TYPE, VOID_TYPE))
3151     return NULL_RTX;
3152
3153   arg0 = CALL_EXPR_ARG (exp, 0);
3154   arg1 = CALL_EXPR_ARG (exp, 1);
3155
3156   if (TREE_CODE (arg1) != REAL_CST
3157       || TREE_OVERFLOW (arg1))
3158     return expand_builtin_mathfn_2 (exp, target, subtarget);
3159
3160   /* Handle constant exponents.  */
3161
3162   /* For integer valued exponents we can expand to an optimal multiplication
3163      sequence using expand_powi.  */
3164   c = TREE_REAL_CST (arg1);
3165   n = real_to_integer (&c);
3166   real_from_integer (&cint, VOIDmode, n, n < 0 ? -1 : 0, 0);
3167   if (real_identical (&c, &cint)
3168       && ((n >= -1 && n <= 2)
3169           || (flag_unsafe_math_optimizations
3170               && optimize_insn_for_speed_p ()
3171               && powi_cost (n) <= POWI_MAX_MULTS)))
3172     {
3173       op = expand_expr (arg0, subtarget, VOIDmode, EXPAND_NORMAL);
3174       if (n != 1)
3175         {
3176           op = force_reg (mode, op);
3177           op = expand_powi (op, mode, n);
3178         }
3179       return op;
3180     }
3181
3182   narg0 = builtin_save_expr (arg0);
3183
3184   /* If the exponent is not integer valued, check if it is half of an integer.
3185      In this case we can expand to sqrt (x) * x**(n/2).  */
3186   fn = mathfn_built_in (type, BUILT_IN_SQRT);
3187   if (fn != NULL_TREE)
3188     {
3189       real_arithmetic (&c2, MULT_EXPR, &c, &dconst2);
3190       n = real_to_integer (&c2);
3191       real_from_integer (&cint, VOIDmode, n, n < 0 ? -1 : 0, 0);
3192       if (real_identical (&c2, &cint)
3193           && ((flag_unsafe_math_optimizations
3194                && optimize_insn_for_speed_p ()
3195                && powi_cost (n/2) <= POWI_MAX_MULTS)
3196               /* Even the c == 0.5 case cannot be done unconditionally
3197                  when we need to preserve signed zeros, as
3198                  pow (-0, 0.5) is +0, while sqrt(-0) is -0.  */
3199               || (!HONOR_SIGNED_ZEROS (mode) && n == 1)
3200               /* For c == 1.5 we can assume that x * sqrt (x) is always
3201                  smaller than pow (x, 1.5) if sqrt will not be expanded
3202                  as a call.  */
3203               || (n == 3
3204                   && optab_handler (sqrt_optab, mode) != CODE_FOR_nothing)))
3205         {
3206           tree call_expr = build_call_nofold_loc (EXPR_LOCATION (exp), fn, 1,
3207                                                   narg0);
3208           /* Use expand_expr in case the newly built call expression
3209              was folded to a non-call.  */
3210           op = expand_expr (call_expr, subtarget, mode, EXPAND_NORMAL);
3211           if (n != 1)
3212             {
3213               op2 = expand_expr (narg0, subtarget, VOIDmode, EXPAND_NORMAL);
3214               op2 = force_reg (mode, op2);
3215               op2 = expand_powi (op2, mode, abs (n / 2));
3216               op = expand_simple_binop (mode, MULT, op, op2, NULL_RTX,
3217                                         0, OPTAB_LIB_WIDEN);
3218               /* If the original exponent was negative, reciprocate the
3219                  result.  */
3220               if (n < 0)
3221                 op = expand_binop (mode, sdiv_optab, CONST1_RTX (mode),
3222                                    op, NULL_RTX, 0, OPTAB_LIB_WIDEN);
3223             }
3224           return op;
3225         }
3226     }
3227
3228   /* Check whether we can do a series of sqrt or cbrt's instead of the pow
3229      call.  */
3230   op = expand_builtin_pow_root (EXPR_LOCATION (exp), arg0, arg1, type,
3231                                 subtarget);
3232   if (op)
3233     return op;
3234
3235   /* Try if the exponent is a third of an integer.  In this case
3236      we can expand to x**(n/3) * cbrt(x)**(n%3).  As cbrt (x) is
3237      different from pow (x, 1./3.) due to rounding and behavior
3238      with negative x we need to constrain this transformation to
3239      unsafe math and positive x or finite math.  */
3240   fn = mathfn_built_in (type, BUILT_IN_CBRT);
3241   if (fn != NULL_TREE
3242       && flag_unsafe_math_optimizations
3243       && (tree_expr_nonnegative_p (arg0)
3244           || !HONOR_NANS (mode)))
3245     {
3246       REAL_VALUE_TYPE dconst3;
3247       real_from_integer (&dconst3, VOIDmode, 3, 0, 0);
3248       real_arithmetic (&c2, MULT_EXPR, &c, &dconst3);
3249       real_round (&c2, mode, &c2);
3250       n = real_to_integer (&c2);
3251       real_from_integer (&cint, VOIDmode, n, n < 0 ? -1 : 0, 0);
3252       real_arithmetic (&c2, RDIV_EXPR, &cint, &dconst3);
3253       real_convert (&c2, mode, &c2);
3254       if (real_identical (&c2, &c)
3255           && ((optimize_insn_for_speed_p ()
3256                && powi_cost (n/3) <= POWI_MAX_MULTS)
3257               || n == 1))
3258         {
3259           tree call_expr = build_call_nofold_loc (EXPR_LOCATION (exp), fn, 1,
3260                                                   narg0);
3261           op = expand_builtin (call_expr, NULL_RTX, subtarget, mode, 0);
3262           if (abs (n) % 3 == 2)
3263             op = expand_simple_binop (mode, MULT, op, op, op,
3264                                       0, OPTAB_LIB_WIDEN);
3265           if (n != 1)
3266             {
3267               op2 = expand_expr (narg0, subtarget, VOIDmode, EXPAND_NORMAL);
3268               op2 = force_reg (mode, op2);
3269               op2 = expand_powi (op2, mode, abs (n / 3));
3270               op = expand_simple_binop (mode, MULT, op, op2, NULL_RTX,
3271                                         0, OPTAB_LIB_WIDEN);
3272               /* If the original exponent was negative, reciprocate the
3273                  result.  */
3274               if (n < 0)
3275                 op = expand_binop (mode, sdiv_optab, CONST1_RTX (mode),
3276                                    op, NULL_RTX, 0, OPTAB_LIB_WIDEN);
3277             }
3278           return op;
3279         }
3280     }
3281
3282   /* Fall back to optab expansion.  */
3283   return expand_builtin_mathfn_2 (exp, target, subtarget);
3284 }
3285
3286 /* Expand a call to the powi built-in mathematical function.  Return NULL_RTX if
3287    a normal call should be emitted rather than expanding the function
3288    in-line.  EXP is the expression that is a call to the builtin
3289    function; if convenient, the result should be placed in TARGET.  */
3290
3291 static rtx
3292 expand_builtin_powi (tree exp, rtx target)
3293 {
3294   tree arg0, arg1;
3295   rtx op0, op1;
3296   enum machine_mode mode;
3297   enum machine_mode mode2;
3298
3299   if (! validate_arglist (exp, REAL_TYPE, INTEGER_TYPE, VOID_TYPE))
3300     return NULL_RTX;
3301
3302   arg0 = CALL_EXPR_ARG (exp, 0);
3303   arg1 = CALL_EXPR_ARG (exp, 1);
3304   mode = TYPE_MODE (TREE_TYPE (exp));
3305
3306   /* Handle constant power.  */
3307
3308   if (TREE_CODE (arg1) == INTEGER_CST
3309       && !TREE_OVERFLOW (arg1))
3310     {
3311       HOST_WIDE_INT n = TREE_INT_CST_LOW (arg1);
3312
3313       /* If the exponent is -1, 0, 1 or 2, then expand_powi is exact.
3314          Otherwise, check the number of multiplications required.  */
3315       if ((TREE_INT_CST_HIGH (arg1) == 0
3316            || TREE_INT_CST_HIGH (arg1) == -1)
3317           && ((n >= -1 && n <= 2)
3318               || (optimize_insn_for_speed_p ()
3319                   && powi_cost (n) <= POWI_MAX_MULTS)))
3320         {
3321           op0 = expand_expr (arg0, NULL_RTX, VOIDmode, EXPAND_NORMAL);
3322           op0 = force_reg (mode, op0);
3323           return expand_powi (op0, mode, n);
3324         }
3325     }
3326
3327   /* Emit a libcall to libgcc.  */
3328
3329   /* Mode of the 2nd argument must match that of an int.  */
3330   mode2 = mode_for_size (INT_TYPE_SIZE, MODE_INT, 0);
3331
3332   if (target == NULL_RTX)
3333     target = gen_reg_rtx (mode);
3334
3335   op0 = expand_expr (arg0, NULL_RTX, mode, EXPAND_NORMAL);
3336   if (GET_MODE (op0) != mode)
3337     op0 = convert_to_mode (mode, op0, 0);
3338   op1 = expand_expr (arg1, NULL_RTX, mode2, EXPAND_NORMAL);
3339   if (GET_MODE (op1) != mode2)
3340     op1 = convert_to_mode (mode2, op1, 0);
3341
3342   target = emit_library_call_value (optab_libfunc (powi_optab, mode),
3343                                     target, LCT_CONST, mode, 2,
3344                                     op0, mode, op1, mode2);
3345
3346   return target;
3347 }
3348
3349 /* Expand expression EXP which is a call to the strlen builtin.  Return
3350    NULL_RTX if we failed the caller should emit a normal call, otherwise
3351    try to get the result in TARGET, if convenient.  */
3352
3353 static rtx
3354 expand_builtin_strlen (tree exp, rtx target,
3355                        enum machine_mode target_mode)
3356 {
3357   if (!validate_arglist (exp, POINTER_TYPE, VOID_TYPE))
3358     return NULL_RTX;
3359   else
3360     {
3361       rtx pat;
3362       tree len;
3363       tree src = CALL_EXPR_ARG (exp, 0);
3364       rtx result, src_reg, char_rtx, before_strlen;
3365       enum machine_mode insn_mode = target_mode, char_mode;
3366       enum insn_code icode = CODE_FOR_nothing;
3367       unsigned int align;
3368
3369       /* If the length can be computed at compile-time, return it.  */
3370       len = c_strlen (src, 0);
3371       if (len)
3372         return expand_expr (len, target, target_mode, EXPAND_NORMAL);
3373
3374       /* If the length can be computed at compile-time and is constant
3375          integer, but there are side-effects in src, evaluate
3376          src for side-effects, then return len.
3377          E.g. x = strlen (i++ ? "xfoo" + 1 : "bar");
3378          can be optimized into: i++; x = 3;  */
3379       len = c_strlen (src, 1);
3380       if (len && TREE_CODE (len) == INTEGER_CST)
3381         {
3382           expand_expr (src, const0_rtx, VOIDmode, EXPAND_NORMAL);
3383           return expand_expr (len, target, target_mode, EXPAND_NORMAL);
3384         }
3385
3386       align = get_pointer_alignment (src, BIGGEST_ALIGNMENT) / BITS_PER_UNIT;
3387
3388       /* If SRC is not a pointer type, don't do this operation inline.  */
3389       if (align == 0)
3390         return NULL_RTX;
3391
3392       /* Bail out if we can't compute strlen in the right mode.  */
3393       while (insn_mode != VOIDmode)
3394         {
3395           icode = optab_handler (strlen_optab, insn_mode);
3396           if (icode != CODE_FOR_nothing)
3397             break;
3398
3399           insn_mode = GET_MODE_WIDER_MODE (insn_mode);
3400         }
3401       if (insn_mode == VOIDmode)
3402         return NULL_RTX;
3403
3404       /* Make a place to write the result of the instruction.  */
3405       result = target;
3406       if (! (result != 0
3407              && REG_P (result)
3408              && GET_MODE (result) == insn_mode
3409              && REGNO (result) >= FIRST_PSEUDO_REGISTER))
3410         result = gen_reg_rtx (insn_mode);
3411
3412       /* Make a place to hold the source address.  We will not expand
3413          the actual source until we are sure that the expansion will
3414          not fail -- there are trees that cannot be expanded twice.  */
3415       src_reg = gen_reg_rtx (Pmode);
3416
3417       /* Mark the beginning of the strlen sequence so we can emit the
3418          source operand later.  */
3419       before_strlen = get_last_insn ();
3420
3421       char_rtx = const0_rtx;
3422       char_mode = insn_data[(int) icode].operand[2].mode;
3423       if (! (*insn_data[(int) icode].operand[2].predicate) (char_rtx,
3424                                                             char_mode))
3425         char_rtx = copy_to_mode_reg (char_mode, char_rtx);
3426
3427       pat = GEN_FCN (icode) (result, gen_rtx_MEM (BLKmode, src_reg),
3428                              char_rtx, GEN_INT (align));
3429       if (! pat)
3430         return NULL_RTX;
3431       emit_insn (pat);
3432
3433       /* Now that we are assured of success, expand the source.  */
3434       start_sequence ();
3435       pat = expand_expr (src, src_reg, ptr_mode, EXPAND_NORMAL);
3436       if (pat != src_reg)
3437         emit_move_insn (src_reg, pat);
3438       pat = get_insns ();
3439       end_sequence ();
3440
3441       if (before_strlen)
3442         emit_insn_after (pat, before_strlen);
3443       else
3444         emit_insn_before (pat, get_insns ());
3445
3446       /* Return the value in the proper mode for this function.  */
3447       if (GET_MODE (result) == target_mode)
3448         target = result;
3449       else if (target != 0)
3450         convert_move (target, result, 0);
3451       else
3452         target = convert_to_mode (target_mode, result, 0);
3453
3454       return target;
3455     }
3456 }
3457
3458 /* Callback routine for store_by_pieces.  Read GET_MODE_BITSIZE (MODE)
3459    bytes from constant string DATA + OFFSET and return it as target
3460    constant.  */
3461
3462 static rtx
3463 builtin_memcpy_read_str (void *data, HOST_WIDE_INT offset,
3464                          enum machine_mode mode)
3465 {
3466   const char *str = (const char *) data;
3467
3468   gcc_assert (offset >= 0
3469               && ((unsigned HOST_WIDE_INT) offset + GET_MODE_SIZE (mode)
3470                   <= strlen (str) + 1));
3471
3472   return c_readstr (str + offset, mode);
3473 }
3474
3475 /* Expand a call EXP to the memcpy builtin.
3476    Return NULL_RTX if we failed, the caller should emit a normal call,
3477    otherwise try to get the result in TARGET, if convenient (and in
3478    mode MODE if that's convenient).  */
3479
3480 static rtx
3481 expand_builtin_memcpy (tree exp, rtx target)
3482 {
3483   if (!validate_arglist (exp,
3484                          POINTER_TYPE, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
3485     return NULL_RTX;
3486   else
3487     {
3488       tree dest = CALL_EXPR_ARG (exp, 0);
3489       tree src = CALL_EXPR_ARG (exp, 1);
3490       tree len = CALL_EXPR_ARG (exp, 2);
3491       const char *src_str;
3492       unsigned int src_align = get_pointer_alignment (src, BIGGEST_ALIGNMENT);
3493       unsigned int dest_align
3494         = get_pointer_alignment (dest, BIGGEST_ALIGNMENT);
3495       rtx dest_mem, src_mem, dest_addr, len_rtx;
3496       HOST_WIDE_INT expected_size = -1;
3497       unsigned int expected_align = 0;
3498
3499       /* If DEST is not a pointer type, call the normal function.  */
3500       if (dest_align == 0)
3501         return NULL_RTX;
3502
3503       /* If either SRC is not a pointer type, don't do this
3504          operation in-line.  */
3505       if (src_align == 0)
3506         return NULL_RTX;
3507
3508       if (currently_expanding_gimple_stmt)
3509         stringop_block_profile (currently_expanding_gimple_stmt,
3510                                 &expected_align, &expected_size);
3511
3512       if (expected_align < dest_align)
3513         expected_align = dest_align;
3514       dest_mem = get_memory_rtx (dest, len);
3515       set_mem_align (dest_mem, dest_align);
3516       len_rtx = expand_normal (len);
3517       src_str = c_getstr (src);
3518
3519       /* If SRC is a string constant and block move would be done
3520          by pieces, we can avoid loading the string from memory
3521          and only stored the computed constants.  */
3522       if (src_str
3523           && CONST_INT_P (len_rtx)
3524           && (unsigned HOST_WIDE_INT) INTVAL (len_rtx) <= strlen (src_str) + 1
3525           && can_store_by_pieces (INTVAL (len_rtx), builtin_memcpy_read_str,
3526                                   CONST_CAST (char *, src_str),
3527                                   dest_align, false))
3528         {
3529           dest_mem = store_by_pieces (dest_mem, INTVAL (len_rtx),
3530                                       builtin_memcpy_read_str,
3531                                       CONST_CAST (char *, src_str),
3532                                       dest_align, false, 0);
3533           dest_mem = force_operand (XEXP (dest_mem, 0), target);
3534           dest_mem = convert_memory_address (ptr_mode, dest_mem);
3535           return dest_mem;
3536         }
3537
3538       src_mem = get_memory_rtx (src, len);
3539       set_mem_align (src_mem, src_align);
3540
3541       /* Copy word part most expediently.  */
3542       dest_addr = emit_block_move_hints (dest_mem, src_mem, len_rtx,
3543                                          CALL_EXPR_TAILCALL (exp)
3544                                          ? BLOCK_OP_TAILCALL : BLOCK_OP_NORMAL,
3545                                          expected_align, expected_size);
3546
3547       if (dest_addr == 0)
3548         {
3549           dest_addr = force_operand (XEXP (dest_mem, 0), target);
3550           dest_addr = convert_memory_address (ptr_mode, dest_addr);
3551         }
3552       return dest_addr;
3553     }
3554 }
3555
3556 /* Expand a call EXP to the mempcpy builtin.
3557    Return NULL_RTX if we failed; the caller should emit a normal call,
3558    otherwise try to get the result in TARGET, if convenient (and in
3559    mode MODE if that's convenient).  If ENDP is 0 return the
3560    destination pointer, if ENDP is 1 return the end pointer ala
3561    mempcpy, and if ENDP is 2 return the end pointer minus one ala
3562    stpcpy.  */
3563
3564 static rtx
3565 expand_builtin_mempcpy (tree exp, rtx target, enum machine_mode mode)
3566 {
3567   if (!validate_arglist (exp,
3568                          POINTER_TYPE, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
3569     return NULL_RTX;
3570   else
3571     {
3572       tree dest = CALL_EXPR_ARG (exp, 0);
3573       tree src = CALL_EXPR_ARG (exp, 1);
3574       tree len = CALL_EXPR_ARG (exp, 2);
3575       return expand_builtin_mempcpy_args (dest, src, len,
3576                                           target, mode, /*endp=*/ 1);
3577     }
3578 }
3579
3580 /* Helper function to do the actual work for expand_builtin_mempcpy.  The
3581    arguments to the builtin_mempcpy call DEST, SRC, and LEN are broken out
3582    so that this can also be called without constructing an actual CALL_EXPR.
3583    The other arguments and return value are the same as for
3584    expand_builtin_mempcpy.  */
3585
3586 static rtx
3587 expand_builtin_mempcpy_args (tree dest, tree src, tree len,
3588                              rtx target, enum machine_mode mode, int endp)
3589 {
3590     /* If return value is ignored, transform mempcpy into memcpy.  */
3591   if (target == const0_rtx && implicit_built_in_decls[BUILT_IN_MEMCPY])
3592     {
3593       tree fn = implicit_built_in_decls[BUILT_IN_MEMCPY];
3594       tree result = build_call_nofold_loc (UNKNOWN_LOCATION, fn, 3,
3595                                            dest, src, len);
3596       return expand_expr (result, target, mode, EXPAND_NORMAL);
3597     }
3598   else
3599     {
3600       const char *src_str;
3601       unsigned int src_align = get_pointer_alignment (src, BIGGEST_ALIGNMENT);
3602       unsigned int dest_align
3603         = get_pointer_alignment (dest, BIGGEST_ALIGNMENT);
3604       rtx dest_mem, src_mem, len_rtx;
3605
3606       /* If either SRC or DEST is not a pointer type, don't do this
3607          operation in-line.  */
3608       if (dest_align == 0 || src_align == 0)
3609         return NULL_RTX;
3610
3611       /* If LEN is not constant, call the normal function.  */
3612       if (! host_integerp (len, 1))
3613         return NULL_RTX;
3614
3615       len_rtx = expand_normal (len);
3616       src_str = c_getstr (src);
3617
3618       /* If SRC is a string constant and block move would be done
3619          by pieces, we can avoid loading the string from memory
3620          and only stored the computed constants.  */
3621       if (src_str
3622           && CONST_INT_P (len_rtx)
3623           && (unsigned HOST_WIDE_INT) INTVAL (len_rtx) <= strlen (src_str) + 1
3624           && can_store_by_pieces (INTVAL (len_rtx), builtin_memcpy_read_str,
3625                                   CONST_CAST (char *, src_str),
3626                                   dest_align, false))
3627         {
3628           dest_mem = get_memory_rtx (dest, len);
3629           set_mem_align (dest_mem, dest_align);
3630           dest_mem = store_by_pieces (dest_mem, INTVAL (len_rtx),
3631                                       builtin_memcpy_read_str,
3632                                       CONST_CAST (char *, src_str),
3633                                       dest_align, false, endp);
3634           dest_mem = force_operand (XEXP (dest_mem, 0), NULL_RTX);
3635           dest_mem = convert_memory_address (ptr_mode, dest_mem);
3636           return dest_mem;
3637         }
3638
3639       if (CONST_INT_P (len_rtx)
3640           && can_move_by_pieces (INTVAL (len_rtx),
3641                                  MIN (dest_align, src_align)))
3642         {
3643           dest_mem = get_memory_rtx (dest, len);
3644           set_mem_align (dest_mem, dest_align);
3645           src_mem = get_memory_rtx (src, len);
3646           set_mem_align (src_mem, src_align);
3647           dest_mem = move_by_pieces (dest_mem, src_mem, INTVAL (len_rtx),
3648                                      MIN (dest_align, src_align), endp);
3649           dest_mem = force_operand (XEXP (dest_mem, 0), NULL_RTX);
3650           dest_mem = convert_memory_address (ptr_mode, dest_mem);
3651           return dest_mem;
3652         }
3653
3654       return NULL_RTX;
3655     }
3656 }
3657
3658 #ifndef HAVE_movstr
3659 # define HAVE_movstr 0
3660 # define CODE_FOR_movstr CODE_FOR_nothing
3661 #endif
3662
3663 /* Expand into a movstr instruction, if one is available.  Return NULL_RTX if
3664    we failed, the caller should emit a normal call, otherwise try to
3665    get the result in TARGET, if convenient.  If ENDP is 0 return the
3666    destination pointer, if ENDP is 1 return the end pointer ala
3667    mempcpy, and if ENDP is 2 return the end pointer minus one ala
3668    stpcpy.  */
3669
3670 static rtx
3671 expand_movstr (tree dest, tree src, rtx target, int endp)
3672 {
3673   rtx end;
3674   rtx dest_mem;
3675   rtx src_mem;
3676   rtx insn;
3677   const struct insn_data_d * data;
3678
3679   if (!HAVE_movstr)
3680     return NULL_RTX;
3681
3682   dest_mem = get_memory_rtx (dest, NULL);
3683   src_mem = get_memory_rtx (src, NULL);
3684   data = insn_data + CODE_FOR_movstr;
3685   if (!endp)
3686     {
3687       target = force_reg (Pmode, XEXP (dest_mem, 0));
3688       dest_mem = replace_equiv_address (dest_mem, target);
3689       end = gen_reg_rtx (Pmode);
3690     }
3691   else
3692     {
3693       if (target == 0
3694           || target == const0_rtx
3695           || ! (*data->operand[0].predicate) (target, Pmode))
3696         {
3697           end = gen_reg_rtx (Pmode);
3698           if (target != const0_rtx)
3699             target = end;
3700         }
3701       else
3702         end = target;
3703     }
3704
3705   if (data->operand[0].mode != VOIDmode)
3706     end = gen_lowpart (data->operand[0].mode, end);
3707
3708   insn = data->genfun (end, dest_mem, src_mem);
3709
3710   gcc_assert (insn);
3711
3712   emit_insn (insn);
3713
3714   /* movstr is supposed to set end to the address of the NUL
3715      terminator.  If the caller requested a mempcpy-like return value,
3716      adjust it.  */
3717   if (endp == 1 && target != const0_rtx)
3718     {
3719       rtx tem = plus_constant (gen_lowpart (GET_MODE (target), end), 1);
3720       emit_move_insn (target, force_operand (tem, NULL_RTX));
3721     }
3722
3723   return target;
3724 }
3725
3726 /* Expand expression EXP, which is a call to the strcpy builtin.  Return
3727    NULL_RTX if we failed the caller should emit a normal call, otherwise
3728    try to get the result in TARGET, if convenient (and in mode MODE if that's
3729    convenient).  */
3730
3731 static rtx
3732 expand_builtin_strcpy (tree exp, rtx target)
3733 {
3734   if (validate_arglist (exp, POINTER_TYPE, POINTER_TYPE, VOID_TYPE))
3735    {
3736      tree dest = CALL_EXPR_ARG (exp, 0);
3737      tree src = CALL_EXPR_ARG (exp, 1);
3738      return expand_builtin_strcpy_args (dest, src, target);
3739    }
3740    return NULL_RTX;
3741 }
3742
3743 /* Helper function to do the actual work for expand_builtin_strcpy.  The
3744    arguments to the builtin_strcpy call DEST and SRC are broken out
3745    so that this can also be called without constructing an actual CALL_EXPR.
3746    The other arguments and return value are the same as for
3747    expand_builtin_strcpy.  */
3748
3749 static rtx
3750 expand_builtin_strcpy_args (tree dest, tree src, rtx target)
3751 {
3752   return expand_movstr (dest, src, target, /*endp=*/0);
3753 }
3754
3755 /* Expand a call EXP to the stpcpy builtin.
3756    Return NULL_RTX if we failed the caller should emit a normal call,
3757    otherwise try to get the result in TARGET, if convenient (and in
3758    mode MODE if that's convenient).  */
3759
3760 static rtx
3761 expand_builtin_stpcpy (tree exp, rtx target, enum machine_mode mode)
3762 {
3763   tree dst, src;
3764   location_t loc = EXPR_LOCATION (exp);
3765
3766   if (!validate_arglist (exp, POINTER_TYPE, POINTER_TYPE, VOID_TYPE))
3767     return NULL_RTX;
3768
3769   dst = CALL_EXPR_ARG (exp, 0);
3770   src = CALL_EXPR_ARG (exp, 1);
3771
3772   /* If return value is ignored, transform stpcpy into strcpy.  */
3773   if (target == const0_rtx && implicit_built_in_decls[BUILT_IN_STRCPY])
3774     {
3775       tree fn = implicit_built_in_decls[BUILT_IN_STRCPY];
3776       tree result = build_call_nofold_loc (loc, fn, 2, dst, src);
3777       return expand_expr (result, target, mode, EXPAND_NORMAL);
3778     }
3779   else
3780     {
3781       tree len, lenp1;
3782       rtx ret;
3783
3784       /* Ensure we get an actual string whose length can be evaluated at
3785          compile-time, not an expression containing a string.  This is
3786          because the latter will potentially produce pessimized code
3787          when used to produce the return value.  */
3788       if (! c_getstr (src) || ! (len = c_strlen (src, 0)))
3789         return expand_movstr (dst, src, target, /*endp=*/2);
3790
3791       lenp1 = size_binop_loc (loc, PLUS_EXPR, len, ssize_int (1));
3792       ret = expand_builtin_mempcpy_args (dst, src, lenp1,
3793                                          target, mode, /*endp=*/2);
3794
3795       if (ret)
3796         return ret;
3797
3798       if (TREE_CODE (len) == INTEGER_CST)
3799         {
3800           rtx len_rtx = expand_normal (len);
3801
3802           if (CONST_INT_P (len_rtx))
3803             {
3804               ret = expand_builtin_strcpy_args (dst, src, target);
3805
3806               if (ret)
3807                 {
3808                   if (! target)
3809                     {
3810                       if (mode != VOIDmode)
3811                         target = gen_reg_rtx (mode);
3812                       else
3813                         target = gen_reg_rtx (GET_MODE (ret));
3814                     }
3815                   if (GET_MODE (target) != GET_MODE (ret))
3816                     ret = gen_lowpart (GET_MODE (target), ret);
3817
3818                   ret = plus_constant (ret, INTVAL (len_rtx));
3819                   ret = emit_move_insn (target, force_operand (ret, NULL_RTX));
3820                   gcc_assert (ret);
3821
3822                   return target;
3823                 }
3824             }
3825         }
3826
3827       return expand_movstr (dst, src, target, /*endp=*/2);
3828     }
3829 }
3830
3831 /* Callback routine for store_by_pieces.  Read GET_MODE_BITSIZE (MODE)
3832    bytes from constant string DATA + OFFSET and return it as target
3833    constant.  */
3834
3835 rtx
3836 builtin_strncpy_read_str (void *data, HOST_WIDE_INT offset,
3837                           enum machine_mode mode)
3838 {
3839   const char *str = (const char *) data;
3840
3841   if ((unsigned HOST_WIDE_INT) offset > strlen (str))
3842     return const0_rtx;
3843
3844   return c_readstr (str + offset, mode);
3845 }
3846
3847 /* Expand expression EXP, which is a call to the strncpy builtin.  Return
3848    NULL_RTX if we failed the caller should emit a normal call.  */
3849
3850 static rtx
3851 expand_builtin_strncpy (tree exp, rtx target)
3852 {
3853   location_t loc = EXPR_LOCATION (exp);
3854
3855   if (validate_arglist (exp,
3856                         POINTER_TYPE, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
3857     {
3858       tree dest = CALL_EXPR_ARG (exp, 0);
3859       tree src = CALL_EXPR_ARG (exp, 1);
3860       tree len = CALL_EXPR_ARG (exp, 2);
3861       tree slen = c_strlen (src, 1);
3862
3863       /* We must be passed a constant len and src parameter.  */
3864       if (!host_integerp (len, 1) || !slen || !host_integerp (slen, 1))
3865         return NULL_RTX;
3866
3867       slen = size_binop_loc (loc, PLUS_EXPR, slen, ssize_int (1));
3868
3869       /* We're required to pad with trailing zeros if the requested
3870          len is greater than strlen(s2)+1.  In that case try to
3871          use store_by_pieces, if it fails, punt.  */
3872       if (tree_int_cst_lt (slen, len))
3873         {
3874           unsigned int dest_align
3875             = get_pointer_alignment (dest, BIGGEST_ALIGNMENT);
3876           const char *p = c_getstr (src);
3877           rtx dest_mem;
3878
3879           if (!p || dest_align == 0 || !host_integerp (len, 1)
3880               || !can_store_by_pieces (tree_low_cst (len, 1),
3881                                        builtin_strncpy_read_str,
3882                                        CONST_CAST (char *, p),
3883                                        dest_align, false))
3884             return NULL_RTX;
3885
3886           dest_mem = get_memory_rtx (dest, len);
3887           store_by_pieces (dest_mem, tree_low_cst (len, 1),
3888                            builtin_strncpy_read_str,
3889                            CONST_CAST (char *, p), dest_align, false, 0);
3890           dest_mem = force_operand (XEXP (dest_mem, 0), target);
3891           dest_mem = convert_memory_address (ptr_mode, dest_mem);
3892           return dest_mem;
3893         }
3894     }
3895   return NULL_RTX;
3896 }
3897
3898 /* Callback routine for store_by_pieces.  Read GET_MODE_BITSIZE (MODE)
3899    bytes from constant string DATA + OFFSET and return it as target
3900    constant.  */
3901
3902 rtx
3903 builtin_memset_read_str (void *data, HOST_WIDE_INT offset ATTRIBUTE_UNUSED,
3904                          enum machine_mode mode)
3905 {
3906   const char *c = (const char *) data;
3907   char *p = XALLOCAVEC (char, GET_MODE_SIZE (mode));
3908
3909   memset (p, *c, GET_MODE_SIZE (mode));
3910
3911   return c_readstr (p, mode);
3912 }
3913
3914 /* Callback routine for store_by_pieces.  Return the RTL of a register
3915    containing GET_MODE_SIZE (MODE) consecutive copies of the unsigned
3916    char value given in the RTL register data.  For example, if mode is
3917    4 bytes wide, return the RTL for 0x01010101*data.  */
3918
3919 static rtx
3920 builtin_memset_gen_str (void *data, HOST_WIDE_INT offset ATTRIBUTE_UNUSED,
3921                         enum machine_mode mode)
3922 {
3923   rtx target, coeff;
3924   size_t size;
3925   char *p;
3926
3927   size = GET_MODE_SIZE (mode);
3928   if (size == 1)
3929     return (rtx) data;
3930
3931   p = XALLOCAVEC (char, size);
3932   memset (p, 1, size);
3933   coeff = c_readstr (p, mode);
3934
3935   target = convert_to_mode (mode, (rtx) data, 1);
3936   target = expand_mult (mode, target, coeff, NULL_RTX, 1);
3937   return force_reg (mode, target);
3938 }
3939
3940 /* Expand expression EXP, which is a call to the memset builtin.  Return
3941    NULL_RTX if we failed the caller should emit a normal call, otherwise
3942    try to get the result in TARGET, if convenient (and in mode MODE if that's
3943    convenient).  */
3944
3945 static rtx
3946 expand_builtin_memset (tree exp, rtx target, enum machine_mode mode)
3947 {
3948   if (!validate_arglist (exp,
3949                          POINTER_TYPE, INTEGER_TYPE, INTEGER_TYPE, VOID_TYPE))
3950     return NULL_RTX;
3951   else
3952     {
3953       tree dest = CALL_EXPR_ARG (exp, 0);
3954       tree val = CALL_EXPR_ARG (exp, 1);
3955       tree len = CALL_EXPR_ARG (exp, 2);
3956       return expand_builtin_memset_args (dest, val, len, target, mode, exp);
3957     }
3958 }
3959
3960 /* Helper function to do the actual work for expand_builtin_memset.  The
3961    arguments to the builtin_memset call DEST, VAL, and LEN are broken out
3962    so that this can also be called without constructing an actual CALL_EXPR.
3963    The other arguments and return value are the same as for
3964    expand_builtin_memset.  */
3965
3966 static rtx
3967 expand_builtin_memset_args (tree dest, tree val, tree len,
3968                             rtx target, enum machine_mode mode, tree orig_exp)
3969 {
3970   tree fndecl, fn;
3971   enum built_in_function fcode;
3972   char c;
3973   unsigned int dest_align;
3974   rtx dest_mem, dest_addr, len_rtx;
3975   HOST_WIDE_INT expected_size = -1;
3976   unsigned int expected_align = 0;
3977
3978   dest_align = get_pointer_alignment (dest, BIGGEST_ALIGNMENT);
3979
3980   /* If DEST is not a pointer type, don't do this operation in-line.  */
3981   if (dest_align == 0)
3982     return NULL_RTX;
3983
3984   if (currently_expanding_gimple_stmt)
3985     stringop_block_profile (currently_expanding_gimple_stmt,
3986                             &expected_align, &expected_size);
3987
3988   if (expected_align < dest_align)
3989     expected_align = dest_align;
3990
3991   /* If the LEN parameter is zero, return DEST.  */
3992   if (integer_zerop (len))
3993     {
3994       /* Evaluate and ignore VAL in case it has side-effects.  */
3995       expand_expr (val, const0_rtx, VOIDmode, EXPAND_NORMAL);
3996       return expand_expr (dest, target, mode, EXPAND_NORMAL);
3997     }
3998
3999   /* Stabilize the arguments in case we fail.  */
4000   dest = builtin_save_expr (dest);
4001   val = builtin_save_expr (val);
4002   len = builtin_save_expr (len);
4003
4004   len_rtx = expand_normal (len);
4005   dest_mem = get_memory_rtx (dest, len);
4006
4007   if (TREE_CODE (val) != INTEGER_CST)
4008     {
4009       rtx val_rtx;
4010
4011       val_rtx = expand_normal (val);
4012       val_rtx = convert_to_mode (TYPE_MODE (unsigned_char_type_node),
4013                                  val_rtx, 0);
4014
4015       /* Assume that we can memset by pieces if we can store
4016        * the coefficients by pieces (in the required modes).
4017        * We can't pass builtin_memset_gen_str as that emits RTL.  */
4018       c = 1;
4019       if (host_integerp (len, 1)
4020           && can_store_by_pieces (tree_low_cst (len, 1),
4021                                   builtin_memset_read_str, &c, dest_align,
4022                                   true))
4023         {
4024           val_rtx = force_reg (TYPE_MODE (unsigned_char_type_node),
4025                                val_rtx);
4026           store_by_pieces (dest_mem, tree_low_cst (len, 1),
4027                            builtin_memset_gen_str, val_rtx, dest_align,
4028                            true, 0);
4029         }
4030       else if (!set_storage_via_setmem (dest_mem, len_rtx, val_rtx,
4031                                         dest_align, expected_align,
4032                                         expected_size))
4033         goto do_libcall;
4034
4035       dest_mem = force_operand (XEXP (dest_mem, 0), NULL_RTX);
4036       dest_mem = convert_memory_address (ptr_mode, dest_mem);
4037       return dest_mem;
4038     }
4039
4040   if (target_char_cast (val, &c))
4041     goto do_libcall;
4042
4043   if (c)
4044     {
4045       if (host_integerp (len, 1)
4046           && can_store_by_pieces (tree_low_cst (len, 1),
4047                                   builtin_memset_read_str, &c, dest_align,
4048                                   true))
4049         store_by_pieces (dest_mem, tree_low_cst (len, 1),
4050                          builtin_memset_read_str, &c, dest_align, true, 0);
4051       else if (!set_storage_via_setmem (dest_mem, len_rtx, GEN_INT (c),
4052                                         dest_align, expected_align,
4053                                         expected_size))
4054         goto do_libcall;
4055
4056       dest_mem = force_operand (XEXP (dest_mem, 0), NULL_RTX);
4057       dest_mem = convert_memory_address (ptr_mode, dest_mem);
4058       return dest_mem;
4059     }
4060
4061   set_mem_align (dest_mem, dest_align);
4062   dest_addr = clear_storage_hints (dest_mem, len_rtx,
4063                                    CALL_EXPR_TAILCALL (orig_exp)
4064                                    ? BLOCK_OP_TAILCALL : BLOCK_OP_NORMAL,
4065                                    expected_align, expected_size);
4066
4067   if (dest_addr == 0)
4068     {
4069       dest_addr = force_operand (XEXP (dest_mem, 0), NULL_RTX);
4070       dest_addr = convert_memory_address (ptr_mode, dest_addr);
4071     }
4072
4073   return dest_addr;
4074
4075  do_libcall:
4076   fndecl = get_callee_fndecl (orig_exp);
4077   fcode = DECL_FUNCTION_CODE (fndecl);
4078   if (fcode == BUILT_IN_MEMSET)
4079     fn = build_call_nofold_loc (EXPR_LOCATION (orig_exp), fndecl, 3,
4080                                 dest, val, len);
4081   else if (fcode == BUILT_IN_BZERO)
4082     fn = build_call_nofold_loc (EXPR_LOCATION (orig_exp), fndecl, 2,
4083                                 dest, len);
4084   else
4085     gcc_unreachable ();
4086   gcc_assert (TREE_CODE (fn) == CALL_EXPR);
4087   CALL_EXPR_TAILCALL (fn) = CALL_EXPR_TAILCALL (orig_exp);
4088   return expand_call (fn, target, target == const0_rtx);
4089 }
4090
4091 /* Expand expression EXP, which is a call to the bzero builtin.  Return
4092    NULL_RTX if we failed the caller should emit a normal call.  */
4093
4094 static rtx
4095 expand_builtin_bzero (tree exp)
4096 {
4097   tree dest, size;
4098   location_t loc = EXPR_LOCATION (exp);
4099
4100   if (!validate_arglist (exp, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
4101     return NULL_RTX;
4102
4103   dest = CALL_EXPR_ARG (exp, 0);
4104   size = CALL_EXPR_ARG (exp, 1);
4105
4106   /* New argument list transforming bzero(ptr x, int y) to
4107      memset(ptr x, int 0, size_t y).   This is done this way
4108      so that if it isn't expanded inline, we fallback to
4109      calling bzero instead of memset.  */
4110
4111   return expand_builtin_memset_args (dest, integer_zero_node,
4112                                      fold_convert_loc (loc, sizetype, size),
4113                                      const0_rtx, VOIDmode, exp);
4114 }
4115
4116 /* Expand expression EXP, which is a call to the memcmp built-in function.
4117    Return NULL_RTX if we failed and the
4118    caller should emit a normal call, otherwise try to get the result in
4119    TARGET, if convenient (and in mode MODE, if that's convenient).  */
4120
4121 static rtx
4122 expand_builtin_memcmp (tree exp, ATTRIBUTE_UNUSED rtx target,
4123                        ATTRIBUTE_UNUSED enum machine_mode mode)
4124 {
4125   location_t loc ATTRIBUTE_UNUSED = EXPR_LOCATION (exp);
4126
4127   if (!validate_arglist (exp,
4128                          POINTER_TYPE, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
4129     return NULL_RTX;
4130
4131 #if defined HAVE_cmpmemsi || defined HAVE_cmpstrnsi
4132   {
4133     rtx arg1_rtx, arg2_rtx, arg3_rtx;
4134     rtx result;
4135     rtx insn;
4136     tree arg1 = CALL_EXPR_ARG (exp, 0);
4137     tree arg2 = CALL_EXPR_ARG (exp, 1);
4138     tree len = CALL_EXPR_ARG (exp, 2);
4139
4140     unsigned int arg1_align
4141       = get_pointer_alignment (arg1, BIGGEST_ALIGNMENT) / BITS_PER_UNIT;
4142     unsigned int arg2_align
4143       = get_pointer_alignment (arg2, BIGGEST_ALIGNMENT) / BITS_PER_UNIT;
4144     enum machine_mode insn_mode;
4145
4146 #ifdef HAVE_cmpmemsi
4147     if (HAVE_cmpmemsi)
4148       insn_mode = insn_data[(int) CODE_FOR_cmpmemsi].operand[0].mode;
4149     else
4150 #endif
4151 #ifdef HAVE_cmpstrnsi
4152     if (HAVE_cmpstrnsi)
4153       insn_mode = insn_data[(int) CODE_FOR_cmpstrnsi].operand[0].mode;
4154     else
4155 #endif
4156       return NULL_RTX;
4157
4158     /* If we don't have POINTER_TYPE, call the function.  */
4159     if (arg1_align == 0 || arg2_align == 0)
4160       return NULL_RTX;
4161
4162     /* Make a place to write the result of the instruction.  */
4163     result = target;
4164     if (! (result != 0
4165            && REG_P (result) && GET_MODE (result) == insn_mode
4166            && REGNO (result) >= FIRST_PSEUDO_REGISTER))
4167       result = gen_reg_rtx (insn_mode);
4168
4169     arg1_rtx = get_memory_rtx (arg1, len);
4170     arg2_rtx = get_memory_rtx (arg2, len);
4171     arg3_rtx = expand_normal (fold_convert_loc (loc, sizetype, len));
4172
4173     /* Set MEM_SIZE as appropriate.  */
4174     if (CONST_INT_P (arg3_rtx))
4175       {
4176         set_mem_size (arg1_rtx, arg3_rtx);
4177         set_mem_size (arg2_rtx, arg3_rtx);
4178       }
4179
4180 #ifdef HAVE_cmpmemsi
4181     if (HAVE_cmpmemsi)
4182       insn = gen_cmpmemsi (result, arg1_rtx, arg2_rtx, arg3_rtx,
4183                            GEN_INT (MIN (arg1_align, arg2_align)));
4184     else
4185 #endif
4186 #ifdef HAVE_cmpstrnsi
4187     if (HAVE_cmpstrnsi)
4188       insn = gen_cmpstrnsi (result, arg1_rtx, arg2_rtx, arg3_rtx,
4189                             GEN_INT (MIN (arg1_align, arg2_align)));
4190     else
4191 #endif
4192       gcc_unreachable ();
4193
4194     if (insn)
4195       emit_insn (insn);
4196     else
4197       emit_library_call_value (memcmp_libfunc, result, LCT_PURE,
4198                                TYPE_MODE (integer_type_node), 3,
4199                                XEXP (arg1_rtx, 0), Pmode,
4200                                XEXP (arg2_rtx, 0), Pmode,
4201                                convert_to_mode (TYPE_MODE (sizetype), arg3_rtx,
4202                                                 TYPE_UNSIGNED (sizetype)),
4203                                TYPE_MODE (sizetype));
4204
4205     /* Return the value in the proper mode for this function.  */
4206     mode = TYPE_MODE (TREE_TYPE (exp));
4207     if (GET_MODE (result) == mode)
4208       return result;
4209     else if (target != 0)
4210       {
4211         convert_move (target, result, 0);
4212         return target;
4213       }
4214     else
4215       return convert_to_mode (mode, result, 0);
4216   }
4217 #endif
4218
4219   return NULL_RTX;
4220 }
4221
4222 /* Expand expression EXP, which is a call to the strcmp builtin.  Return NULL_RTX
4223    if we failed the caller should emit a normal call, otherwise try to get
4224    the result in TARGET, if convenient.  */
4225
4226 static rtx
4227 expand_builtin_strcmp (tree exp, ATTRIBUTE_UNUSED rtx target)
4228 {
4229   if (!validate_arglist (exp, POINTER_TYPE, POINTER_TYPE, VOID_TYPE))
4230     return NULL_RTX;
4231
4232 #if defined HAVE_cmpstrsi || defined HAVE_cmpstrnsi
4233   if (direct_optab_handler (cmpstr_optab, SImode) != CODE_FOR_nothing
4234       || direct_optab_handler (cmpstrn_optab, SImode) != CODE_FOR_nothing)
4235     {
4236       rtx arg1_rtx, arg2_rtx;
4237       rtx result, insn = NULL_RTX;
4238       tree fndecl, fn;
4239       tree arg1 = CALL_EXPR_ARG (exp, 0);
4240       tree arg2 = CALL_EXPR_ARG (exp, 1);
4241
4242       unsigned int arg1_align
4243         = get_pointer_alignment (arg1, BIGGEST_ALIGNMENT) / BITS_PER_UNIT;
4244       unsigned int arg2_align
4245         = get_pointer_alignment (arg2, BIGGEST_ALIGNMENT) / BITS_PER_UNIT;
4246
4247       /* If we don't have POINTER_TYPE, call the function.  */
4248       if (arg1_align == 0 || arg2_align == 0)
4249         return NULL_RTX;
4250
4251       /* Stabilize the arguments in case gen_cmpstr(n)si fail.  */
4252       arg1 = builtin_save_expr (arg1);
4253       arg2 = builtin_save_expr (arg2);
4254
4255       arg1_rtx = get_memory_rtx (arg1, NULL);
4256       arg2_rtx = get_memory_rtx (arg2, NULL);
4257
4258 #ifdef HAVE_cmpstrsi
4259       /* Try to call cmpstrsi.  */
4260       if (HAVE_cmpstrsi)
4261         {
4262           enum machine_mode insn_mode
4263             = insn_data[(int) CODE_FOR_cmpstrsi].operand[0].mode;
4264
4265           /* Make a place to write the result of the instruction.  */
4266           result = target;
4267           if (! (result != 0
4268                  && REG_P (result) && GET_MODE (result) == insn_mode
4269                  && REGNO (result) >= FIRST_PSEUDO_REGISTER))
4270             result = gen_reg_rtx (insn_mode);
4271
4272           insn = gen_cmpstrsi (result, arg1_rtx, arg2_rtx,
4273                                GEN_INT (MIN (arg1_align, arg2_align)));
4274         }
4275 #endif
4276 #ifdef HAVE_cmpstrnsi
4277       /* Try to determine at least one length and call cmpstrnsi.  */
4278       if (!insn && HAVE_cmpstrnsi)
4279         {
4280           tree len;
4281           rtx arg3_rtx;
4282
4283           enum machine_mode insn_mode
4284             = insn_data[(int) CODE_FOR_cmpstrnsi].operand[0].mode;
4285           tree len1 = c_strlen (arg1, 1);
4286           tree len2 = c_strlen (arg2, 1);
4287
4288           if (len1)
4289             len1 = size_binop (PLUS_EXPR, ssize_int (1), len1);
4290           if (len2)
4291             len2 = size_binop (PLUS_EXPR, ssize_int (1), len2);
4292
4293           /* If we don't have a constant length for the first, use the length
4294              of the second, if we know it.  We don't require a constant for
4295              this case; some cost analysis could be done if both are available
4296              but neither is constant.  For now, assume they're equally cheap,
4297              unless one has side effects.  If both strings have constant lengths,
4298              use the smaller.  */
4299
4300           if (!len1)
4301             len = len2;
4302           else if (!len2)
4303             len = len1;
4304           else if (TREE_SIDE_EFFECTS (len1))
4305             len = len2;
4306           else if (TREE_SIDE_EFFECTS (len2))
4307             len = len1;
4308           else if (TREE_CODE (len1) != INTEGER_CST)
4309             len = len2;
4310           else if (TREE_CODE (len2) != INTEGER_CST)
4311             len = len1;
4312           else if (tree_int_cst_lt (len1, len2))
4313             len = len1;
4314           else
4315             len = len2;
4316
4317           /* If both arguments have side effects, we cannot optimize.  */
4318           if (!len || TREE_SIDE_EFFECTS (len))
4319             goto do_libcall;
4320
4321           arg3_rtx = expand_normal (len);
4322
4323           /* Make a place to write the result of the instruction.  */
4324           result = target;
4325           if (! (result != 0
4326                  && REG_P (result) && GET_MODE (result) == insn_mode
4327                  && REGNO (result) >= FIRST_PSEUDO_REGISTER))
4328             result = gen_reg_rtx (insn_mode);
4329
4330           insn = gen_cmpstrnsi (result, arg1_rtx, arg2_rtx, arg3_rtx,
4331                                 GEN_INT (MIN (arg1_align, arg2_align)));
4332         }
4333 #endif
4334
4335       if (insn)
4336         {
4337           enum machine_mode mode;
4338           emit_insn (insn);
4339
4340           /* Return the value in the proper mode for this function.  */
4341           mode = TYPE_MODE (TREE_TYPE (exp));
4342           if (GET_MODE (result) == mode)
4343             return result;
4344           if (target == 0)
4345             return convert_to_mode (mode, result, 0);
4346           convert_move (target, result, 0);
4347           return target;
4348         }
4349
4350       /* Expand the library call ourselves using a stabilized argument
4351          list to avoid re-evaluating the function's arguments twice.  */
4352 #ifdef HAVE_cmpstrnsi
4353     do_libcall:
4354 #endif
4355       fndecl = get_callee_fndecl (exp);
4356       fn = build_call_nofold_loc (EXPR_LOCATION (exp), fndecl, 2, arg1, arg2);
4357       gcc_assert (TREE_CODE (fn) == CALL_EXPR);
4358       CALL_EXPR_TAILCALL (fn) = CALL_EXPR_TAILCALL (exp);
4359       return expand_call (fn, target, target == const0_rtx);
4360     }
4361 #endif
4362   return NULL_RTX;
4363 }
4364
4365 /* Expand expression EXP, which is a call to the strncmp builtin. Return
4366    NULL_RTX if we failed the caller should emit a normal call, otherwise try to get
4367    the result in TARGET, if convenient.  */
4368
4369 static rtx
4370 expand_builtin_strncmp (tree exp, ATTRIBUTE_UNUSED rtx target,
4371                         ATTRIBUTE_UNUSED enum machine_mode mode)
4372 {
4373   location_t loc ATTRIBUTE_UNUSED = EXPR_LOCATION (exp);
4374
4375   if (!validate_arglist (exp,
4376                          POINTER_TYPE, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
4377     return NULL_RTX;
4378
4379   /* If c_strlen can determine an expression for one of the string
4380      lengths, and it doesn't have side effects, then emit cmpstrnsi
4381      using length MIN(strlen(string)+1, arg3).  */
4382 #ifdef HAVE_cmpstrnsi
4383   if (HAVE_cmpstrnsi)
4384   {
4385     tree len, len1, len2;
4386     rtx arg1_rtx, arg2_rtx, arg3_rtx;
4387     rtx result, insn;
4388     tree fndecl, fn;
4389     tree arg1 = CALL_EXPR_ARG (exp, 0);
4390     tree arg2 = CALL_EXPR_ARG (exp, 1);
4391     tree arg3 = CALL_EXPR_ARG (exp, 2);
4392
4393     unsigned int arg1_align
4394       = get_pointer_alignment (arg1, BIGGEST_ALIGNMENT) / BITS_PER_UNIT;
4395     unsigned int arg2_align
4396       = get_pointer_alignment (arg2, BIGGEST_ALIGNMENT) / BITS_PER_UNIT;
4397     enum machine_mode insn_mode
4398       = insn_data[(int) CODE_FOR_cmpstrnsi].operand[0].mode;
4399
4400     len1 = c_strlen (arg1, 1);
4401     len2 = c_strlen (arg2, 1);
4402
4403     if (len1)
4404       len1 = size_binop_loc (loc, PLUS_EXPR, ssize_int (1), len1);
4405     if (len2)
4406       len2 = size_binop_loc (loc, PLUS_EXPR, ssize_int (1), len2);
4407
4408     /* If we don't have a constant length for the first, use the length
4409        of the second, if we know it.  We don't require a constant for
4410        this case; some cost analysis could be done if both are available
4411        but neither is constant.  For now, assume they're equally cheap,
4412        unless one has side effects.  If both strings have constant lengths,
4413        use the smaller.  */
4414
4415     if (!len1)
4416       len = len2;
4417     else if (!len2)
4418       len = len1;
4419     else if (TREE_SIDE_EFFECTS (len1))
4420       len = len2;
4421     else if (TREE_SIDE_EFFECTS (len2))
4422       len = len1;
4423     else if (TREE_CODE (len1) != INTEGER_CST)
4424       len = len2;
4425     else if (TREE_CODE (len2) != INTEGER_CST)
4426       len = len1;
4427     else if (tree_int_cst_lt (len1, len2))
4428       len = len1;
4429     else
4430       len = len2;
4431
4432     /* If both arguments have side effects, we cannot optimize.  */
4433     if (!len || TREE_SIDE_EFFECTS (len))
4434       return NULL_RTX;
4435
4436     /* The actual new length parameter is MIN(len,arg3).  */
4437     len = fold_build2_loc (loc, MIN_EXPR, TREE_TYPE (len), len,
4438                        fold_convert_loc (loc, TREE_TYPE (len), arg3));
4439
4440     /* If we don't have POINTER_TYPE, call the function.  */
4441     if (arg1_align == 0 || arg2_align == 0)
4442       return NULL_RTX;
4443
4444     /* Make a place to write the result of the instruction.  */
4445     result = target;
4446     if (! (result != 0
4447            && REG_P (result) && GET_MODE (result) == insn_mode
4448            && REGNO (result) >= FIRST_PSEUDO_REGISTER))
4449       result = gen_reg_rtx (insn_mode);
4450
4451     /* Stabilize the arguments in case gen_cmpstrnsi fails.  */
4452     arg1 = builtin_save_expr (arg1);
4453     arg2 = builtin_save_expr (arg2);
4454     len = builtin_save_expr (len);
4455
4456     arg1_rtx = get_memory_rtx (arg1, len);
4457     arg2_rtx = get_memory_rtx (arg2, len);
4458     arg3_rtx = expand_normal (len);
4459     insn = gen_cmpstrnsi (result, arg1_rtx, arg2_rtx, arg3_rtx,
4460                           GEN_INT (MIN (arg1_align, arg2_align)));
4461     if (insn)
4462       {
4463         emit_insn (insn);
4464
4465         /* Return the value in the proper mode for this function.  */
4466         mode = TYPE_MODE (TREE_TYPE (exp));
4467         if (GET_MODE (result) == mode)
4468           return result;
4469         if (target == 0)
4470           return convert_to_mode (mode, result, 0);
4471         convert_move (target, result, 0);
4472         return target;
4473       }
4474
4475     /* Expand the library call ourselves using a stabilized argument
4476        list to avoid re-evaluating the function's arguments twice.  */
4477     fndecl = get_callee_fndecl (exp);
4478     fn = build_call_nofold_loc (EXPR_LOCATION (exp), fndecl, 3,
4479                                 arg1, arg2, len);
4480     gcc_assert (TREE_CODE (fn) == CALL_EXPR);
4481     CALL_EXPR_TAILCALL (fn) = CALL_EXPR_TAILCALL (exp);
4482     return expand_call (fn, target, target == const0_rtx);
4483   }
4484 #endif
4485   return NULL_RTX;
4486 }
4487
4488 /* Expand a call to __builtin_saveregs, generating the result in TARGET,
4489    if that's convenient.  */
4490
4491 rtx
4492 expand_builtin_saveregs (void)
4493 {
4494   rtx val, seq;
4495
4496   /* Don't do __builtin_saveregs more than once in a function.
4497      Save the result of the first call and reuse it.  */
4498   if (saveregs_value != 0)
4499     return saveregs_value;
4500
4501   /* When this function is called, it means that registers must be
4502      saved on entry to this function.  So we migrate the call to the
4503      first insn of this function.  */
4504
4505   start_sequence ();
4506
4507   /* Do whatever the machine needs done in this case.  */
4508   val = targetm.calls.expand_builtin_saveregs ();
4509
4510   seq = get_insns ();
4511   end_sequence ();
4512
4513   saveregs_value = val;
4514
4515   /* Put the insns after the NOTE that starts the function.  If this
4516      is inside a start_sequence, make the outer-level insn chain current, so
4517      the code is placed at the start of the function.  */
4518   push_topmost_sequence ();
4519   emit_insn_after (seq, entry_of_function ());
4520   pop_topmost_sequence ();
4521
4522   return val;
4523 }
4524
4525 /* Expand a call to __builtin_next_arg.  */
4526
4527 static rtx
4528 expand_builtin_next_arg (void)
4529 {
4530   /* Checking arguments is already done in fold_builtin_next_arg
4531      that must be called before this function.  */
4532   return expand_binop (ptr_mode, add_optab,
4533                        crtl->args.internal_arg_pointer,
4534                        crtl->args.arg_offset_rtx,
4535                        NULL_RTX, 0, OPTAB_LIB_WIDEN);
4536 }
4537
4538 /* Make it easier for the backends by protecting the valist argument
4539    from multiple evaluations.  */
4540
4541 static tree
4542 stabilize_va_list_loc (location_t loc, tree valist, int needs_lvalue)
4543 {
4544   tree vatype = targetm.canonical_va_list_type (TREE_TYPE (valist));
4545
4546   /* The current way of determining the type of valist is completely
4547      bogus.  We should have the information on the va builtin instead.  */
4548   if (!vatype)
4549     vatype = targetm.fn_abi_va_list (cfun->decl);
4550
4551   if (TREE_CODE (vatype) == ARRAY_TYPE)
4552     {
4553       if (TREE_SIDE_EFFECTS (valist))
4554         valist = save_expr (valist);
4555
4556       /* For this case, the backends will be expecting a pointer to
4557          vatype, but it's possible we've actually been given an array
4558          (an actual TARGET_CANONICAL_VA_LIST_TYPE (valist)).
4559          So fix it.  */
4560       if (TREE_CODE (TREE_TYPE (valist)) == ARRAY_TYPE)
4561         {
4562           tree p1 = build_pointer_type (TREE_TYPE (vatype));
4563           valist = build_fold_addr_expr_with_type_loc (loc, valist, p1);
4564         }
4565     }
4566   else
4567     {
4568       tree pt = build_pointer_type (vatype);
4569
4570       if (! needs_lvalue)
4571         {
4572           if (! TREE_SIDE_EFFECTS (valist))
4573             return valist;
4574
4575           valist = fold_build1_loc (loc, ADDR_EXPR, pt, valist);
4576           TREE_SIDE_EFFECTS (valist) = 1;
4577         }
4578
4579       if (TREE_SIDE_EFFECTS (valist))
4580         valist = save_expr (valist);
4581       valist = fold_build2_loc (loc, MEM_REF,
4582                                 vatype, valist, build_int_cst (pt, 0));
4583     }
4584
4585   return valist;
4586 }
4587
4588 /* The "standard" definition of va_list is void*.  */
4589
4590 tree
4591 std_build_builtin_va_list (void)
4592 {
4593   return ptr_type_node;
4594 }
4595
4596 /* The "standard" abi va_list is va_list_type_node.  */
4597
4598 tree
4599 std_fn_abi_va_list (tree fndecl ATTRIBUTE_UNUSED)
4600 {
4601   return va_list_type_node;
4602 }
4603
4604 /* The "standard" type of va_list is va_list_type_node.  */
4605
4606 tree
4607 std_canonical_va_list_type (tree type)
4608 {
4609   tree wtype, htype;
4610
4611   if (INDIRECT_REF_P (type))
4612     type = TREE_TYPE (type);
4613   else if (POINTER_TYPE_P (type) && POINTER_TYPE_P (TREE_TYPE(type)))
4614     type = TREE_TYPE (type);
4615   wtype = va_list_type_node;
4616   htype = type;
4617   /* Treat structure va_list types.  */
4618   if (TREE_CODE (wtype) == RECORD_TYPE && POINTER_TYPE_P (htype))
4619     htype = TREE_TYPE (htype);
4620   else if (TREE_CODE (wtype) == ARRAY_TYPE)
4621     {
4622       /* If va_list is an array type, the argument may have decayed
4623          to a pointer type, e.g. by being passed to another function.
4624          In that case, unwrap both types so that we can compare the
4625          underlying records.  */
4626       if (TREE_CODE (htype) == ARRAY_TYPE
4627           || POINTER_TYPE_P (htype))
4628         {
4629           wtype = TREE_TYPE (wtype);
4630           htype = TREE_TYPE (htype);
4631         }
4632     }
4633   if (TYPE_MAIN_VARIANT (wtype) == TYPE_MAIN_VARIANT (htype))
4634     return va_list_type_node;
4635
4636   return NULL_TREE;
4637 }
4638
4639 /* The "standard" implementation of va_start: just assign `nextarg' to
4640    the variable.  */
4641
4642 void
4643 std_expand_builtin_va_start (tree valist, rtx nextarg)
4644 {
4645   rtx va_r = expand_expr (valist, NULL_RTX, VOIDmode, EXPAND_WRITE);
4646   convert_move (va_r, nextarg, 0);
4647 }
4648
4649 /* Expand EXP, a call to __builtin_va_start.  */
4650
4651 static rtx
4652 expand_builtin_va_start (tree exp)
4653 {
4654   rtx nextarg;
4655   tree valist;
4656   location_t loc = EXPR_LOCATION (exp);
4657
4658   if (call_expr_nargs (exp) < 2)
4659     {
4660       error_at (loc, "too few arguments to function %<va_start%>");
4661       return const0_rtx;
4662     }
4663
4664   if (fold_builtin_next_arg (exp, true))
4665     return const0_rtx;
4666
4667   nextarg = expand_builtin_next_arg ();
4668   valist = stabilize_va_list_loc (loc, CALL_EXPR_ARG (exp, 0), 1);
4669
4670   if (targetm.expand_builtin_va_start)
4671     targetm.expand_builtin_va_start (valist, nextarg);
4672   else
4673     std_expand_builtin_va_start (valist, nextarg);
4674
4675   return const0_rtx;
4676 }
4677
4678 /* The "standard" implementation of va_arg: read the value from the
4679    current (padded) address and increment by the (padded) size.  */
4680
4681 tree
4682 std_gimplify_va_arg_expr (tree valist, tree type, gimple_seq *pre_p,
4683                           gimple_seq *post_p)
4684 {
4685   tree addr, t, type_size, rounded_size, valist_tmp;
4686   unsigned HOST_WIDE_INT align, boundary;
4687   bool indirect;
4688
4689 #ifdef ARGS_GROW_DOWNWARD
4690   /* All of the alignment and movement below is for args-grow-up machines.
4691      As of 2004, there are only 3 ARGS_GROW_DOWNWARD targets, and they all
4692      implement their own specialized gimplify_va_arg_expr routines.  */
4693   gcc_unreachable ();
4694 #endif
4695
4696   indirect = pass_by_reference (NULL, TYPE_MODE (type), type, false);
4697   if (indirect)
4698     type = build_pointer_type (type);
4699
4700   align = PARM_BOUNDARY / BITS_PER_UNIT;
4701   boundary = FUNCTION_ARG_BOUNDARY (TYPE_MODE (type), type);
4702
4703   /* When we align parameter on stack for caller, if the parameter
4704      alignment is beyond MAX_SUPPORTED_STACK_ALIGNMENT, it will be
4705      aligned at MAX_SUPPORTED_STACK_ALIGNMENT.  We will match callee
4706      here with caller.  */
4707   if (boundary > MAX_SUPPORTED_STACK_ALIGNMENT)
4708     boundary = MAX_SUPPORTED_STACK_ALIGNMENT;
4709
4710   boundary /= BITS_PER_UNIT;
4711
4712   /* Hoist the valist value into a temporary for the moment.  */
4713   valist_tmp = get_initialized_tmp_var (valist, pre_p, NULL);
4714
4715   /* va_list pointer is aligned to PARM_BOUNDARY.  If argument actually
4716      requires greater alignment, we must perform dynamic alignment.  */
4717   if (boundary > align
4718       && !integer_zerop (TYPE_SIZE (type)))
4719     {
4720       t = build2 (MODIFY_EXPR, TREE_TYPE (valist), valist_tmp,
4721                   fold_build2 (POINTER_PLUS_EXPR,
4722                                TREE_TYPE (valist),
4723                                valist_tmp, size_int (boundary - 1)));
4724       gimplify_and_add (t, pre_p);
4725
4726       t = fold_convert (sizetype, valist_tmp);
4727       t = build2 (MODIFY_EXPR, TREE_TYPE (valist), valist_tmp,
4728                   fold_convert (TREE_TYPE (valist),
4729                                 fold_build2 (BIT_AND_EXPR, sizetype, t,
4730                                              size_int (-boundary))));
4731       gimplify_and_add (t, pre_p);
4732     }
4733   else
4734     boundary = align;
4735
4736   /* If the actual alignment is less than the alignment of the type,
4737      adjust the type accordingly so that we don't assume strict alignment
4738      when dereferencing the pointer.  */
4739   boundary *= BITS_PER_UNIT;
4740   if (boundary < TYPE_ALIGN (type))
4741     {
4742       type = build_variant_type_copy (type);
4743       TYPE_ALIGN (type) = boundary;
4744     }
4745
4746   /* Compute the rounded size of the type.  */
4747   type_size = size_in_bytes (type);
4748   rounded_size = round_up (type_size, align);
4749
4750   /* Reduce rounded_size so it's sharable with the postqueue.  */
4751   gimplify_expr (&rounded_size, pre_p, post_p, is_gimple_val, fb_rvalue);
4752
4753   /* Get AP.  */
4754   addr = valist_tmp;
4755   if (PAD_VARARGS_DOWN && !integer_zerop (rounded_size))
4756     {
4757       /* Small args are padded downward.  */
4758       t = fold_build2_loc (input_location, GT_EXPR, sizetype,
4759                        rounded_size, size_int (align));
4760       t = fold_build3 (COND_EXPR, sizetype, t, size_zero_node,
4761                        size_binop (MINUS_EXPR, rounded_size, type_size));
4762       addr = fold_build2 (POINTER_PLUS_EXPR,
4763                           TREE_TYPE (addr), addr, t);
4764     }
4765
4766   /* Compute new value for AP.  */
4767   t = build2 (POINTER_PLUS_EXPR, TREE_TYPE (valist), valist_tmp, rounded_size);
4768   t = build2 (MODIFY_EXPR, TREE_TYPE (valist), valist, t);
4769   gimplify_and_add (t, pre_p);
4770
4771   addr = fold_convert (build_pointer_type (type), addr);
4772
4773   if (indirect)
4774     addr = build_va_arg_indirect_ref (addr);
4775
4776   return build_va_arg_indirect_ref (addr);
4777 }
4778
4779 /* Build an indirect-ref expression over the given TREE, which represents a
4780    piece of a va_arg() expansion.  */
4781 tree
4782 build_va_arg_indirect_ref (tree addr)
4783 {
4784   addr = build_fold_indirect_ref_loc (EXPR_LOCATION (addr), addr);
4785
4786   if (flag_mudflap) /* Don't instrument va_arg INDIRECT_REF.  */
4787     mf_mark (addr);
4788
4789   return addr;
4790 }
4791
4792 /* Return a dummy expression of type TYPE in order to keep going after an
4793    error.  */
4794
4795 static tree
4796 dummy_object (tree type)
4797 {
4798   tree t = build_int_cst (build_pointer_type (type), 0);
4799   return build2 (MEM_REF, type, t, t);
4800 }
4801
4802 /* Gimplify __builtin_va_arg, aka VA_ARG_EXPR, which is not really a
4803    builtin function, but a very special sort of operator.  */
4804
4805 enum gimplify_status
4806 gimplify_va_arg_expr (tree *expr_p, gimple_seq *pre_p, gimple_seq *post_p)
4807 {
4808   tree promoted_type, have_va_type;
4809   tree valist = TREE_OPERAND (*expr_p, 0);
4810   tree type = TREE_TYPE (*expr_p);
4811   tree t;
4812   location_t loc = EXPR_LOCATION (*expr_p);
4813
4814   /* Verify that valist is of the proper type.  */
4815   have_va_type = TREE_TYPE (valist);
4816   if (have_va_type == error_mark_node)
4817     return GS_ERROR;
4818   have_va_type = targetm.canonical_va_list_type (have_va_type);
4819
4820   if (have_va_type == NULL_TREE)
4821     {
4822       error_at (loc, "first argument to %<va_arg%> not of type %<va_list%>");
4823       return GS_ERROR;
4824     }
4825
4826   /* Generate a diagnostic for requesting data of a type that cannot
4827      be passed through `...' due to type promotion at the call site.  */
4828   if ((promoted_type = lang_hooks.types.type_promotes_to (type))
4829            != type)
4830     {
4831       static bool gave_help;
4832       bool warned;
4833
4834       /* Unfortunately, this is merely undefined, rather than a constraint
4835          violation, so we cannot make this an error.  If this call is never
4836          executed, the program is still strictly conforming.  */
4837       warned = warning_at (loc, 0,
4838                            "%qT is promoted to %qT when passed through %<...%>",
4839                            type, promoted_type);
4840       if (!gave_help && warned)
4841         {
4842           gave_help = true;
4843           inform (loc, "(so you should pass %qT not %qT to %<va_arg%>)",
4844                   promoted_type, type);
4845         }
4846
4847       /* We can, however, treat "undefined" any way we please.
4848          Call abort to encourage the user to fix the program.  */
4849       if (warned)
4850         inform (loc, "if this code is reached, the program will abort");
4851       /* Before the abort, allow the evaluation of the va_list
4852          expression to exit or longjmp.  */
4853       gimplify_and_add (valist, pre_p);
4854       t = build_call_expr_loc (loc,
4855                                implicit_built_in_decls[BUILT_IN_TRAP], 0);
4856       gimplify_and_add (t, pre_p);
4857
4858       /* This is dead code, but go ahead and finish so that the
4859          mode of the result comes out right.  */
4860       *expr_p = dummy_object (type);
4861       return GS_ALL_DONE;
4862     }
4863   else
4864     {
4865       /* Make it easier for the backends by protecting the valist argument
4866          from multiple evaluations.  */
4867       if (TREE_CODE (have_va_type) == ARRAY_TYPE)
4868         {
4869           /* For this case, the backends will be expecting a pointer to
4870              TREE_TYPE (abi), but it's possible we've
4871              actually been given an array (an actual TARGET_FN_ABI_VA_LIST).
4872              So fix it.  */
4873           if (TREE_CODE (TREE_TYPE (valist)) == ARRAY_TYPE)
4874             {
4875               tree p1 = build_pointer_type (TREE_TYPE (have_va_type));
4876               valist = fold_convert_loc (loc, p1,
4877                                          build_fold_addr_expr_loc (loc, valist));
4878             }
4879
4880           gimplify_expr (&valist, pre_p, post_p, is_gimple_val, fb_rvalue);
4881         }
4882       else
4883         gimplify_expr (&valist, pre_p, post_p, is_gimple_min_lval, fb_lvalue);
4884
4885       if (!targetm.gimplify_va_arg_expr)
4886         /* FIXME: Once most targets are converted we should merely
4887            assert this is non-null.  */
4888         return GS_ALL_DONE;
4889
4890       *expr_p = targetm.gimplify_va_arg_expr (valist, type, pre_p, post_p);
4891       return GS_OK;
4892     }
4893 }
4894
4895 /* Expand EXP, a call to __builtin_va_end.  */
4896
4897 static rtx
4898 expand_builtin_va_end (tree exp)
4899 {
4900   tree valist = CALL_EXPR_ARG (exp, 0);
4901
4902   /* Evaluate for side effects, if needed.  I hate macros that don't
4903      do that.  */
4904   if (TREE_SIDE_EFFECTS (valist))
4905     expand_expr (valist, const0_rtx, VOIDmode, EXPAND_NORMAL);
4906
4907   return const0_rtx;
4908 }
4909
4910 /* Expand EXP, a call to __builtin_va_copy.  We do this as a
4911    builtin rather than just as an assignment in stdarg.h because of the
4912    nastiness of array-type va_list types.  */
4913
4914 static rtx
4915 expand_builtin_va_copy (tree exp)
4916 {
4917   tree dst, src, t;
4918   location_t loc = EXPR_LOCATION (exp);
4919
4920   dst = CALL_EXPR_ARG (exp, 0);
4921   src = CALL_EXPR_ARG (exp, 1);
4922
4923   dst = stabilize_va_list_loc (loc, dst, 1);
4924   src = stabilize_va_list_loc (loc, src, 0);
4925
4926   gcc_assert (cfun != NULL && cfun->decl != NULL_TREE);
4927
4928   if (TREE_CODE (targetm.fn_abi_va_list (cfun->decl)) != ARRAY_TYPE)
4929     {
4930       t = build2 (MODIFY_EXPR, targetm.fn_abi_va_list (cfun->decl), dst, src);
4931       TREE_SIDE_EFFECTS (t) = 1;
4932       expand_expr (t, const0_rtx, VOIDmode, EXPAND_NORMAL);
4933     }
4934   else
4935     {
4936       rtx dstb, srcb, size;
4937
4938       /* Evaluate to pointers.  */
4939       dstb = expand_expr (dst, NULL_RTX, Pmode, EXPAND_NORMAL);
4940       srcb = expand_expr (src, NULL_RTX, Pmode, EXPAND_NORMAL);
4941       size = expand_expr (TYPE_SIZE_UNIT (targetm.fn_abi_va_list (cfun->decl)),
4942                   NULL_RTX, VOIDmode, EXPAND_NORMAL);
4943
4944       dstb = convert_memory_address (Pmode, dstb);
4945       srcb = convert_memory_address (Pmode, srcb);
4946
4947       /* "Dereference" to BLKmode memories.  */
4948       dstb = gen_rtx_MEM (BLKmode, dstb);
4949       set_mem_alias_set (dstb, get_alias_set (TREE_TYPE (TREE_TYPE (dst))));
4950       set_mem_align (dstb, TYPE_ALIGN (targetm.fn_abi_va_list (cfun->decl)));
4951       srcb = gen_rtx_MEM (BLKmode, srcb);
4952       set_mem_alias_set (srcb, get_alias_set (TREE_TYPE (TREE_TYPE (src))));
4953       set_mem_align (srcb, TYPE_ALIGN (targetm.fn_abi_va_list (cfun->decl)));
4954
4955       /* Copy.  */
4956       emit_block_move (dstb, srcb, size, BLOCK_OP_NORMAL);
4957     }
4958
4959   return const0_rtx;
4960 }
4961
4962 /* Expand a call to one of the builtin functions __builtin_frame_address or
4963    __builtin_return_address.  */
4964
4965 static rtx
4966 expand_builtin_frame_address (tree fndecl, tree exp)
4967 {
4968   /* The argument must be a nonnegative integer constant.
4969      It counts the number of frames to scan up the stack.
4970      The value is the return address saved in that frame.  */
4971   if (call_expr_nargs (exp) == 0)
4972     /* Warning about missing arg was already issued.  */
4973     return const0_rtx;
4974   else if (! host_integerp (CALL_EXPR_ARG (exp, 0), 1))
4975     {
4976       if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_FRAME_ADDRESS)
4977         error ("invalid argument to %<__builtin_frame_address%>");
4978       else
4979         error ("invalid argument to %<__builtin_return_address%>");
4980       return const0_rtx;
4981     }
4982   else
4983     {
4984       rtx tem
4985         = expand_builtin_return_addr (DECL_FUNCTION_CODE (fndecl),
4986                                       tree_low_cst (CALL_EXPR_ARG (exp, 0), 1));
4987
4988       /* Some ports cannot access arbitrary stack frames.  */
4989       if (tem == NULL)
4990         {
4991           if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_FRAME_ADDRESS)
4992             warning (0, "unsupported argument to %<__builtin_frame_address%>");
4993           else
4994             warning (0, "unsupported argument to %<__builtin_return_address%>");
4995           return const0_rtx;
4996         }
4997
4998       /* For __builtin_frame_address, return what we've got.  */
4999       if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_FRAME_ADDRESS)
5000         return tem;
5001
5002       if (!REG_P (tem)
5003           && ! CONSTANT_P (tem))
5004         tem = copy_to_mode_reg (Pmode, tem);
5005       return tem;
5006     }
5007 }
5008
5009 /* Expand EXP, a call to the alloca builtin.  Return NULL_RTX if we
5010    failed and the caller should emit a normal call.  CANNOT_ACCUMULATE
5011    is the same as for allocate_dynamic_stack_space.  */
5012
5013 static rtx
5014 expand_builtin_alloca (tree exp, bool cannot_accumulate)
5015 {
5016   rtx op0;
5017   rtx result;
5018
5019   /* Emit normal call if marked not-inlineable.  */
5020   if (CALL_CANNOT_INLINE_P (exp))
5021     return NULL_RTX;
5022
5023   if (!validate_arglist (exp, INTEGER_TYPE, VOID_TYPE))
5024     return NULL_RTX;
5025
5026   /* Compute the argument.  */
5027   op0 = expand_normal (CALL_EXPR_ARG (exp, 0));
5028
5029   /* Allocate the desired space.  */
5030   result = allocate_dynamic_stack_space (op0, 0, BIGGEST_ALIGNMENT,
5031                                          cannot_accumulate);
5032   result = convert_memory_address (ptr_mode, result);
5033
5034   return result;
5035 }
5036
5037 /* Expand a call to a bswap builtin with argument ARG0.  MODE
5038    is the mode to expand with.  */
5039
5040 static rtx
5041 expand_builtin_bswap (tree exp, rtx target, rtx subtarget)
5042 {
5043   enum machine_mode mode;
5044   tree arg;
5045   rtx op0;
5046
5047   if (!validate_arglist (exp, INTEGER_TYPE, VOID_TYPE))
5048     return NULL_RTX;
5049
5050   arg = CALL_EXPR_ARG (exp, 0);
5051   mode = TYPE_MODE (TREE_TYPE (arg));
5052   op0 = expand_expr (arg, subtarget, VOIDmode, EXPAND_NORMAL);
5053
5054   target = expand_unop (mode, bswap_optab, op0, target, 1);
5055
5056   gcc_assert (target);
5057
5058   return convert_to_mode (mode, target, 0);
5059 }
5060
5061 /* Expand a call to a unary builtin in EXP.
5062    Return NULL_RTX if a normal call should be emitted rather than expanding the
5063    function in-line.  If convenient, the result should be placed in TARGET.
5064    SUBTARGET may be used as the target for computing one of EXP's operands.  */
5065
5066 static rtx
5067 expand_builtin_unop (enum machine_mode target_mode, tree exp, rtx target,
5068                      rtx subtarget, optab op_optab)
5069 {
5070   rtx op0;
5071
5072   if (!validate_arglist (exp, INTEGER_TYPE, VOID_TYPE))
5073     return NULL_RTX;
5074
5075   /* Compute the argument.  */
5076   op0 = expand_expr (CALL_EXPR_ARG (exp, 0),
5077                      (subtarget
5078                       && (TYPE_MODE (TREE_TYPE (CALL_EXPR_ARG (exp, 0)))
5079                           == GET_MODE (subtarget))) ? subtarget : NULL_RTX,
5080                      VOIDmode, EXPAND_NORMAL);
5081   /* Compute op, into TARGET if possible.
5082      Set TARGET to wherever the result comes back.  */
5083   target = expand_unop (TYPE_MODE (TREE_TYPE (CALL_EXPR_ARG (exp, 0))),
5084                         op_optab, op0, target, 1);
5085   gcc_assert (target);
5086
5087   return convert_to_mode (target_mode, target, 0);
5088 }
5089
5090 /* Expand a call to __builtin_expect.  We just return our argument
5091    as the builtin_expect semantic should've been already executed by
5092    tree branch prediction pass. */
5093
5094 static rtx
5095 expand_builtin_expect (tree exp, rtx target)
5096 {
5097   tree arg;
5098
5099   if (call_expr_nargs (exp) < 2)
5100     return const0_rtx;
5101   arg = CALL_EXPR_ARG (exp, 0);
5102
5103   target = expand_expr (arg, target, VOIDmode, EXPAND_NORMAL);
5104   /* When guessing was done, the hints should be already stripped away.  */
5105   gcc_assert (!flag_guess_branch_prob
5106               || optimize == 0 || seen_error ());
5107   return target;
5108 }
5109
5110 void
5111 expand_builtin_trap (void)
5112 {
5113 #ifdef HAVE_trap
5114   if (HAVE_trap)
5115     emit_insn (gen_trap ());
5116   else
5117 #endif
5118     emit_library_call (abort_libfunc, LCT_NORETURN, VOIDmode, 0);
5119   emit_barrier ();
5120 }
5121
5122 /* Expand a call to __builtin_unreachable.  We do nothing except emit
5123    a barrier saying that control flow will not pass here.
5124
5125    It is the responsibility of the program being compiled to ensure
5126    that control flow does never reach __builtin_unreachable.  */
5127 static void
5128 expand_builtin_unreachable (void)
5129 {
5130   emit_barrier ();
5131 }
5132
5133 /* Expand EXP, a call to fabs, fabsf or fabsl.
5134    Return NULL_RTX if a normal call should be emitted rather than expanding
5135    the function inline.  If convenient, the result should be placed
5136    in TARGET.  SUBTARGET may be used as the target for computing
5137    the operand.  */
5138
5139 static rtx
5140 expand_builtin_fabs (tree exp, rtx target, rtx subtarget)
5141 {
5142   enum machine_mode mode;
5143   tree arg;
5144   rtx op0;
5145
5146   if (!validate_arglist (exp, REAL_TYPE, VOID_TYPE))
5147     return NULL_RTX;
5148
5149   arg = CALL_EXPR_ARG (exp, 0);
5150   CALL_EXPR_ARG (exp, 0) = arg = builtin_save_expr (arg);
5151   mode = TYPE_MODE (TREE_TYPE (arg));
5152   op0 = expand_expr (arg, subtarget, VOIDmode, EXPAND_NORMAL);
5153   return expand_abs (mode, op0, target, 0, safe_from_p (target, arg, 1));
5154 }
5155
5156 /* Expand EXP, a call to copysign, copysignf, or copysignl.
5157    Return NULL is a normal call should be emitted rather than expanding the
5158    function inline.  If convenient, the result should be placed in TARGET.
5159    SUBTARGET may be used as the target for computing the operand.  */
5160
5161 static rtx
5162 expand_builtin_copysign (tree exp, rtx target, rtx subtarget)
5163 {
5164   rtx op0, op1;
5165   tree arg;
5166
5167   if (!validate_arglist (exp, REAL_TYPE, REAL_TYPE, VOID_TYPE))
5168     return NULL_RTX;
5169
5170   arg = CALL_EXPR_ARG (exp, 0);
5171   op0 = expand_expr (arg, subtarget, VOIDmode, EXPAND_NORMAL);
5172
5173   arg = CALL_EXPR_ARG (exp, 1);
5174   op1 = expand_normal (arg);
5175
5176   return expand_copysign (op0, op1, target);
5177 }
5178
5179 /* Create a new constant string literal and return a char* pointer to it.
5180    The STRING_CST value is the LEN characters at STR.  */
5181 tree
5182 build_string_literal (int len, const char *str)
5183 {
5184   tree t, elem, index, type;
5185
5186   t = build_string (len, str);
5187   elem = build_type_variant (char_type_node, 1, 0);
5188   index = build_index_type (size_int (len - 1));
5189   type = build_array_type (elem, index);
5190   TREE_TYPE (t) = type;
5191   TREE_CONSTANT (t) = 1;
5192   TREE_READONLY (t) = 1;
5193   TREE_STATIC (t) = 1;
5194
5195   type = build_pointer_type (elem);
5196   t = build1 (ADDR_EXPR, type,
5197               build4 (ARRAY_REF, elem,
5198                       t, integer_zero_node, NULL_TREE, NULL_TREE));
5199   return t;
5200 }
5201
5202 /* Expand a call to either the entry or exit function profiler.  */
5203
5204 static rtx
5205 expand_builtin_profile_func (bool exitp)
5206 {
5207   rtx this_rtx, which;
5208
5209   this_rtx = DECL_RTL (current_function_decl);
5210   gcc_assert (MEM_P (this_rtx));
5211   this_rtx = XEXP (this_rtx, 0);
5212
5213   if (exitp)
5214     which = profile_function_exit_libfunc;
5215   else
5216     which = profile_function_entry_libfunc;
5217
5218   emit_library_call (which, LCT_NORMAL, VOIDmode, 2, this_rtx, Pmode,
5219                      expand_builtin_return_addr (BUILT_IN_RETURN_ADDRESS,
5220                                                  0),
5221                      Pmode);
5222
5223   return const0_rtx;
5224 }
5225
5226 /* Expand a call to __builtin___clear_cache.  */
5227
5228 static rtx
5229 expand_builtin___clear_cache (tree exp ATTRIBUTE_UNUSED)
5230 {
5231 #ifndef HAVE_clear_cache
5232 #ifdef CLEAR_INSN_CACHE
5233   /* There is no "clear_cache" insn, and __clear_cache() in libgcc
5234      does something.  Just do the default expansion to a call to
5235      __clear_cache().  */
5236   return NULL_RTX;
5237 #else
5238   /* There is no "clear_cache" insn, and __clear_cache() in libgcc
5239      does nothing.  There is no need to call it.  Do nothing.  */
5240   return const0_rtx;
5241 #endif /* CLEAR_INSN_CACHE */
5242 #else
5243   /* We have a "clear_cache" insn, and it will handle everything.  */
5244   tree begin, end;
5245   rtx begin_rtx, end_rtx;
5246   enum insn_code icode;
5247
5248   /* We must not expand to a library call.  If we did, any
5249      fallback library function in libgcc that might contain a call to
5250      __builtin___clear_cache() would recurse infinitely.  */
5251   if (!validate_arglist (exp, POINTER_TYPE, POINTER_TYPE, VOID_TYPE))
5252     {
5253       error ("both arguments to %<__builtin___clear_cache%> must be pointers");
5254       return const0_rtx;
5255     }
5256
5257   if (HAVE_clear_cache)
5258     {
5259       icode = CODE_FOR_clear_cache;
5260
5261       begin = CALL_EXPR_ARG (exp, 0);
5262       begin_rtx = expand_expr (begin, NULL_RTX, Pmode, EXPAND_NORMAL);
5263       begin_rtx = convert_memory_address (Pmode, begin_rtx);
5264       if (!insn_data[icode].operand[0].predicate (begin_rtx, Pmode))
5265         begin_rtx = copy_to_mode_reg (Pmode, begin_rtx);
5266
5267       end = CALL_EXPR_ARG (exp, 1);
5268       end_rtx = expand_expr (end, NULL_RTX, Pmode, EXPAND_NORMAL);
5269       end_rtx = convert_memory_address (Pmode, end_rtx);
5270       if (!insn_data[icode].operand[1].predicate (end_rtx, Pmode))
5271         end_rtx = copy_to_mode_reg (Pmode, end_rtx);
5272
5273       emit_insn (gen_clear_cache (begin_rtx, end_rtx));
5274     }
5275   return const0_rtx;
5276 #endif /* HAVE_clear_cache */
5277 }
5278
5279 /* Given a trampoline address, make sure it satisfies TRAMPOLINE_ALIGNMENT.  */
5280
5281 static rtx
5282 round_trampoline_addr (rtx tramp)
5283 {
5284   rtx temp, addend, mask;
5285
5286   /* If we don't need too much alignment, we'll have been guaranteed
5287      proper alignment by get_trampoline_type.  */
5288   if (TRAMPOLINE_ALIGNMENT <= STACK_BOUNDARY)
5289     return tramp;
5290
5291   /* Round address up to desired boundary.  */
5292   temp = gen_reg_rtx (Pmode);
5293   addend = GEN_INT (TRAMPOLINE_ALIGNMENT / BITS_PER_UNIT - 1);
5294   mask = GEN_INT (-TRAMPOLINE_ALIGNMENT / BITS_PER_UNIT);
5295
5296   temp  = expand_simple_binop (Pmode, PLUS, tramp, addend,
5297                                temp, 0, OPTAB_LIB_WIDEN);
5298   tramp = expand_simple_binop (Pmode, AND, temp, mask,
5299                                temp, 0, OPTAB_LIB_WIDEN);
5300
5301   return tramp;
5302 }
5303
5304 static rtx
5305 expand_builtin_init_trampoline (tree exp)
5306 {
5307   tree t_tramp, t_func, t_chain;
5308   rtx m_tramp, r_tramp, r_chain, tmp;
5309
5310   if (!validate_arglist (exp, POINTER_TYPE, POINTER_TYPE,
5311                          POINTER_TYPE, VOID_TYPE))
5312     return NULL_RTX;
5313
5314   t_tramp = CALL_EXPR_ARG (exp, 0);
5315   t_func = CALL_EXPR_ARG (exp, 1);
5316   t_chain = CALL_EXPR_ARG (exp, 2);
5317
5318   r_tramp = expand_normal (t_tramp);
5319   m_tramp = gen_rtx_MEM (BLKmode, r_tramp);
5320   MEM_NOTRAP_P (m_tramp) = 1;
5321
5322   /* The TRAMP argument should be the address of a field within the
5323      local function's FRAME decl.  Let's see if we can fill in the
5324      to fill in the MEM_ATTRs for this memory.  */
5325   if (TREE_CODE (t_tramp) == ADDR_EXPR)
5326     set_mem_attributes_minus_bitpos (m_tramp, TREE_OPERAND (t_tramp, 0),
5327                                      true, 0);
5328
5329   tmp = round_trampoline_addr (r_tramp);
5330   if (tmp != r_tramp)
5331     {
5332       m_tramp = change_address (m_tramp, BLKmode, tmp);
5333       set_mem_align (m_tramp, TRAMPOLINE_ALIGNMENT);
5334       set_mem_size (m_tramp, GEN_INT (TRAMPOLINE_SIZE));
5335     }
5336
5337   /* The FUNC argument should be the address of the nested function.
5338      Extract the actual function decl to pass to the hook.  */
5339   gcc_assert (TREE_CODE (t_func) == ADDR_EXPR);
5340   t_func = TREE_OPERAND (t_func, 0);
5341   gcc_assert (TREE_CODE (t_func) == FUNCTION_DECL);
5342
5343   r_chain = expand_normal (t_chain);
5344
5345   /* Generate insns to initialize the trampoline.  */
5346   targetm.calls.trampoline_init (m_tramp, t_func, r_chain);
5347
5348   trampolines_created = 1;
5349
5350   warning_at (DECL_SOURCE_LOCATION (t_func), OPT_Wtrampolines,
5351               "trampoline generated for nested function %qD", t_func);
5352
5353   return const0_rtx;
5354 }
5355
5356 static rtx
5357 expand_builtin_adjust_trampoline (tree exp)
5358 {
5359   rtx tramp;
5360
5361   if (!validate_arglist (exp, POINTER_TYPE, VOID_TYPE))
5362     return NULL_RTX;
5363
5364   tramp = expand_normal (CALL_EXPR_ARG (exp, 0));
5365   tramp = round_trampoline_addr (tramp);
5366   if (targetm.calls.trampoline_adjust_address)
5367     tramp = targetm.calls.trampoline_adjust_address (tramp);
5368
5369   return tramp;
5370 }
5371
5372 /* Expand the call EXP to the built-in signbit, signbitf or signbitl
5373    function.  The function first checks whether the back end provides
5374    an insn to implement signbit for the respective mode.  If not, it
5375    checks whether the floating point format of the value is such that
5376    the sign bit can be extracted.  If that is not the case, the
5377    function returns NULL_RTX to indicate that a normal call should be
5378    emitted rather than expanding the function in-line.  EXP is the
5379    expression that is a call to the builtin function; if convenient,
5380    the result should be placed in TARGET.  */
5381 static rtx
5382 expand_builtin_signbit (tree exp, rtx target)
5383 {
5384   const struct real_format *fmt;
5385   enum machine_mode fmode, imode, rmode;
5386   tree arg;
5387   int word, bitpos;
5388   enum insn_code icode;
5389   rtx temp;
5390   location_t loc = EXPR_LOCATION (exp);
5391
5392   if (!validate_arglist (exp, REAL_TYPE, VOID_TYPE))
5393     return NULL_RTX;
5394
5395   arg = CALL_EXPR_ARG (exp, 0);
5396   fmode = TYPE_MODE (TREE_TYPE (arg));
5397   rmode = TYPE_MODE (TREE_TYPE (exp));
5398   fmt = REAL_MODE_FORMAT (fmode);
5399
5400   arg = builtin_save_expr (arg);
5401
5402   /* Expand the argument yielding a RTX expression. */
5403   temp = expand_normal (arg);
5404
5405   /* Check if the back end provides an insn that handles signbit for the
5406      argument's mode. */
5407   icode = optab_handler (signbit_optab, fmode);
5408   if (icode != CODE_FOR_nothing)
5409     {
5410       rtx last = get_last_insn ();
5411       target = gen_reg_rtx (TYPE_MODE (TREE_TYPE (exp)));
5412       if (maybe_emit_unop_insn (icode, target, temp, UNKNOWN))
5413         return target;
5414       delete_insns_since (last);
5415     }
5416
5417   /* For floating point formats without a sign bit, implement signbit
5418      as "ARG < 0.0".  */
5419   bitpos = fmt->signbit_ro;
5420   if (bitpos < 0)
5421   {
5422     /* But we can't do this if the format supports signed zero.  */
5423     if (fmt->has_signed_zero && HONOR_SIGNED_ZEROS (fmode))
5424       return NULL_RTX;
5425
5426     arg = fold_build2_loc (loc, LT_EXPR, TREE_TYPE (exp), arg,
5427                        build_real (TREE_TYPE (arg), dconst0));
5428     return expand_expr (arg, target, VOIDmode, EXPAND_NORMAL);
5429   }
5430
5431   if (GET_MODE_SIZE (fmode) <= UNITS_PER_WORD)
5432     {
5433       imode = int_mode_for_mode (fmode);
5434       if (imode == BLKmode)
5435         return NULL_RTX;
5436       temp = gen_lowpart (imode, temp);
5437     }
5438   else
5439     {
5440       imode = word_mode;
5441       /* Handle targets with different FP word orders.  */
5442       if (FLOAT_WORDS_BIG_ENDIAN)
5443         word = (GET_MODE_BITSIZE (fmode) - bitpos) / BITS_PER_WORD;
5444       else
5445         word = bitpos / BITS_PER_WORD;
5446       temp = operand_subword_force (temp, word, fmode);
5447       bitpos = bitpos % BITS_PER_WORD;
5448     }
5449
5450   /* Force the intermediate word_mode (or narrower) result into a
5451      register.  This avoids attempting to create paradoxical SUBREGs
5452      of floating point modes below.  */
5453   temp = force_reg (imode, temp);
5454
5455   /* If the bitpos is within the "result mode" lowpart, the operation
5456      can be implement with a single bitwise AND.  Otherwise, we need
5457      a right shift and an AND.  */
5458
5459   if (bitpos < GET_MODE_BITSIZE (rmode))
5460     {
5461       double_int mask = double_int_setbit (double_int_zero, bitpos);
5462
5463       if (GET_MODE_SIZE (imode) > GET_MODE_SIZE (rmode))
5464         temp = gen_lowpart (rmode, temp);
5465       temp = expand_binop (rmode, and_optab, temp,
5466                            immed_double_int_const (mask, rmode),
5467                            NULL_RTX, 1, OPTAB_LIB_WIDEN);
5468     }
5469   else
5470     {
5471       /* Perform a logical right shift to place the signbit in the least
5472          significant bit, then truncate the result to the desired mode
5473          and mask just this bit.  */
5474       temp = expand_shift (RSHIFT_EXPR, imode, temp,
5475                            build_int_cst (NULL_TREE, bitpos), NULL_RTX, 1);
5476       temp = gen_lowpart (rmode, temp);
5477       temp = expand_binop (rmode, and_optab, temp, const1_rtx,
5478                            NULL_RTX, 1, OPTAB_LIB_WIDEN);
5479     }
5480
5481   return temp;
5482 }
5483
5484 /* Expand fork or exec calls.  TARGET is the desired target of the
5485    call.  EXP is the call. FN is the
5486    identificator of the actual function.  IGNORE is nonzero if the
5487    value is to be ignored.  */
5488
5489 static rtx
5490 expand_builtin_fork_or_exec (tree fn, tree exp, rtx target, int ignore)
5491 {
5492   tree id, decl;
5493   tree call;
5494
5495   /* If we are not profiling, just call the function.  */
5496   if (!profile_arc_flag)
5497     return NULL_RTX;
5498
5499   /* Otherwise call the wrapper.  This should be equivalent for the rest of
5500      compiler, so the code does not diverge, and the wrapper may run the
5501      code necessary for keeping the profiling sane.  */
5502
5503   switch (DECL_FUNCTION_CODE (fn))
5504     {
5505     case BUILT_IN_FORK:
5506       id = get_identifier ("__gcov_fork");
5507       break;
5508
5509     case BUILT_IN_EXECL:
5510       id = get_identifier ("__gcov_execl");
5511       break;
5512
5513     case BUILT_IN_EXECV:
5514       id = get_identifier ("__gcov_execv");
5515       break;
5516
5517     case BUILT_IN_EXECLP:
5518       id = get_identifier ("__gcov_execlp");
5519       break;
5520
5521     case BUILT_IN_EXECLE:
5522       id = get_identifier ("__gcov_execle");
5523       break;
5524
5525     case BUILT_IN_EXECVP:
5526       id = get_identifier ("__gcov_execvp");
5527       break;
5528
5529     case BUILT_IN_EXECVE:
5530       id = get_identifier ("__gcov_execve");
5531       break;
5532
5533     default:
5534       gcc_unreachable ();
5535     }
5536
5537   decl = build_decl (DECL_SOURCE_LOCATION (fn),
5538                      FUNCTION_DECL, id, TREE_TYPE (fn));
5539   DECL_EXTERNAL (decl) = 1;
5540   TREE_PUBLIC (decl) = 1;
5541   DECL_ARTIFICIAL (decl) = 1;
5542   TREE_NOTHROW (decl) = 1;
5543   DECL_VISIBILITY (decl) = VISIBILITY_DEFAULT;
5544   DECL_VISIBILITY_SPECIFIED (decl) = 1;
5545   call = rewrite_call_expr (EXPR_LOCATION (exp), exp, 0, decl, 0);
5546   return expand_call (call, target, ignore);
5547  }
5548
5549
5550 \f
5551 /* Reconstitute a mode for a __sync intrinsic operation.  Since the type of
5552    the pointer in these functions is void*, the tree optimizers may remove
5553    casts.  The mode computed in expand_builtin isn't reliable either, due
5554    to __sync_bool_compare_and_swap.
5555
5556    FCODE_DIFF should be fcode - base, where base is the FOO_1 code for the
5557    group of builtins.  This gives us log2 of the mode size.  */
5558
5559 static inline enum machine_mode
5560 get_builtin_sync_mode (int fcode_diff)
5561 {
5562   /* The size is not negotiable, so ask not to get BLKmode in return
5563      if the target indicates that a smaller size would be better.  */
5564   return mode_for_size (BITS_PER_UNIT << fcode_diff, MODE_INT, 0);
5565 }
5566
5567 /* Expand the memory expression LOC and return the appropriate memory operand
5568    for the builtin_sync operations.  */
5569
5570 static rtx
5571 get_builtin_sync_mem (tree loc, enum machine_mode mode)
5572 {
5573   rtx addr, mem;
5574
5575   addr = expand_expr (loc, NULL_RTX, ptr_mode, EXPAND_SUM);
5576   addr = convert_memory_address (Pmode, addr);
5577
5578   /* Note that we explicitly do not want any alias information for this
5579      memory, so that we kill all other live memories.  Otherwise we don't
5580      satisfy the full barrier semantics of the intrinsic.  */
5581   mem = validize_mem (gen_rtx_MEM (mode, addr));
5582
5583   /* The alignment needs to be at least according to that of the mode.  */
5584   set_mem_align (mem, MAX (GET_MODE_ALIGNMENT (mode),
5585                            get_pointer_alignment (loc, BIGGEST_ALIGNMENT)));
5586   set_mem_alias_set (mem, ALIAS_SET_MEMORY_BARRIER);
5587   MEM_VOLATILE_P (mem) = 1;
5588
5589   return mem;
5590 }
5591
5592 /* Expand the __sync_xxx_and_fetch and __sync_fetch_and_xxx intrinsics.
5593    EXP is the CALL_EXPR.  CODE is the rtx code
5594    that corresponds to the arithmetic or logical operation from the name;
5595    an exception here is that NOT actually means NAND.  TARGET is an optional
5596    place for us to store the results; AFTER is true if this is the
5597    fetch_and_xxx form.  IGNORE is true if we don't actually care about
5598    the result of the operation at all.  */
5599
5600 static rtx
5601 expand_builtin_sync_operation (enum machine_mode mode, tree exp,
5602                                enum rtx_code code, bool after,
5603                                rtx target, bool ignore)
5604 {
5605   rtx val, mem;
5606   enum machine_mode old_mode;
5607   location_t loc = EXPR_LOCATION (exp);
5608
5609   if (code == NOT && warn_sync_nand)
5610     {
5611       tree fndecl = get_callee_fndecl (exp);
5612       enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
5613
5614       static bool warned_f_a_n, warned_n_a_f;
5615
5616       switch (fcode)
5617         {
5618         case BUILT_IN_FETCH_AND_NAND_1:
5619         case BUILT_IN_FETCH_AND_NAND_2:
5620         case BUILT_IN_FETCH_AND_NAND_4:
5621         case BUILT_IN_FETCH_AND_NAND_8:
5622         case BUILT_IN_FETCH_AND_NAND_16:
5623
5624           if (warned_f_a_n)
5625             break;
5626
5627           fndecl = implicit_built_in_decls[BUILT_IN_FETCH_AND_NAND_N];
5628           inform (loc, "%qD changed semantics in GCC 4.4", fndecl);
5629           warned_f_a_n = true;
5630           break;
5631
5632         case BUILT_IN_NAND_AND_FETCH_1:
5633         case BUILT_IN_NAND_AND_FETCH_2:
5634         case BUILT_IN_NAND_AND_FETCH_4:
5635         case BUILT_IN_NAND_AND_FETCH_8:
5636         case BUILT_IN_NAND_AND_FETCH_16:
5637
5638           if (warned_n_a_f)
5639             break;
5640
5641           fndecl = implicit_built_in_decls[BUILT_IN_NAND_AND_FETCH_N];
5642           inform (loc, "%qD changed semantics in GCC 4.4", fndecl);
5643           warned_n_a_f = true;
5644           break;
5645
5646         default:
5647           gcc_unreachable ();
5648         }
5649     }
5650
5651   /* Expand the operands.  */
5652   mem = get_builtin_sync_mem (CALL_EXPR_ARG (exp, 0), mode);
5653
5654   val = expand_expr (CALL_EXPR_ARG (exp, 1), NULL_RTX, mode, EXPAND_NORMAL);
5655   /* If VAL is promoted to a wider mode, convert it back to MODE.  Take care
5656      of CONST_INTs, where we know the old_mode only from the call argument.  */
5657   old_mode = GET_MODE (val);
5658   if (old_mode == VOIDmode)
5659     old_mode = TYPE_MODE (TREE_TYPE (CALL_EXPR_ARG (exp, 1)));
5660   val = convert_modes (mode, old_mode, val, 1);
5661
5662   if (ignore)
5663     return expand_sync_operation (mem, val, code);
5664   else
5665     return expand_sync_fetch_operation (mem, val, code, after, target);
5666 }
5667
5668 /* Expand the __sync_val_compare_and_swap and __sync_bool_compare_and_swap
5669    intrinsics. EXP is the CALL_EXPR.  IS_BOOL is
5670    true if this is the boolean form.  TARGET is a place for us to store the
5671    results; this is NOT optional if IS_BOOL is true.  */
5672
5673 static rtx
5674 expand_builtin_compare_and_swap (enum machine_mode mode, tree exp,
5675                                  bool is_bool, rtx target)
5676 {
5677   rtx old_val, new_val, mem;
5678   enum machine_mode old_mode;
5679
5680   /* Expand the operands.  */
5681   mem = get_builtin_sync_mem (CALL_EXPR_ARG (exp, 0), mode);
5682
5683
5684   old_val = expand_expr (CALL_EXPR_ARG (exp, 1), NULL_RTX,
5685                          mode, EXPAND_NORMAL);
5686   /* If VAL is promoted to a wider mode, convert it back to MODE.  Take care
5687      of CONST_INTs, where we know the old_mode only from the call argument.  */
5688   old_mode = GET_MODE (old_val);
5689   if (old_mode == VOIDmode)
5690     old_mode = TYPE_MODE (TREE_TYPE (CALL_EXPR_ARG (exp, 1)));
5691   old_val = convert_modes (mode, old_mode, old_val, 1);
5692
5693   new_val = expand_expr (CALL_EXPR_ARG (exp, 2), NULL_RTX,
5694                          mode, EXPAND_NORMAL);
5695   /* If VAL is promoted to a wider mode, convert it back to MODE.  Take care
5696      of CONST_INTs, where we know the old_mode only from the call argument.  */
5697   old_mode = GET_MODE (new_val);
5698   if (old_mode == VOIDmode)
5699     old_mode = TYPE_MODE (TREE_TYPE (CALL_EXPR_ARG (exp, 2)));
5700   new_val = convert_modes (mode, old_mode, new_val, 1);
5701
5702   if (is_bool)
5703     return expand_bool_compare_and_swap (mem, old_val, new_val, target);
5704   else
5705     return expand_val_compare_and_swap (mem, old_val, new_val, target);
5706 }
5707
5708 /* Expand the __sync_lock_test_and_set intrinsic.  Note that the most
5709    general form is actually an atomic exchange, and some targets only
5710    support a reduced form with the second argument being a constant 1.
5711    EXP is the CALL_EXPR; TARGET is an optional place for us to store
5712    the results.  */
5713
5714 static rtx
5715 expand_builtin_lock_test_and_set (enum machine_mode mode, tree exp,
5716                                   rtx target)
5717 {
5718   rtx val, mem;
5719   enum machine_mode old_mode;
5720
5721   /* Expand the operands.  */
5722   mem = get_builtin_sync_mem (CALL_EXPR_ARG (exp, 0), mode);
5723   val = expand_expr (CALL_EXPR_ARG (exp, 1), NULL_RTX, mode, EXPAND_NORMAL);
5724   /* If VAL is promoted to a wider mode, convert it back to MODE.  Take care
5725      of CONST_INTs, where we know the old_mode only from the call argument.  */
5726   old_mode = GET_MODE (val);
5727   if (old_mode == VOIDmode)
5728     old_mode = TYPE_MODE (TREE_TYPE (CALL_EXPR_ARG (exp, 1)));
5729   val = convert_modes (mode, old_mode, val, 1);
5730
5731   return expand_sync_lock_test_and_set (mem, val, target);
5732 }
5733
5734 /* Expand the __sync_synchronize intrinsic.  */
5735
5736 static void
5737 expand_builtin_synchronize (void)
5738 {
5739   gimple x;
5740   VEC (tree, gc) *v_clobbers;
5741
5742 #ifdef HAVE_memory_barrier
5743   if (HAVE_memory_barrier)
5744     {
5745       emit_insn (gen_memory_barrier ());
5746       return;
5747     }
5748 #endif
5749
5750   if (synchronize_libfunc != NULL_RTX)
5751     {
5752       emit_library_call (synchronize_libfunc, LCT_NORMAL, VOIDmode, 0);
5753       return;
5754     }
5755
5756   /* If no explicit memory barrier instruction is available, create an
5757      empty asm stmt with a memory clobber.  */
5758   v_clobbers = VEC_alloc (tree, gc, 1);
5759   VEC_quick_push (tree, v_clobbers,
5760                   tree_cons (NULL, build_string (6, "memory"), NULL));
5761   x = gimple_build_asm_vec ("", NULL, NULL, v_clobbers, NULL);
5762   gimple_asm_set_volatile (x, true);
5763   expand_asm_stmt (x);
5764 }
5765
5766 /* Expand the __sync_lock_release intrinsic.  EXP is the CALL_EXPR.  */
5767
5768 static void
5769 expand_builtin_lock_release (enum machine_mode mode, tree exp)
5770 {
5771   enum insn_code icode;
5772   rtx mem, insn;
5773   rtx val = const0_rtx;
5774
5775   /* Expand the operands.  */
5776   mem = get_builtin_sync_mem (CALL_EXPR_ARG (exp, 0), mode);
5777
5778   /* If there is an explicit operation in the md file, use it.  */
5779   icode = direct_optab_handler (sync_lock_release_optab, mode);
5780   if (icode != CODE_FOR_nothing)
5781     {
5782       if (!insn_data[icode].operand[1].predicate (val, mode))
5783         val = force_reg (mode, val);
5784
5785       insn = GEN_FCN (icode) (mem, val);
5786       if (insn)
5787         {
5788           emit_insn (insn);
5789           return;
5790         }
5791     }
5792
5793   /* Otherwise we can implement this operation by emitting a barrier
5794      followed by a store of zero.  */
5795   expand_builtin_synchronize ();
5796   emit_move_insn (mem, val);
5797 }
5798 \f
5799 /* Expand an expression EXP that calls a built-in function,
5800    with result going to TARGET if that's convenient
5801    (and in mode MODE if that's convenient).
5802    SUBTARGET may be used as the target for computing one of EXP's operands.
5803    IGNORE is nonzero if the value is to be ignored.  */
5804
5805 rtx
5806 expand_builtin (tree exp, rtx target, rtx subtarget, enum machine_mode mode,
5807                 int ignore)
5808 {
5809   tree fndecl = get_callee_fndecl (exp);
5810   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
5811   enum machine_mode target_mode = TYPE_MODE (TREE_TYPE (exp));
5812   int flags;
5813
5814   if (DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_MD)
5815     return targetm.expand_builtin (exp, target, subtarget, mode, ignore);
5816
5817   /* When not optimizing, generate calls to library functions for a certain
5818      set of builtins.  */
5819   if (!optimize
5820       && !called_as_built_in (fndecl)
5821       && DECL_ASSEMBLER_NAME_SET_P (fndecl)
5822       && fcode != BUILT_IN_ALLOCA
5823       && fcode != BUILT_IN_FREE)
5824     return expand_call (exp, target, ignore);
5825
5826   /* The built-in function expanders test for target == const0_rtx
5827      to determine whether the function's result will be ignored.  */
5828   if (ignore)
5829     target = const0_rtx;
5830
5831   /* If the result of a pure or const built-in function is ignored, and
5832      none of its arguments are volatile, we can avoid expanding the
5833      built-in call and just evaluate the arguments for side-effects.  */
5834   if (target == const0_rtx
5835       && ((flags = flags_from_decl_or_type (fndecl)) & (ECF_CONST | ECF_PURE))
5836       && !(flags & ECF_LOOPING_CONST_OR_PURE))
5837     {
5838       bool volatilep = false;
5839       tree arg;
5840       call_expr_arg_iterator iter;
5841
5842       FOR_EACH_CALL_EXPR_ARG (arg, iter, exp)
5843         if (TREE_THIS_VOLATILE (arg))
5844           {
5845             volatilep = true;
5846             break;
5847           }
5848
5849       if (! volatilep)
5850         {
5851           FOR_EACH_CALL_EXPR_ARG (arg, iter, exp)
5852             expand_expr (arg, const0_rtx, VOIDmode, EXPAND_NORMAL);
5853           return const0_rtx;
5854         }
5855     }
5856
5857   switch (fcode)
5858     {
5859     CASE_FLT_FN (BUILT_IN_FABS):
5860       target = expand_builtin_fabs (exp, target, subtarget);
5861       if (target)
5862         return target;
5863       break;
5864
5865     CASE_FLT_FN (BUILT_IN_COPYSIGN):
5866       target = expand_builtin_copysign (exp, target, subtarget);
5867       if (target)
5868         return target;
5869       break;
5870
5871       /* Just do a normal library call if we were unable to fold
5872          the values.  */
5873     CASE_FLT_FN (BUILT_IN_CABS):
5874       break;
5875
5876     CASE_FLT_FN (BUILT_IN_EXP):
5877     CASE_FLT_FN (BUILT_IN_EXP10):
5878     CASE_FLT_FN (BUILT_IN_POW10):
5879     CASE_FLT_FN (BUILT_IN_EXP2):
5880     CASE_FLT_FN (BUILT_IN_EXPM1):
5881     CASE_FLT_FN (BUILT_IN_LOGB):
5882     CASE_FLT_FN (BUILT_IN_LOG):
5883     CASE_FLT_FN (BUILT_IN_LOG10):
5884     CASE_FLT_FN (BUILT_IN_LOG2):
5885     CASE_FLT_FN (BUILT_IN_LOG1P):
5886     CASE_FLT_FN (BUILT_IN_TAN):
5887     CASE_FLT_FN (BUILT_IN_ASIN):
5888     CASE_FLT_FN (BUILT_IN_ACOS):
5889     CASE_FLT_FN (BUILT_IN_ATAN):
5890     CASE_FLT_FN (BUILT_IN_SIGNIFICAND):
5891       /* Treat these like sqrt only if unsafe math optimizations are allowed,
5892          because of possible accuracy problems.  */
5893       if (! flag_unsafe_math_optimizations)
5894         break;
5895     CASE_FLT_FN (BUILT_IN_SQRT):
5896     CASE_FLT_FN (BUILT_IN_FLOOR):
5897     CASE_FLT_FN (BUILT_IN_CEIL):
5898     CASE_FLT_FN (BUILT_IN_TRUNC):
5899     CASE_FLT_FN (BUILT_IN_ROUND):
5900     CASE_FLT_FN (BUILT_IN_NEARBYINT):
5901     CASE_FLT_FN (BUILT_IN_RINT):
5902       target = expand_builtin_mathfn (exp, target, subtarget);
5903       if (target)
5904         return target;
5905       break;
5906
5907     CASE_FLT_FN (BUILT_IN_FMA):
5908       target = expand_builtin_mathfn_ternary (exp, target, subtarget);
5909       if (target)
5910         return target;
5911       break;
5912
5913     CASE_FLT_FN (BUILT_IN_ILOGB):
5914       if (! flag_unsafe_math_optimizations)
5915         break;
5916     CASE_FLT_FN (BUILT_IN_ISINF):
5917     CASE_FLT_FN (BUILT_IN_FINITE):
5918     case BUILT_IN_ISFINITE:
5919     case BUILT_IN_ISNORMAL:
5920       target = expand_builtin_interclass_mathfn (exp, target);
5921       if (target)
5922         return target;
5923       break;
5924
5925     CASE_FLT_FN (BUILT_IN_LCEIL):
5926     CASE_FLT_FN (BUILT_IN_LLCEIL):
5927     CASE_FLT_FN (BUILT_IN_LFLOOR):
5928     CASE_FLT_FN (BUILT_IN_LLFLOOR):
5929       target = expand_builtin_int_roundingfn (exp, target);
5930       if (target)
5931         return target;
5932       break;
5933
5934     CASE_FLT_FN (BUILT_IN_LRINT):
5935     CASE_FLT_FN (BUILT_IN_LLRINT):
5936     CASE_FLT_FN (BUILT_IN_LROUND):
5937     CASE_FLT_FN (BUILT_IN_LLROUND):
5938       target = expand_builtin_int_roundingfn_2 (exp, target);
5939       if (target)
5940         return target;
5941       break;
5942
5943     CASE_FLT_FN (BUILT_IN_POW):
5944       target = expand_builtin_pow (exp, target, subtarget);
5945       if (target)
5946         return target;
5947       break;
5948
5949     CASE_FLT_FN (BUILT_IN_POWI):
5950       target = expand_builtin_powi (exp, target);
5951       if (target)
5952         return target;
5953       break;
5954
5955     CASE_FLT_FN (BUILT_IN_ATAN2):
5956     CASE_FLT_FN (BUILT_IN_LDEXP):
5957     CASE_FLT_FN (BUILT_IN_SCALB):
5958     CASE_FLT_FN (BUILT_IN_SCALBN):
5959     CASE_FLT_FN (BUILT_IN_SCALBLN):
5960       if (! flag_unsafe_math_optimizations)
5961         break;
5962
5963     CASE_FLT_FN (BUILT_IN_FMOD):
5964     CASE_FLT_FN (BUILT_IN_REMAINDER):
5965     CASE_FLT_FN (BUILT_IN_DREM):
5966       target = expand_builtin_mathfn_2 (exp, target, subtarget);
5967       if (target)
5968         return target;
5969       break;
5970
5971     CASE_FLT_FN (BUILT_IN_CEXPI):
5972       target = expand_builtin_cexpi (exp, target);
5973       gcc_assert (target);
5974       return target;
5975
5976     CASE_FLT_FN (BUILT_IN_SIN):
5977     CASE_FLT_FN (BUILT_IN_COS):
5978       if (! flag_unsafe_math_optimizations)
5979         break;
5980       target = expand_builtin_mathfn_3 (exp, target, subtarget);
5981       if (target)
5982         return target;
5983       break;
5984
5985     CASE_FLT_FN (BUILT_IN_SINCOS):
5986       if (! flag_unsafe_math_optimizations)
5987         break;
5988       target = expand_builtin_sincos (exp);
5989       if (target)
5990         return target;
5991       break;
5992
5993     case BUILT_IN_APPLY_ARGS:
5994       return expand_builtin_apply_args ();
5995
5996       /* __builtin_apply (FUNCTION, ARGUMENTS, ARGSIZE) invokes
5997          FUNCTION with a copy of the parameters described by
5998          ARGUMENTS, and ARGSIZE.  It returns a block of memory
5999          allocated on the stack into which is stored all the registers
6000          that might possibly be used for returning the result of a
6001          function.  ARGUMENTS is the value returned by
6002          __builtin_apply_args.  ARGSIZE is the number of bytes of
6003          arguments that must be copied.  ??? How should this value be
6004          computed?  We'll also need a safe worst case value for varargs
6005          functions.  */
6006     case BUILT_IN_APPLY:
6007       if (!validate_arglist (exp, POINTER_TYPE,
6008                              POINTER_TYPE, INTEGER_TYPE, VOID_TYPE)
6009           && !validate_arglist (exp, REFERENCE_TYPE,
6010                                 POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
6011         return const0_rtx;
6012       else
6013         {
6014           rtx ops[3];
6015
6016           ops[0] = expand_normal (CALL_EXPR_ARG (exp, 0));
6017           ops[1] = expand_normal (CALL_EXPR_ARG (exp, 1));
6018           ops[2] = expand_normal (CALL_EXPR_ARG (exp, 2));
6019
6020           return expand_builtin_apply (ops[0], ops[1], ops[2]);
6021         }
6022
6023       /* __builtin_return (RESULT) causes the function to return the
6024          value described by RESULT.  RESULT is address of the block of
6025          memory returned by __builtin_apply.  */
6026     case BUILT_IN_RETURN:
6027       if (validate_arglist (exp, POINTER_TYPE, VOID_TYPE))
6028         expand_builtin_return (expand_normal (CALL_EXPR_ARG (exp, 0)));
6029       return const0_rtx;
6030
6031     case BUILT_IN_SAVEREGS:
6032       return expand_builtin_saveregs ();
6033
6034     case BUILT_IN_VA_ARG_PACK:
6035       /* All valid uses of __builtin_va_arg_pack () are removed during
6036          inlining.  */
6037       error ("%Kinvalid use of %<__builtin_va_arg_pack ()%>", exp);
6038       return const0_rtx;
6039
6040     case BUILT_IN_VA_ARG_PACK_LEN:
6041       /* All valid uses of __builtin_va_arg_pack_len () are removed during
6042          inlining.  */
6043       error ("%Kinvalid use of %<__builtin_va_arg_pack_len ()%>", exp);
6044       return const0_rtx;
6045
6046       /* Return the address of the first anonymous stack arg.  */
6047     case BUILT_IN_NEXT_ARG:
6048       if (fold_builtin_next_arg (exp, false))
6049         return const0_rtx;
6050       return expand_builtin_next_arg ();
6051
6052     case BUILT_IN_CLEAR_CACHE:
6053       target = expand_builtin___clear_cache (exp);
6054       if (target)
6055         return target;
6056       break;
6057
6058     case BUILT_IN_CLASSIFY_TYPE:
6059       return expand_builtin_classify_type (exp);
6060
6061     case BUILT_IN_CONSTANT_P:
6062       return const0_rtx;
6063
6064     case BUILT_IN_FRAME_ADDRESS:
6065     case BUILT_IN_RETURN_ADDRESS:
6066       return expand_builtin_frame_address (fndecl, exp);
6067
6068     /* Returns the address of the area where the structure is returned.
6069        0 otherwise.  */
6070     case BUILT_IN_AGGREGATE_INCOMING_ADDRESS:
6071       if (call_expr_nargs (exp) != 0
6072           || ! AGGREGATE_TYPE_P (TREE_TYPE (TREE_TYPE (current_function_decl)))
6073           || !MEM_P (DECL_RTL (DECL_RESULT (current_function_decl))))
6074         return const0_rtx;
6075       else
6076         return XEXP (DECL_RTL (DECL_RESULT (current_function_decl)), 0);
6077
6078     case BUILT_IN_ALLOCA:
6079       /* If the allocation stems from the declaration of a variable-sized
6080          object, it cannot accumulate.  */
6081       target = expand_builtin_alloca (exp, ALLOCA_FOR_VAR_P (exp));
6082       if (target)
6083         return target;
6084       break;
6085
6086     case BUILT_IN_STACK_SAVE:
6087       return expand_stack_save ();
6088
6089     case BUILT_IN_STACK_RESTORE:
6090       expand_stack_restore (CALL_EXPR_ARG (exp, 0));
6091       return const0_rtx;
6092
6093     case BUILT_IN_BSWAP32:
6094     case BUILT_IN_BSWAP64:
6095       target = expand_builtin_bswap (exp, target, subtarget);
6096
6097       if (target)
6098         return target;
6099       break;
6100
6101     CASE_INT_FN (BUILT_IN_FFS):
6102     case BUILT_IN_FFSIMAX:
6103       target = expand_builtin_unop (target_mode, exp, target,
6104                                     subtarget, ffs_optab);
6105       if (target)
6106         return target;
6107       break;
6108
6109     CASE_INT_FN (BUILT_IN_CLZ):
6110     case BUILT_IN_CLZIMAX:
6111       target = expand_builtin_unop (target_mode, exp, target,
6112                                     subtarget, clz_optab);
6113       if (target)
6114         return target;
6115       break;
6116
6117     CASE_INT_FN (BUILT_IN_CTZ):
6118     case BUILT_IN_CTZIMAX:
6119       target = expand_builtin_unop (target_mode, exp, target,
6120                                     subtarget, ctz_optab);
6121       if (target)
6122         return target;
6123       break;
6124
6125     CASE_INT_FN (BUILT_IN_POPCOUNT):
6126     case BUILT_IN_POPCOUNTIMAX:
6127       target = expand_builtin_unop (target_mode, exp, target,
6128                                     subtarget, popcount_optab);
6129       if (target)
6130         return target;
6131       break;
6132
6133     CASE_INT_FN (BUILT_IN_PARITY):
6134     case BUILT_IN_PARITYIMAX:
6135       target = expand_builtin_unop (target_mode, exp, target,
6136                                     subtarget, parity_optab);
6137       if (target)
6138         return target;
6139       break;
6140
6141     case BUILT_IN_STRLEN:
6142       target = expand_builtin_strlen (exp, target, target_mode);
6143       if (target)
6144         return target;
6145       break;
6146
6147     case BUILT_IN_STRCPY:
6148       target = expand_builtin_strcpy (exp, target);
6149       if (target)
6150         return target;
6151       break;
6152
6153     case BUILT_IN_STRNCPY:
6154       target = expand_builtin_strncpy (exp, target);
6155       if (target)
6156         return target;
6157       break;
6158
6159     case BUILT_IN_STPCPY:
6160       target = expand_builtin_stpcpy (exp, target, mode);
6161       if (target)
6162         return target;
6163       break;
6164
6165     case BUILT_IN_MEMCPY:
6166       target = expand_builtin_memcpy (exp, target);
6167       if (target)
6168         return target;
6169       break;
6170
6171     case BUILT_IN_MEMPCPY:
6172       target = expand_builtin_mempcpy (exp, target, mode);
6173       if (target)
6174         return target;
6175       break;
6176
6177     case BUILT_IN_MEMSET:
6178       target = expand_builtin_memset (exp, target, mode);
6179       if (target)
6180         return target;
6181       break;
6182
6183     case BUILT_IN_BZERO:
6184       target = expand_builtin_bzero (exp);
6185       if (target)
6186         return target;
6187       break;
6188
6189     case BUILT_IN_STRCMP:
6190       target = expand_builtin_strcmp (exp, target);
6191       if (target)
6192         return target;
6193       break;
6194
6195     case BUILT_IN_STRNCMP:
6196       target = expand_builtin_strncmp (exp, target, mode);
6197       if (target)
6198         return target;
6199       break;
6200
6201     case BUILT_IN_BCMP:
6202     case BUILT_IN_MEMCMP:
6203       target = expand_builtin_memcmp (exp, target, mode);
6204       if (target)
6205         return target;
6206       break;
6207
6208     case BUILT_IN_SETJMP:
6209       /* This should have been lowered to the builtins below.  */
6210       gcc_unreachable ();
6211
6212     case BUILT_IN_SETJMP_SETUP:
6213       /* __builtin_setjmp_setup is passed a pointer to an array of five words
6214           and the receiver label.  */
6215       if (validate_arglist (exp, POINTER_TYPE, POINTER_TYPE, VOID_TYPE))
6216         {
6217           rtx buf_addr = expand_expr (CALL_EXPR_ARG (exp, 0), subtarget,
6218                                       VOIDmode, EXPAND_NORMAL);
6219           tree label = TREE_OPERAND (CALL_EXPR_ARG (exp, 1), 0);
6220           rtx label_r = label_rtx (label);
6221
6222           /* This is copied from the handling of non-local gotos.  */
6223           expand_builtin_setjmp_setup (buf_addr, label_r);
6224           nonlocal_goto_handler_labels
6225             = gen_rtx_EXPR_LIST (VOIDmode, label_r,
6226                                  nonlocal_goto_handler_labels);
6227           /* ??? Do not let expand_label treat us as such since we would
6228              not want to be both on the list of non-local labels and on
6229              the list of forced labels.  */
6230           FORCED_LABEL (label) = 0;
6231           return const0_rtx;
6232         }
6233       break;
6234
6235     case BUILT_IN_SETJMP_DISPATCHER:
6236        /* __builtin_setjmp_dispatcher is passed the dispatcher label.  */
6237       if (validate_arglist (exp, POINTER_TYPE, VOID_TYPE))
6238         {
6239           tree label = TREE_OPERAND (CALL_EXPR_ARG (exp, 0), 0);
6240           rtx label_r = label_rtx (label);
6241
6242           /* Remove the dispatcher label from the list of non-local labels
6243              since the receiver labels have been added to it above.  */
6244           remove_node_from_expr_list (label_r, &nonlocal_goto_handler_labels);
6245           return const0_rtx;
6246         }
6247       break;
6248
6249     case BUILT_IN_SETJMP_RECEIVER:
6250        /* __builtin_setjmp_receiver is passed the receiver label.  */
6251       if (validate_arglist (exp, POINTER_TYPE, VOID_TYPE))
6252         {
6253           tree label = TREE_OPERAND (CALL_EXPR_ARG (exp, 0), 0);
6254           rtx label_r = label_rtx (label);
6255
6256           expand_builtin_setjmp_receiver (label_r);
6257           return const0_rtx;
6258         }
6259       break;
6260
6261       /* __builtin_longjmp is passed a pointer to an array of five words.
6262          It's similar to the C library longjmp function but works with
6263          __builtin_setjmp above.  */
6264     case BUILT_IN_LONGJMP:
6265       if (validate_arglist (exp, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
6266         {
6267           rtx buf_addr = expand_expr (CALL_EXPR_ARG (exp, 0), subtarget,
6268                                       VOIDmode, EXPAND_NORMAL);
6269           rtx value = expand_normal (CALL_EXPR_ARG (exp, 1));
6270
6271           if (value != const1_rtx)
6272             {
6273               error ("%<__builtin_longjmp%> second argument must be 1");
6274               return const0_rtx;
6275             }
6276
6277           expand_builtin_longjmp (buf_addr, value);
6278           return const0_rtx;
6279         }
6280       break;
6281
6282     case BUILT_IN_NONLOCAL_GOTO:
6283       target = expand_builtin_nonlocal_goto (exp);
6284       if (target)
6285         return target;
6286       break;
6287
6288       /* This updates the setjmp buffer that is its argument with the value
6289          of the current stack pointer.  */
6290     case BUILT_IN_UPDATE_SETJMP_BUF:
6291       if (validate_arglist (exp, POINTER_TYPE, VOID_TYPE))
6292         {
6293           rtx buf_addr
6294             = expand_normal (CALL_EXPR_ARG (exp, 0));
6295
6296           expand_builtin_update_setjmp_buf (buf_addr);
6297           return const0_rtx;
6298         }
6299       break;
6300
6301     case BUILT_IN_TRAP:
6302       expand_builtin_trap ();
6303       return const0_rtx;
6304
6305     case BUILT_IN_UNREACHABLE:
6306       expand_builtin_unreachable ();
6307       return const0_rtx;
6308
6309     CASE_FLT_FN (BUILT_IN_SIGNBIT):
6310     case BUILT_IN_SIGNBITD32:
6311     case BUILT_IN_SIGNBITD64:
6312     case BUILT_IN_SIGNBITD128:
6313       target = expand_builtin_signbit (exp, target);
6314       if (target)
6315         return target;
6316       break;
6317
6318       /* Various hooks for the DWARF 2 __throw routine.  */
6319     case BUILT_IN_UNWIND_INIT:
6320       expand_builtin_unwind_init ();
6321       return const0_rtx;
6322     case BUILT_IN_DWARF_CFA:
6323       return virtual_cfa_rtx;
6324 #ifdef DWARF2_UNWIND_INFO
6325     case BUILT_IN_DWARF_SP_COLUMN:
6326       return expand_builtin_dwarf_sp_column ();
6327     case BUILT_IN_INIT_DWARF_REG_SIZES:
6328       expand_builtin_init_dwarf_reg_sizes (CALL_EXPR_ARG (exp, 0));
6329       return const0_rtx;
6330 #endif
6331     case BUILT_IN_FROB_RETURN_ADDR:
6332       return expand_builtin_frob_return_addr (CALL_EXPR_ARG (exp, 0));
6333     case BUILT_IN_EXTRACT_RETURN_ADDR:
6334       return expand_builtin_extract_return_addr (CALL_EXPR_ARG (exp, 0));
6335     case BUILT_IN_EH_RETURN:
6336       expand_builtin_eh_return (CALL_EXPR_ARG (exp, 0),
6337                                 CALL_EXPR_ARG (exp, 1));
6338       return const0_rtx;
6339 #ifdef EH_RETURN_DATA_REGNO
6340     case BUILT_IN_EH_RETURN_DATA_REGNO:
6341       return expand_builtin_eh_return_data_regno (exp);
6342 #endif
6343     case BUILT_IN_EXTEND_POINTER:
6344       return expand_builtin_extend_pointer (CALL_EXPR_ARG (exp, 0));
6345     case BUILT_IN_EH_POINTER:
6346       return expand_builtin_eh_pointer (exp);
6347     case BUILT_IN_EH_FILTER:
6348       return expand_builtin_eh_filter (exp);
6349     case BUILT_IN_EH_COPY_VALUES:
6350       return expand_builtin_eh_copy_values (exp);
6351
6352     case BUILT_IN_VA_START:
6353       return expand_builtin_va_start (exp);
6354     case BUILT_IN_VA_END:
6355       return expand_builtin_va_end (exp);
6356     case BUILT_IN_VA_COPY:
6357       return expand_builtin_va_copy (exp);
6358     case BUILT_IN_EXPECT:
6359       return expand_builtin_expect (exp, target);
6360     case BUILT_IN_PREFETCH:
6361       expand_builtin_prefetch (exp);
6362       return const0_rtx;
6363
6364     case BUILT_IN_PROFILE_FUNC_ENTER:
6365       return expand_builtin_profile_func (false);
6366     case BUILT_IN_PROFILE_FUNC_EXIT:
6367       return expand_builtin_profile_func (true);
6368
6369     case BUILT_IN_INIT_TRAMPOLINE:
6370       return expand_builtin_init_trampoline (exp);
6371     case BUILT_IN_ADJUST_TRAMPOLINE:
6372       return expand_builtin_adjust_trampoline (exp);
6373
6374     case BUILT_IN_FORK:
6375     case BUILT_IN_EXECL:
6376     case BUILT_IN_EXECV:
6377     case BUILT_IN_EXECLP:
6378     case BUILT_IN_EXECLE:
6379     case BUILT_IN_EXECVP:
6380     case BUILT_IN_EXECVE:
6381       target = expand_builtin_fork_or_exec (fndecl, exp, target, ignore);
6382       if (target)
6383         return target;
6384       break;
6385
6386     case BUILT_IN_FETCH_AND_ADD_1:
6387     case BUILT_IN_FETCH_AND_ADD_2:
6388     case BUILT_IN_FETCH_AND_ADD_4:
6389     case BUILT_IN_FETCH_AND_ADD_8:
6390     case BUILT_IN_FETCH_AND_ADD_16:
6391       mode = get_builtin_sync_mode (fcode - BUILT_IN_FETCH_AND_ADD_1);
6392       target = expand_builtin_sync_operation (mode, exp, PLUS,
6393                                               false, target, ignore);
6394       if (target)
6395         return target;
6396       break;
6397
6398     case BUILT_IN_FETCH_AND_SUB_1:
6399     case BUILT_IN_FETCH_AND_SUB_2:
6400     case BUILT_IN_FETCH_AND_SUB_4:
6401     case BUILT_IN_FETCH_AND_SUB_8:
6402     case BUILT_IN_FETCH_AND_SUB_16:
6403       mode = get_builtin_sync_mode (fcode - BUILT_IN_FETCH_AND_SUB_1);
6404       target = expand_builtin_sync_operation (mode, exp, MINUS,
6405                                               false, target, ignore);
6406       if (target)
6407         return target;
6408       break;
6409
6410     case BUILT_IN_FETCH_AND_OR_1:
6411     case BUILT_IN_FETCH_AND_OR_2:
6412     case BUILT_IN_FETCH_AND_OR_4:
6413     case BUILT_IN_FETCH_AND_OR_8:
6414     case BUILT_IN_FETCH_AND_OR_16:
6415       mode = get_builtin_sync_mode (fcode - BUILT_IN_FETCH_AND_OR_1);
6416       target = expand_builtin_sync_operation (mode, exp, IOR,
6417                                               false, target, ignore);
6418       if (target)
6419         return target;
6420       break;
6421
6422     case BUILT_IN_FETCH_AND_AND_1:
6423     case BUILT_IN_FETCH_AND_AND_2:
6424     case BUILT_IN_FETCH_AND_AND_4:
6425     case BUILT_IN_FETCH_AND_AND_8:
6426     case BUILT_IN_FETCH_AND_AND_16:
6427       mode = get_builtin_sync_mode (fcode - BUILT_IN_FETCH_AND_AND_1);
6428       target = expand_builtin_sync_operation (mode, exp, AND,
6429                                               false, target, ignore);
6430       if (target)
6431         return target;
6432       break;
6433
6434     case BUILT_IN_FETCH_AND_XOR_1:
6435     case BUILT_IN_FETCH_AND_XOR_2:
6436     case BUILT_IN_FETCH_AND_XOR_4:
6437     case BUILT_IN_FETCH_AND_XOR_8:
6438     case BUILT_IN_FETCH_AND_XOR_16:
6439       mode = get_builtin_sync_mode (fcode - BUILT_IN_FETCH_AND_XOR_1);
6440       target = expand_builtin_sync_operation (mode, exp, XOR,
6441                                               false, target, ignore);
6442       if (target)
6443         return target;
6444       break;
6445
6446     case BUILT_IN_FETCH_AND_NAND_1:
6447     case BUILT_IN_FETCH_AND_NAND_2:
6448     case BUILT_IN_FETCH_AND_NAND_4:
6449     case BUILT_IN_FETCH_AND_NAND_8:
6450     case BUILT_IN_FETCH_AND_NAND_16:
6451       mode = get_builtin_sync_mode (fcode - BUILT_IN_FETCH_AND_NAND_1);
6452       target = expand_builtin_sync_operation (mode, exp, NOT,
6453                                               false, target, ignore);
6454       if (target)
6455         return target;
6456       break;
6457
6458     case BUILT_IN_ADD_AND_FETCH_1:
6459     case BUILT_IN_ADD_AND_FETCH_2:
6460     case BUILT_IN_ADD_AND_FETCH_4:
6461     case BUILT_IN_ADD_AND_FETCH_8:
6462     case BUILT_IN_ADD_AND_FETCH_16:
6463       mode = get_builtin_sync_mode (fcode - BUILT_IN_ADD_AND_FETCH_1);
6464       target = expand_builtin_sync_operation (mode, exp, PLUS,
6465                                               true, target, ignore);
6466       if (target)
6467         return target;
6468       break;
6469
6470     case BUILT_IN_SUB_AND_FETCH_1:
6471     case BUILT_IN_SUB_AND_FETCH_2:
6472     case BUILT_IN_SUB_AND_FETCH_4:
6473     case BUILT_IN_SUB_AND_FETCH_8:
6474     case BUILT_IN_SUB_AND_FETCH_16:
6475       mode = get_builtin_sync_mode (fcode - BUILT_IN_SUB_AND_FETCH_1);
6476       target = expand_builtin_sync_operation (mode, exp, MINUS,
6477                                               true, target, ignore);
6478       if (target)
6479         return target;
6480       break;
6481
6482     case BUILT_IN_OR_AND_FETCH_1:
6483     case BUILT_IN_OR_AND_FETCH_2:
6484     case BUILT_IN_OR_AND_FETCH_4:
6485     case BUILT_IN_OR_AND_FETCH_8:
6486     case BUILT_IN_OR_AND_FETCH_16:
6487       mode = get_builtin_sync_mode (fcode - BUILT_IN_OR_AND_FETCH_1);
6488       target = expand_builtin_sync_operation (mode, exp, IOR,
6489                                               true, target, ignore);
6490       if (target)
6491         return target;
6492       break;
6493
6494     case BUILT_IN_AND_AND_FETCH_1:
6495     case BUILT_IN_AND_AND_FETCH_2:
6496     case BUILT_IN_AND_AND_FETCH_4:
6497     case BUILT_IN_AND_AND_FETCH_8:
6498     case BUILT_IN_AND_AND_FETCH_16:
6499       mode = get_builtin_sync_mode (fcode - BUILT_IN_AND_AND_FETCH_1);
6500       target = expand_builtin_sync_operation (mode, exp, AND,
6501                                               true, target, ignore);
6502       if (target)
6503         return target;
6504       break;
6505
6506     case BUILT_IN_XOR_AND_FETCH_1:
6507     case BUILT_IN_XOR_AND_FETCH_2:
6508     case BUILT_IN_XOR_AND_FETCH_4:
6509     case BUILT_IN_XOR_AND_FETCH_8:
6510     case BUILT_IN_XOR_AND_FETCH_16:
6511       mode = get_builtin_sync_mode (fcode - BUILT_IN_XOR_AND_FETCH_1);
6512       target = expand_builtin_sync_operation (mode, exp, XOR,
6513                                               true, target, ignore);
6514       if (target)
6515         return target;
6516       break;
6517
6518     case BUILT_IN_NAND_AND_FETCH_1:
6519     case BUILT_IN_NAND_AND_FETCH_2:
6520     case BUILT_IN_NAND_AND_FETCH_4:
6521     case BUILT_IN_NAND_AND_FETCH_8:
6522     case BUILT_IN_NAND_AND_FETCH_16:
6523       mode = get_builtin_sync_mode (fcode - BUILT_IN_NAND_AND_FETCH_1);
6524       target = expand_builtin_sync_operation (mode, exp, NOT,
6525                                               true, target, ignore);
6526       if (target)
6527         return target;
6528       break;
6529
6530     case BUILT_IN_BOOL_COMPARE_AND_SWAP_1:
6531     case BUILT_IN_BOOL_COMPARE_AND_SWAP_2:
6532     case BUILT_IN_BOOL_COMPARE_AND_SWAP_4:
6533     case BUILT_IN_BOOL_COMPARE_AND_SWAP_8:
6534     case BUILT_IN_BOOL_COMPARE_AND_SWAP_16:
6535       if (mode == VOIDmode)
6536         mode = TYPE_MODE (boolean_type_node);
6537       if (!target || !register_operand (target, mode))
6538         target = gen_reg_rtx (mode);
6539
6540       mode = get_builtin_sync_mode (fcode - BUILT_IN_BOOL_COMPARE_AND_SWAP_1);
6541       target = expand_builtin_compare_and_swap (mode, exp, true, target);
6542       if (target)
6543         return target;
6544       break;
6545
6546     case BUILT_IN_VAL_COMPARE_AND_SWAP_1:
6547     case BUILT_IN_VAL_COMPARE_AND_SWAP_2:
6548     case BUILT_IN_VAL_COMPARE_AND_SWAP_4:
6549     case BUILT_IN_VAL_COMPARE_AND_SWAP_8:
6550     case BUILT_IN_VAL_COMPARE_AND_SWAP_16:
6551       mode = get_builtin_sync_mode (fcode - BUILT_IN_VAL_COMPARE_AND_SWAP_1);
6552       target = expand_builtin_compare_and_swap (mode, exp, false, target);
6553       if (target)
6554         return target;
6555       break;
6556
6557     case BUILT_IN_LOCK_TEST_AND_SET_1:
6558     case BUILT_IN_LOCK_TEST_AND_SET_2:
6559     case BUILT_IN_LOCK_TEST_AND_SET_4:
6560     case BUILT_IN_LOCK_TEST_AND_SET_8:
6561     case BUILT_IN_LOCK_TEST_AND_SET_16:
6562       mode = get_builtin_sync_mode (fcode - BUILT_IN_LOCK_TEST_AND_SET_1);
6563       target = expand_builtin_lock_test_and_set (mode, exp, target);
6564       if (target)
6565         return target;
6566       break;
6567
6568     case BUILT_IN_LOCK_RELEASE_1:
6569     case BUILT_IN_LOCK_RELEASE_2:
6570     case BUILT_IN_LOCK_RELEASE_4:
6571     case BUILT_IN_LOCK_RELEASE_8:
6572     case BUILT_IN_LOCK_RELEASE_16:
6573       mode = get_builtin_sync_mode (fcode - BUILT_IN_LOCK_RELEASE_1);
6574       expand_builtin_lock_release (mode, exp);
6575       return const0_rtx;
6576
6577     case BUILT_IN_SYNCHRONIZE:
6578       expand_builtin_synchronize ();
6579       return const0_rtx;
6580
6581     case BUILT_IN_OBJECT_SIZE:
6582       return expand_builtin_object_size (exp);
6583
6584     case BUILT_IN_MEMCPY_CHK:
6585     case BUILT_IN_MEMPCPY_CHK:
6586     case BUILT_IN_MEMMOVE_CHK:
6587     case BUILT_IN_MEMSET_CHK:
6588       target = expand_builtin_memory_chk (exp, target, mode, fcode);
6589       if (target)
6590         return target;
6591       break;
6592
6593     case BUILT_IN_STRCPY_CHK:
6594     case BUILT_IN_STPCPY_CHK:
6595     case BUILT_IN_STRNCPY_CHK:
6596     case BUILT_IN_STRCAT_CHK:
6597     case BUILT_IN_STRNCAT_CHK:
6598     case BUILT_IN_SNPRINTF_CHK:
6599     case BUILT_IN_VSNPRINTF_CHK:
6600       maybe_emit_chk_warning (exp, fcode);
6601       break;
6602
6603     case BUILT_IN_SPRINTF_CHK:
6604     case BUILT_IN_VSPRINTF_CHK:
6605       maybe_emit_sprintf_chk_warning (exp, fcode);
6606       break;
6607
6608     case BUILT_IN_FREE:
6609       maybe_emit_free_warning (exp);
6610       break;
6611
6612     default:    /* just do library call, if unknown builtin */
6613       break;
6614     }
6615
6616   /* The switch statement above can drop through to cause the function
6617      to be called normally.  */
6618   return expand_call (exp, target, ignore);
6619 }
6620
6621 /* Determine whether a tree node represents a call to a built-in
6622    function.  If the tree T is a call to a built-in function with
6623    the right number of arguments of the appropriate types, return
6624    the DECL_FUNCTION_CODE of the call, e.g. BUILT_IN_SQRT.
6625    Otherwise the return value is END_BUILTINS.  */
6626
6627 enum built_in_function
6628 builtin_mathfn_code (const_tree t)
6629 {
6630   const_tree fndecl, arg, parmlist;
6631   const_tree argtype, parmtype;
6632   const_call_expr_arg_iterator iter;
6633
6634   if (TREE_CODE (t) != CALL_EXPR
6635       || TREE_CODE (CALL_EXPR_FN (t)) != ADDR_EXPR)
6636     return END_BUILTINS;
6637
6638   fndecl = get_callee_fndecl (t);
6639   if (fndecl == NULL_TREE
6640       || TREE_CODE (fndecl) != FUNCTION_DECL
6641       || ! DECL_BUILT_IN (fndecl)
6642       || DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_MD)
6643     return END_BUILTINS;
6644
6645   parmlist = TYPE_ARG_TYPES (TREE_TYPE (fndecl));
6646   init_const_call_expr_arg_iterator (t, &iter);
6647   for (; parmlist; parmlist = TREE_CHAIN (parmlist))
6648     {
6649       /* If a function doesn't take a variable number of arguments,
6650          the last element in the list will have type `void'.  */
6651       parmtype = TREE_VALUE (parmlist);
6652       if (VOID_TYPE_P (parmtype))
6653         {
6654           if (more_const_call_expr_args_p (&iter))
6655             return END_BUILTINS;
6656           return DECL_FUNCTION_CODE (fndecl);
6657         }
6658
6659       if (! more_const_call_expr_args_p (&iter))
6660         return END_BUILTINS;
6661
6662       arg = next_const_call_expr_arg (&iter);
6663       argtype = TREE_TYPE (arg);
6664
6665       if (SCALAR_FLOAT_TYPE_P (parmtype))
6666         {
6667           if (! SCALAR_FLOAT_TYPE_P (argtype))
6668             return END_BUILTINS;
6669         }
6670       else if (COMPLEX_FLOAT_TYPE_P (parmtype))
6671         {
6672           if (! COMPLEX_FLOAT_TYPE_P (argtype))
6673             return END_BUILTINS;
6674         }
6675       else if (POINTER_TYPE_P (parmtype))
6676         {
6677           if (! POINTER_TYPE_P (argtype))
6678             return END_BUILTINS;
6679         }
6680       else if (INTEGRAL_TYPE_P (parmtype))
6681         {
6682           if (! INTEGRAL_TYPE_P (argtype))
6683             return END_BUILTINS;
6684         }
6685       else
6686         return END_BUILTINS;
6687     }
6688
6689   /* Variable-length argument list.  */
6690   return DECL_FUNCTION_CODE (fndecl);
6691 }
6692
6693 /* Fold a call to __builtin_constant_p, if we know its argument ARG will
6694    evaluate to a constant.  */
6695
6696 static tree
6697 fold_builtin_constant_p (tree arg)
6698 {
6699   /* We return 1 for a numeric type that's known to be a constant
6700      value at compile-time or for an aggregate type that's a
6701      literal constant.  */
6702   STRIP_NOPS (arg);
6703
6704   /* If we know this is a constant, emit the constant of one.  */
6705   if (CONSTANT_CLASS_P (arg)
6706       || (TREE_CODE (arg) == CONSTRUCTOR
6707           && TREE_CONSTANT (arg)))
6708     return integer_one_node;
6709   if (TREE_CODE (arg) == ADDR_EXPR)
6710     {
6711        tree op = TREE_OPERAND (arg, 0);
6712        if (TREE_CODE (op) == STRING_CST
6713            || (TREE_CODE (op) == ARRAY_REF
6714                && integer_zerop (TREE_OPERAND (op, 1))
6715                && TREE_CODE (TREE_OPERAND (op, 0)) == STRING_CST))
6716          return integer_one_node;
6717     }
6718
6719   /* If this expression has side effects, show we don't know it to be a
6720      constant.  Likewise if it's a pointer or aggregate type since in
6721      those case we only want literals, since those are only optimized
6722      when generating RTL, not later.
6723      And finally, if we are compiling an initializer, not code, we
6724      need to return a definite result now; there's not going to be any
6725      more optimization done.  */
6726   if (TREE_SIDE_EFFECTS (arg)
6727       || AGGREGATE_TYPE_P (TREE_TYPE (arg))
6728       || POINTER_TYPE_P (TREE_TYPE (arg))
6729       || cfun == 0
6730       || folding_initializer)
6731     return integer_zero_node;
6732
6733   return NULL_TREE;
6734 }
6735
6736 /* Create builtin_expect with PRED and EXPECTED as its arguments and
6737    return it as a truthvalue.  */
6738
6739 static tree
6740 build_builtin_expect_predicate (location_t loc, tree pred, tree expected)
6741 {
6742   tree fn, arg_types, pred_type, expected_type, call_expr, ret_type;
6743
6744   fn = built_in_decls[BUILT_IN_EXPECT];
6745   arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
6746   ret_type = TREE_TYPE (TREE_TYPE (fn));
6747   pred_type = TREE_VALUE (arg_types);
6748   expected_type = TREE_VALUE (TREE_CHAIN (arg_types));
6749
6750   pred = fold_convert_loc (loc, pred_type, pred);
6751   expected = fold_convert_loc (loc, expected_type, expected);
6752   call_expr = build_call_expr_loc (loc, fn, 2, pred, expected);
6753
6754   return build2 (NE_EXPR, TREE_TYPE (pred), call_expr,
6755                  build_int_cst (ret_type, 0));
6756 }
6757
6758 /* Fold a call to builtin_expect with arguments ARG0 and ARG1.  Return
6759    NULL_TREE if no simplification is possible.  */
6760
6761 static tree
6762 fold_builtin_expect (location_t loc, tree arg0, tree arg1)
6763 {
6764   tree inner, fndecl;
6765   enum tree_code code;
6766
6767   /* If this is a builtin_expect within a builtin_expect keep the
6768      inner one.  See through a comparison against a constant.  It
6769      might have been added to create a thruthvalue.  */
6770   inner = arg0;
6771   if (COMPARISON_CLASS_P (inner)
6772       && TREE_CODE (TREE_OPERAND (inner, 1)) == INTEGER_CST)
6773     inner = TREE_OPERAND (inner, 0);
6774
6775   if (TREE_CODE (inner) == CALL_EXPR
6776       && (fndecl = get_callee_fndecl (inner))
6777       && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL
6778       && DECL_FUNCTION_CODE (fndecl) == BUILT_IN_EXPECT)
6779     return arg0;
6780
6781   /* Distribute the expected value over short-circuiting operators.
6782      See through the cast from truthvalue_type_node to long.  */
6783   inner = arg0;
6784   while (TREE_CODE (inner) == NOP_EXPR
6785          && INTEGRAL_TYPE_P (TREE_TYPE (inner))
6786          && INTEGRAL_TYPE_P (TREE_TYPE (TREE_OPERAND (inner, 0))))
6787     inner = TREE_OPERAND (inner, 0);
6788
6789   code = TREE_CODE (inner);
6790   if (code == TRUTH_ANDIF_EXPR || code == TRUTH_ORIF_EXPR)
6791     {
6792       tree op0 = TREE_OPERAND (inner, 0);
6793       tree op1 = TREE_OPERAND (inner, 1);
6794
6795       op0 = build_builtin_expect_predicate (loc, op0, arg1);
6796       op1 = build_builtin_expect_predicate (loc, op1, arg1);
6797       inner = build2 (code, TREE_TYPE (inner), op0, op1);
6798
6799       return fold_convert_loc (loc, TREE_TYPE (arg0), inner);
6800     }
6801
6802   /* If the argument isn't invariant then there's nothing else we can do.  */
6803   if (!TREE_CONSTANT (arg0))
6804     return NULL_TREE;
6805
6806   /* If we expect that a comparison against the argument will fold to
6807      a constant return the constant.  In practice, this means a true
6808      constant or the address of a non-weak symbol.  */
6809   inner = arg0;
6810   STRIP_NOPS (inner);
6811   if (TREE_CODE (inner) == ADDR_EXPR)
6812     {
6813       do
6814         {
6815           inner = TREE_OPERAND (inner, 0);
6816         }
6817       while (TREE_CODE (inner) == COMPONENT_REF
6818              || TREE_CODE (inner) == ARRAY_REF);
6819       if ((TREE_CODE (inner) == VAR_DECL
6820            || TREE_CODE (inner) == FUNCTION_DECL)
6821           && DECL_WEAK (inner))
6822         return NULL_TREE;
6823     }
6824
6825   /* Otherwise, ARG0 already has the proper type for the return value.  */
6826   return arg0;
6827 }
6828
6829 /* Fold a call to __builtin_classify_type with argument ARG.  */
6830
6831 static tree
6832 fold_builtin_classify_type (tree arg)
6833 {
6834   if (arg == 0)
6835     return build_int_cst (NULL_TREE, no_type_class);
6836
6837   return build_int_cst (NULL_TREE, type_to_class (TREE_TYPE (arg)));
6838 }
6839
6840 /* Fold a call to __builtin_strlen with argument ARG.  */
6841
6842 static tree
6843 fold_builtin_strlen (location_t loc, tree type, tree arg)
6844 {
6845   if (!validate_arg (arg, POINTER_TYPE))
6846     return NULL_TREE;
6847   else
6848     {
6849       tree len = c_strlen (arg, 0);
6850
6851       if (len)
6852         return fold_convert_loc (loc, type, len);
6853
6854       return NULL_TREE;
6855     }
6856 }
6857
6858 /* Fold a call to __builtin_inf or __builtin_huge_val.  */
6859
6860 static tree
6861 fold_builtin_inf (location_t loc, tree type, int warn)
6862 {
6863   REAL_VALUE_TYPE real;
6864
6865   /* __builtin_inff is intended to be usable to define INFINITY on all
6866      targets.  If an infinity is not available, INFINITY expands "to a
6867      positive constant of type float that overflows at translation
6868      time", footnote "In this case, using INFINITY will violate the
6869      constraint in 6.4.4 and thus require a diagnostic." (C99 7.12#4).
6870      Thus we pedwarn to ensure this constraint violation is
6871      diagnosed.  */
6872   if (!MODE_HAS_INFINITIES (TYPE_MODE (type)) && warn)
6873     pedwarn (loc, 0, "target format does not support infinity");
6874
6875   real_inf (&real);
6876   return build_real (type, real);
6877 }
6878
6879 /* Fold a call to __builtin_nan or __builtin_nans with argument ARG.  */
6880
6881 static tree
6882 fold_builtin_nan (tree arg, tree type, int quiet)
6883 {
6884   REAL_VALUE_TYPE real;
6885   const char *str;
6886
6887   if (!validate_arg (arg, POINTER_TYPE))
6888     return NULL_TREE;
6889   str = c_getstr (arg);
6890   if (!str)
6891     return NULL_TREE;
6892
6893   if (!real_nan (&real, str, quiet, TYPE_MODE (type)))
6894     return NULL_TREE;
6895
6896   return build_real (type, real);
6897 }
6898
6899 /* Return true if the floating point expression T has an integer value.
6900    We also allow +Inf, -Inf and NaN to be considered integer values.  */
6901
6902 static bool
6903 integer_valued_real_p (tree t)
6904 {
6905   switch (TREE_CODE (t))
6906     {
6907     case FLOAT_EXPR:
6908       return true;
6909
6910     case ABS_EXPR:
6911     case SAVE_EXPR:
6912       return integer_valued_real_p (TREE_OPERAND (t, 0));
6913
6914     case COMPOUND_EXPR:
6915     case MODIFY_EXPR:
6916     case BIND_EXPR:
6917       return integer_valued_real_p (TREE_OPERAND (t, 1));
6918
6919     case PLUS_EXPR:
6920     case MINUS_EXPR:
6921     case MULT_EXPR:
6922     case MIN_EXPR:
6923     case MAX_EXPR:
6924       return integer_valued_real_p (TREE_OPERAND (t, 0))
6925              && integer_valued_real_p (TREE_OPERAND (t, 1));
6926
6927     case COND_EXPR:
6928       return integer_valued_real_p (TREE_OPERAND (t, 1))
6929              && integer_valued_real_p (TREE_OPERAND (t, 2));
6930
6931     case REAL_CST:
6932       return real_isinteger (TREE_REAL_CST_PTR (t), TYPE_MODE (TREE_TYPE (t)));
6933
6934     case NOP_EXPR:
6935       {
6936         tree type = TREE_TYPE (TREE_OPERAND (t, 0));
6937         if (TREE_CODE (type) == INTEGER_TYPE)
6938           return true;
6939         if (TREE_CODE (type) == REAL_TYPE)
6940           return integer_valued_real_p (TREE_OPERAND (t, 0));
6941         break;
6942       }
6943
6944     case CALL_EXPR:
6945       switch (builtin_mathfn_code (t))
6946         {
6947         CASE_FLT_FN (BUILT_IN_CEIL):
6948         CASE_FLT_FN (BUILT_IN_FLOOR):
6949         CASE_FLT_FN (BUILT_IN_NEARBYINT):
6950         CASE_FLT_FN (BUILT_IN_RINT):
6951         CASE_FLT_FN (BUILT_IN_ROUND):
6952         CASE_FLT_FN (BUILT_IN_TRUNC):
6953           return true;
6954
6955         CASE_FLT_FN (BUILT_IN_FMIN):
6956         CASE_FLT_FN (BUILT_IN_FMAX):
6957           return integer_valued_real_p (CALL_EXPR_ARG (t, 0))
6958             && integer_valued_real_p (CALL_EXPR_ARG (t, 1));
6959
6960         default:
6961           break;
6962         }
6963       break;
6964
6965     default:
6966       break;
6967     }
6968   return false;
6969 }
6970
6971 /* FNDECL is assumed to be a builtin where truncation can be propagated
6972    across (for instance floor((double)f) == (double)floorf (f).
6973    Do the transformation for a call with argument ARG.  */
6974
6975 static tree
6976 fold_trunc_transparent_mathfn (location_t loc, tree fndecl, tree arg)
6977 {
6978   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
6979
6980   if (!validate_arg (arg, REAL_TYPE))
6981     return NULL_TREE;
6982
6983   /* Integer rounding functions are idempotent.  */
6984   if (fcode == builtin_mathfn_code (arg))
6985     return arg;
6986
6987   /* If argument is already integer valued, and we don't need to worry
6988      about setting errno, there's no need to perform rounding.  */
6989   if (! flag_errno_math && integer_valued_real_p (arg))
6990     return arg;
6991
6992   if (optimize)
6993     {
6994       tree arg0 = strip_float_extensions (arg);
6995       tree ftype = TREE_TYPE (TREE_TYPE (fndecl));
6996       tree newtype = TREE_TYPE (arg0);
6997       tree decl;
6998
6999       if (TYPE_PRECISION (newtype) < TYPE_PRECISION (ftype)
7000           && (decl = mathfn_built_in (newtype, fcode)))
7001         return fold_convert_loc (loc, ftype,
7002                                  build_call_expr_loc (loc, decl, 1,
7003                                                   fold_convert_loc (loc,
7004                                                                     newtype,
7005                                                                     arg0)));
7006     }
7007   return NULL_TREE;
7008 }
7009
7010 /* FNDECL is assumed to be builtin which can narrow the FP type of
7011    the argument, for instance lround((double)f) -> lroundf (f).
7012    Do the transformation for a call with argument ARG.  */
7013
7014 static tree
7015 fold_fixed_mathfn (location_t loc, tree fndecl, tree arg)
7016 {
7017   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
7018
7019   if (!validate_arg (arg, REAL_TYPE))
7020     return NULL_TREE;
7021
7022   /* If argument is already integer valued, and we don't need to worry
7023      about setting errno, there's no need to perform rounding.  */
7024   if (! flag_errno_math && integer_valued_real_p (arg))
7025     return fold_build1_loc (loc, FIX_TRUNC_EXPR,
7026                         TREE_TYPE (TREE_TYPE (fndecl)), arg);
7027
7028   if (optimize)
7029     {
7030       tree ftype = TREE_TYPE (arg);
7031       tree arg0 = strip_float_extensions (arg);
7032       tree newtype = TREE_TYPE (arg0);
7033       tree decl;
7034
7035       if (TYPE_PRECISION (newtype) < TYPE_PRECISION (ftype)
7036           && (decl = mathfn_built_in (newtype, fcode)))
7037         return build_call_expr_loc (loc, decl, 1,
7038                                 fold_convert_loc (loc, newtype, arg0));
7039     }
7040
7041   /* Canonicalize llround (x) to lround (x) on LP64 targets where
7042      sizeof (long long) == sizeof (long).  */
7043   if (TYPE_PRECISION (long_long_integer_type_node)
7044       == TYPE_PRECISION (long_integer_type_node))
7045     {
7046       tree newfn = NULL_TREE;
7047       switch (fcode)
7048         {
7049         CASE_FLT_FN (BUILT_IN_LLCEIL):
7050           newfn = mathfn_built_in (TREE_TYPE (arg), BUILT_IN_LCEIL);
7051           break;
7052
7053         CASE_FLT_FN (BUILT_IN_LLFLOOR):
7054           newfn = mathfn_built_in (TREE_TYPE (arg), BUILT_IN_LFLOOR);
7055           break;
7056
7057         CASE_FLT_FN (BUILT_IN_LLROUND):
7058           newfn = mathfn_built_in (TREE_TYPE (arg), BUILT_IN_LROUND);
7059           break;
7060
7061         CASE_FLT_FN (BUILT_IN_LLRINT):
7062           newfn = mathfn_built_in (TREE_TYPE (arg), BUILT_IN_LRINT);
7063           break;
7064
7065         default:
7066           break;
7067         }
7068
7069       if (newfn)
7070         {
7071           tree newcall = build_call_expr_loc (loc, newfn, 1, arg);
7072           return fold_convert_loc (loc,
7073                                    TREE_TYPE (TREE_TYPE (fndecl)), newcall);
7074         }
7075     }
7076
7077   return NULL_TREE;
7078 }
7079
7080 /* Fold call to builtin cabs, cabsf or cabsl with argument ARG.  TYPE is the
7081    return type.  Return NULL_TREE if no simplification can be made.  */
7082
7083 static tree
7084 fold_builtin_cabs (location_t loc, tree arg, tree type, tree fndecl)
7085 {
7086   tree res;
7087
7088   if (!validate_arg (arg, COMPLEX_TYPE)
7089       || TREE_CODE (TREE_TYPE (TREE_TYPE (arg))) != REAL_TYPE)
7090     return NULL_TREE;
7091
7092   /* Calculate the result when the argument is a constant.  */
7093   if (TREE_CODE (arg) == COMPLEX_CST
7094       && (res = do_mpfr_arg2 (TREE_REALPART (arg), TREE_IMAGPART (arg),
7095                               type, mpfr_hypot)))
7096     return res;
7097
7098   if (TREE_CODE (arg) == COMPLEX_EXPR)
7099     {
7100       tree real = TREE_OPERAND (arg, 0);
7101       tree imag = TREE_OPERAND (arg, 1);
7102
7103       /* If either part is zero, cabs is fabs of the other.  */
7104       if (real_zerop (real))
7105         return fold_build1_loc (loc, ABS_EXPR, type, imag);
7106       if (real_zerop (imag))
7107         return fold_build1_loc (loc, ABS_EXPR, type, real);
7108
7109       /* cabs(x+xi) -> fabs(x)*sqrt(2).  */
7110       if (flag_unsafe_math_optimizations
7111           && operand_equal_p (real, imag, OEP_PURE_SAME))
7112         {
7113           const REAL_VALUE_TYPE sqrt2_trunc
7114             = real_value_truncate (TYPE_MODE (type), dconst_sqrt2 ());
7115           STRIP_NOPS (real);
7116           return fold_build2_loc (loc, MULT_EXPR, type,
7117                               fold_build1_loc (loc, ABS_EXPR, type, real),
7118                               build_real (type, sqrt2_trunc));
7119         }
7120     }
7121
7122   /* Optimize cabs(-z) and cabs(conj(z)) as cabs(z).  */
7123   if (TREE_CODE (arg) == NEGATE_EXPR
7124       || TREE_CODE (arg) == CONJ_EXPR)
7125     return build_call_expr_loc (loc, fndecl, 1, TREE_OPERAND (arg, 0));
7126
7127   /* Don't do this when optimizing for size.  */
7128   if (flag_unsafe_math_optimizations
7129       && optimize && optimize_function_for_speed_p (cfun))
7130     {
7131       tree sqrtfn = mathfn_built_in (type, BUILT_IN_SQRT);
7132
7133       if (sqrtfn != NULL_TREE)
7134         {
7135           tree rpart, ipart, result;
7136
7137           arg = builtin_save_expr (arg);
7138
7139           rpart = fold_build1_loc (loc, REALPART_EXPR, type, arg);
7140           ipart = fold_build1_loc (loc, IMAGPART_EXPR, type, arg);
7141
7142           rpart = builtin_save_expr (rpart);
7143           ipart = builtin_save_expr (ipart);
7144
7145           result = fold_build2_loc (loc, PLUS_EXPR, type,
7146                                 fold_build2_loc (loc, MULT_EXPR, type,
7147                                              rpart, rpart),
7148                                 fold_build2_loc (loc, MULT_EXPR, type,
7149                                              ipart, ipart));
7150
7151           return build_call_expr_loc (loc, sqrtfn, 1, result);
7152         }
7153     }
7154
7155   return NULL_TREE;
7156 }
7157
7158 /* Build a complex (inf +- 0i) for the result of cproj.  TYPE is the
7159    complex tree type of the result.  If NEG is true, the imaginary
7160    zero is negative.  */
7161
7162 static tree
7163 build_complex_cproj (tree type, bool neg)
7164 {
7165   REAL_VALUE_TYPE rinf, rzero = dconst0;
7166   
7167   real_inf (&rinf);
7168   rzero.sign = neg;
7169   return build_complex (type, build_real (TREE_TYPE (type), rinf),
7170                         build_real (TREE_TYPE (type), rzero));
7171 }
7172
7173 /* Fold call to builtin cproj, cprojf or cprojl with argument ARG.  TYPE is the
7174    return type.  Return NULL_TREE if no simplification can be made.  */
7175
7176 static tree
7177 fold_builtin_cproj (location_t loc, tree arg, tree type)
7178 {
7179   if (!validate_arg (arg, COMPLEX_TYPE)
7180       || TREE_CODE (TREE_TYPE (TREE_TYPE (arg))) != REAL_TYPE)
7181     return NULL_TREE;
7182
7183   /* If there are no infinities, return arg.  */
7184   if (! HONOR_INFINITIES (TYPE_MODE (TREE_TYPE (type))))
7185     return non_lvalue_loc (loc, arg);
7186
7187   /* Calculate the result when the argument is a constant.  */
7188   if (TREE_CODE (arg) == COMPLEX_CST)
7189     {
7190       const REAL_VALUE_TYPE *real = TREE_REAL_CST_PTR (TREE_REALPART (arg));
7191       const REAL_VALUE_TYPE *imag = TREE_REAL_CST_PTR (TREE_IMAGPART (arg));
7192       
7193       if (real_isinf (real) || real_isinf (imag))
7194         return build_complex_cproj (type, imag->sign);
7195       else
7196         return arg;
7197     }
7198   else if (TREE_CODE (arg) == COMPLEX_EXPR)
7199     {
7200       tree real = TREE_OPERAND (arg, 0);
7201       tree imag = TREE_OPERAND (arg, 1);
7202
7203       STRIP_NOPS (real);
7204       STRIP_NOPS (imag);
7205       
7206       /* If the real part is inf and the imag part is known to be
7207          nonnegative, return (inf + 0i).  Remember side-effects are
7208          possible in the imag part.  */
7209       if (TREE_CODE (real) == REAL_CST
7210           && real_isinf (TREE_REAL_CST_PTR (real))
7211           && tree_expr_nonnegative_p (imag))
7212         return omit_one_operand_loc (loc, type,
7213                                      build_complex_cproj (type, false),
7214                                      arg);
7215       
7216       /* If the imag part is inf, return (inf+I*copysign(0,imag)).
7217          Remember side-effects are possible in the real part.  */
7218       if (TREE_CODE (imag) == REAL_CST
7219           && real_isinf (TREE_REAL_CST_PTR (imag)))
7220         return
7221           omit_one_operand_loc (loc, type,
7222                                 build_complex_cproj (type, TREE_REAL_CST_PTR
7223                                                      (imag)->sign), arg);
7224     }
7225
7226   return NULL_TREE;
7227 }
7228
7229 /* Fold a builtin function call to sqrt, sqrtf, or sqrtl with argument ARG.
7230    Return NULL_TREE if no simplification can be made.  */
7231
7232 static tree
7233 fold_builtin_sqrt (location_t loc, tree arg, tree type)
7234 {
7235
7236   enum built_in_function fcode;
7237   tree res;
7238
7239   if (!validate_arg (arg, REAL_TYPE))
7240     return NULL_TREE;
7241
7242   /* Calculate the result when the argument is a constant.  */
7243   if ((res = do_mpfr_arg1 (arg, type, mpfr_sqrt, &dconst0, NULL, true)))
7244     return res;
7245
7246   /* Optimize sqrt(expN(x)) = expN(x*0.5).  */
7247   fcode = builtin_mathfn_code (arg);
7248   if (flag_unsafe_math_optimizations && BUILTIN_EXPONENT_P (fcode))
7249     {
7250       tree expfn = TREE_OPERAND (CALL_EXPR_FN (arg), 0);
7251       arg = fold_build2_loc (loc, MULT_EXPR, type,
7252                          CALL_EXPR_ARG (arg, 0),
7253                          build_real (type, dconsthalf));
7254       return build_call_expr_loc (loc, expfn, 1, arg);
7255     }
7256
7257   /* Optimize sqrt(Nroot(x)) -> pow(x,1/(2*N)).  */
7258   if (flag_unsafe_math_optimizations && BUILTIN_ROOT_P (fcode))
7259     {
7260       tree powfn = mathfn_built_in (type, BUILT_IN_POW);
7261
7262       if (powfn)
7263         {
7264           tree arg0 = CALL_EXPR_ARG (arg, 0);
7265           tree tree_root;
7266           /* The inner root was either sqrt or cbrt.  */
7267           /* This was a conditional expression but it triggered a bug
7268              in Sun C 5.5.  */
7269           REAL_VALUE_TYPE dconstroot;
7270           if (BUILTIN_SQRT_P (fcode))
7271             dconstroot = dconsthalf;
7272           else
7273             dconstroot = dconst_third ();
7274
7275           /* Adjust for the outer root.  */
7276           SET_REAL_EXP (&dconstroot, REAL_EXP (&dconstroot) - 1);
7277           dconstroot = real_value_truncate (TYPE_MODE (type), dconstroot);
7278           tree_root = build_real (type, dconstroot);
7279           return build_call_expr_loc (loc, powfn, 2, arg0, tree_root);
7280         }
7281     }
7282
7283   /* Optimize sqrt(pow(x,y)) = pow(|x|,y*0.5).  */
7284   if (flag_unsafe_math_optimizations
7285       && (fcode == BUILT_IN_POW
7286           || fcode == BUILT_IN_POWF
7287           || fcode == BUILT_IN_POWL))
7288     {
7289       tree powfn = TREE_OPERAND (CALL_EXPR_FN (arg), 0);
7290       tree arg0 = CALL_EXPR_ARG (arg, 0);
7291       tree arg1 = CALL_EXPR_ARG (arg, 1);
7292       tree narg1;
7293       if (!tree_expr_nonnegative_p (arg0))
7294         arg0 = build1 (ABS_EXPR, type, arg0);
7295       narg1 = fold_build2_loc (loc, MULT_EXPR, type, arg1,
7296                            build_real (type, dconsthalf));
7297       return build_call_expr_loc (loc, powfn, 2, arg0, narg1);
7298     }
7299
7300   return NULL_TREE;
7301 }
7302
7303 /* Fold a builtin function call to cbrt, cbrtf, or cbrtl with argument ARG.
7304    Return NULL_TREE if no simplification can be made.  */
7305
7306 static tree
7307 fold_builtin_cbrt (location_t loc, tree arg, tree type)
7308 {
7309   const enum built_in_function fcode = builtin_mathfn_code (arg);
7310   tree res;
7311
7312   if (!validate_arg (arg, REAL_TYPE))
7313     return NULL_TREE;
7314
7315   /* Calculate the result when the argument is a constant.  */
7316   if ((res = do_mpfr_arg1 (arg, type, mpfr_cbrt, NULL, NULL, 0)))
7317     return res;
7318
7319   if (flag_unsafe_math_optimizations)
7320     {
7321       /* Optimize cbrt(expN(x)) -> expN(x/3).  */
7322       if (BUILTIN_EXPONENT_P (fcode))
7323         {
7324           tree expfn = TREE_OPERAND (CALL_EXPR_FN (arg), 0);
7325           const REAL_VALUE_TYPE third_trunc =
7326             real_value_truncate (TYPE_MODE (type), dconst_third ());
7327           arg = fold_build2_loc (loc, MULT_EXPR, type,
7328                              CALL_EXPR_ARG (arg, 0),
7329                              build_real (type, third_trunc));
7330           return build_call_expr_loc (loc, expfn, 1, arg);
7331         }
7332
7333       /* Optimize cbrt(sqrt(x)) -> pow(x,1/6).  */
7334       if (BUILTIN_SQRT_P (fcode))
7335         {
7336           tree powfn = mathfn_built_in (type, BUILT_IN_POW);
7337
7338           if (powfn)
7339             {
7340               tree arg0 = CALL_EXPR_ARG (arg, 0);
7341               tree tree_root;
7342               REAL_VALUE_TYPE dconstroot = dconst_third ();
7343
7344               SET_REAL_EXP (&dconstroot, REAL_EXP (&dconstroot) - 1);
7345               dconstroot = real_value_truncate (TYPE_MODE (type), dconstroot);
7346               tree_root = build_real (type, dconstroot);
7347               return build_call_expr_loc (loc, powfn, 2, arg0, tree_root);
7348             }
7349         }
7350
7351       /* Optimize cbrt(cbrt(x)) -> pow(x,1/9) iff x is nonnegative.  */
7352       if (BUILTIN_CBRT_P (fcode))
7353         {
7354           tree arg0 = CALL_EXPR_ARG (arg, 0);
7355           if (tree_expr_nonnegative_p (arg0))
7356             {
7357               tree powfn = mathfn_built_in (type, BUILT_IN_POW);
7358
7359               if (powfn)
7360                 {
7361                   tree tree_root;
7362                   REAL_VALUE_TYPE dconstroot;
7363
7364                   real_arithmetic (&dconstroot, MULT_EXPR,
7365                                    dconst_third_ptr (), dconst_third_ptr ());
7366                   dconstroot = real_value_truncate (TYPE_MODE (type), dconstroot);
7367                   tree_root = build_real (type, dconstroot);
7368                   return build_call_expr_loc (loc, powfn, 2, arg0, tree_root);
7369                 }
7370             }
7371         }
7372
7373       /* Optimize cbrt(pow(x,y)) -> pow(x,y/3) iff x is nonnegative.  */
7374       if (fcode == BUILT_IN_POW
7375           || fcode == BUILT_IN_POWF
7376           || fcode == BUILT_IN_POWL)
7377         {
7378           tree arg00 = CALL_EXPR_ARG (arg, 0);
7379           tree arg01 = CALL_EXPR_ARG (arg, 1);
7380           if (tree_expr_nonnegative_p (arg00))
7381             {
7382               tree powfn = TREE_OPERAND (CALL_EXPR_FN (arg), 0);
7383               const REAL_VALUE_TYPE dconstroot
7384                 = real_value_truncate (TYPE_MODE (type), dconst_third ());
7385               tree narg01 = fold_build2_loc (loc, MULT_EXPR, type, arg01,
7386                                          build_real (type, dconstroot));
7387               return build_call_expr_loc (loc, powfn, 2, arg00, narg01);
7388             }
7389         }
7390     }
7391   return NULL_TREE;
7392 }
7393
7394 /* Fold function call to builtin cos, cosf, or cosl with argument ARG.
7395    TYPE is the type of the return value.  Return NULL_TREE if no
7396    simplification can be made.  */
7397
7398 static tree
7399 fold_builtin_cos (location_t loc,
7400                   tree arg, tree type, tree fndecl)
7401 {
7402   tree res, narg;
7403
7404   if (!validate_arg (arg, REAL_TYPE))
7405     return NULL_TREE;
7406
7407   /* Calculate the result when the argument is a constant.  */
7408   if ((res = do_mpfr_arg1 (arg, type, mpfr_cos, NULL, NULL, 0)))
7409     return res;
7410
7411   /* Optimize cos(-x) into cos (x).  */
7412   if ((narg = fold_strip_sign_ops (arg)))
7413     return build_call_expr_loc (loc, fndecl, 1, narg);
7414
7415   return NULL_TREE;
7416 }
7417
7418 /* Fold function call to builtin cosh, coshf, or coshl with argument ARG.
7419    Return NULL_TREE if no simplification can be made.  */
7420
7421 static tree
7422 fold_builtin_cosh (location_t loc, tree arg, tree type, tree fndecl)
7423 {
7424   if (validate_arg (arg, REAL_TYPE))
7425     {
7426       tree res, narg;
7427
7428       /* Calculate the result when the argument is a constant.  */
7429       if ((res = do_mpfr_arg1 (arg, type, mpfr_cosh, NULL, NULL, 0)))
7430         return res;
7431
7432       /* Optimize cosh(-x) into cosh (x).  */
7433       if ((narg = fold_strip_sign_ops (arg)))
7434         return build_call_expr_loc (loc, fndecl, 1, narg);
7435     }
7436
7437   return NULL_TREE;
7438 }
7439
7440 /* Fold function call to builtin ccos (or ccosh if HYPER is TRUE) with
7441    argument ARG.  TYPE is the type of the return value.  Return
7442    NULL_TREE if no simplification can be made.  */
7443
7444 static tree
7445 fold_builtin_ccos (location_t loc, tree arg, tree type, tree fndecl,
7446                    bool hyper)
7447 {
7448   if (validate_arg (arg, COMPLEX_TYPE)
7449       && TREE_CODE (TREE_TYPE (TREE_TYPE (arg))) == REAL_TYPE)
7450     {
7451       tree tmp;
7452
7453       /* Calculate the result when the argument is a constant.  */
7454       if ((tmp = do_mpc_arg1 (arg, type, (hyper ? mpc_cosh : mpc_cos))))
7455         return tmp;
7456
7457       /* Optimize fn(-x) into fn(x).  */
7458       if ((tmp = fold_strip_sign_ops (arg)))
7459         return build_call_expr_loc (loc, fndecl, 1, tmp);
7460     }
7461
7462   return NULL_TREE;
7463 }
7464
7465 /* Fold function call to builtin tan, tanf, or tanl with argument ARG.
7466    Return NULL_TREE if no simplification can be made.  */
7467
7468 static tree
7469 fold_builtin_tan (tree arg, tree type)
7470 {
7471   enum built_in_function fcode;
7472   tree res;
7473
7474   if (!validate_arg (arg, REAL_TYPE))
7475     return NULL_TREE;
7476
7477   /* Calculate the result when the argument is a constant.  */
7478   if ((res = do_mpfr_arg1 (arg, type, mpfr_tan, NULL, NULL, 0)))
7479     return res;
7480
7481   /* Optimize tan(atan(x)) = x.  */
7482   fcode = builtin_mathfn_code (arg);
7483   if (flag_unsafe_math_optimizations
7484       && (fcode == BUILT_IN_ATAN
7485           || fcode == BUILT_IN_ATANF
7486           || fcode == BUILT_IN_ATANL))
7487     return CALL_EXPR_ARG (arg, 0);
7488
7489   return NULL_TREE;
7490 }
7491
7492 /* Fold function call to builtin sincos, sincosf, or sincosl.  Return
7493    NULL_TREE if no simplification can be made.  */
7494
7495 static tree
7496 fold_builtin_sincos (location_t loc,
7497                      tree arg0, tree arg1, tree arg2)
7498 {
7499   tree type;
7500   tree res, fn, call;
7501
7502   if (!validate_arg (arg0, REAL_TYPE)
7503       || !validate_arg (arg1, POINTER_TYPE)
7504       || !validate_arg (arg2, POINTER_TYPE))
7505     return NULL_TREE;
7506
7507   type = TREE_TYPE (arg0);
7508
7509   /* Calculate the result when the argument is a constant.  */
7510   if ((res = do_mpfr_sincos (arg0, arg1, arg2)))
7511     return res;
7512
7513   /* Canonicalize sincos to cexpi.  */
7514   if (!TARGET_C99_FUNCTIONS)
7515     return NULL_TREE;
7516   fn = mathfn_built_in (type, BUILT_IN_CEXPI);
7517   if (!fn)
7518     return NULL_TREE;
7519
7520   call = build_call_expr_loc (loc, fn, 1, arg0);
7521   call = builtin_save_expr (call);
7522
7523   return build2 (COMPOUND_EXPR, void_type_node,
7524                  build2 (MODIFY_EXPR, void_type_node,
7525                          build_fold_indirect_ref_loc (loc, arg1),
7526                          build1 (IMAGPART_EXPR, type, call)),
7527                  build2 (MODIFY_EXPR, void_type_node,
7528                          build_fold_indirect_ref_loc (loc, arg2),
7529                          build1 (REALPART_EXPR, type, call)));
7530 }
7531
7532 /* Fold function call to builtin cexp, cexpf, or cexpl.  Return
7533    NULL_TREE if no simplification can be made.  */
7534
7535 static tree
7536 fold_builtin_cexp (location_t loc, tree arg0, tree type)
7537 {
7538   tree rtype;
7539   tree realp, imagp, ifn;
7540   tree res;
7541
7542   if (!validate_arg (arg0, COMPLEX_TYPE)
7543       || TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) != REAL_TYPE)
7544     return NULL_TREE;
7545
7546   /* Calculate the result when the argument is a constant.  */
7547   if ((res = do_mpc_arg1 (arg0, type, mpc_exp)))
7548     return res;
7549
7550   rtype = TREE_TYPE (TREE_TYPE (arg0));
7551
7552   /* In case we can figure out the real part of arg0 and it is constant zero
7553      fold to cexpi.  */
7554   if (!TARGET_C99_FUNCTIONS)
7555     return NULL_TREE;
7556   ifn = mathfn_built_in (rtype, BUILT_IN_CEXPI);
7557   if (!ifn)
7558     return NULL_TREE;
7559
7560   if ((realp = fold_unary_loc (loc, REALPART_EXPR, rtype, arg0))
7561       && real_zerop (realp))
7562     {
7563       tree narg = fold_build1_loc (loc, IMAGPART_EXPR, rtype, arg0);
7564       return build_call_expr_loc (loc, ifn, 1, narg);
7565     }
7566
7567   /* In case we can easily decompose real and imaginary parts split cexp
7568      to exp (r) * cexpi (i).  */
7569   if (flag_unsafe_math_optimizations
7570       && realp)
7571     {
7572       tree rfn, rcall, icall;
7573
7574       rfn = mathfn_built_in (rtype, BUILT_IN_EXP);
7575       if (!rfn)
7576         return NULL_TREE;
7577
7578       imagp = fold_unary_loc (loc, IMAGPART_EXPR, rtype, arg0);
7579       if (!imagp)
7580         return NULL_TREE;
7581
7582       icall = build_call_expr_loc (loc, ifn, 1, imagp);
7583       icall = builtin_save_expr (icall);
7584       rcall = build_call_expr_loc (loc, rfn, 1, realp);
7585       rcall = builtin_save_expr (rcall);
7586       return fold_build2_loc (loc, COMPLEX_EXPR, type,
7587                           fold_build2_loc (loc, MULT_EXPR, rtype,
7588                                        rcall,
7589                                        fold_build1_loc (loc, REALPART_EXPR,
7590                                                     rtype, icall)),
7591                           fold_build2_loc (loc, MULT_EXPR, rtype,
7592                                        rcall,
7593                                        fold_build1_loc (loc, IMAGPART_EXPR,
7594                                                     rtype, icall)));
7595     }
7596
7597   return NULL_TREE;
7598 }
7599
7600 /* Fold function call to builtin trunc, truncf or truncl with argument ARG.
7601    Return NULL_TREE if no simplification can be made.  */
7602
7603 static tree
7604 fold_builtin_trunc (location_t loc, tree fndecl, tree arg)
7605 {
7606   if (!validate_arg (arg, REAL_TYPE))
7607     return NULL_TREE;
7608
7609   /* Optimize trunc of constant value.  */
7610   if (TREE_CODE (arg) == REAL_CST && !TREE_OVERFLOW (arg))
7611     {
7612       REAL_VALUE_TYPE r, x;
7613       tree type = TREE_TYPE (TREE_TYPE (fndecl));
7614
7615       x = TREE_REAL_CST (arg);
7616       real_trunc (&r, TYPE_MODE (type), &x);
7617       return build_real (type, r);
7618     }
7619
7620   return fold_trunc_transparent_mathfn (loc, fndecl, arg);
7621 }
7622
7623 /* Fold function call to builtin floor, floorf or floorl with argument ARG.
7624    Return NULL_TREE if no simplification can be made.  */
7625
7626 static tree
7627 fold_builtin_floor (location_t loc, tree fndecl, tree arg)
7628 {
7629   if (!validate_arg (arg, REAL_TYPE))
7630     return NULL_TREE;
7631
7632   /* Optimize floor of constant value.  */
7633   if (TREE_CODE (arg) == REAL_CST && !TREE_OVERFLOW (arg))
7634     {
7635       REAL_VALUE_TYPE x;
7636
7637       x = TREE_REAL_CST (arg);
7638       if (! REAL_VALUE_ISNAN (x) || ! flag_errno_math)
7639         {
7640           tree type = TREE_TYPE (TREE_TYPE (fndecl));
7641           REAL_VALUE_TYPE r;
7642
7643           real_floor (&r, TYPE_MODE (type), &x);
7644           return build_real (type, r);
7645         }
7646     }
7647
7648   /* Fold floor (x) where x is nonnegative to trunc (x).  */
7649   if (tree_expr_nonnegative_p (arg))
7650     {
7651       tree truncfn = mathfn_built_in (TREE_TYPE (arg), BUILT_IN_TRUNC);
7652       if (truncfn)
7653         return build_call_expr_loc (loc, truncfn, 1, arg);
7654     }
7655
7656   return fold_trunc_transparent_mathfn (loc, fndecl, arg);
7657 }
7658
7659 /* Fold function call to builtin ceil, ceilf or ceill with argument ARG.
7660    Return NULL_TREE if no simplification can be made.  */
7661
7662 static tree
7663 fold_builtin_ceil (location_t loc, tree fndecl, tree arg)
7664 {
7665   if (!validate_arg (arg, REAL_TYPE))
7666     return NULL_TREE;
7667
7668   /* Optimize ceil of constant value.  */
7669   if (TREE_CODE (arg) == REAL_CST && !TREE_OVERFLOW (arg))
7670     {
7671       REAL_VALUE_TYPE x;
7672
7673       x = TREE_REAL_CST (arg);
7674       if (! REAL_VALUE_ISNAN (x) || ! flag_errno_math)
7675         {
7676           tree type = TREE_TYPE (TREE_TYPE (fndecl));
7677           REAL_VALUE_TYPE r;
7678
7679           real_ceil (&r, TYPE_MODE (type), &x);
7680           return build_real (type, r);
7681         }
7682     }
7683
7684   return fold_trunc_transparent_mathfn (loc, fndecl, arg);
7685 }
7686
7687 /* Fold function call to builtin round, roundf or roundl with argument ARG.
7688    Return NULL_TREE if no simplification can be made.  */
7689
7690 static tree
7691 fold_builtin_round (location_t loc, tree fndecl, tree arg)
7692 {
7693   if (!validate_arg (arg, REAL_TYPE))
7694     return NULL_TREE;
7695
7696   /* Optimize round of constant value.  */
7697   if (TREE_CODE (arg) == REAL_CST && !TREE_OVERFLOW (arg))
7698     {
7699       REAL_VALUE_TYPE x;
7700
7701       x = TREE_REAL_CST (arg);
7702       if (! REAL_VALUE_ISNAN (x) || ! flag_errno_math)
7703         {
7704           tree type = TREE_TYPE (TREE_TYPE (fndecl));
7705           REAL_VALUE_TYPE r;
7706
7707           real_round (&r, TYPE_MODE (type), &x);
7708           return build_real (type, r);
7709         }
7710     }
7711
7712   return fold_trunc_transparent_mathfn (loc, fndecl, arg);
7713 }
7714
7715 /* Fold function call to builtin lround, lroundf or lroundl (or the
7716    corresponding long long versions) and other rounding functions.  ARG
7717    is the argument to the call.  Return NULL_TREE if no simplification
7718    can be made.  */
7719
7720 static tree
7721 fold_builtin_int_roundingfn (location_t loc, tree fndecl, tree arg)
7722 {
7723   if (!validate_arg (arg, REAL_TYPE))
7724     return NULL_TREE;
7725
7726   /* Optimize lround of constant value.  */
7727   if (TREE_CODE (arg) == REAL_CST && !TREE_OVERFLOW (arg))
7728     {
7729       const REAL_VALUE_TYPE x = TREE_REAL_CST (arg);
7730
7731       if (real_isfinite (&x))
7732         {
7733           tree itype = TREE_TYPE (TREE_TYPE (fndecl));
7734           tree ftype = TREE_TYPE (arg);
7735           double_int val;
7736           REAL_VALUE_TYPE r;
7737
7738           switch (DECL_FUNCTION_CODE (fndecl))
7739             {
7740             CASE_FLT_FN (BUILT_IN_LFLOOR):
7741             CASE_FLT_FN (BUILT_IN_LLFLOOR):
7742               real_floor (&r, TYPE_MODE (ftype), &x);
7743               break;
7744
7745             CASE_FLT_FN (BUILT_IN_LCEIL):
7746             CASE_FLT_FN (BUILT_IN_LLCEIL):
7747               real_ceil (&r, TYPE_MODE (ftype), &x);
7748               break;
7749
7750             CASE_FLT_FN (BUILT_IN_LROUND):
7751             CASE_FLT_FN (BUILT_IN_LLROUND):
7752               real_round (&r, TYPE_MODE (ftype), &x);
7753               break;
7754
7755             default:
7756               gcc_unreachable ();
7757             }
7758
7759           real_to_integer2 ((HOST_WIDE_INT *)&val.low, &val.high, &r);
7760           if (double_int_fits_to_tree_p (itype, val))
7761             return double_int_to_tree (itype, val);
7762         }
7763     }
7764
7765   switch (DECL_FUNCTION_CODE (fndecl))
7766     {
7767     CASE_FLT_FN (BUILT_IN_LFLOOR):
7768     CASE_FLT_FN (BUILT_IN_LLFLOOR):
7769       /* Fold lfloor (x) where x is nonnegative to FIX_TRUNC (x).  */
7770       if (tree_expr_nonnegative_p (arg))
7771         return fold_build1_loc (loc, FIX_TRUNC_EXPR,
7772                             TREE_TYPE (TREE_TYPE (fndecl)), arg);
7773       break;
7774     default:;
7775     }
7776
7777   return fold_fixed_mathfn (loc, fndecl, arg);
7778 }
7779
7780 /* Fold function call to builtin ffs, clz, ctz, popcount and parity
7781    and their long and long long variants (i.e. ffsl and ffsll).  ARG is
7782    the argument to the call.  Return NULL_TREE if no simplification can
7783    be made.  */
7784
7785 static tree
7786 fold_builtin_bitop (tree fndecl, tree arg)
7787 {
7788   if (!validate_arg (arg, INTEGER_TYPE))
7789     return NULL_TREE;
7790
7791   /* Optimize for constant argument.  */
7792   if (TREE_CODE (arg) == INTEGER_CST && !TREE_OVERFLOW (arg))
7793     {
7794       HOST_WIDE_INT hi, width, result;
7795       unsigned HOST_WIDE_INT lo;
7796       tree type;
7797
7798       type = TREE_TYPE (arg);
7799       width = TYPE_PRECISION (type);
7800       lo = TREE_INT_CST_LOW (arg);
7801
7802       /* Clear all the bits that are beyond the type's precision.  */
7803       if (width > HOST_BITS_PER_WIDE_INT)
7804         {
7805           hi = TREE_INT_CST_HIGH (arg);
7806           if (width < 2 * HOST_BITS_PER_WIDE_INT)
7807             hi &= ~((HOST_WIDE_INT) (-1) >> (width - HOST_BITS_PER_WIDE_INT));
7808         }
7809       else
7810         {
7811           hi = 0;
7812           if (width < HOST_BITS_PER_WIDE_INT)
7813             lo &= ~((unsigned HOST_WIDE_INT) (-1) << width);
7814         }
7815
7816       switch (DECL_FUNCTION_CODE (fndecl))
7817         {
7818         CASE_INT_FN (BUILT_IN_FFS):
7819           if (lo != 0)
7820             result = ffs_hwi (lo);
7821           else if (hi != 0)
7822             result = HOST_BITS_PER_WIDE_INT + ffs_hwi (hi);
7823           else
7824             result = 0;
7825           break;
7826
7827         CASE_INT_FN (BUILT_IN_CLZ):
7828           if (hi != 0)
7829             result = width - floor_log2 (hi) - 1 - HOST_BITS_PER_WIDE_INT;
7830           else if (lo != 0)
7831             result = width - floor_log2 (lo) - 1;
7832           else if (! CLZ_DEFINED_VALUE_AT_ZERO (TYPE_MODE (type), result))
7833             result = width;
7834           break;
7835
7836         CASE_INT_FN (BUILT_IN_CTZ):
7837           if (lo != 0)
7838             result = ctz_hwi (lo);
7839           else if (hi != 0)
7840             result = HOST_BITS_PER_WIDE_INT + ctz_hwi (hi);
7841           else if (! CTZ_DEFINED_VALUE_AT_ZERO (TYPE_MODE (type), result))
7842             result = width;
7843           break;
7844
7845         CASE_INT_FN (BUILT_IN_POPCOUNT):
7846           result = 0;
7847           while (lo)
7848             result++, lo &= lo - 1;
7849           while (hi)
7850             result++, hi &= (unsigned HOST_WIDE_INT) hi - 1;
7851           break;
7852
7853         CASE_INT_FN (BUILT_IN_PARITY):
7854           result = 0;
7855           while (lo)
7856             result++, lo &= lo - 1;
7857           while (hi)
7858             result++, hi &= (unsigned HOST_WIDE_INT) hi - 1;
7859           result &= 1;
7860           break;
7861
7862         default:
7863           gcc_unreachable ();
7864         }
7865
7866       return build_int_cst (TREE_TYPE (TREE_TYPE (fndecl)), result);
7867     }
7868
7869   return NULL_TREE;
7870 }
7871
7872 /* Fold function call to builtin_bswap and the long and long long
7873    variants.  Return NULL_TREE if no simplification can be made.  */
7874 static tree
7875 fold_builtin_bswap (tree fndecl, tree arg)
7876 {
7877   if (! validate_arg (arg, INTEGER_TYPE))
7878     return NULL_TREE;
7879
7880   /* Optimize constant value.  */
7881   if (TREE_CODE (arg) == INTEGER_CST && !TREE_OVERFLOW (arg))
7882     {
7883       HOST_WIDE_INT hi, width, r_hi = 0;
7884       unsigned HOST_WIDE_INT lo, r_lo = 0;
7885       tree type;
7886
7887       type = TREE_TYPE (arg);
7888       width = TYPE_PRECISION (type);
7889       lo = TREE_INT_CST_LOW (arg);
7890       hi = TREE_INT_CST_HIGH (arg);
7891
7892       switch (DECL_FUNCTION_CODE (fndecl))
7893         {
7894           case BUILT_IN_BSWAP32:
7895           case BUILT_IN_BSWAP64:
7896             {
7897               int s;
7898
7899               for (s = 0; s < width; s += 8)
7900                 {
7901                   int d = width - s - 8;
7902                   unsigned HOST_WIDE_INT byte;
7903
7904                   if (s < HOST_BITS_PER_WIDE_INT)
7905                     byte = (lo >> s) & 0xff;
7906                   else
7907                     byte = (hi >> (s - HOST_BITS_PER_WIDE_INT)) & 0xff;
7908
7909                   if (d < HOST_BITS_PER_WIDE_INT)
7910                     r_lo |= byte << d;
7911                   else
7912                     r_hi |= byte << (d - HOST_BITS_PER_WIDE_INT);
7913                 }
7914             }
7915
7916             break;
7917
7918         default:
7919           gcc_unreachable ();
7920         }
7921
7922       if (width < HOST_BITS_PER_WIDE_INT)
7923         return build_int_cst (TREE_TYPE (TREE_TYPE (fndecl)), r_lo);
7924       else
7925         return build_int_cst_wide (TREE_TYPE (TREE_TYPE (fndecl)), r_lo, r_hi);
7926     }
7927
7928   return NULL_TREE;
7929 }
7930
7931 /* A subroutine of fold_builtin to fold the various logarithmic
7932    functions.  Return NULL_TREE if no simplification can me made.
7933    FUNC is the corresponding MPFR logarithm function.  */
7934
7935 static tree
7936 fold_builtin_logarithm (location_t loc, tree fndecl, tree arg,
7937                         int (*func)(mpfr_ptr, mpfr_srcptr, mp_rnd_t))
7938 {
7939   if (validate_arg (arg, REAL_TYPE))
7940     {
7941       tree type = TREE_TYPE (TREE_TYPE (fndecl));
7942       tree res;
7943       const enum built_in_function fcode = builtin_mathfn_code (arg);
7944
7945       /* Calculate the result when the argument is a constant.  */
7946       if ((res = do_mpfr_arg1 (arg, type, func, &dconst0, NULL, false)))
7947         return res;
7948
7949       /* Special case, optimize logN(expN(x)) = x.  */
7950       if (flag_unsafe_math_optimizations
7951           && ((func == mpfr_log
7952                && (fcode == BUILT_IN_EXP
7953                    || fcode == BUILT_IN_EXPF
7954                    || fcode == BUILT_IN_EXPL))
7955               || (func == mpfr_log2
7956                   && (fcode == BUILT_IN_EXP2
7957                       || fcode == BUILT_IN_EXP2F
7958                       || fcode == BUILT_IN_EXP2L))
7959               || (func == mpfr_log10 && (BUILTIN_EXP10_P (fcode)))))
7960         return fold_convert_loc (loc, type, CALL_EXPR_ARG (arg, 0));
7961
7962       /* Optimize logN(func()) for various exponential functions.  We
7963          want to determine the value "x" and the power "exponent" in
7964          order to transform logN(x**exponent) into exponent*logN(x).  */
7965       if (flag_unsafe_math_optimizations)
7966         {
7967           tree exponent = 0, x = 0;
7968
7969           switch (fcode)
7970           {
7971           CASE_FLT_FN (BUILT_IN_EXP):
7972             /* Prepare to do logN(exp(exponent) -> exponent*logN(e).  */
7973             x = build_real (type, real_value_truncate (TYPE_MODE (type),
7974                                                        dconst_e ()));
7975             exponent = CALL_EXPR_ARG (arg, 0);
7976             break;
7977           CASE_FLT_FN (BUILT_IN_EXP2):
7978             /* Prepare to do logN(exp2(exponent) -> exponent*logN(2).  */
7979             x = build_real (type, dconst2);
7980             exponent = CALL_EXPR_ARG (arg, 0);
7981             break;
7982           CASE_FLT_FN (BUILT_IN_EXP10):
7983           CASE_FLT_FN (BUILT_IN_POW10):
7984             /* Prepare to do logN(exp10(exponent) -> exponent*logN(10).  */
7985             {
7986               REAL_VALUE_TYPE dconst10;
7987               real_from_integer (&dconst10, VOIDmode, 10, 0, 0);
7988               x = build_real (type, dconst10);
7989             }
7990             exponent = CALL_EXPR_ARG (arg, 0);
7991             break;
7992           CASE_FLT_FN (BUILT_IN_SQRT):
7993             /* Prepare to do logN(sqrt(x) -> 0.5*logN(x).  */
7994             x = CALL_EXPR_ARG (arg, 0);
7995             exponent = build_real (type, dconsthalf);
7996             break;
7997           CASE_FLT_FN (BUILT_IN_CBRT):
7998             /* Prepare to do logN(cbrt(x) -> (1/3)*logN(x).  */
7999             x = CALL_EXPR_ARG (arg, 0);
8000             exponent = build_real (type, real_value_truncate (TYPE_MODE (type),
8001                                                               dconst_third ()));
8002             break;
8003           CASE_FLT_FN (BUILT_IN_POW):
8004             /* Prepare to do logN(pow(x,exponent) -> exponent*logN(x).  */
8005             x = CALL_EXPR_ARG (arg, 0);
8006             exponent = CALL_EXPR_ARG (arg, 1);
8007             break;
8008           default:
8009             break;
8010           }
8011
8012           /* Now perform the optimization.  */
8013           if (x && exponent)
8014             {
8015               tree logfn = build_call_expr_loc (loc, fndecl, 1, x);
8016               return fold_build2_loc (loc, MULT_EXPR, type, exponent, logfn);
8017             }
8018         }
8019     }
8020
8021   return NULL_TREE;
8022 }
8023
8024 /* Fold a builtin function call to hypot, hypotf, or hypotl.  Return
8025    NULL_TREE if no simplification can be made.  */
8026
8027 static tree
8028 fold_builtin_hypot (location_t loc, tree fndecl,
8029                     tree arg0, tree arg1, tree type)
8030 {
8031   tree res, narg0, narg1;
8032
8033   if (!validate_arg (arg0, REAL_TYPE)
8034       || !validate_arg (arg1, REAL_TYPE))
8035     return NULL_TREE;
8036
8037   /* Calculate the result when the argument is a constant.  */
8038   if ((res = do_mpfr_arg2 (arg0, arg1, type, mpfr_hypot)))
8039     return res;
8040
8041   /* If either argument to hypot has a negate or abs, strip that off.
8042      E.g. hypot(-x,fabs(y)) -> hypot(x,y).  */
8043   narg0 = fold_strip_sign_ops (arg0);
8044   narg1 = fold_strip_sign_ops (arg1);
8045   if (narg0 || narg1)
8046     {
8047       return build_call_expr_loc (loc, fndecl, 2, narg0 ? narg0 : arg0,
8048                               narg1 ? narg1 : arg1);
8049     }
8050
8051   /* If either argument is zero, hypot is fabs of the other.  */
8052   if (real_zerop (arg0))
8053     return fold_build1_loc (loc, ABS_EXPR, type, arg1);
8054   else if (real_zerop (arg1))
8055     return fold_build1_loc (loc, ABS_EXPR, type, arg0);
8056
8057   /* hypot(x,x) -> fabs(x)*sqrt(2).  */
8058   if (flag_unsafe_math_optimizations
8059       && operand_equal_p (arg0, arg1, OEP_PURE_SAME))
8060     {
8061       const REAL_VALUE_TYPE sqrt2_trunc
8062         = real_value_truncate (TYPE_MODE (type), dconst_sqrt2 ());
8063       return fold_build2_loc (loc, MULT_EXPR, type,
8064                           fold_build1_loc (loc, ABS_EXPR, type, arg0),
8065                           build_real (type, sqrt2_trunc));
8066     }
8067
8068   return NULL_TREE;
8069 }
8070
8071
8072 /* Fold a builtin function call to pow, powf, or powl.  Return
8073    NULL_TREE if no simplification can be made.  */
8074 static tree
8075 fold_builtin_pow (location_t loc, tree fndecl, tree arg0, tree arg1, tree type)
8076 {
8077   tree res;
8078
8079   if (!validate_arg (arg0, REAL_TYPE)
8080        || !validate_arg (arg1, REAL_TYPE))
8081     return NULL_TREE;
8082
8083   /* Calculate the result when the argument is a constant.  */
8084   if ((res = do_mpfr_arg2 (arg0, arg1, type, mpfr_pow)))
8085     return res;
8086
8087   /* Optimize pow(1.0,y) = 1.0.  */
8088   if (real_onep (arg0))
8089     return omit_one_operand_loc (loc, type, build_real (type, dconst1), arg1);
8090
8091   if (TREE_CODE (arg1) == REAL_CST
8092       && !TREE_OVERFLOW (arg1))
8093     {
8094       REAL_VALUE_TYPE cint;
8095       REAL_VALUE_TYPE c;
8096       HOST_WIDE_INT n;
8097
8098       c = TREE_REAL_CST (arg1);
8099
8100       /* Optimize pow(x,0.0) = 1.0.  */
8101       if (REAL_VALUES_EQUAL (c, dconst0))
8102         return omit_one_operand_loc (loc, type, build_real (type, dconst1),
8103                                  arg0);
8104
8105       /* Optimize pow(x,1.0) = x.  */
8106       if (REAL_VALUES_EQUAL (c, dconst1))
8107         return arg0;
8108
8109       /* Optimize pow(x,-1.0) = 1.0/x.  */
8110       if (REAL_VALUES_EQUAL (c, dconstm1))
8111         return fold_build2_loc (loc, RDIV_EXPR, type,
8112                             build_real (type, dconst1), arg0);
8113
8114       /* Optimize pow(x,0.5) = sqrt(x).  */
8115       if (flag_unsafe_math_optimizations
8116           && REAL_VALUES_EQUAL (c, dconsthalf))
8117         {
8118           tree sqrtfn = mathfn_built_in (type, BUILT_IN_SQRT);
8119
8120           if (sqrtfn != NULL_TREE)
8121             return build_call_expr_loc (loc, sqrtfn, 1, arg0);
8122         }
8123
8124       /* Optimize pow(x,1.0/3.0) = cbrt(x).  */
8125       if (flag_unsafe_math_optimizations)
8126         {
8127           const REAL_VALUE_TYPE dconstroot
8128             = real_value_truncate (TYPE_MODE (type), dconst_third ());
8129
8130           if (REAL_VALUES_EQUAL (c, dconstroot))
8131             {
8132               tree cbrtfn = mathfn_built_in (type, BUILT_IN_CBRT);
8133               if (cbrtfn != NULL_TREE)
8134                 return build_call_expr_loc (loc, cbrtfn, 1, arg0);
8135             }
8136         }
8137
8138       /* Check for an integer exponent.  */
8139       n = real_to_integer (&c);
8140       real_from_integer (&cint, VOIDmode, n, n < 0 ? -1 : 0, 0);
8141       if (real_identical (&c, &cint))
8142         {
8143           /* Attempt to evaluate pow at compile-time, unless this should
8144              raise an exception.  */
8145           if (TREE_CODE (arg0) == REAL_CST
8146               && !TREE_OVERFLOW (arg0)
8147               && (n > 0
8148                   || (!flag_trapping_math && !flag_errno_math)
8149                   || !REAL_VALUES_EQUAL (TREE_REAL_CST (arg0), dconst0)))
8150             {
8151               REAL_VALUE_TYPE x;
8152               bool inexact;
8153
8154               x = TREE_REAL_CST (arg0);
8155               inexact = real_powi (&x, TYPE_MODE (type), &x, n);
8156               if (flag_unsafe_math_optimizations || !inexact)
8157                 return build_real (type, x);
8158             }
8159
8160           /* Strip sign ops from even integer powers.  */
8161           if ((n & 1) == 0 && flag_unsafe_math_optimizations)
8162             {
8163               tree narg0 = fold_strip_sign_ops (arg0);
8164               if (narg0)
8165                 return build_call_expr_loc (loc, fndecl, 2, narg0, arg1);
8166             }
8167         }
8168     }
8169
8170   if (flag_unsafe_math_optimizations)
8171     {
8172       const enum built_in_function fcode = builtin_mathfn_code (arg0);
8173
8174       /* Optimize pow(expN(x),y) = expN(x*y).  */
8175       if (BUILTIN_EXPONENT_P (fcode))
8176         {
8177           tree expfn = TREE_OPERAND (CALL_EXPR_FN (arg0), 0);
8178           tree arg = CALL_EXPR_ARG (arg0, 0);
8179           arg = fold_build2_loc (loc, MULT_EXPR, type, arg, arg1);
8180           return build_call_expr_loc (loc, expfn, 1, arg);
8181         }
8182
8183       /* Optimize pow(sqrt(x),y) = pow(x,y*0.5).  */
8184       if (BUILTIN_SQRT_P (fcode))
8185         {
8186           tree narg0 = CALL_EXPR_ARG (arg0, 0);
8187           tree narg1 = fold_build2_loc (loc, MULT_EXPR, type, arg1,
8188                                     build_real (type, dconsthalf));
8189           return build_call_expr_loc (loc, fndecl, 2, narg0, narg1);
8190         }
8191
8192       /* Optimize pow(cbrt(x),y) = pow(x,y/3) iff x is nonnegative.  */
8193       if (BUILTIN_CBRT_P (fcode))
8194         {
8195           tree arg = CALL_EXPR_ARG (arg0, 0);
8196           if (tree_expr_nonnegative_p (arg))
8197             {
8198               const REAL_VALUE_TYPE dconstroot
8199                 = real_value_truncate (TYPE_MODE (type), dconst_third ());
8200               tree narg1 = fold_build2_loc (loc, MULT_EXPR, type, arg1,
8201                                         build_real (type, dconstroot));
8202               return build_call_expr_loc (loc, fndecl, 2, arg, narg1);
8203             }
8204         }
8205
8206       /* Optimize pow(pow(x,y),z) = pow(x,y*z) iff x is nonnegative.  */
8207       if (fcode == BUILT_IN_POW
8208           || fcode == BUILT_IN_POWF
8209           || fcode == BUILT_IN_POWL)
8210         {
8211           tree arg00 = CALL_EXPR_ARG (arg0, 0);
8212           if (tree_expr_nonnegative_p (arg00))
8213             {
8214               tree arg01 = CALL_EXPR_ARG (arg0, 1);
8215               tree narg1 = fold_build2_loc (loc, MULT_EXPR, type, arg01, arg1);
8216               return build_call_expr_loc (loc, fndecl, 2, arg00, narg1);
8217             }
8218         }
8219     }
8220
8221   return NULL_TREE;
8222 }
8223
8224 /* Fold a builtin function call to powi, powif, or powil with argument ARG.
8225    Return NULL_TREE if no simplification can be made.  */
8226 static tree
8227 fold_builtin_powi (location_t loc, tree fndecl ATTRIBUTE_UNUSED,
8228                    tree arg0, tree arg1, tree type)
8229 {
8230   if (!validate_arg (arg0, REAL_TYPE)
8231       || !validate_arg (arg1, INTEGER_TYPE))
8232     return NULL_TREE;
8233
8234   /* Optimize pow(1.0,y) = 1.0.  */
8235   if (real_onep (arg0))
8236     return omit_one_operand_loc (loc, type, build_real (type, dconst1), arg1);
8237
8238   if (host_integerp (arg1, 0))
8239     {
8240       HOST_WIDE_INT c = TREE_INT_CST_LOW (arg1);
8241
8242       /* Evaluate powi at compile-time.  */
8243       if (TREE_CODE (arg0) == REAL_CST
8244           && !TREE_OVERFLOW (arg0))
8245         {
8246           REAL_VALUE_TYPE x;
8247           x = TREE_REAL_CST (arg0);
8248           real_powi (&x, TYPE_MODE (type), &x, c);
8249           return build_real (type, x);
8250         }
8251
8252       /* Optimize pow(x,0) = 1.0.  */
8253       if (c == 0)
8254         return omit_one_operand_loc (loc, type, build_real (type, dconst1),
8255                                  arg0);
8256
8257       /* Optimize pow(x,1) = x.  */
8258       if (c == 1)
8259         return arg0;
8260
8261       /* Optimize pow(x,-1) = 1.0/x.  */
8262       if (c == -1)
8263         return fold_build2_loc (loc, RDIV_EXPR, type,
8264                            build_real (type, dconst1), arg0);
8265     }
8266
8267   return NULL_TREE;
8268 }
8269
8270 /* A subroutine of fold_builtin to fold the various exponent
8271    functions.  Return NULL_TREE if no simplification can be made.
8272    FUNC is the corresponding MPFR exponent function.  */
8273
8274 static tree
8275 fold_builtin_exponent (location_t loc, tree fndecl, tree arg,
8276                        int (*func)(mpfr_ptr, mpfr_srcptr, mp_rnd_t))
8277 {
8278   if (validate_arg (arg, REAL_TYPE))
8279     {
8280       tree type = TREE_TYPE (TREE_TYPE (fndecl));
8281       tree res;
8282
8283       /* Calculate the result when the argument is a constant.  */
8284       if ((res = do_mpfr_arg1 (arg, type, func, NULL, NULL, 0)))
8285         return res;
8286
8287       /* Optimize expN(logN(x)) = x.  */
8288       if (flag_unsafe_math_optimizations)
8289         {
8290           const enum built_in_function fcode = builtin_mathfn_code (arg);
8291
8292           if ((func == mpfr_exp
8293                && (fcode == BUILT_IN_LOG
8294                    || fcode == BUILT_IN_LOGF
8295                    || fcode == BUILT_IN_LOGL))
8296               || (func == mpfr_exp2
8297                   && (fcode == BUILT_IN_LOG2
8298                       || fcode == BUILT_IN_LOG2F
8299                       || fcode == BUILT_IN_LOG2L))
8300               || (func == mpfr_exp10
8301                   && (fcode == BUILT_IN_LOG10
8302                       || fcode == BUILT_IN_LOG10F
8303                       || fcode == BUILT_IN_LOG10L)))
8304             return fold_convert_loc (loc, type, CALL_EXPR_ARG (arg, 0));
8305         }
8306     }
8307
8308   return NULL_TREE;
8309 }
8310
8311 /* Return true if VAR is a VAR_DECL or a component thereof.  */
8312
8313 static bool
8314 var_decl_component_p (tree var)
8315 {
8316   tree inner = var;
8317   while (handled_component_p (inner))
8318     inner = TREE_OPERAND (inner, 0);
8319   return SSA_VAR_P (inner);
8320 }
8321
8322 /* Fold function call to builtin memset.  Return
8323    NULL_TREE if no simplification can be made.  */
8324
8325 static tree
8326 fold_builtin_memset (location_t loc, tree dest, tree c, tree len,
8327                      tree type, bool ignore)
8328 {
8329   tree var, ret, etype;
8330   unsigned HOST_WIDE_INT length, cval;
8331
8332   if (! validate_arg (dest, POINTER_TYPE)
8333       || ! validate_arg (c, INTEGER_TYPE)
8334       || ! validate_arg (len, INTEGER_TYPE))
8335     return NULL_TREE;
8336
8337   if (! host_integerp (len, 1))
8338     return NULL_TREE;
8339
8340   /* If the LEN parameter is zero, return DEST.  */
8341   if (integer_zerop (len))
8342     return omit_one_operand_loc (loc, type, dest, c);
8343
8344   if (! host_integerp (c, 1) || TREE_SIDE_EFFECTS (dest))
8345     return NULL_TREE;
8346
8347   var = dest;
8348   STRIP_NOPS (var);
8349   if (TREE_CODE (var) != ADDR_EXPR)
8350     return NULL_TREE;
8351
8352   var = TREE_OPERAND (var, 0);
8353   if (TREE_THIS_VOLATILE (var))
8354     return NULL_TREE;
8355
8356   etype = TREE_TYPE (var);
8357   if (TREE_CODE (etype) == ARRAY_TYPE)
8358     etype = TREE_TYPE (etype);
8359
8360   if (!INTEGRAL_TYPE_P (etype)
8361       && !POINTER_TYPE_P (etype))
8362     return NULL_TREE;
8363
8364   if (! var_decl_component_p (var))
8365     return NULL_TREE;
8366
8367   length = tree_low_cst (len, 1);
8368   if (GET_MODE_SIZE (TYPE_MODE (etype)) != length
8369       || get_pointer_alignment (dest, BIGGEST_ALIGNMENT) / BITS_PER_UNIT
8370          < length)
8371     return NULL_TREE;
8372
8373   if (length > HOST_BITS_PER_WIDE_INT / BITS_PER_UNIT)
8374     return NULL_TREE;
8375
8376   if (integer_zerop (c))
8377     cval = 0;
8378   else
8379     {
8380       if (CHAR_BIT != 8 || BITS_PER_UNIT != 8 || HOST_BITS_PER_WIDE_INT > 64)
8381         return NULL_TREE;
8382
8383       cval = tree_low_cst (c, 1);
8384       cval &= 0xff;
8385       cval |= cval << 8;
8386       cval |= cval << 16;
8387       cval |= (cval << 31) << 1;
8388     }
8389
8390   ret = build_int_cst_type (etype, cval);
8391   var = build_fold_indirect_ref_loc (loc,
8392                                  fold_convert_loc (loc,
8393                                                    build_pointer_type (etype),
8394                                                    dest));
8395   ret = build2 (MODIFY_EXPR, etype, var, ret);
8396   if (ignore)
8397     return ret;
8398
8399   return omit_one_operand_loc (loc, type, dest, ret);
8400 }
8401
8402 /* Fold function call to builtin memset.  Return
8403    NULL_TREE if no simplification can be made.  */
8404
8405 static tree
8406 fold_builtin_bzero (location_t loc, tree dest, tree size, bool ignore)
8407 {
8408   if (! validate_arg (dest, POINTER_TYPE)
8409       || ! validate_arg (size, INTEGER_TYPE))
8410     return NULL_TREE;
8411
8412   if (!ignore)
8413     return NULL_TREE;
8414
8415   /* New argument list transforming bzero(ptr x, int y) to
8416      memset(ptr x, int 0, size_t y).   This is done this way
8417      so that if it isn't expanded inline, we fallback to
8418      calling bzero instead of memset.  */
8419
8420   return fold_builtin_memset (loc, dest, integer_zero_node,
8421                               fold_convert_loc (loc, sizetype, size),
8422                               void_type_node, ignore);
8423 }
8424
8425 /* Fold function call to builtin mem{{,p}cpy,move}.  Return
8426    NULL_TREE if no simplification can be made.
8427    If ENDP is 0, return DEST (like memcpy).
8428    If ENDP is 1, return DEST+LEN (like mempcpy).
8429    If ENDP is 2, return DEST+LEN-1 (like stpcpy).
8430    If ENDP is 3, return DEST, additionally *SRC and *DEST may overlap
8431    (memmove).   */
8432
8433 static tree
8434 fold_builtin_memory_op (location_t loc, tree dest, tree src,
8435                         tree len, tree type, bool ignore, int endp)
8436 {
8437   tree destvar, srcvar, expr;
8438
8439   if (! validate_arg (dest, POINTER_TYPE)
8440       || ! validate_arg (src, POINTER_TYPE)
8441       || ! validate_arg (len, INTEGER_TYPE))
8442     return NULL_TREE;
8443
8444   /* If the LEN parameter is zero, return DEST.  */
8445   if (integer_zerop (len))
8446     return omit_one_operand_loc (loc, type, dest, src);
8447
8448   /* If SRC and DEST are the same (and not volatile), return
8449      DEST{,+LEN,+LEN-1}.  */
8450   if (operand_equal_p (src, dest, 0))
8451     expr = len;
8452   else
8453     {
8454       tree srctype, desttype;
8455       unsigned int src_align, dest_align;
8456       tree off0;
8457
8458       if (endp == 3)
8459         {
8460           src_align = get_pointer_alignment (src, BIGGEST_ALIGNMENT);
8461           dest_align = get_pointer_alignment (dest, BIGGEST_ALIGNMENT);
8462
8463           /* Both DEST and SRC must be pointer types.
8464              ??? This is what old code did.  Is the testing for pointer types
8465              really mandatory?
8466
8467              If either SRC is readonly or length is 1, we can use memcpy.  */
8468           if (!dest_align || !src_align)
8469             return NULL_TREE;
8470           if (readonly_data_expr (src)
8471               || (host_integerp (len, 1)
8472                   && (MIN (src_align, dest_align) / BITS_PER_UNIT
8473                       >= (unsigned HOST_WIDE_INT) tree_low_cst (len, 1))))
8474             {
8475               tree fn = implicit_built_in_decls[BUILT_IN_MEMCPY];
8476               if (!fn)
8477                 return NULL_TREE;
8478               return build_call_expr_loc (loc, fn, 3, dest, src, len);
8479             }
8480
8481           /* If *src and *dest can't overlap, optimize into memcpy as well.  */
8482           if (TREE_CODE (src) == ADDR_EXPR
8483               && TREE_CODE (dest) == ADDR_EXPR)
8484             {
8485               tree src_base, dest_base, fn;
8486               HOST_WIDE_INT src_offset = 0, dest_offset = 0;
8487               HOST_WIDE_INT size = -1;
8488               HOST_WIDE_INT maxsize = -1;
8489
8490               srcvar = TREE_OPERAND (src, 0);
8491               src_base = get_ref_base_and_extent (srcvar, &src_offset,
8492                                                   &size, &maxsize);
8493               destvar = TREE_OPERAND (dest, 0);
8494               dest_base = get_ref_base_and_extent (destvar, &dest_offset,
8495                                                    &size, &maxsize);
8496               if (host_integerp (len, 1))
8497                 maxsize = tree_low_cst (len, 1);
8498               else
8499                 maxsize = -1;
8500               src_offset /= BITS_PER_UNIT;
8501               dest_offset /= BITS_PER_UNIT;
8502               if (SSA_VAR_P (src_base)
8503                   && SSA_VAR_P (dest_base))
8504                 {
8505                   if (operand_equal_p (src_base, dest_base, 0)
8506                       && ranges_overlap_p (src_offset, maxsize,
8507                                            dest_offset, maxsize))
8508                     return NULL_TREE;
8509                 }
8510               else if (TREE_CODE (src_base) == MEM_REF
8511                        && TREE_CODE (dest_base) == MEM_REF)
8512                 {
8513                   double_int off;
8514                   if (! operand_equal_p (TREE_OPERAND (src_base, 0),
8515                                          TREE_OPERAND (dest_base, 0), 0))
8516                     return NULL_TREE;
8517                   off = double_int_add (mem_ref_offset (src_base),
8518                                         shwi_to_double_int (src_offset));
8519                   if (!double_int_fits_in_shwi_p (off))
8520                     return NULL_TREE;
8521                   src_offset = off.low;
8522                   off = double_int_add (mem_ref_offset (dest_base),
8523                                         shwi_to_double_int (dest_offset));
8524                   if (!double_int_fits_in_shwi_p (off))
8525                     return NULL_TREE;
8526                   dest_offset = off.low;
8527                   if (ranges_overlap_p (src_offset, maxsize,
8528                                         dest_offset, maxsize))
8529                     return NULL_TREE;
8530                 }
8531               else
8532                 return NULL_TREE;
8533
8534               fn = implicit_built_in_decls[BUILT_IN_MEMCPY];
8535               if (!fn)
8536                 return NULL_TREE;
8537               return build_call_expr_loc (loc, fn, 3, dest, src, len);
8538             }
8539
8540           /* If the destination and source do not alias optimize into
8541              memcpy as well.  */
8542           if ((is_gimple_min_invariant (dest)
8543                || TREE_CODE (dest) == SSA_NAME)
8544               && (is_gimple_min_invariant (src)
8545                   || TREE_CODE (src) == SSA_NAME))
8546             {
8547               ao_ref destr, srcr;
8548               ao_ref_init_from_ptr_and_size (&destr, dest, len);
8549               ao_ref_init_from_ptr_and_size (&srcr, src, len);
8550               if (!refs_may_alias_p_1 (&destr, &srcr, false))
8551                 {
8552                   tree fn;
8553                   fn = implicit_built_in_decls[BUILT_IN_MEMCPY];
8554                   if (!fn)
8555                     return NULL_TREE;
8556                   return build_call_expr_loc (loc, fn, 3, dest, src, len);
8557                 }
8558             }
8559
8560           return NULL_TREE;
8561         }
8562
8563       if (!host_integerp (len, 0))
8564         return NULL_TREE;
8565       /* FIXME:
8566          This logic lose for arguments like (type *)malloc (sizeof (type)),
8567          since we strip the casts of up to VOID return value from malloc.
8568          Perhaps we ought to inherit type from non-VOID argument here?  */
8569       STRIP_NOPS (src);
8570       STRIP_NOPS (dest);
8571       /* As we fold (void *)(p + CST) to (void *)p + CST undo this here.  */
8572       if (TREE_CODE (src) == POINTER_PLUS_EXPR)
8573         {
8574           tree tem = TREE_OPERAND (src, 0);
8575           STRIP_NOPS (tem);
8576           if (tem != TREE_OPERAND (src, 0))
8577             src = build1 (NOP_EXPR, TREE_TYPE (tem), src);
8578         }
8579       if (TREE_CODE (dest) == POINTER_PLUS_EXPR)
8580         {
8581           tree tem = TREE_OPERAND (dest, 0);
8582           STRIP_NOPS (tem);
8583           if (tem != TREE_OPERAND (dest, 0))
8584             dest = build1 (NOP_EXPR, TREE_TYPE (tem), dest);
8585         }
8586       srctype = TREE_TYPE (TREE_TYPE (src));
8587       if (srctype
8588           && TREE_CODE (srctype) == ARRAY_TYPE
8589           && !tree_int_cst_equal (TYPE_SIZE_UNIT (srctype), len))
8590         {
8591           srctype = TREE_TYPE (srctype);
8592           STRIP_NOPS (src);
8593           src = build1 (NOP_EXPR, build_pointer_type (srctype), src);
8594         }
8595       desttype = TREE_TYPE (TREE_TYPE (dest));
8596       if (desttype
8597           && TREE_CODE (desttype) == ARRAY_TYPE
8598           && !tree_int_cst_equal (TYPE_SIZE_UNIT (desttype), len))
8599         {
8600           desttype = TREE_TYPE (desttype);
8601           STRIP_NOPS (dest);
8602           dest = build1 (NOP_EXPR, build_pointer_type (desttype), dest);
8603         }
8604       if (!srctype || !desttype
8605           || TREE_ADDRESSABLE (srctype)
8606           || TREE_ADDRESSABLE (desttype)
8607           || !TYPE_SIZE_UNIT (srctype)
8608           || !TYPE_SIZE_UNIT (desttype)
8609           || TREE_CODE (TYPE_SIZE_UNIT (srctype)) != INTEGER_CST
8610           || TREE_CODE (TYPE_SIZE_UNIT (desttype)) != INTEGER_CST)
8611         return NULL_TREE;
8612
8613       src_align = get_pointer_alignment (src, BIGGEST_ALIGNMENT);
8614       dest_align = get_pointer_alignment (dest, BIGGEST_ALIGNMENT);
8615       if (dest_align < TYPE_ALIGN (desttype)
8616           || src_align < TYPE_ALIGN (srctype))
8617         return NULL_TREE;
8618
8619       if (!ignore)
8620         dest = builtin_save_expr (dest);
8621
8622       /* Build accesses at offset zero with a ref-all character type.  */
8623       off0 = build_int_cst (build_pointer_type_for_mode (char_type_node,
8624                                                          ptr_mode, true), 0);
8625
8626       destvar = dest;
8627       STRIP_NOPS (destvar);
8628       if (TREE_CODE (destvar) == ADDR_EXPR
8629           && var_decl_component_p (TREE_OPERAND (destvar, 0))
8630           && tree_int_cst_equal (TYPE_SIZE_UNIT (desttype), len))
8631         destvar = fold_build2 (MEM_REF, desttype, destvar, off0);
8632       else
8633         destvar = NULL_TREE;
8634
8635       srcvar = src;
8636       STRIP_NOPS (srcvar);
8637       if (TREE_CODE (srcvar) == ADDR_EXPR
8638           && var_decl_component_p (TREE_OPERAND (srcvar, 0))
8639           && tree_int_cst_equal (TYPE_SIZE_UNIT (srctype), len))
8640         {
8641           if (!destvar
8642               || src_align >= TYPE_ALIGN (desttype))
8643             srcvar = fold_build2 (MEM_REF, destvar ? desttype : srctype,
8644                                   srcvar, off0);
8645           else if (!STRICT_ALIGNMENT)
8646             {
8647               srctype = build_aligned_type (TYPE_MAIN_VARIANT (desttype),
8648                                             src_align);
8649               srcvar = fold_build2 (MEM_REF, srctype, srcvar, off0);
8650             }
8651           else
8652             srcvar = NULL_TREE;
8653         }
8654       else
8655         srcvar = NULL_TREE;
8656
8657       if (srcvar == NULL_TREE && destvar == NULL_TREE)
8658         return NULL_TREE;
8659
8660       if (srcvar == NULL_TREE)
8661         {
8662           STRIP_NOPS (src);
8663           if (src_align >= TYPE_ALIGN (desttype))
8664             srcvar = fold_build2 (MEM_REF, desttype, src, off0);
8665           else
8666             {
8667               if (STRICT_ALIGNMENT)
8668                 return NULL_TREE;
8669               srctype = build_aligned_type (TYPE_MAIN_VARIANT (desttype),
8670                                             src_align);
8671               srcvar = fold_build2 (MEM_REF, srctype, src, off0);
8672             }
8673         }
8674       else if (destvar == NULL_TREE)
8675         {
8676           STRIP_NOPS (dest);
8677           if (dest_align >= TYPE_ALIGN (srctype))
8678             destvar = fold_build2 (MEM_REF, srctype, dest, off0);
8679           else
8680             {
8681               if (STRICT_ALIGNMENT)
8682                 return NULL_TREE;
8683               desttype = build_aligned_type (TYPE_MAIN_VARIANT (srctype),
8684                                              dest_align);
8685               destvar = fold_build2 (MEM_REF, desttype, dest, off0);
8686             }
8687         }
8688
8689       expr = build2 (MODIFY_EXPR, TREE_TYPE (destvar), destvar, srcvar);
8690     }
8691
8692   if (ignore)
8693     return expr;
8694
8695   if (endp == 0 || endp == 3)
8696     return omit_one_operand_loc (loc, type, dest, expr);
8697
8698   if (expr == len)
8699     expr = NULL_TREE;
8700
8701   if (endp == 2)
8702     len = fold_build2_loc (loc, MINUS_EXPR, TREE_TYPE (len), len,
8703                        ssize_int (1));
8704
8705   len = fold_convert_loc (loc, sizetype, len);
8706   dest = fold_build2_loc (loc, POINTER_PLUS_EXPR, TREE_TYPE (dest), dest, len);
8707   dest = fold_convert_loc (loc, type, dest);
8708   if (expr)
8709     dest = omit_one_operand_loc (loc, type, dest, expr);
8710   return dest;
8711 }
8712
8713 /* Fold function call to builtin strcpy with arguments DEST and SRC.
8714    If LEN is not NULL, it represents the length of the string to be
8715    copied.  Return NULL_TREE if no simplification can be made.  */
8716
8717 tree
8718 fold_builtin_strcpy (location_t loc, tree fndecl, tree dest, tree src, tree len)
8719 {
8720   tree fn;
8721
8722   if (!validate_arg (dest, POINTER_TYPE)
8723       || !validate_arg (src, POINTER_TYPE))
8724     return NULL_TREE;
8725
8726   /* If SRC and DEST are the same (and not volatile), return DEST.  */
8727   if (operand_equal_p (src, dest, 0))
8728     return fold_convert_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)), dest);
8729
8730   if (optimize_function_for_size_p (cfun))
8731     return NULL_TREE;
8732
8733   fn = implicit_built_in_decls[BUILT_IN_MEMCPY];
8734   if (!fn)
8735     return NULL_TREE;
8736
8737   if (!len)
8738     {
8739       len = c_strlen (src, 1);
8740       if (! len || TREE_SIDE_EFFECTS (len))
8741         return NULL_TREE;
8742     }
8743
8744   len = size_binop_loc (loc, PLUS_EXPR, len, ssize_int (1));
8745   return fold_convert_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)),
8746                            build_call_expr_loc (loc, fn, 3, dest, src, len));
8747 }
8748
8749 /* Fold function call to builtin stpcpy with arguments DEST and SRC.
8750    Return NULL_TREE if no simplification can be made.  */
8751
8752 static tree
8753 fold_builtin_stpcpy (location_t loc, tree fndecl, tree dest, tree src)
8754 {
8755   tree fn, len, lenp1, call, type;
8756
8757   if (!validate_arg (dest, POINTER_TYPE)
8758       || !validate_arg (src, POINTER_TYPE))
8759     return NULL_TREE;
8760
8761   len = c_strlen (src, 1);
8762   if (!len
8763       || TREE_CODE (len) != INTEGER_CST)
8764     return NULL_TREE;
8765
8766   if (optimize_function_for_size_p (cfun)
8767       /* If length is zero it's small enough.  */
8768       && !integer_zerop (len))
8769     return NULL_TREE;
8770
8771   fn = implicit_built_in_decls[BUILT_IN_MEMCPY];
8772   if (!fn)
8773     return NULL_TREE;
8774
8775   lenp1 = size_binop_loc (loc, PLUS_EXPR, len, ssize_int (1));
8776   /* We use dest twice in building our expression.  Save it from
8777      multiple expansions.  */
8778   dest = builtin_save_expr (dest);
8779   call = build_call_expr_loc (loc, fn, 3, dest, src, lenp1);
8780
8781   type = TREE_TYPE (TREE_TYPE (fndecl));
8782   len = fold_convert_loc (loc, sizetype, len);
8783   dest = fold_build2_loc (loc, POINTER_PLUS_EXPR, TREE_TYPE (dest), dest, len);
8784   dest = fold_convert_loc (loc, type, dest);
8785   dest = omit_one_operand_loc (loc, type, dest, call);
8786   return dest;
8787 }
8788
8789 /* Fold function call to builtin strncpy with arguments DEST, SRC, and LEN.
8790    If SLEN is not NULL, it represents the length of the source string.
8791    Return NULL_TREE if no simplification can be made.  */
8792
8793 tree
8794 fold_builtin_strncpy (location_t loc, tree fndecl, tree dest,
8795                       tree src, tree len, tree slen)
8796 {
8797   tree fn;
8798
8799   if (!validate_arg (dest, POINTER_TYPE)
8800       || !validate_arg (src, POINTER_TYPE)
8801       || !validate_arg (len, INTEGER_TYPE))
8802     return NULL_TREE;
8803
8804   /* If the LEN parameter is zero, return DEST.  */
8805   if (integer_zerop (len))
8806     return omit_one_operand_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)), dest, src);
8807
8808   /* We can't compare slen with len as constants below if len is not a
8809      constant.  */
8810   if (len == 0 || TREE_CODE (len) != INTEGER_CST)
8811     return NULL_TREE;
8812
8813   if (!slen)
8814     slen = c_strlen (src, 1);
8815
8816   /* Now, we must be passed a constant src ptr parameter.  */
8817   if (slen == 0 || TREE_CODE (slen) != INTEGER_CST)
8818     return NULL_TREE;
8819
8820   slen = size_binop_loc (loc, PLUS_EXPR, slen, ssize_int (1));
8821
8822   /* We do not support simplification of this case, though we do
8823      support it when expanding trees into RTL.  */
8824   /* FIXME: generate a call to __builtin_memset.  */
8825   if (tree_int_cst_lt (slen, len))
8826     return NULL_TREE;
8827
8828   /* OK transform into builtin memcpy.  */
8829   fn = implicit_built_in_decls[BUILT_IN_MEMCPY];
8830   if (!fn)
8831     return NULL_TREE;
8832   return fold_convert_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)),
8833                            build_call_expr_loc (loc, fn, 3, dest, src, len));
8834 }
8835
8836 /* Fold function call to builtin memchr.  ARG1, ARG2 and LEN are the
8837    arguments to the call, and TYPE is its return type.
8838    Return NULL_TREE if no simplification can be made.  */
8839
8840 static tree
8841 fold_builtin_memchr (location_t loc, tree arg1, tree arg2, tree len, tree type)
8842 {
8843   if (!validate_arg (arg1, POINTER_TYPE)
8844       || !validate_arg (arg2, INTEGER_TYPE)
8845       || !validate_arg (len, INTEGER_TYPE))
8846     return NULL_TREE;
8847   else
8848     {
8849       const char *p1;
8850
8851       if (TREE_CODE (arg2) != INTEGER_CST
8852           || !host_integerp (len, 1))
8853         return NULL_TREE;
8854
8855       p1 = c_getstr (arg1);
8856       if (p1 && compare_tree_int (len, strlen (p1) + 1) <= 0)
8857         {
8858           char c;
8859           const char *r;
8860           tree tem;
8861
8862           if (target_char_cast (arg2, &c))
8863             return NULL_TREE;
8864
8865           r = (char *) memchr (p1, c, tree_low_cst (len, 1));
8866
8867           if (r == NULL)
8868             return build_int_cst (TREE_TYPE (arg1), 0);
8869
8870           tem = fold_build2_loc (loc, POINTER_PLUS_EXPR, TREE_TYPE (arg1), arg1,
8871                              size_int (r - p1));
8872           return fold_convert_loc (loc, type, tem);
8873         }
8874       return NULL_TREE;
8875     }
8876 }
8877
8878 /* Fold function call to builtin memcmp with arguments ARG1 and ARG2.
8879    Return NULL_TREE if no simplification can be made.  */
8880
8881 static tree
8882 fold_builtin_memcmp (location_t loc, tree arg1, tree arg2, tree len)
8883 {
8884   const char *p1, *p2;
8885
8886   if (!validate_arg (arg1, POINTER_TYPE)
8887       || !validate_arg (arg2, POINTER_TYPE)
8888       || !validate_arg (len, INTEGER_TYPE))
8889     return NULL_TREE;
8890
8891   /* If the LEN parameter is zero, return zero.  */
8892   if (integer_zerop (len))
8893     return omit_two_operands_loc (loc, integer_type_node, integer_zero_node,
8894                               arg1, arg2);
8895
8896   /* If ARG1 and ARG2 are the same (and not volatile), return zero.  */
8897   if (operand_equal_p (arg1, arg2, 0))
8898     return omit_one_operand_loc (loc, integer_type_node, integer_zero_node, len);
8899
8900   p1 = c_getstr (arg1);
8901   p2 = c_getstr (arg2);
8902
8903   /* If all arguments are constant, and the value of len is not greater
8904      than the lengths of arg1 and arg2, evaluate at compile-time.  */
8905   if (host_integerp (len, 1) && p1 && p2
8906       && compare_tree_int (len, strlen (p1) + 1) <= 0
8907       && compare_tree_int (len, strlen (p2) + 1) <= 0)
8908     {
8909       const int r = memcmp (p1, p2, tree_low_cst (len, 1));
8910
8911       if (r > 0)
8912         return integer_one_node;
8913       else if (r < 0)
8914         return integer_minus_one_node;
8915       else
8916         return integer_zero_node;
8917     }
8918
8919   /* If len parameter is one, return an expression corresponding to
8920      (*(const unsigned char*)arg1 - (const unsigned char*)arg2).  */
8921   if (host_integerp (len, 1) && tree_low_cst (len, 1) == 1)
8922     {
8923       tree cst_uchar_node = build_type_variant (unsigned_char_type_node, 1, 0);
8924       tree cst_uchar_ptr_node
8925         = build_pointer_type_for_mode (cst_uchar_node, ptr_mode, true);
8926
8927       tree ind1
8928         = fold_convert_loc (loc, integer_type_node,
8929                             build1 (INDIRECT_REF, cst_uchar_node,
8930                                     fold_convert_loc (loc,
8931                                                       cst_uchar_ptr_node,
8932                                                       arg1)));
8933       tree ind2
8934         = fold_convert_loc (loc, integer_type_node,
8935                             build1 (INDIRECT_REF, cst_uchar_node,
8936                                     fold_convert_loc (loc,
8937                                                       cst_uchar_ptr_node,
8938                                                       arg2)));
8939       return fold_build2_loc (loc, MINUS_EXPR, integer_type_node, ind1, ind2);
8940     }
8941
8942   return NULL_TREE;
8943 }
8944
8945 /* Fold function call to builtin strcmp with arguments ARG1 and ARG2.
8946    Return NULL_TREE if no simplification can be made.  */
8947
8948 static tree
8949 fold_builtin_strcmp (location_t loc, tree arg1, tree arg2)
8950 {
8951   const char *p1, *p2;
8952
8953   if (!validate_arg (arg1, POINTER_TYPE)
8954       || !validate_arg (arg2, POINTER_TYPE))
8955     return NULL_TREE;
8956
8957   /* If ARG1 and ARG2 are the same (and not volatile), return zero.  */
8958   if (operand_equal_p (arg1, arg2, 0))
8959     return integer_zero_node;
8960
8961   p1 = c_getstr (arg1);
8962   p2 = c_getstr (arg2);
8963
8964   if (p1 && p2)
8965     {
8966       const int i = strcmp (p1, p2);
8967       if (i < 0)
8968         return integer_minus_one_node;
8969       else if (i > 0)
8970         return integer_one_node;
8971       else
8972         return integer_zero_node;
8973     }
8974
8975   /* If the second arg is "", return *(const unsigned char*)arg1.  */
8976   if (p2 && *p2 == '\0')
8977     {
8978       tree cst_uchar_node = build_type_variant (unsigned_char_type_node, 1, 0);
8979       tree cst_uchar_ptr_node
8980         = build_pointer_type_for_mode (cst_uchar_node, ptr_mode, true);
8981
8982       return fold_convert_loc (loc, integer_type_node,
8983                                build1 (INDIRECT_REF, cst_uchar_node,
8984                                        fold_convert_loc (loc,
8985                                                          cst_uchar_ptr_node,
8986                                                          arg1)));
8987     }
8988
8989   /* If the first arg is "", return -*(const unsigned char*)arg2.  */
8990   if (p1 && *p1 == '\0')
8991     {
8992       tree cst_uchar_node = build_type_variant (unsigned_char_type_node, 1, 0);
8993       tree cst_uchar_ptr_node
8994         = build_pointer_type_for_mode (cst_uchar_node, ptr_mode, true);
8995
8996       tree temp
8997         = fold_convert_loc (loc, integer_type_node,
8998                             build1 (INDIRECT_REF, cst_uchar_node,
8999                                     fold_convert_loc (loc,
9000                                                       cst_uchar_ptr_node,
9001                                                       arg2)));
9002       return fold_build1_loc (loc, NEGATE_EXPR, integer_type_node, temp);
9003     }
9004
9005   return NULL_TREE;
9006 }
9007
9008 /* Fold function call to builtin strncmp with arguments ARG1, ARG2, and LEN.
9009    Return NULL_TREE if no simplification can be made.  */
9010
9011 static tree
9012 fold_builtin_strncmp (location_t loc, tree arg1, tree arg2, tree len)
9013 {
9014   const char *p1, *p2;
9015
9016   if (!validate_arg (arg1, POINTER_TYPE)
9017       || !validate_arg (arg2, POINTER_TYPE)
9018       || !validate_arg (len, INTEGER_TYPE))
9019     return NULL_TREE;
9020
9021   /* If the LEN parameter is zero, return zero.  */
9022   if (integer_zerop (len))
9023     return omit_two_operands_loc (loc, integer_type_node, integer_zero_node,
9024                               arg1, arg2);
9025
9026   /* If ARG1 and ARG2 are the same (and not volatile), return zero.  */
9027   if (operand_equal_p (arg1, arg2, 0))
9028     return omit_one_operand_loc (loc, integer_type_node, integer_zero_node, len);
9029
9030   p1 = c_getstr (arg1);
9031   p2 = c_getstr (arg2);
9032
9033   if (host_integerp (len, 1) && p1 && p2)
9034     {
9035       const int i = strncmp (p1, p2, tree_low_cst (len, 1));
9036       if (i > 0)
9037         return integer_one_node;
9038       else if (i < 0)
9039         return integer_minus_one_node;
9040       else
9041         return integer_zero_node;
9042     }
9043
9044   /* If the second arg is "", and the length is greater than zero,
9045      return *(const unsigned char*)arg1.  */
9046   if (p2 && *p2 == '\0'
9047       && TREE_CODE (len) == INTEGER_CST
9048       && tree_int_cst_sgn (len) == 1)
9049     {
9050       tree cst_uchar_node = build_type_variant (unsigned_char_type_node, 1, 0);
9051       tree cst_uchar_ptr_node
9052         = build_pointer_type_for_mode (cst_uchar_node, ptr_mode, true);
9053
9054       return fold_convert_loc (loc, integer_type_node,
9055                                build1 (INDIRECT_REF, cst_uchar_node,
9056                                        fold_convert_loc (loc,
9057                                                          cst_uchar_ptr_node,
9058                                                          arg1)));
9059     }
9060
9061   /* If the first arg is "", and the length is greater than zero,
9062      return -*(const unsigned char*)arg2.  */
9063   if (p1 && *p1 == '\0'
9064       && TREE_CODE (len) == INTEGER_CST
9065       && tree_int_cst_sgn (len) == 1)
9066     {
9067       tree cst_uchar_node = build_type_variant (unsigned_char_type_node, 1, 0);
9068       tree cst_uchar_ptr_node
9069         = build_pointer_type_for_mode (cst_uchar_node, ptr_mode, true);
9070
9071       tree temp = fold_convert_loc (loc, integer_type_node,
9072                                     build1 (INDIRECT_REF, cst_uchar_node,
9073                                             fold_convert_loc (loc,
9074                                                               cst_uchar_ptr_node,
9075                                                               arg2)));
9076       return fold_build1_loc (loc, NEGATE_EXPR, integer_type_node, temp);
9077     }
9078
9079   /* If len parameter is one, return an expression corresponding to
9080      (*(const unsigned char*)arg1 - (const unsigned char*)arg2).  */
9081   if (host_integerp (len, 1) && tree_low_cst (len, 1) == 1)
9082     {
9083       tree cst_uchar_node = build_type_variant (unsigned_char_type_node, 1, 0);
9084       tree cst_uchar_ptr_node
9085         = build_pointer_type_for_mode (cst_uchar_node, ptr_mode, true);
9086
9087       tree ind1 = fold_convert_loc (loc, integer_type_node,
9088                                     build1 (INDIRECT_REF, cst_uchar_node,
9089                                             fold_convert_loc (loc,
9090                                                               cst_uchar_ptr_node,
9091                                                               arg1)));
9092       tree ind2 = fold_convert_loc (loc, integer_type_node,
9093                                     build1 (INDIRECT_REF, cst_uchar_node,
9094                                             fold_convert_loc (loc,
9095                                                               cst_uchar_ptr_node,
9096                                                               arg2)));
9097       return fold_build2_loc (loc, MINUS_EXPR, integer_type_node, ind1, ind2);
9098     }
9099
9100   return NULL_TREE;
9101 }
9102
9103 /* Fold function call to builtin signbit, signbitf or signbitl with argument
9104    ARG.  Return NULL_TREE if no simplification can be made.  */
9105
9106 static tree
9107 fold_builtin_signbit (location_t loc, tree arg, tree type)
9108 {
9109   if (!validate_arg (arg, REAL_TYPE))
9110     return NULL_TREE;
9111
9112   /* If ARG is a compile-time constant, determine the result.  */
9113   if (TREE_CODE (arg) == REAL_CST
9114       && !TREE_OVERFLOW (arg))
9115     {
9116       REAL_VALUE_TYPE c;
9117
9118       c = TREE_REAL_CST (arg);
9119       return (REAL_VALUE_NEGATIVE (c)
9120               ? build_one_cst (type)
9121               : build_zero_cst (type));
9122     }
9123
9124   /* If ARG is non-negative, the result is always zero.  */
9125   if (tree_expr_nonnegative_p (arg))
9126     return omit_one_operand_loc (loc, type, integer_zero_node, arg);
9127
9128   /* If ARG's format doesn't have signed zeros, return "arg < 0.0".  */
9129   if (!HONOR_SIGNED_ZEROS (TYPE_MODE (TREE_TYPE (arg))))
9130     return fold_build2_loc (loc, LT_EXPR, type, arg,
9131                         build_real (TREE_TYPE (arg), dconst0));
9132
9133   return NULL_TREE;
9134 }
9135
9136 /* Fold function call to builtin copysign, copysignf or copysignl with
9137    arguments ARG1 and ARG2.  Return NULL_TREE if no simplification can
9138    be made.  */
9139
9140 static tree
9141 fold_builtin_copysign (location_t loc, tree fndecl,
9142                        tree arg1, tree arg2, tree type)
9143 {
9144   tree tem;
9145
9146   if (!validate_arg (arg1, REAL_TYPE)
9147       || !validate_arg (arg2, REAL_TYPE))
9148     return NULL_TREE;
9149
9150   /* copysign(X,X) is X.  */
9151   if (operand_equal_p (arg1, arg2, 0))
9152     return fold_convert_loc (loc, type, arg1);
9153
9154   /* If ARG1 and ARG2 are compile-time constants, determine the result.  */
9155   if (TREE_CODE (arg1) == REAL_CST
9156       && TREE_CODE (arg2) == REAL_CST
9157       && !TREE_OVERFLOW (arg1)
9158       && !TREE_OVERFLOW (arg2))
9159     {
9160       REAL_VALUE_TYPE c1, c2;
9161
9162       c1 = TREE_REAL_CST (arg1);
9163       c2 = TREE_REAL_CST (arg2);
9164       /* c1.sign := c2.sign.  */
9165       real_copysign (&c1, &c2);
9166       return build_real (type, c1);
9167     }
9168
9169   /* copysign(X, Y) is fabs(X) when Y is always non-negative.
9170      Remember to evaluate Y for side-effects.  */
9171   if (tree_expr_nonnegative_p (arg2))
9172     return omit_one_operand_loc (loc, type,
9173                              fold_build1_loc (loc, ABS_EXPR, type, arg1),
9174                              arg2);
9175
9176   /* Strip sign changing operations for the first argument.  */
9177   tem = fold_strip_sign_ops (arg1);
9178   if (tem)
9179     return build_call_expr_loc (loc, fndecl, 2, tem, arg2);
9180
9181   return NULL_TREE;
9182 }
9183
9184 /* Fold a call to builtin isascii with argument ARG.  */
9185
9186 static tree
9187 fold_builtin_isascii (location_t loc, tree arg)
9188 {
9189   if (!validate_arg (arg, INTEGER_TYPE))
9190     return NULL_TREE;
9191   else
9192     {
9193       /* Transform isascii(c) -> ((c & ~0x7f) == 0).  */
9194       arg = fold_build2 (BIT_AND_EXPR, integer_type_node, arg,
9195                          build_int_cst (NULL_TREE,
9196                                         ~ (unsigned HOST_WIDE_INT) 0x7f));
9197       return fold_build2_loc (loc, EQ_EXPR, integer_type_node,
9198                           arg, integer_zero_node);
9199     }
9200 }
9201
9202 /* Fold a call to builtin toascii with argument ARG.  */
9203
9204 static tree
9205 fold_builtin_toascii (location_t loc, tree arg)
9206 {
9207   if (!validate_arg (arg, INTEGER_TYPE))
9208     return NULL_TREE;
9209
9210   /* Transform toascii(c) -> (c & 0x7f).  */
9211   return fold_build2_loc (loc, BIT_AND_EXPR, integer_type_node, arg,
9212                       build_int_cst (NULL_TREE, 0x7f));
9213 }
9214
9215 /* Fold a call to builtin isdigit with argument ARG.  */
9216
9217 static tree
9218 fold_builtin_isdigit (location_t loc, tree arg)
9219 {
9220   if (!validate_arg (arg, INTEGER_TYPE))
9221     return NULL_TREE;
9222   else
9223     {
9224       /* Transform isdigit(c) -> (unsigned)(c) - '0' <= 9.  */
9225       /* According to the C standard, isdigit is unaffected by locale.
9226          However, it definitely is affected by the target character set.  */
9227       unsigned HOST_WIDE_INT target_digit0
9228         = lang_hooks.to_target_charset ('0');
9229
9230       if (target_digit0 == 0)
9231         return NULL_TREE;
9232
9233       arg = fold_convert_loc (loc, unsigned_type_node, arg);
9234       arg = fold_build2 (MINUS_EXPR, unsigned_type_node, arg,
9235                          build_int_cst (unsigned_type_node, target_digit0));
9236       return fold_build2_loc (loc, LE_EXPR, integer_type_node, arg,
9237                           build_int_cst (unsigned_type_node, 9));
9238     }
9239 }
9240
9241 /* Fold a call to fabs, fabsf or fabsl with argument ARG.  */
9242
9243 static tree
9244 fold_builtin_fabs (location_t loc, tree arg, tree type)
9245 {
9246   if (!validate_arg (arg, REAL_TYPE))
9247     return NULL_TREE;
9248
9249   arg = fold_convert_loc (loc, type, arg);
9250   if (TREE_CODE (arg) == REAL_CST)
9251     return fold_abs_const (arg, type);
9252   return fold_build1_loc (loc, ABS_EXPR, type, arg);
9253 }
9254
9255 /* Fold a call to abs, labs, llabs or imaxabs with argument ARG.  */
9256
9257 static tree
9258 fold_builtin_abs (location_t loc, tree arg, tree type)
9259 {
9260   if (!validate_arg (arg, INTEGER_TYPE))
9261     return NULL_TREE;
9262
9263   arg = fold_convert_loc (loc, type, arg);
9264   if (TREE_CODE (arg) == INTEGER_CST)
9265     return fold_abs_const (arg, type);
9266   return fold_build1_loc (loc, ABS_EXPR, type, arg);
9267 }
9268
9269 /* Fold a call to builtin fmin or fmax.  */
9270
9271 static tree
9272 fold_builtin_fmin_fmax (location_t loc, tree arg0, tree arg1,
9273                         tree type, bool max)
9274 {
9275   if (validate_arg (arg0, REAL_TYPE) && validate_arg (arg1, REAL_TYPE))
9276     {
9277       /* Calculate the result when the argument is a constant.  */
9278       tree res = do_mpfr_arg2 (arg0, arg1, type, (max ? mpfr_max : mpfr_min));
9279
9280       if (res)
9281         return res;
9282
9283       /* If either argument is NaN, return the other one.  Avoid the
9284          transformation if we get (and honor) a signalling NaN.  Using
9285          omit_one_operand() ensures we create a non-lvalue.  */
9286       if (TREE_CODE (arg0) == REAL_CST
9287           && real_isnan (&TREE_REAL_CST (arg0))
9288           && (! HONOR_SNANS (TYPE_MODE (TREE_TYPE (arg0)))
9289               || ! TREE_REAL_CST (arg0).signalling))
9290         return omit_one_operand_loc (loc, type, arg1, arg0);
9291       if (TREE_CODE (arg1) == REAL_CST
9292           && real_isnan (&TREE_REAL_CST (arg1))
9293           && (! HONOR_SNANS (TYPE_MODE (TREE_TYPE (arg1)))
9294               || ! TREE_REAL_CST (arg1).signalling))
9295         return omit_one_operand_loc (loc, type, arg0, arg1);
9296
9297       /* Transform fmin/fmax(x,x) -> x.  */
9298       if (operand_equal_p (arg0, arg1, OEP_PURE_SAME))
9299         return omit_one_operand_loc (loc, type, arg0, arg1);
9300
9301       /* Convert fmin/fmax to MIN_EXPR/MAX_EXPR.  C99 requires these
9302          functions to return the numeric arg if the other one is NaN.
9303          These tree codes don't honor that, so only transform if
9304          -ffinite-math-only is set.  C99 doesn't require -0.0 to be
9305          handled, so we don't have to worry about it either.  */
9306       if (flag_finite_math_only)
9307         return fold_build2_loc (loc, (max ? MAX_EXPR : MIN_EXPR), type,
9308                             fold_convert_loc (loc, type, arg0),
9309                             fold_convert_loc (loc, type, arg1));
9310     }
9311   return NULL_TREE;
9312 }
9313
9314 /* Fold a call to builtin carg(a+bi) -> atan2(b,a).  */
9315
9316 static tree
9317 fold_builtin_carg (location_t loc, tree arg, tree type)
9318 {
9319   if (validate_arg (arg, COMPLEX_TYPE)
9320       && TREE_CODE (TREE_TYPE (TREE_TYPE (arg))) == REAL_TYPE)
9321     {
9322       tree atan2_fn = mathfn_built_in (type, BUILT_IN_ATAN2);
9323
9324       if (atan2_fn)
9325         {
9326           tree new_arg = builtin_save_expr (arg);
9327           tree r_arg = fold_build1_loc (loc, REALPART_EXPR, type, new_arg);
9328           tree i_arg = fold_build1_loc (loc, IMAGPART_EXPR, type, new_arg);
9329           return build_call_expr_loc (loc, atan2_fn, 2, i_arg, r_arg);
9330         }
9331     }
9332
9333   return NULL_TREE;
9334 }
9335
9336 /* Fold a call to builtin logb/ilogb.  */
9337
9338 static tree
9339 fold_builtin_logb (location_t loc, tree arg, tree rettype)
9340 {
9341   if (! validate_arg (arg, REAL_TYPE))
9342     return NULL_TREE;
9343
9344   STRIP_NOPS (arg);
9345
9346   if (TREE_CODE (arg) == REAL_CST && ! TREE_OVERFLOW (arg))
9347     {
9348       const REAL_VALUE_TYPE *const value = TREE_REAL_CST_PTR (arg);
9349
9350       switch (value->cl)
9351       {
9352       case rvc_nan:
9353       case rvc_inf:
9354         /* If arg is Inf or NaN and we're logb, return it.  */
9355         if (TREE_CODE (rettype) == REAL_TYPE)
9356           return fold_convert_loc (loc, rettype, arg);
9357         /* Fall through... */
9358       case rvc_zero:
9359         /* Zero may set errno and/or raise an exception for logb, also
9360            for ilogb we don't know FP_ILOGB0.  */
9361         return NULL_TREE;
9362       case rvc_normal:
9363         /* For normal numbers, proceed iff radix == 2.  In GCC,
9364            normalized significands are in the range [0.5, 1.0).  We
9365            want the exponent as if they were [1.0, 2.0) so get the
9366            exponent and subtract 1.  */
9367         if (REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (arg)))->b == 2)
9368           return fold_convert_loc (loc, rettype,
9369                                    build_int_cst (NULL_TREE,
9370                                                   REAL_EXP (value)-1));
9371         break;
9372       }
9373     }
9374
9375   return NULL_TREE;
9376 }
9377
9378 /* Fold a call to builtin significand, if radix == 2.  */
9379
9380 static tree
9381 fold_builtin_significand (location_t loc, tree arg, tree rettype)
9382 {
9383   if (! validate_arg (arg, REAL_TYPE))
9384     return NULL_TREE;
9385
9386   STRIP_NOPS (arg);
9387
9388   if (TREE_CODE (arg) == REAL_CST && ! TREE_OVERFLOW (arg))
9389     {
9390       const REAL_VALUE_TYPE *const value = TREE_REAL_CST_PTR (arg);
9391
9392       switch (value->cl)
9393       {
9394       case rvc_zero:
9395       case rvc_nan:
9396       case rvc_inf:
9397         /* If arg is +-0, +-Inf or +-NaN, then return it.  */
9398         return fold_convert_loc (loc, rettype, arg);
9399       case rvc_normal:
9400         /* For normal numbers, proceed iff radix == 2.  */
9401         if (REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (arg)))->b == 2)
9402           {
9403             REAL_VALUE_TYPE result = *value;
9404             /* In GCC, normalized significands are in the range [0.5,
9405                1.0).  We want them to be [1.0, 2.0) so set the
9406                exponent to 1.  */
9407             SET_REAL_EXP (&result, 1);
9408             return build_real (rettype, result);
9409           }
9410         break;
9411       }
9412     }
9413
9414   return NULL_TREE;
9415 }
9416
9417 /* Fold a call to builtin frexp, we can assume the base is 2.  */
9418
9419 static tree
9420 fold_builtin_frexp (location_t loc, tree arg0, tree arg1, tree rettype)
9421 {
9422   if (! validate_arg (arg0, REAL_TYPE) || ! validate_arg (arg1, POINTER_TYPE))
9423     return NULL_TREE;
9424
9425   STRIP_NOPS (arg0);
9426
9427   if (!(TREE_CODE (arg0) == REAL_CST && ! TREE_OVERFLOW (arg0)))
9428     return NULL_TREE;
9429
9430   arg1 = build_fold_indirect_ref_loc (loc, arg1);
9431
9432   /* Proceed if a valid pointer type was passed in.  */
9433   if (TYPE_MAIN_VARIANT (TREE_TYPE (arg1)) == integer_type_node)
9434     {
9435       const REAL_VALUE_TYPE *const value = TREE_REAL_CST_PTR (arg0);
9436       tree frac, exp;
9437
9438       switch (value->cl)
9439       {
9440       case rvc_zero:
9441         /* For +-0, return (*exp = 0, +-0).  */
9442         exp = integer_zero_node;
9443         frac = arg0;
9444         break;
9445       case rvc_nan:
9446       case rvc_inf:
9447         /* For +-NaN or +-Inf, *exp is unspecified, return arg0.  */
9448         return omit_one_operand_loc (loc, rettype, arg0, arg1);
9449       case rvc_normal:
9450         {
9451           /* Since the frexp function always expects base 2, and in
9452              GCC normalized significands are already in the range
9453              [0.5, 1.0), we have exactly what frexp wants.  */
9454           REAL_VALUE_TYPE frac_rvt = *value;
9455           SET_REAL_EXP (&frac_rvt, 0);
9456           frac = build_real (rettype, frac_rvt);
9457           exp = build_int_cst (NULL_TREE, REAL_EXP (value));
9458         }
9459         break;
9460       default:
9461         gcc_unreachable ();
9462       }
9463
9464       /* Create the COMPOUND_EXPR (*arg1 = trunc, frac). */
9465       arg1 = fold_build2_loc (loc, MODIFY_EXPR, rettype, arg1, exp);
9466       TREE_SIDE_EFFECTS (arg1) = 1;
9467       return fold_build2_loc (loc, COMPOUND_EXPR, rettype, arg1, frac);
9468     }
9469
9470   return NULL_TREE;
9471 }
9472
9473 /* Fold a call to builtin ldexp or scalbn/scalbln.  If LDEXP is true
9474    then we can assume the base is two.  If it's false, then we have to
9475    check the mode of the TYPE parameter in certain cases.  */
9476
9477 static tree
9478 fold_builtin_load_exponent (location_t loc, tree arg0, tree arg1,
9479                             tree type, bool ldexp)
9480 {
9481   if (validate_arg (arg0, REAL_TYPE) && validate_arg (arg1, INTEGER_TYPE))
9482     {
9483       STRIP_NOPS (arg0);
9484       STRIP_NOPS (arg1);
9485
9486       /* If arg0 is 0, Inf or NaN, or if arg1 is 0, then return arg0.  */
9487       if (real_zerop (arg0) || integer_zerop (arg1)
9488           || (TREE_CODE (arg0) == REAL_CST
9489               && !real_isfinite (&TREE_REAL_CST (arg0))))
9490         return omit_one_operand_loc (loc, type, arg0, arg1);
9491
9492       /* If both arguments are constant, then try to evaluate it.  */
9493       if ((ldexp || REAL_MODE_FORMAT (TYPE_MODE (type))->b == 2)
9494           && TREE_CODE (arg0) == REAL_CST && !TREE_OVERFLOW (arg0)
9495           && host_integerp (arg1, 0))
9496         {
9497           /* Bound the maximum adjustment to twice the range of the
9498              mode's valid exponents.  Use abs to ensure the range is
9499              positive as a sanity check.  */
9500           const long max_exp_adj = 2 *
9501             labs (REAL_MODE_FORMAT (TYPE_MODE (type))->emax
9502                  - REAL_MODE_FORMAT (TYPE_MODE (type))->emin);
9503
9504           /* Get the user-requested adjustment.  */
9505           const HOST_WIDE_INT req_exp_adj = tree_low_cst (arg1, 0);
9506
9507           /* The requested adjustment must be inside this range.  This
9508              is a preliminary cap to avoid things like overflow, we
9509              may still fail to compute the result for other reasons.  */
9510           if (-max_exp_adj < req_exp_adj && req_exp_adj < max_exp_adj)
9511             {
9512               REAL_VALUE_TYPE initial_result;
9513
9514               real_ldexp (&initial_result, &TREE_REAL_CST (arg0), req_exp_adj);
9515
9516               /* Ensure we didn't overflow.  */
9517               if (! real_isinf (&initial_result))
9518                 {
9519                   const REAL_VALUE_TYPE trunc_result
9520                     = real_value_truncate (TYPE_MODE (type), initial_result);
9521
9522                   /* Only proceed if the target mode can hold the
9523                      resulting value.  */
9524                   if (REAL_VALUES_EQUAL (initial_result, trunc_result))
9525                     return build_real (type, trunc_result);
9526                 }
9527             }
9528         }
9529     }
9530
9531   return NULL_TREE;
9532 }
9533
9534 /* Fold a call to builtin modf.  */
9535
9536 static tree
9537 fold_builtin_modf (location_t loc, tree arg0, tree arg1, tree rettype)
9538 {
9539   if (! validate_arg (arg0, REAL_TYPE) || ! validate_arg (arg1, POINTER_TYPE))
9540     return NULL_TREE;
9541
9542   STRIP_NOPS (arg0);
9543
9544   if (!(TREE_CODE (arg0) == REAL_CST && ! TREE_OVERFLOW (arg0)))
9545     return NULL_TREE;
9546
9547   arg1 = build_fold_indirect_ref_loc (loc, arg1);
9548
9549   /* Proceed if a valid pointer type was passed in.  */
9550   if (TYPE_MAIN_VARIANT (TREE_TYPE (arg1)) == TYPE_MAIN_VARIANT (rettype))
9551     {
9552       const REAL_VALUE_TYPE *const value = TREE_REAL_CST_PTR (arg0);
9553       REAL_VALUE_TYPE trunc, frac;
9554
9555       switch (value->cl)
9556       {
9557       case rvc_nan:
9558       case rvc_zero:
9559         /* For +-NaN or +-0, return (*arg1 = arg0, arg0).  */
9560         trunc = frac = *value;
9561         break;
9562       case rvc_inf:
9563         /* For +-Inf, return (*arg1 = arg0, +-0).  */
9564         frac = dconst0;
9565         frac.sign = value->sign;
9566         trunc = *value;
9567         break;
9568       case rvc_normal:
9569         /* Return (*arg1 = trunc(arg0), arg0-trunc(arg0)).  */
9570         real_trunc (&trunc, VOIDmode, value);
9571         real_arithmetic (&frac, MINUS_EXPR, value, &trunc);
9572         /* If the original number was negative and already
9573            integral, then the fractional part is -0.0.  */
9574         if (value->sign && frac.cl == rvc_zero)
9575           frac.sign = value->sign;
9576         break;
9577       }
9578
9579       /* Create the COMPOUND_EXPR (*arg1 = trunc, frac). */
9580       arg1 = fold_build2_loc (loc, MODIFY_EXPR, rettype, arg1,
9581                           build_real (rettype, trunc));
9582       TREE_SIDE_EFFECTS (arg1) = 1;
9583       return fold_build2_loc (loc, COMPOUND_EXPR, rettype, arg1,
9584                           build_real (rettype, frac));
9585     }
9586
9587   return NULL_TREE;
9588 }
9589
9590 /* Given a location LOC, an interclass builtin function decl FNDECL
9591    and its single argument ARG, return an folded expression computing
9592    the same, or NULL_TREE if we either couldn't or didn't want to fold
9593    (the latter happen if there's an RTL instruction available).  */
9594
9595 static tree
9596 fold_builtin_interclass_mathfn (location_t loc, tree fndecl, tree arg)
9597 {
9598   enum machine_mode mode;
9599
9600   if (!validate_arg (arg, REAL_TYPE))
9601     return NULL_TREE;
9602
9603   if (interclass_mathfn_icode (arg, fndecl) != CODE_FOR_nothing)
9604     return NULL_TREE;
9605
9606   mode = TYPE_MODE (TREE_TYPE (arg));
9607
9608   /* If there is no optab, try generic code.  */
9609   switch (DECL_FUNCTION_CODE (fndecl))
9610     {
9611       tree result;
9612
9613     CASE_FLT_FN (BUILT_IN_ISINF):
9614       {
9615         /* isinf(x) -> isgreater(fabs(x),DBL_MAX).  */
9616         tree const isgr_fn = built_in_decls[BUILT_IN_ISGREATER];
9617         tree const type = TREE_TYPE (arg);
9618         REAL_VALUE_TYPE r;
9619         char buf[128];
9620
9621         get_max_float (REAL_MODE_FORMAT (mode), buf, sizeof (buf));
9622         real_from_string (&r, buf);
9623         result = build_call_expr (isgr_fn, 2,
9624                                   fold_build1_loc (loc, ABS_EXPR, type, arg),
9625                                   build_real (type, r));
9626         return result;
9627       }
9628     CASE_FLT_FN (BUILT_IN_FINITE):
9629     case BUILT_IN_ISFINITE:
9630       {
9631         /* isfinite(x) -> islessequal(fabs(x),DBL_MAX).  */
9632         tree const isle_fn = built_in_decls[BUILT_IN_ISLESSEQUAL];
9633         tree const type = TREE_TYPE (arg);
9634         REAL_VALUE_TYPE r;
9635         char buf[128];
9636
9637         get_max_float (REAL_MODE_FORMAT (mode), buf, sizeof (buf));
9638         real_from_string (&r, buf);
9639         result = build_call_expr (isle_fn, 2,
9640                                   fold_build1_loc (loc, ABS_EXPR, type, arg),
9641                                   build_real (type, r));
9642         /*result = fold_build2_loc (loc, UNGT_EXPR,
9643                                   TREE_TYPE (TREE_TYPE (fndecl)),
9644                                   fold_build1_loc (loc, ABS_EXPR, type, arg),
9645                                   build_real (type, r));
9646         result = fold_build1_loc (loc, TRUTH_NOT_EXPR,
9647                                   TREE_TYPE (TREE_TYPE (fndecl)),
9648                                   result);*/
9649         return result;
9650       }
9651     case BUILT_IN_ISNORMAL:
9652       {
9653         /* isnormal(x) -> isgreaterequal(fabs(x),DBL_MIN) &
9654            islessequal(fabs(x),DBL_MAX).  */
9655         tree const isle_fn = built_in_decls[BUILT_IN_ISLESSEQUAL];
9656         tree const isge_fn = built_in_decls[BUILT_IN_ISGREATEREQUAL];
9657         tree const type = TREE_TYPE (arg);
9658         REAL_VALUE_TYPE rmax, rmin;
9659         char buf[128];
9660
9661         get_max_float (REAL_MODE_FORMAT (mode), buf, sizeof (buf));
9662         real_from_string (&rmax, buf);
9663         sprintf (buf, "0x1p%d", REAL_MODE_FORMAT (mode)->emin - 1);
9664         real_from_string (&rmin, buf);
9665         arg = builtin_save_expr (fold_build1_loc (loc, ABS_EXPR, type, arg));
9666         result = build_call_expr (isle_fn, 2, arg,
9667                                   build_real (type, rmax));
9668         result = fold_build2 (BIT_AND_EXPR, integer_type_node, result,
9669                               build_call_expr (isge_fn, 2, arg,
9670                                                build_real (type, rmin)));
9671         return result;
9672       }
9673     default:
9674       break;
9675     }
9676
9677   return NULL_TREE;
9678 }
9679
9680 /* Fold a call to __builtin_isnan(), __builtin_isinf, __builtin_finite.
9681    ARG is the argument for the call.  */
9682
9683 static tree
9684 fold_builtin_classify (location_t loc, tree fndecl, tree arg, int builtin_index)
9685 {
9686   tree type = TREE_TYPE (TREE_TYPE (fndecl));
9687   REAL_VALUE_TYPE r;
9688
9689   if (!validate_arg (arg, REAL_TYPE))
9690     return NULL_TREE;
9691
9692   switch (builtin_index)
9693     {
9694     case BUILT_IN_ISINF:
9695       if (!HONOR_INFINITIES (TYPE_MODE (TREE_TYPE (arg))))
9696         return omit_one_operand_loc (loc, type, integer_zero_node, arg);
9697
9698       if (TREE_CODE (arg) == REAL_CST)
9699         {
9700           r = TREE_REAL_CST (arg);
9701           if (real_isinf (&r))
9702             return real_compare (GT_EXPR, &r, &dconst0)
9703                    ? integer_one_node : integer_minus_one_node;
9704           else
9705             return integer_zero_node;
9706         }
9707
9708       return NULL_TREE;
9709
9710     case BUILT_IN_ISINF_SIGN:
9711       {
9712         /* isinf_sign(x) -> isinf(x) ? (signbit(x) ? -1 : 1) : 0 */
9713         /* In a boolean context, GCC will fold the inner COND_EXPR to
9714            1.  So e.g. "if (isinf_sign(x))" would be folded to just
9715            "if (isinf(x) ? 1 : 0)" which becomes "if (isinf(x))". */
9716         tree signbit_fn = mathfn_built_in_1 (TREE_TYPE (arg), BUILT_IN_SIGNBIT, 0);
9717         tree isinf_fn = built_in_decls[BUILT_IN_ISINF];
9718         tree tmp = NULL_TREE;
9719
9720         arg = builtin_save_expr (arg);
9721
9722         if (signbit_fn && isinf_fn)
9723           {
9724             tree signbit_call = build_call_expr_loc (loc, signbit_fn, 1, arg);
9725             tree isinf_call = build_call_expr_loc (loc, isinf_fn, 1, arg);
9726
9727             signbit_call = fold_build2_loc (loc, NE_EXPR, integer_type_node,
9728                                         signbit_call, integer_zero_node);
9729             isinf_call = fold_build2_loc (loc, NE_EXPR, integer_type_node,
9730                                       isinf_call, integer_zero_node);
9731
9732             tmp = fold_build3_loc (loc, COND_EXPR, integer_type_node, signbit_call,
9733                                integer_minus_one_node, integer_one_node);
9734             tmp = fold_build3_loc (loc, COND_EXPR, integer_type_node,
9735                                isinf_call, tmp,
9736                                integer_zero_node);
9737           }
9738
9739         return tmp;
9740       }
9741
9742     case BUILT_IN_ISFINITE:
9743       if (!HONOR_NANS (TYPE_MODE (TREE_TYPE (arg)))
9744           && !HONOR_INFINITIES (TYPE_MODE (TREE_TYPE (arg))))
9745         return omit_one_operand_loc (loc, type, integer_one_node, arg);
9746
9747       if (TREE_CODE (arg) == REAL_CST)
9748         {
9749           r = TREE_REAL_CST (arg);
9750           return real_isfinite (&r) ? integer_one_node : integer_zero_node;
9751         }
9752
9753       return NULL_TREE;
9754
9755     case BUILT_IN_ISNAN:
9756       if (!HONOR_NANS (TYPE_MODE (TREE_TYPE (arg))))
9757         return omit_one_operand_loc (loc, type, integer_zero_node, arg);
9758
9759       if (TREE_CODE (arg) == REAL_CST)
9760         {
9761           r = TREE_REAL_CST (arg);
9762           return real_isnan (&r) ? integer_one_node : integer_zero_node;
9763         }
9764
9765       arg = builtin_save_expr (arg);
9766       return fold_build2_loc (loc, UNORDERED_EXPR, type, arg, arg);
9767
9768     default:
9769       gcc_unreachable ();
9770     }
9771 }
9772
9773 /* Fold a call to __builtin_fpclassify(int, int, int, int, int, ...).
9774    This builtin will generate code to return the appropriate floating
9775    point classification depending on the value of the floating point
9776    number passed in.  The possible return values must be supplied as
9777    int arguments to the call in the following order: FP_NAN, FP_INFINITE,
9778    FP_NORMAL, FP_SUBNORMAL and FP_ZERO.  The ellipses is for exactly
9779    one floating point argument which is "type generic".  */
9780
9781 static tree
9782 fold_builtin_fpclassify (location_t loc, tree exp)
9783 {
9784   tree fp_nan, fp_infinite, fp_normal, fp_subnormal, fp_zero,
9785     arg, type, res, tmp;
9786   enum machine_mode mode;
9787   REAL_VALUE_TYPE r;
9788   char buf[128];
9789
9790   /* Verify the required arguments in the original call.  */
9791   if (!validate_arglist (exp, INTEGER_TYPE, INTEGER_TYPE,
9792                          INTEGER_TYPE, INTEGER_TYPE,
9793                          INTEGER_TYPE, REAL_TYPE, VOID_TYPE))
9794     return NULL_TREE;
9795
9796   fp_nan = CALL_EXPR_ARG (exp, 0);
9797   fp_infinite = CALL_EXPR_ARG (exp, 1);
9798   fp_normal = CALL_EXPR_ARG (exp, 2);
9799   fp_subnormal = CALL_EXPR_ARG (exp, 3);
9800   fp_zero = CALL_EXPR_ARG (exp, 4);
9801   arg = CALL_EXPR_ARG (exp, 5);
9802   type = TREE_TYPE (arg);
9803   mode = TYPE_MODE (type);
9804   arg = builtin_save_expr (fold_build1_loc (loc, ABS_EXPR, type, arg));
9805
9806   /* fpclassify(x) ->
9807        isnan(x) ? FP_NAN :
9808          (fabs(x) == Inf ? FP_INFINITE :
9809            (fabs(x) >= DBL_MIN ? FP_NORMAL :
9810              (x == 0 ? FP_ZERO : FP_SUBNORMAL))).  */
9811
9812   tmp = fold_build2_loc (loc, EQ_EXPR, integer_type_node, arg,
9813                      build_real (type, dconst0));
9814   res = fold_build3_loc (loc, COND_EXPR, integer_type_node,
9815                      tmp, fp_zero, fp_subnormal);
9816
9817   sprintf (buf, "0x1p%d", REAL_MODE_FORMAT (mode)->emin - 1);
9818   real_from_string (&r, buf);
9819   tmp = fold_build2_loc (loc, GE_EXPR, integer_type_node,
9820                      arg, build_real (type, r));
9821   res = fold_build3_loc (loc, COND_EXPR, integer_type_node, tmp, fp_normal, res);
9822
9823   if (HONOR_INFINITIES (mode))
9824     {
9825       real_inf (&r);
9826       tmp = fold_build2_loc (loc, EQ_EXPR, integer_type_node, arg,
9827                          build_real (type, r));
9828       res = fold_build3_loc (loc, COND_EXPR, integer_type_node, tmp,
9829                          fp_infinite, res);
9830     }
9831
9832   if (HONOR_NANS (mode))
9833     {
9834       tmp = fold_build2_loc (loc, ORDERED_EXPR, integer_type_node, arg, arg);
9835       res = fold_build3_loc (loc, COND_EXPR, integer_type_node, tmp, res, fp_nan);
9836     }
9837
9838   return res;
9839 }
9840
9841 /* Fold a call to an unordered comparison function such as
9842    __builtin_isgreater().  FNDECL is the FUNCTION_DECL for the function
9843    being called and ARG0 and ARG1 are the arguments for the call.
9844    UNORDERED_CODE and ORDERED_CODE are comparison codes that give
9845    the opposite of the desired result.  UNORDERED_CODE is used
9846    for modes that can hold NaNs and ORDERED_CODE is used for
9847    the rest.  */
9848
9849 static tree
9850 fold_builtin_unordered_cmp (location_t loc, tree fndecl, tree arg0, tree arg1,
9851                             enum tree_code unordered_code,
9852                             enum tree_code ordered_code)
9853 {
9854   tree type = TREE_TYPE (TREE_TYPE (fndecl));
9855   enum tree_code code;
9856   tree type0, type1;
9857   enum tree_code code0, code1;
9858   tree cmp_type = NULL_TREE;
9859
9860   type0 = TREE_TYPE (arg0);
9861   type1 = TREE_TYPE (arg1);
9862
9863   code0 = TREE_CODE (type0);
9864   code1 = TREE_CODE (type1);
9865
9866   if (code0 == REAL_TYPE && code1 == REAL_TYPE)
9867     /* Choose the wider of two real types.  */
9868     cmp_type = TYPE_PRECISION (type0) >= TYPE_PRECISION (type1)
9869       ? type0 : type1;
9870   else if (code0 == REAL_TYPE && code1 == INTEGER_TYPE)
9871     cmp_type = type0;
9872   else if (code0 == INTEGER_TYPE && code1 == REAL_TYPE)
9873     cmp_type = type1;
9874
9875   arg0 = fold_convert_loc (loc, cmp_type, arg0);
9876   arg1 = fold_convert_loc (loc, cmp_type, arg1);
9877
9878   if (unordered_code == UNORDERED_EXPR)
9879     {
9880       if (!HONOR_NANS (TYPE_MODE (TREE_TYPE (arg0))))
9881         return omit_two_operands_loc (loc, type, integer_zero_node, arg0, arg1);
9882       return fold_build2_loc (loc, UNORDERED_EXPR, type, arg0, arg1);
9883     }
9884
9885   code = HONOR_NANS (TYPE_MODE (TREE_TYPE (arg0))) ? unordered_code
9886                                                    : ordered_code;
9887   return fold_build1_loc (loc, TRUTH_NOT_EXPR, type,
9888                       fold_build2_loc (loc, code, type, arg0, arg1));
9889 }
9890
9891 /* Fold a call to built-in function FNDECL with 0 arguments.
9892    IGNORE is true if the result of the function call is ignored.  This
9893    function returns NULL_TREE if no simplification was possible.  */
9894
9895 static tree
9896 fold_builtin_0 (location_t loc, tree fndecl, bool ignore ATTRIBUTE_UNUSED)
9897 {
9898   tree type = TREE_TYPE (TREE_TYPE (fndecl));
9899   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
9900   switch (fcode)
9901     {
9902     CASE_FLT_FN (BUILT_IN_INF):
9903     case BUILT_IN_INFD32:
9904     case BUILT_IN_INFD64:
9905     case BUILT_IN_INFD128:
9906       return fold_builtin_inf (loc, type, true);
9907
9908     CASE_FLT_FN (BUILT_IN_HUGE_VAL):
9909       return fold_builtin_inf (loc, type, false);
9910
9911     case BUILT_IN_CLASSIFY_TYPE:
9912       return fold_builtin_classify_type (NULL_TREE);
9913
9914     default:
9915       break;
9916     }
9917   return NULL_TREE;
9918 }
9919
9920 /* Fold a call to built-in function FNDECL with 1 argument, ARG0.
9921    IGNORE is true if the result of the function call is ignored.  This
9922    function returns NULL_TREE if no simplification was possible.  */
9923
9924 static tree
9925 fold_builtin_1 (location_t loc, tree fndecl, tree arg0, bool ignore)
9926 {
9927   tree type = TREE_TYPE (TREE_TYPE (fndecl));
9928   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
9929   switch (fcode)
9930     {
9931     case BUILT_IN_CONSTANT_P:
9932       {
9933         tree val = fold_builtin_constant_p (arg0);
9934
9935         /* Gimplification will pull the CALL_EXPR for the builtin out of
9936            an if condition.  When not optimizing, we'll not CSE it back.
9937            To avoid link error types of regressions, return false now.  */
9938         if (!val && !optimize)
9939           val = integer_zero_node;
9940
9941         return val;
9942       }
9943
9944     case BUILT_IN_CLASSIFY_TYPE:
9945       return fold_builtin_classify_type (arg0);
9946
9947     case BUILT_IN_STRLEN:
9948       return fold_builtin_strlen (loc, type, arg0);
9949
9950     CASE_FLT_FN (BUILT_IN_FABS):
9951       return fold_builtin_fabs (loc, arg0, type);
9952
9953     case BUILT_IN_ABS:
9954     case BUILT_IN_LABS:
9955     case BUILT_IN_LLABS:
9956     case BUILT_IN_IMAXABS:
9957       return fold_builtin_abs (loc, arg0, type);
9958
9959     CASE_FLT_FN (BUILT_IN_CONJ):
9960       if (validate_arg (arg0, COMPLEX_TYPE)
9961         && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
9962         return fold_build1_loc (loc, CONJ_EXPR, type, arg0);
9963     break;
9964
9965     CASE_FLT_FN (BUILT_IN_CREAL):
9966       if (validate_arg (arg0, COMPLEX_TYPE)
9967         && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
9968         return non_lvalue_loc (loc, fold_build1_loc (loc, REALPART_EXPR, type, arg0));;
9969     break;
9970
9971     CASE_FLT_FN (BUILT_IN_CIMAG):
9972       if (validate_arg (arg0, COMPLEX_TYPE)
9973           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
9974         return non_lvalue_loc (loc, fold_build1_loc (loc, IMAGPART_EXPR, type, arg0));
9975     break;
9976
9977     CASE_FLT_FN (BUILT_IN_CCOS):
9978       return fold_builtin_ccos(loc, arg0, type, fndecl, /*hyper=*/ false);
9979
9980     CASE_FLT_FN (BUILT_IN_CCOSH):
9981       return fold_builtin_ccos(loc, arg0, type, fndecl, /*hyper=*/ true);
9982
9983     CASE_FLT_FN (BUILT_IN_CPROJ):
9984       return fold_builtin_cproj(loc, arg0, type);
9985
9986     CASE_FLT_FN (BUILT_IN_CSIN):
9987       if (validate_arg (arg0, COMPLEX_TYPE)
9988           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
9989         return do_mpc_arg1 (arg0, type, mpc_sin);
9990     break;
9991
9992     CASE_FLT_FN (BUILT_IN_CSINH):
9993       if (validate_arg (arg0, COMPLEX_TYPE)
9994           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
9995         return do_mpc_arg1 (arg0, type, mpc_sinh);
9996     break;
9997
9998     CASE_FLT_FN (BUILT_IN_CTAN):
9999       if (validate_arg (arg0, COMPLEX_TYPE)
10000           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
10001         return do_mpc_arg1 (arg0, type, mpc_tan);
10002     break;
10003
10004     CASE_FLT_FN (BUILT_IN_CTANH):
10005       if (validate_arg (arg0, COMPLEX_TYPE)
10006           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
10007         return do_mpc_arg1 (arg0, type, mpc_tanh);
10008     break;
10009
10010     CASE_FLT_FN (BUILT_IN_CLOG):
10011       if (validate_arg (arg0, COMPLEX_TYPE)
10012           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
10013         return do_mpc_arg1 (arg0, type, mpc_log);
10014     break;
10015
10016     CASE_FLT_FN (BUILT_IN_CSQRT):
10017       if (validate_arg (arg0, COMPLEX_TYPE)
10018           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
10019         return do_mpc_arg1 (arg0, type, mpc_sqrt);
10020     break;
10021
10022     CASE_FLT_FN (BUILT_IN_CASIN):
10023       if (validate_arg (arg0, COMPLEX_TYPE)
10024           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
10025         return do_mpc_arg1 (arg0, type, mpc_asin);
10026     break;
10027
10028     CASE_FLT_FN (BUILT_IN_CACOS):
10029       if (validate_arg (arg0, COMPLEX_TYPE)
10030           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
10031         return do_mpc_arg1 (arg0, type, mpc_acos);
10032     break;
10033
10034     CASE_FLT_FN (BUILT_IN_CATAN):
10035       if (validate_arg (arg0, COMPLEX_TYPE)
10036           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
10037         return do_mpc_arg1 (arg0, type, mpc_atan);
10038     break;
10039
10040     CASE_FLT_FN (BUILT_IN_CASINH):
10041       if (validate_arg (arg0, COMPLEX_TYPE)
10042           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
10043         return do_mpc_arg1 (arg0, type, mpc_asinh);
10044     break;
10045
10046     CASE_FLT_FN (BUILT_IN_CACOSH):
10047       if (validate_arg (arg0, COMPLEX_TYPE)
10048           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
10049         return do_mpc_arg1 (arg0, type, mpc_acosh);
10050     break;
10051
10052     CASE_FLT_FN (BUILT_IN_CATANH):
10053       if (validate_arg (arg0, COMPLEX_TYPE)
10054           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
10055         return do_mpc_arg1 (arg0, type, mpc_atanh);
10056     break;
10057
10058     CASE_FLT_FN (BUILT_IN_CABS):
10059       return fold_builtin_cabs (loc, arg0, type, fndecl);
10060
10061     CASE_FLT_FN (BUILT_IN_CARG):
10062       return fold_builtin_carg (loc, arg0, type);
10063
10064     CASE_FLT_FN (BUILT_IN_SQRT):
10065       return fold_builtin_sqrt (loc, arg0, type);
10066
10067     CASE_FLT_FN (BUILT_IN_CBRT):
10068       return fold_builtin_cbrt (loc, arg0, type);
10069
10070     CASE_FLT_FN (BUILT_IN_ASIN):
10071       if (validate_arg (arg0, REAL_TYPE))
10072         return do_mpfr_arg1 (arg0, type, mpfr_asin,
10073                              &dconstm1, &dconst1, true);
10074     break;
10075
10076     CASE_FLT_FN (BUILT_IN_ACOS):
10077       if (validate_arg (arg0, REAL_TYPE))
10078         return do_mpfr_arg1 (arg0, type, mpfr_acos,
10079                              &dconstm1, &dconst1, true);
10080     break;
10081
10082     CASE_FLT_FN (BUILT_IN_ATAN):
10083       if (validate_arg (arg0, REAL_TYPE))
10084         return do_mpfr_arg1 (arg0, type, mpfr_atan, NULL, NULL, 0);
10085     break;
10086
10087     CASE_FLT_FN (BUILT_IN_ASINH):
10088       if (validate_arg (arg0, REAL_TYPE))
10089         return do_mpfr_arg1 (arg0, type, mpfr_asinh, NULL, NULL, 0);
10090     break;
10091
10092     CASE_FLT_FN (BUILT_IN_ACOSH):
10093       if (validate_arg (arg0, REAL_TYPE))
10094         return do_mpfr_arg1 (arg0, type, mpfr_acosh,
10095                              &dconst1, NULL, true);
10096     break;
10097
10098     CASE_FLT_FN (BUILT_IN_ATANH):
10099       if (validate_arg (arg0, REAL_TYPE))
10100         return do_mpfr_arg1 (arg0, type, mpfr_atanh,
10101                              &dconstm1, &dconst1, false);
10102     break;
10103
10104     CASE_FLT_FN (BUILT_IN_SIN):
10105       if (validate_arg (arg0, REAL_TYPE))
10106         return do_mpfr_arg1 (arg0, type, mpfr_sin, NULL, NULL, 0);
10107     break;
10108
10109     CASE_FLT_FN (BUILT_IN_COS):
10110       return fold_builtin_cos (loc, arg0, type, fndecl);
10111
10112     CASE_FLT_FN (BUILT_IN_TAN):
10113       return fold_builtin_tan (arg0, type);
10114
10115     CASE_FLT_FN (BUILT_IN_CEXP):
10116       return fold_builtin_cexp (loc, arg0, type);
10117
10118     CASE_FLT_FN (BUILT_IN_CEXPI):
10119       if (validate_arg (arg0, REAL_TYPE))
10120         return do_mpfr_sincos (arg0, NULL_TREE, NULL_TREE);
10121     break;
10122
10123     CASE_FLT_FN (BUILT_IN_SINH):
10124       if (validate_arg (arg0, REAL_TYPE))
10125         return do_mpfr_arg1 (arg0, type, mpfr_sinh, NULL, NULL, 0);
10126     break;
10127
10128     CASE_FLT_FN (BUILT_IN_COSH):
10129       return fold_builtin_cosh (loc, arg0, type, fndecl);
10130
10131     CASE_FLT_FN (BUILT_IN_TANH):
10132       if (validate_arg (arg0, REAL_TYPE))
10133         return do_mpfr_arg1 (arg0, type, mpfr_tanh, NULL, NULL, 0);
10134     break;
10135
10136     CASE_FLT_FN (BUILT_IN_ERF):
10137       if (validate_arg (arg0, REAL_TYPE))
10138         return do_mpfr_arg1 (arg0, type, mpfr_erf, NULL, NULL, 0);
10139     break;
10140
10141     CASE_FLT_FN (BUILT_IN_ERFC):
10142       if (validate_arg (arg0, REAL_TYPE))
10143         return do_mpfr_arg1 (arg0, type, mpfr_erfc, NULL, NULL, 0);
10144     break;
10145
10146     CASE_FLT_FN (BUILT_IN_TGAMMA):
10147       if (validate_arg (arg0, REAL_TYPE))
10148         return do_mpfr_arg1 (arg0, type, mpfr_gamma, NULL, NULL, 0);
10149     break;
10150
10151     CASE_FLT_FN (BUILT_IN_EXP):
10152       return fold_builtin_exponent (loc, fndecl, arg0, mpfr_exp);
10153
10154     CASE_FLT_FN (BUILT_IN_EXP2):
10155       return fold_builtin_exponent (loc, fndecl, arg0, mpfr_exp2);
10156
10157     CASE_FLT_FN (BUILT_IN_EXP10):
10158     CASE_FLT_FN (BUILT_IN_POW10):
10159       return fold_builtin_exponent (loc, fndecl, arg0, mpfr_exp10);
10160
10161     CASE_FLT_FN (BUILT_IN_EXPM1):
10162       if (validate_arg (arg0, REAL_TYPE))
10163         return do_mpfr_arg1 (arg0, type, mpfr_expm1, NULL, NULL, 0);
10164     break;
10165
10166     CASE_FLT_FN (BUILT_IN_LOG):
10167     return fold_builtin_logarithm (loc, fndecl, arg0, mpfr_log);
10168
10169     CASE_FLT_FN (BUILT_IN_LOG2):
10170       return fold_builtin_logarithm (loc, fndecl, arg0, mpfr_log2);
10171
10172     CASE_FLT_FN (BUILT_IN_LOG10):
10173       return fold_builtin_logarithm (loc, fndecl, arg0, mpfr_log10);
10174
10175     CASE_FLT_FN (BUILT_IN_LOG1P):
10176       if (validate_arg (arg0, REAL_TYPE))
10177         return do_mpfr_arg1 (arg0, type, mpfr_log1p,
10178                              &dconstm1, NULL, false);
10179     break;
10180
10181     CASE_FLT_FN (BUILT_IN_J0):
10182       if (validate_arg (arg0, REAL_TYPE))
10183         return do_mpfr_arg1 (arg0, type, mpfr_j0,
10184                              NULL, NULL, 0);
10185     break;
10186
10187     CASE_FLT_FN (BUILT_IN_J1):
10188       if (validate_arg (arg0, REAL_TYPE))
10189         return do_mpfr_arg1 (arg0, type, mpfr_j1,
10190                              NULL, NULL, 0);
10191     break;
10192
10193     CASE_FLT_FN (BUILT_IN_Y0):
10194       if (validate_arg (arg0, REAL_TYPE))
10195         return do_mpfr_arg1 (arg0, type, mpfr_y0,
10196                              &dconst0, NULL, false);
10197     break;
10198
10199     CASE_FLT_FN (BUILT_IN_Y1):
10200       if (validate_arg (arg0, REAL_TYPE))
10201         return do_mpfr_arg1 (arg0, type, mpfr_y1,
10202                              &dconst0, NULL, false);
10203     break;
10204
10205     CASE_FLT_FN (BUILT_IN_NAN):
10206     case BUILT_IN_NAND32:
10207     case BUILT_IN_NAND64:
10208     case BUILT_IN_NAND128:
10209       return fold_builtin_nan (arg0, type, true);
10210
10211     CASE_FLT_FN (BUILT_IN_NANS):
10212       return fold_builtin_nan (arg0, type, false);
10213
10214     CASE_FLT_FN (BUILT_IN_FLOOR):
10215       return fold_builtin_floor (loc, fndecl, arg0);
10216
10217     CASE_FLT_FN (BUILT_IN_CEIL):
10218       return fold_builtin_ceil (loc, fndecl, arg0);
10219
10220     CASE_FLT_FN (BUILT_IN_TRUNC):
10221       return fold_builtin_trunc (loc, fndecl, arg0);
10222
10223     CASE_FLT_FN (BUILT_IN_ROUND):
10224       return fold_builtin_round (loc, fndecl, arg0);
10225
10226     CASE_FLT_FN (BUILT_IN_NEARBYINT):
10227     CASE_FLT_FN (BUILT_IN_RINT):
10228       return fold_trunc_transparent_mathfn (loc, fndecl, arg0);
10229
10230     CASE_FLT_FN (BUILT_IN_LCEIL):
10231     CASE_FLT_FN (BUILT_IN_LLCEIL):
10232     CASE_FLT_FN (BUILT_IN_LFLOOR):
10233     CASE_FLT_FN (BUILT_IN_LLFLOOR):
10234     CASE_FLT_FN (BUILT_IN_LROUND):
10235     CASE_FLT_FN (BUILT_IN_LLROUND):
10236       return fold_builtin_int_roundingfn (loc, fndecl, arg0);
10237
10238     CASE_FLT_FN (BUILT_IN_LRINT):
10239     CASE_FLT_FN (BUILT_IN_LLRINT):
10240       return fold_fixed_mathfn (loc, fndecl, arg0);
10241
10242     case BUILT_IN_BSWAP32:
10243     case BUILT_IN_BSWAP64:
10244       return fold_builtin_bswap (fndecl, arg0);
10245
10246     CASE_INT_FN (BUILT_IN_FFS):
10247     CASE_INT_FN (BUILT_IN_CLZ):
10248     CASE_INT_FN (BUILT_IN_CTZ):
10249     CASE_INT_FN (BUILT_IN_POPCOUNT):
10250     CASE_INT_FN (BUILT_IN_PARITY):
10251       return fold_builtin_bitop (fndecl, arg0);
10252
10253     CASE_FLT_FN (BUILT_IN_SIGNBIT):
10254       return fold_builtin_signbit (loc, arg0, type);
10255
10256     CASE_FLT_FN (BUILT_IN_SIGNIFICAND):
10257       return fold_builtin_significand (loc, arg0, type);
10258
10259     CASE_FLT_FN (BUILT_IN_ILOGB):
10260     CASE_FLT_FN (BUILT_IN_LOGB):
10261       return fold_builtin_logb (loc, arg0, type);
10262
10263     case BUILT_IN_ISASCII:
10264       return fold_builtin_isascii (loc, arg0);
10265
10266     case BUILT_IN_TOASCII:
10267       return fold_builtin_toascii (loc, arg0);
10268
10269     case BUILT_IN_ISDIGIT:
10270       return fold_builtin_isdigit (loc, arg0);
10271
10272     CASE_FLT_FN (BUILT_IN_FINITE):
10273     case BUILT_IN_FINITED32:
10274     case BUILT_IN_FINITED64:
10275     case BUILT_IN_FINITED128:
10276     case BUILT_IN_ISFINITE:
10277       {
10278         tree ret = fold_builtin_classify (loc, fndecl, arg0, BUILT_IN_ISFINITE);
10279         if (ret)
10280           return ret;
10281         return fold_builtin_interclass_mathfn (loc, fndecl, arg0);
10282       }
10283
10284     CASE_FLT_FN (BUILT_IN_ISINF):
10285     case BUILT_IN_ISINFD32:
10286     case BUILT_IN_ISINFD64:
10287     case BUILT_IN_ISINFD128:
10288       {
10289         tree ret = fold_builtin_classify (loc, fndecl, arg0, BUILT_IN_ISINF);
10290         if (ret)
10291           return ret;
10292         return fold_builtin_interclass_mathfn (loc, fndecl, arg0);
10293       }
10294
10295     case BUILT_IN_ISNORMAL:
10296       return fold_builtin_interclass_mathfn (loc, fndecl, arg0);
10297
10298     case BUILT_IN_ISINF_SIGN:
10299       return fold_builtin_classify (loc, fndecl, arg0, BUILT_IN_ISINF_SIGN);
10300
10301     CASE_FLT_FN (BUILT_IN_ISNAN):
10302     case BUILT_IN_ISNAND32:
10303     case BUILT_IN_ISNAND64:
10304     case BUILT_IN_ISNAND128:
10305       return fold_builtin_classify (loc, fndecl, arg0, BUILT_IN_ISNAN);
10306
10307     case BUILT_IN_PRINTF:
10308     case BUILT_IN_PRINTF_UNLOCKED:
10309     case BUILT_IN_VPRINTF:
10310       return fold_builtin_printf (loc, fndecl, arg0, NULL_TREE, ignore, fcode);
10311
10312     case BUILT_IN_FREE:
10313       if (integer_zerop (arg0))
10314         return build_empty_stmt (loc);
10315       break;
10316
10317     default:
10318       break;
10319     }
10320
10321   return NULL_TREE;
10322
10323 }
10324
10325 /* Fold a call to built-in function FNDECL with 2 arguments, ARG0 and ARG1.
10326    IGNORE is true if the result of the function call is ignored.  This
10327    function returns NULL_TREE if no simplification was possible.  */
10328
10329 static tree
10330 fold_builtin_2 (location_t loc, tree fndecl, tree arg0, tree arg1, bool ignore)
10331 {
10332   tree type = TREE_TYPE (TREE_TYPE (fndecl));
10333   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
10334
10335   switch (fcode)
10336     {
10337     CASE_FLT_FN (BUILT_IN_JN):
10338       if (validate_arg (arg0, INTEGER_TYPE)
10339           && validate_arg (arg1, REAL_TYPE))
10340         return do_mpfr_bessel_n (arg0, arg1, type, mpfr_jn, NULL, 0);
10341     break;
10342
10343     CASE_FLT_FN (BUILT_IN_YN):
10344       if (validate_arg (arg0, INTEGER_TYPE)
10345           && validate_arg (arg1, REAL_TYPE))
10346         return do_mpfr_bessel_n (arg0, arg1, type, mpfr_yn,
10347                                  &dconst0, false);
10348     break;
10349
10350     CASE_FLT_FN (BUILT_IN_DREM):
10351     CASE_FLT_FN (BUILT_IN_REMAINDER):
10352       if (validate_arg (arg0, REAL_TYPE)
10353           && validate_arg(arg1, REAL_TYPE))
10354         return do_mpfr_arg2 (arg0, arg1, type, mpfr_remainder);
10355     break;
10356
10357     CASE_FLT_FN_REENT (BUILT_IN_GAMMA): /* GAMMA_R */
10358     CASE_FLT_FN_REENT (BUILT_IN_LGAMMA): /* LGAMMA_R */
10359       if (validate_arg (arg0, REAL_TYPE)
10360           && validate_arg(arg1, POINTER_TYPE))
10361         return do_mpfr_lgamma_r (arg0, arg1, type);
10362     break;
10363
10364     CASE_FLT_FN (BUILT_IN_ATAN2):
10365       if (validate_arg (arg0, REAL_TYPE)
10366           && validate_arg(arg1, REAL_TYPE))
10367         return do_mpfr_arg2 (arg0, arg1, type, mpfr_atan2);
10368     break;
10369
10370     CASE_FLT_FN (BUILT_IN_FDIM):
10371       if (validate_arg (arg0, REAL_TYPE)
10372           && validate_arg(arg1, REAL_TYPE))
10373         return do_mpfr_arg2 (arg0, arg1, type, mpfr_dim);
10374     break;
10375
10376     CASE_FLT_FN (BUILT_IN_HYPOT):
10377       return fold_builtin_hypot (loc, fndecl, arg0, arg1, type);
10378
10379     CASE_FLT_FN (BUILT_IN_CPOW):
10380       if (validate_arg (arg0, COMPLEX_TYPE)
10381           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE
10382           && validate_arg (arg1, COMPLEX_TYPE)
10383           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg1))) == REAL_TYPE)
10384         return do_mpc_arg2 (arg0, arg1, type, /*do_nonfinite=*/ 0, mpc_pow);
10385     break;
10386
10387     CASE_FLT_FN (BUILT_IN_LDEXP):
10388       return fold_builtin_load_exponent (loc, arg0, arg1, type, /*ldexp=*/true);
10389     CASE_FLT_FN (BUILT_IN_SCALBN):
10390     CASE_FLT_FN (BUILT_IN_SCALBLN):
10391       return fold_builtin_load_exponent (loc, arg0, arg1,
10392                                          type, /*ldexp=*/false);
10393
10394     CASE_FLT_FN (BUILT_IN_FREXP):
10395       return fold_builtin_frexp (loc, arg0, arg1, type);
10396
10397     CASE_FLT_FN (BUILT_IN_MODF):
10398       return fold_builtin_modf (loc, arg0, arg1, type);
10399
10400     case BUILT_IN_BZERO:
10401       return fold_builtin_bzero (loc, arg0, arg1, ignore);
10402
10403     case BUILT_IN_FPUTS:
10404       return fold_builtin_fputs (loc, arg0, arg1, ignore, false, NULL_TREE);
10405
10406     case BUILT_IN_FPUTS_UNLOCKED:
10407       return fold_builtin_fputs (loc, arg0, arg1, ignore, true, NULL_TREE);
10408
10409     case BUILT_IN_STRSTR:
10410       return fold_builtin_strstr (loc, arg0, arg1, type);
10411
10412     case BUILT_IN_STRCAT:
10413       return fold_builtin_strcat (loc, arg0, arg1);
10414
10415     case BUILT_IN_STRSPN:
10416       return fold_builtin_strspn (loc, arg0, arg1);
10417
10418     case BUILT_IN_STRCSPN:
10419       return fold_builtin_strcspn (loc, arg0, arg1);
10420
10421     case BUILT_IN_STRCHR:
10422     case BUILT_IN_INDEX:
10423       return fold_builtin_strchr (loc, arg0, arg1, type);
10424
10425     case BUILT_IN_STRRCHR:
10426     case BUILT_IN_RINDEX:
10427       return fold_builtin_strrchr (loc, arg0, arg1, type);
10428
10429     case BUILT_IN_STRCPY:
10430       return fold_builtin_strcpy (loc, fndecl, arg0, arg1, NULL_TREE);
10431
10432     case BUILT_IN_STPCPY:
10433       if (ignore)
10434         {
10435           tree fn = implicit_built_in_decls[BUILT_IN_STRCPY];
10436           if (!fn)
10437             break;
10438
10439           return build_call_expr_loc (loc, fn, 2, arg0, arg1);
10440         }
10441       else
10442         return fold_builtin_stpcpy (loc, fndecl, arg0, arg1);
10443       break;
10444
10445     case BUILT_IN_STRCMP:
10446       return fold_builtin_strcmp (loc, arg0, arg1);
10447
10448     case BUILT_IN_STRPBRK:
10449       return fold_builtin_strpbrk (loc, arg0, arg1, type);
10450
10451     case BUILT_IN_EXPECT:
10452       return fold_builtin_expect (loc, arg0, arg1);
10453
10454     CASE_FLT_FN (BUILT_IN_POW):
10455       return fold_builtin_pow (loc, fndecl, arg0, arg1, type);
10456
10457     CASE_FLT_FN (BUILT_IN_POWI):
10458       return fold_builtin_powi (loc, fndecl, arg0, arg1, type);
10459
10460     CASE_FLT_FN (BUILT_IN_COPYSIGN):
10461       return fold_builtin_copysign (loc, fndecl, arg0, arg1, type);
10462
10463     CASE_FLT_FN (BUILT_IN_FMIN):
10464       return fold_builtin_fmin_fmax (loc, arg0, arg1, type, /*max=*/false);
10465
10466     CASE_FLT_FN (BUILT_IN_FMAX):
10467       return fold_builtin_fmin_fmax (loc, arg0, arg1, type, /*max=*/true);
10468
10469     case BUILT_IN_ISGREATER:
10470       return fold_builtin_unordered_cmp (loc, fndecl,
10471                                          arg0, arg1, UNLE_EXPR, LE_EXPR);
10472     case BUILT_IN_ISGREATEREQUAL:
10473       return fold_builtin_unordered_cmp (loc, fndecl,
10474                                          arg0, arg1, UNLT_EXPR, LT_EXPR);
10475     case BUILT_IN_ISLESS:
10476       return fold_builtin_unordered_cmp (loc, fndecl,
10477                                          arg0, arg1, UNGE_EXPR, GE_EXPR);
10478     case BUILT_IN_ISLESSEQUAL:
10479       return fold_builtin_unordered_cmp (loc, fndecl,
10480                                          arg0, arg1, UNGT_EXPR, GT_EXPR);
10481     case BUILT_IN_ISLESSGREATER:
10482       return fold_builtin_unordered_cmp (loc, fndecl,
10483                                          arg0, arg1, UNEQ_EXPR, EQ_EXPR);
10484     case BUILT_IN_ISUNORDERED:
10485       return fold_builtin_unordered_cmp (loc, fndecl,
10486                                          arg0, arg1, UNORDERED_EXPR,
10487                                          NOP_EXPR);
10488
10489       /* We do the folding for va_start in the expander.  */
10490     case BUILT_IN_VA_START:
10491       break;
10492
10493     case BUILT_IN_SPRINTF:
10494       return fold_builtin_sprintf (loc, arg0, arg1, NULL_TREE, ignore);
10495
10496     case BUILT_IN_OBJECT_SIZE:
10497       return fold_builtin_object_size (arg0, arg1);
10498
10499     case BUILT_IN_PRINTF:
10500     case BUILT_IN_PRINTF_UNLOCKED:
10501     case BUILT_IN_VPRINTF:
10502       return fold_builtin_printf (loc, fndecl, arg0, arg1, ignore, fcode);
10503
10504     case BUILT_IN_PRINTF_CHK:
10505     case BUILT_IN_VPRINTF_CHK:
10506       if (!validate_arg (arg0, INTEGER_TYPE)
10507           || TREE_SIDE_EFFECTS (arg0))
10508         return NULL_TREE;
10509       else
10510         return fold_builtin_printf (loc, fndecl,
10511                                     arg1, NULL_TREE, ignore, fcode);
10512     break;
10513
10514     case BUILT_IN_FPRINTF:
10515     case BUILT_IN_FPRINTF_UNLOCKED:
10516     case BUILT_IN_VFPRINTF:
10517       return fold_builtin_fprintf (loc, fndecl, arg0, arg1, NULL_TREE,
10518                                    ignore, fcode);
10519
10520     default:
10521       break;
10522     }
10523   return NULL_TREE;
10524 }
10525
10526 /* Fold a call to built-in function FNDECL with 3 arguments, ARG0, ARG1,
10527    and ARG2.  IGNORE is true if the result of the function call is ignored.
10528    This function returns NULL_TREE if no simplification was possible.  */
10529
10530 static tree
10531 fold_builtin_3 (location_t loc, tree fndecl,
10532                 tree arg0, tree arg1, tree arg2, bool ignore)
10533 {
10534   tree type = TREE_TYPE (TREE_TYPE (fndecl));
10535   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
10536   switch (fcode)
10537     {
10538
10539     CASE_FLT_FN (BUILT_IN_SINCOS):
10540       return fold_builtin_sincos (loc, arg0, arg1, arg2);
10541
10542     CASE_FLT_FN (BUILT_IN_FMA):
10543       if (validate_arg (arg0, REAL_TYPE)
10544           && validate_arg(arg1, REAL_TYPE)
10545           && validate_arg(arg2, REAL_TYPE))
10546         return do_mpfr_arg3 (arg0, arg1, arg2, type, mpfr_fma);
10547     break;
10548
10549     CASE_FLT_FN (BUILT_IN_REMQUO):
10550       if (validate_arg (arg0, REAL_TYPE)
10551           && validate_arg(arg1, REAL_TYPE)
10552           && validate_arg(arg2, POINTER_TYPE))
10553         return do_mpfr_remquo (arg0, arg1, arg2);
10554     break;
10555
10556     case BUILT_IN_MEMSET:
10557       return fold_builtin_memset (loc, arg0, arg1, arg2, type, ignore);
10558
10559     case BUILT_IN_BCOPY:
10560       return fold_builtin_memory_op (loc, arg1, arg0, arg2,
10561                                      void_type_node, true, /*endp=*/3);
10562
10563     case BUILT_IN_MEMCPY:
10564       return fold_builtin_memory_op (loc, arg0, arg1, arg2,
10565                                      type, ignore, /*endp=*/0);
10566
10567     case BUILT_IN_MEMPCPY:
10568       return fold_builtin_memory_op (loc, arg0, arg1, arg2,
10569                                      type, ignore, /*endp=*/1);
10570
10571     case BUILT_IN_MEMMOVE:
10572       return fold_builtin_memory_op (loc, arg0, arg1, arg2,
10573                                      type, ignore, /*endp=*/3);
10574
10575     case BUILT_IN_STRNCAT:
10576       return fold_builtin_strncat (loc, arg0, arg1, arg2);
10577
10578     case BUILT_IN_STRNCPY:
10579       return fold_builtin_strncpy (loc, fndecl, arg0, arg1, arg2, NULL_TREE);
10580
10581     case BUILT_IN_STRNCMP:
10582       return fold_builtin_strncmp (loc, arg0, arg1, arg2);
10583
10584     case BUILT_IN_MEMCHR:
10585       return fold_builtin_memchr (loc, arg0, arg1, arg2, type);
10586
10587     case BUILT_IN_BCMP:
10588     case BUILT_IN_MEMCMP:
10589       return fold_builtin_memcmp (loc, arg0, arg1, arg2);;
10590
10591     case BUILT_IN_SPRINTF:
10592       return fold_builtin_sprintf (loc, arg0, arg1, arg2, ignore);
10593
10594     case BUILT_IN_STRCPY_CHK:
10595     case BUILT_IN_STPCPY_CHK:
10596       return fold_builtin_stxcpy_chk (loc, fndecl, arg0, arg1, arg2, NULL_TREE,
10597                                       ignore, fcode);
10598
10599     case BUILT_IN_STRCAT_CHK:
10600       return fold_builtin_strcat_chk (loc, fndecl, arg0, arg1, arg2);
10601
10602     case BUILT_IN_PRINTF_CHK:
10603     case BUILT_IN_VPRINTF_CHK:
10604       if (!validate_arg (arg0, INTEGER_TYPE)
10605           || TREE_SIDE_EFFECTS (arg0))
10606         return NULL_TREE;
10607       else
10608         return fold_builtin_printf (loc, fndecl, arg1, arg2, ignore, fcode);
10609     break;
10610
10611     case BUILT_IN_FPRINTF:
10612     case BUILT_IN_FPRINTF_UNLOCKED:
10613     case BUILT_IN_VFPRINTF:
10614       return fold_builtin_fprintf (loc, fndecl, arg0, arg1, arg2,
10615                                    ignore, fcode);
10616
10617     case BUILT_IN_FPRINTF_CHK:
10618     case BUILT_IN_VFPRINTF_CHK:
10619       if (!validate_arg (arg1, INTEGER_TYPE)
10620           || TREE_SIDE_EFFECTS (arg1))
10621         return NULL_TREE;
10622       else
10623         return fold_builtin_fprintf (loc, fndecl, arg0, arg2, NULL_TREE,
10624                                      ignore, fcode);
10625
10626     default:
10627       break;
10628     }
10629   return NULL_TREE;
10630 }
10631
10632 /* Fold a call to built-in function FNDECL with 4 arguments, ARG0, ARG1,
10633    ARG2, and ARG3.  IGNORE is true if the result of the function call is
10634    ignored.  This function returns NULL_TREE if no simplification was
10635    possible.  */
10636
10637 static tree
10638 fold_builtin_4 (location_t loc, tree fndecl,
10639                 tree arg0, tree arg1, tree arg2, tree arg3, bool ignore)
10640 {
10641   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
10642
10643   switch (fcode)
10644     {
10645     case BUILT_IN_MEMCPY_CHK:
10646     case BUILT_IN_MEMPCPY_CHK:
10647     case BUILT_IN_MEMMOVE_CHK:
10648     case BUILT_IN_MEMSET_CHK:
10649       return fold_builtin_memory_chk (loc, fndecl, arg0, arg1, arg2, arg3,
10650                                       NULL_TREE, ignore,
10651                                       DECL_FUNCTION_CODE (fndecl));
10652
10653     case BUILT_IN_STRNCPY_CHK:
10654       return fold_builtin_strncpy_chk (loc, arg0, arg1, arg2, arg3, NULL_TREE);
10655
10656     case BUILT_IN_STRNCAT_CHK:
10657       return fold_builtin_strncat_chk (loc, fndecl, arg0, arg1, arg2, arg3);
10658
10659     case BUILT_IN_FPRINTF_CHK:
10660     case BUILT_IN_VFPRINTF_CHK:
10661       if (!validate_arg (arg1, INTEGER_TYPE)
10662           || TREE_SIDE_EFFECTS (arg1))
10663         return NULL_TREE;
10664       else
10665         return fold_builtin_fprintf (loc, fndecl, arg0, arg2, arg3,
10666                                      ignore, fcode);
10667     break;
10668
10669     default:
10670       break;
10671     }
10672   return NULL_TREE;
10673 }
10674
10675 /* Fold a call to built-in function FNDECL.  ARGS is an array of NARGS
10676     arguments, where NARGS <= 4.  IGNORE is true if the result of the
10677     function call is ignored.  This function returns NULL_TREE if no
10678     simplification was possible.  Note that this only folds builtins with
10679     fixed argument patterns.  Foldings that do varargs-to-varargs
10680     transformations, or that match calls with more than 4 arguments,
10681     need to be handled with fold_builtin_varargs instead.  */
10682
10683 #define MAX_ARGS_TO_FOLD_BUILTIN 4
10684
10685 static tree
10686 fold_builtin_n (location_t loc, tree fndecl, tree *args, int nargs, bool ignore)
10687 {
10688   tree ret = NULL_TREE;
10689
10690   switch (nargs)
10691     {
10692     case 0:
10693       ret = fold_builtin_0 (loc, fndecl, ignore);
10694       break;
10695     case 1:
10696       ret = fold_builtin_1 (loc, fndecl, args[0], ignore);
10697       break;
10698     case 2:
10699       ret = fold_builtin_2 (loc, fndecl, args[0], args[1], ignore);
10700       break;
10701     case 3:
10702       ret = fold_builtin_3 (loc, fndecl, args[0], args[1], args[2], ignore);
10703       break;
10704     case 4:
10705       ret = fold_builtin_4 (loc, fndecl, args[0], args[1], args[2], args[3],
10706                             ignore);
10707       break;
10708     default:
10709       break;
10710     }
10711   if (ret)
10712     {
10713       ret = build1 (NOP_EXPR, TREE_TYPE (ret), ret);
10714       SET_EXPR_LOCATION (ret, loc);
10715       TREE_NO_WARNING (ret) = 1;
10716       return ret;
10717     }
10718   return NULL_TREE;
10719 }
10720
10721 /* Builtins with folding operations that operate on "..." arguments
10722    need special handling; we need to store the arguments in a convenient
10723    data structure before attempting any folding.  Fortunately there are
10724    only a few builtins that fall into this category.  FNDECL is the
10725    function, EXP is the CALL_EXPR for the call, and IGNORE is true if the
10726    result of the function call is ignored.  */
10727
10728 static tree
10729 fold_builtin_varargs (location_t loc, tree fndecl, tree exp,
10730                       bool ignore ATTRIBUTE_UNUSED)
10731 {
10732   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
10733   tree ret = NULL_TREE;
10734
10735   switch (fcode)
10736     {
10737     case BUILT_IN_SPRINTF_CHK:
10738     case BUILT_IN_VSPRINTF_CHK:
10739       ret = fold_builtin_sprintf_chk (loc, exp, fcode);
10740       break;
10741
10742     case BUILT_IN_SNPRINTF_CHK:
10743     case BUILT_IN_VSNPRINTF_CHK:
10744       ret = fold_builtin_snprintf_chk (loc, exp, NULL_TREE, fcode);
10745       break;
10746
10747     case BUILT_IN_FPCLASSIFY:
10748       ret = fold_builtin_fpclassify (loc, exp);
10749       break;
10750
10751     default:
10752       break;
10753     }
10754   if (ret)
10755     {
10756       ret = build1 (NOP_EXPR, TREE_TYPE (ret), ret);
10757       SET_EXPR_LOCATION (ret, loc);
10758       TREE_NO_WARNING (ret) = 1;
10759       return ret;
10760     }
10761   return NULL_TREE;
10762 }
10763
10764 /* Return true if FNDECL shouldn't be folded right now.
10765    If a built-in function has an inline attribute always_inline
10766    wrapper, defer folding it after always_inline functions have
10767    been inlined, otherwise e.g. -D_FORTIFY_SOURCE checking
10768    might not be performed.  */
10769
10770 static bool
10771 avoid_folding_inline_builtin (tree fndecl)
10772 {
10773   return (DECL_DECLARED_INLINE_P (fndecl)
10774           && DECL_DISREGARD_INLINE_LIMITS (fndecl)
10775           && cfun
10776           && !cfun->always_inline_functions_inlined
10777           && lookup_attribute ("always_inline", DECL_ATTRIBUTES (fndecl)));
10778 }
10779
10780 /* A wrapper function for builtin folding that prevents warnings for
10781    "statement without effect" and the like, caused by removing the
10782    call node earlier than the warning is generated.  */
10783
10784 tree
10785 fold_call_expr (location_t loc, tree exp, bool ignore)
10786 {
10787   tree ret = NULL_TREE;
10788   tree fndecl = get_callee_fndecl (exp);
10789   if (fndecl
10790       && TREE_CODE (fndecl) == FUNCTION_DECL
10791       && DECL_BUILT_IN (fndecl)
10792       /* If CALL_EXPR_VA_ARG_PACK is set, the arguments aren't finalized
10793          yet.  Defer folding until we see all the arguments
10794          (after inlining).  */
10795       && !CALL_EXPR_VA_ARG_PACK (exp))
10796     {
10797       int nargs = call_expr_nargs (exp);
10798
10799       /* Before gimplification CALL_EXPR_VA_ARG_PACK is not set, but
10800          instead last argument is __builtin_va_arg_pack ().  Defer folding
10801          even in that case, until arguments are finalized.  */
10802       if (nargs && TREE_CODE (CALL_EXPR_ARG (exp, nargs - 1)) == CALL_EXPR)
10803         {
10804           tree fndecl2 = get_callee_fndecl (CALL_EXPR_ARG (exp, nargs - 1));
10805           if (fndecl2
10806               && TREE_CODE (fndecl2) == FUNCTION_DECL
10807               && DECL_BUILT_IN_CLASS (fndecl2) == BUILT_IN_NORMAL
10808               && DECL_FUNCTION_CODE (fndecl2) == BUILT_IN_VA_ARG_PACK)
10809             return NULL_TREE;
10810         }
10811
10812       if (avoid_folding_inline_builtin (fndecl))
10813         return NULL_TREE;
10814
10815       if (DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_MD)
10816         return targetm.fold_builtin (fndecl, call_expr_nargs (exp),
10817                                      CALL_EXPR_ARGP (exp), ignore);
10818       else
10819         {
10820           if (nargs <= MAX_ARGS_TO_FOLD_BUILTIN)
10821             {
10822               tree *args = CALL_EXPR_ARGP (exp);
10823               ret = fold_builtin_n (loc, fndecl, args, nargs, ignore);
10824             }
10825           if (!ret)
10826             ret = fold_builtin_varargs (loc, fndecl, exp, ignore);
10827           if (ret)
10828             return ret;
10829         }
10830     }
10831   return NULL_TREE;
10832 }
10833
10834 /* Conveniently construct a function call expression.  FNDECL names the
10835    function to be called and N arguments are passed in the array
10836    ARGARRAY.  */
10837
10838 tree
10839 build_call_expr_loc_array (location_t loc, tree fndecl, int n, tree *argarray)
10840 {
10841   tree fntype = TREE_TYPE (fndecl);
10842   tree fn = build1 (ADDR_EXPR, build_pointer_type (fntype), fndecl);
10843  
10844   return fold_builtin_call_array (loc, TREE_TYPE (fntype), fn, n, argarray);
10845 }
10846
10847 /* Conveniently construct a function call expression.  FNDECL names the
10848    function to be called and the arguments are passed in the vector
10849    VEC.  */
10850
10851 tree
10852 build_call_expr_loc_vec (location_t loc, tree fndecl, VEC(tree,gc) *vec)
10853 {
10854   return build_call_expr_loc_array (loc, fndecl, VEC_length (tree, vec),
10855                                     VEC_address (tree, vec));
10856 }
10857
10858
10859 /* Conveniently construct a function call expression.  FNDECL names the
10860    function to be called, N is the number of arguments, and the "..."
10861    parameters are the argument expressions.  */
10862
10863 tree
10864 build_call_expr_loc (location_t loc, tree fndecl, int n, ...)
10865 {
10866   va_list ap;
10867   tree *argarray = XALLOCAVEC (tree, n);
10868   int i;
10869
10870   va_start (ap, n);
10871   for (i = 0; i < n; i++)
10872     argarray[i] = va_arg (ap, tree);
10873   va_end (ap);
10874   return build_call_expr_loc_array (loc, fndecl, n, argarray);
10875 }
10876
10877 /* Like build_call_expr_loc (UNKNOWN_LOCATION, ...).  Duplicated because
10878    varargs macros aren't supported by all bootstrap compilers.  */
10879
10880 tree
10881 build_call_expr (tree fndecl, int n, ...)
10882 {
10883   va_list ap;
10884   tree *argarray = XALLOCAVEC (tree, n);
10885   int i;
10886
10887   va_start (ap, n);
10888   for (i = 0; i < n; i++)
10889     argarray[i] = va_arg (ap, tree);
10890   va_end (ap);
10891   return build_call_expr_loc_array (UNKNOWN_LOCATION, fndecl, n, argarray);
10892 }
10893
10894 /* Construct a CALL_EXPR with type TYPE with FN as the function expression.
10895    N arguments are passed in the array ARGARRAY.  */
10896
10897 tree
10898 fold_builtin_call_array (location_t loc, tree type,
10899                          tree fn,
10900                          int n,
10901                          tree *argarray)
10902 {
10903   tree ret = NULL_TREE;
10904    tree exp;
10905
10906   if (TREE_CODE (fn) == ADDR_EXPR)
10907   {
10908     tree fndecl = TREE_OPERAND (fn, 0);
10909     if (TREE_CODE (fndecl) == FUNCTION_DECL
10910         && DECL_BUILT_IN (fndecl))
10911       {
10912         /* If last argument is __builtin_va_arg_pack (), arguments to this
10913            function are not finalized yet.  Defer folding until they are.  */
10914         if (n && TREE_CODE (argarray[n - 1]) == CALL_EXPR)
10915           {
10916             tree fndecl2 = get_callee_fndecl (argarray[n - 1]);
10917             if (fndecl2
10918                 && TREE_CODE (fndecl2) == FUNCTION_DECL
10919                 && DECL_BUILT_IN_CLASS (fndecl2) == BUILT_IN_NORMAL
10920                 && DECL_FUNCTION_CODE (fndecl2) == BUILT_IN_VA_ARG_PACK)
10921               return build_call_array_loc (loc, type, fn, n, argarray);
10922           }
10923         if (avoid_folding_inline_builtin (fndecl))
10924           return build_call_array_loc (loc, type, fn, n, argarray);
10925         if (DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_MD)
10926           {
10927             ret = targetm.fold_builtin (fndecl, n, argarray, false);
10928             if (ret)
10929               return ret;
10930
10931             return build_call_array_loc (loc, type, fn, n, argarray);
10932           }
10933         else if (n <= MAX_ARGS_TO_FOLD_BUILTIN)
10934           {
10935             /* First try the transformations that don't require consing up
10936                an exp.  */
10937             ret = fold_builtin_n (loc, fndecl, argarray, n, false);
10938             if (ret)
10939               return ret;
10940           }
10941
10942         /* If we got this far, we need to build an exp.  */
10943         exp = build_call_array_loc (loc, type, fn, n, argarray);
10944         ret = fold_builtin_varargs (loc, fndecl, exp, false);
10945         return ret ? ret : exp;
10946       }
10947   }
10948
10949   return build_call_array_loc (loc, type, fn, n, argarray);
10950 }
10951
10952 /* Construct a new CALL_EXPR to FNDECL using the tail of the argument
10953    list ARGS along with N new arguments in NEWARGS.  SKIP is the number
10954    of arguments in ARGS to be omitted.  OLDNARGS is the number of
10955    elements in ARGS.  */
10956
10957 static tree
10958 rewrite_call_expr_valist (location_t loc, int oldnargs, tree *args,
10959                           int skip, tree fndecl, int n, va_list newargs)
10960 {
10961   int nargs = oldnargs - skip + n;
10962   tree *buffer;
10963
10964   if (n > 0)
10965     {
10966       int i, j;
10967
10968       buffer = XALLOCAVEC (tree, nargs);
10969       for (i = 0; i < n; i++)
10970         buffer[i] = va_arg (newargs, tree);
10971       for (j = skip; j < oldnargs; j++, i++)
10972         buffer[i] = args[j];
10973     }
10974   else
10975     buffer = args + skip;
10976
10977   return build_call_expr_loc_array (loc, fndecl, nargs, buffer);
10978 }
10979
10980 /* Construct a new CALL_EXPR to FNDECL using the tail of the argument
10981    list ARGS along with N new arguments specified as the "..."
10982    parameters.  SKIP is the number of arguments in ARGS to be omitted.
10983    OLDNARGS is the number of elements in ARGS.  */
10984
10985 static tree
10986 rewrite_call_expr_array (location_t loc, int oldnargs, tree *args,
10987                          int skip, tree fndecl, int n, ...)
10988 {
10989   va_list ap;
10990   tree t;
10991
10992   va_start (ap, n);
10993   t = rewrite_call_expr_valist (loc, oldnargs, args, skip, fndecl, n, ap);
10994   va_end (ap);
10995
10996   return t;
10997 }
10998
10999 /* Construct a new CALL_EXPR using the tail of the argument list of EXP
11000    along with N new arguments specified as the "..." parameters.  SKIP
11001    is the number of arguments in EXP to be omitted.  This function is used
11002    to do varargs-to-varargs transformations.  */
11003
11004 static tree
11005 rewrite_call_expr (location_t loc, tree exp, int skip, tree fndecl, int n, ...)
11006 {
11007   va_list ap;
11008   tree t;
11009
11010   va_start (ap, n);
11011   t = rewrite_call_expr_valist (loc, call_expr_nargs (exp),
11012                                 CALL_EXPR_ARGP (exp), skip, fndecl, n, ap);
11013   va_end (ap);
11014
11015   return t;
11016 }
11017
11018 /* Validate a single argument ARG against a tree code CODE representing
11019    a type.  */
11020
11021 static bool
11022 validate_arg (const_tree arg, enum tree_code code)
11023 {
11024   if (!arg)
11025     return false;
11026   else if (code == POINTER_TYPE)
11027     return POINTER_TYPE_P (TREE_TYPE (arg));
11028   else if (code == INTEGER_TYPE)
11029     return INTEGRAL_TYPE_P (TREE_TYPE (arg));
11030   return code == TREE_CODE (TREE_TYPE (arg));
11031 }
11032
11033 /* This function validates the types of a function call argument list
11034    against a specified list of tree_codes.  If the last specifier is a 0,
11035    that represents an ellipses, otherwise the last specifier must be a
11036    VOID_TYPE.
11037
11038    This is the GIMPLE version of validate_arglist.  Eventually we want to
11039    completely convert builtins.c to work from GIMPLEs and the tree based
11040    validate_arglist will then be removed.  */
11041
11042 bool
11043 validate_gimple_arglist (const_gimple call, ...)
11044 {
11045   enum tree_code code;
11046   bool res = 0;
11047   va_list ap;
11048   const_tree arg;
11049   size_t i;
11050
11051   va_start (ap, call);
11052   i = 0;
11053
11054   do
11055     {
11056       code = (enum tree_code) va_arg (ap, int);
11057       switch (code)
11058         {
11059         case 0:
11060           /* This signifies an ellipses, any further arguments are all ok.  */
11061           res = true;
11062           goto end;
11063         case VOID_TYPE:
11064           /* This signifies an endlink, if no arguments remain, return
11065              true, otherwise return false.  */
11066           res = (i == gimple_call_num_args (call));
11067           goto end;
11068         default:
11069           /* If no parameters remain or the parameter's code does not
11070              match the specified code, return false.  Otherwise continue
11071              checking any remaining arguments.  */
11072           arg = gimple_call_arg (call, i++);
11073           if (!validate_arg (arg, code))
11074             goto end;
11075           break;
11076         }
11077     }
11078   while (1);
11079
11080   /* We need gotos here since we can only have one VA_CLOSE in a
11081      function.  */
11082  end: ;
11083   va_end (ap);
11084
11085   return res;
11086 }
11087
11088 /* This function validates the types of a function call argument list
11089    against a specified list of tree_codes.  If the last specifier is a 0,
11090    that represents an ellipses, otherwise the last specifier must be a
11091    VOID_TYPE.  */
11092
11093 bool
11094 validate_arglist (const_tree callexpr, ...)
11095 {
11096   enum tree_code code;
11097   bool res = 0;
11098   va_list ap;
11099   const_call_expr_arg_iterator iter;
11100   const_tree arg;
11101
11102   va_start (ap, callexpr);
11103   init_const_call_expr_arg_iterator (callexpr, &iter);
11104
11105   do
11106     {
11107       code = (enum tree_code) va_arg (ap, int);
11108       switch (code)
11109         {
11110         case 0:
11111           /* This signifies an ellipses, any further arguments are all ok.  */
11112           res = true;
11113           goto end;
11114         case VOID_TYPE:
11115           /* This signifies an endlink, if no arguments remain, return
11116              true, otherwise return false.  */
11117           res = !more_const_call_expr_args_p (&iter);
11118           goto end;
11119         default:
11120           /* If no parameters remain or the parameter's code does not
11121              match the specified code, return false.  Otherwise continue
11122              checking any remaining arguments.  */
11123           arg = next_const_call_expr_arg (&iter);
11124           if (!validate_arg (arg, code))
11125             goto end;
11126           break;
11127         }
11128     }
11129   while (1);
11130
11131   /* We need gotos here since we can only have one VA_CLOSE in a
11132      function.  */
11133  end: ;
11134   va_end (ap);
11135
11136   return res;
11137 }
11138
11139 /* Default target-specific builtin expander that does nothing.  */
11140
11141 rtx
11142 default_expand_builtin (tree exp ATTRIBUTE_UNUSED,
11143                         rtx target ATTRIBUTE_UNUSED,
11144                         rtx subtarget ATTRIBUTE_UNUSED,
11145                         enum machine_mode mode ATTRIBUTE_UNUSED,
11146                         int ignore ATTRIBUTE_UNUSED)
11147 {
11148   return NULL_RTX;
11149 }
11150
11151 /* Returns true is EXP represents data that would potentially reside
11152    in a readonly section.  */
11153
11154 static bool
11155 readonly_data_expr (tree exp)
11156 {
11157   STRIP_NOPS (exp);
11158
11159   if (TREE_CODE (exp) != ADDR_EXPR)
11160     return false;
11161
11162   exp = get_base_address (TREE_OPERAND (exp, 0));
11163   if (!exp)
11164     return false;
11165
11166   /* Make sure we call decl_readonly_section only for trees it
11167      can handle (since it returns true for everything it doesn't
11168      understand).  */
11169   if (TREE_CODE (exp) == STRING_CST
11170       || TREE_CODE (exp) == CONSTRUCTOR
11171       || (TREE_CODE (exp) == VAR_DECL && TREE_STATIC (exp)))
11172     return decl_readonly_section (exp, 0);
11173   else
11174     return false;
11175 }
11176
11177 /* Simplify a call to the strstr builtin.  S1 and S2 are the arguments
11178    to the call, and TYPE is its return type.
11179
11180    Return NULL_TREE if no simplification was possible, otherwise return the
11181    simplified form of the call as a tree.
11182
11183    The simplified form may be a constant or other expression which
11184    computes the same value, but in a more efficient manner (including
11185    calls to other builtin functions).
11186
11187    The call may contain arguments which need to be evaluated, but
11188    which are not useful to determine the result of the call.  In
11189    this case we return a chain of COMPOUND_EXPRs.  The LHS of each
11190    COMPOUND_EXPR will be an argument which must be evaluated.
11191    COMPOUND_EXPRs are chained through their RHS.  The RHS of the last
11192    COMPOUND_EXPR in the chain will contain the tree for the simplified
11193    form of the builtin function call.  */
11194
11195 static tree
11196 fold_builtin_strstr (location_t loc, tree s1, tree s2, tree type)
11197 {
11198   if (!validate_arg (s1, POINTER_TYPE)
11199       || !validate_arg (s2, POINTER_TYPE))
11200     return NULL_TREE;
11201   else
11202     {
11203       tree fn;
11204       const char *p1, *p2;
11205
11206       p2 = c_getstr (s2);
11207       if (p2 == NULL)
11208         return NULL_TREE;
11209
11210       p1 = c_getstr (s1);
11211       if (p1 != NULL)
11212         {
11213           const char *r = strstr (p1, p2);
11214           tree tem;
11215
11216           if (r == NULL)
11217             return build_int_cst (TREE_TYPE (s1), 0);
11218
11219           /* Return an offset into the constant string argument.  */
11220           tem = fold_build2_loc (loc, POINTER_PLUS_EXPR, TREE_TYPE (s1),
11221                              s1, size_int (r - p1));
11222           return fold_convert_loc (loc, type, tem);
11223         }
11224
11225       /* The argument is const char *, and the result is char *, so we need
11226          a type conversion here to avoid a warning.  */
11227       if (p2[0] == '\0')
11228         return fold_convert_loc (loc, type, s1);
11229
11230       if (p2[1] != '\0')
11231         return NULL_TREE;
11232
11233       fn = implicit_built_in_decls[BUILT_IN_STRCHR];
11234       if (!fn)
11235         return NULL_TREE;
11236
11237       /* New argument list transforming strstr(s1, s2) to
11238          strchr(s1, s2[0]).  */
11239       return build_call_expr_loc (loc, fn, 2, s1, build_int_cst (NULL_TREE, p2[0]));
11240     }
11241 }
11242
11243 /* Simplify a call to the strchr builtin.  S1 and S2 are the arguments to
11244    the call, and TYPE is its return type.
11245
11246    Return NULL_TREE if no simplification was possible, otherwise return the
11247    simplified form of the call as a tree.
11248
11249    The simplified form may be a constant or other expression which
11250    computes the same value, but in a more efficient manner (including
11251    calls to other builtin functions).
11252
11253    The call may contain arguments which need to be evaluated, but
11254    which are not useful to determine the result of the call.  In
11255    this case we return a chain of COMPOUND_EXPRs.  The LHS of each
11256    COMPOUND_EXPR will be an argument which must be evaluated.
11257    COMPOUND_EXPRs are chained through their RHS.  The RHS of the last
11258    COMPOUND_EXPR in the chain will contain the tree for the simplified
11259    form of the builtin function call.  */
11260
11261 static tree
11262 fold_builtin_strchr (location_t loc, tree s1, tree s2, tree type)
11263 {
11264   if (!validate_arg (s1, POINTER_TYPE)
11265       || !validate_arg (s2, INTEGER_TYPE))
11266     return NULL_TREE;
11267   else
11268     {
11269       const char *p1;
11270
11271       if (TREE_CODE (s2) != INTEGER_CST)
11272         return NULL_TREE;
11273
11274       p1 = c_getstr (s1);
11275       if (p1 != NULL)
11276         {
11277           char c;
11278           const char *r;
11279           tree tem;
11280
11281           if (target_char_cast (s2, &c))
11282             return NULL_TREE;
11283
11284           r = strchr (p1, c);
11285
11286           if (r == NULL)
11287             return build_int_cst (TREE_TYPE (s1), 0);
11288
11289           /* Return an offset into the constant string argument.  */
11290           tem = fold_build2_loc (loc, POINTER_PLUS_EXPR, TREE_TYPE (s1),
11291                              s1, size_int (r - p1));
11292           return fold_convert_loc (loc, type, tem);
11293         }
11294       return NULL_TREE;
11295     }
11296 }
11297
11298 /* Simplify a call to the strrchr builtin.  S1 and S2 are the arguments to
11299    the call, and TYPE is its return type.
11300
11301    Return NULL_TREE if no simplification was possible, otherwise return the
11302    simplified form of the call as a tree.
11303
11304    The simplified form may be a constant or other expression which
11305    computes the same value, but in a more efficient manner (including
11306    calls to other builtin functions).
11307
11308    The call may contain arguments which need to be evaluated, but
11309    which are not useful to determine the result of the call.  In
11310    this case we return a chain of COMPOUND_EXPRs.  The LHS of each
11311    COMPOUND_EXPR will be an argument which must be evaluated.
11312    COMPOUND_EXPRs are chained through their RHS.  The RHS of the last
11313    COMPOUND_EXPR in the chain will contain the tree for the simplified
11314    form of the builtin function call.  */
11315
11316 static tree
11317 fold_builtin_strrchr (location_t loc, tree s1, tree s2, tree type)
11318 {
11319   if (!validate_arg (s1, POINTER_TYPE)
11320       || !validate_arg (s2, INTEGER_TYPE))
11321     return NULL_TREE;
11322   else
11323     {
11324       tree fn;
11325       const char *p1;
11326
11327       if (TREE_CODE (s2) != INTEGER_CST)
11328         return NULL_TREE;
11329
11330       p1 = c_getstr (s1);
11331       if (p1 != NULL)
11332         {
11333           char c;
11334           const char *r;
11335           tree tem;
11336
11337           if (target_char_cast (s2, &c))
11338             return NULL_TREE;
11339
11340           r = strrchr (p1, c);
11341
11342           if (r == NULL)
11343             return build_int_cst (TREE_TYPE (s1), 0);
11344
11345           /* Return an offset into the constant string argument.  */
11346           tem = fold_build2_loc (loc, POINTER_PLUS_EXPR, TREE_TYPE (s1),
11347                              s1, size_int (r - p1));
11348           return fold_convert_loc (loc, type, tem);
11349         }
11350
11351       if (! integer_zerop (s2))
11352         return NULL_TREE;
11353
11354       fn = implicit_built_in_decls[BUILT_IN_STRCHR];
11355       if (!fn)
11356         return NULL_TREE;
11357
11358       /* Transform strrchr(s1, '\0') to strchr(s1, '\0').  */
11359       return build_call_expr_loc (loc, fn, 2, s1, s2);
11360     }
11361 }
11362
11363 /* Simplify a call to the strpbrk builtin.  S1 and S2 are the arguments
11364    to the call, and TYPE is its return type.
11365
11366    Return NULL_TREE if no simplification was possible, otherwise return the
11367    simplified form of the call as a tree.
11368
11369    The simplified form may be a constant or other expression which
11370    computes the same value, but in a more efficient manner (including
11371    calls to other builtin functions).
11372
11373    The call may contain arguments which need to be evaluated, but
11374    which are not useful to determine the result of the call.  In
11375    this case we return a chain of COMPOUND_EXPRs.  The LHS of each
11376    COMPOUND_EXPR will be an argument which must be evaluated.
11377    COMPOUND_EXPRs are chained through their RHS.  The RHS of the last
11378    COMPOUND_EXPR in the chain will contain the tree for the simplified
11379    form of the builtin function call.  */
11380
11381 static tree
11382 fold_builtin_strpbrk (location_t loc, tree s1, tree s2, tree type)
11383 {
11384   if (!validate_arg (s1, POINTER_TYPE)
11385       || !validate_arg (s2, POINTER_TYPE))
11386     return NULL_TREE;
11387   else
11388     {
11389       tree fn;
11390       const char *p1, *p2;
11391
11392       p2 = c_getstr (s2);
11393       if (p2 == NULL)
11394         return NULL_TREE;
11395
11396       p1 = c_getstr (s1);
11397       if (p1 != NULL)
11398         {
11399           const char *r = strpbrk (p1, p2);
11400           tree tem;
11401
11402           if (r == NULL)
11403             return build_int_cst (TREE_TYPE (s1), 0);
11404
11405           /* Return an offset into the constant string argument.  */
11406           tem = fold_build2_loc (loc, POINTER_PLUS_EXPR, TREE_TYPE (s1),
11407                              s1, size_int (r - p1));
11408           return fold_convert_loc (loc, type, tem);
11409         }
11410
11411       if (p2[0] == '\0')
11412         /* strpbrk(x, "") == NULL.
11413            Evaluate and ignore s1 in case it had side-effects.  */
11414         return omit_one_operand_loc (loc, TREE_TYPE (s1), integer_zero_node, s1);
11415
11416       if (p2[1] != '\0')
11417         return NULL_TREE;  /* Really call strpbrk.  */
11418
11419       fn = implicit_built_in_decls[BUILT_IN_STRCHR];
11420       if (!fn)
11421         return NULL_TREE;
11422
11423       /* New argument list transforming strpbrk(s1, s2) to
11424          strchr(s1, s2[0]).  */
11425       return build_call_expr_loc (loc, fn, 2, s1, build_int_cst (NULL_TREE, p2[0]));
11426     }
11427 }
11428
11429 /* Simplify a call to the strcat builtin.  DST and SRC are the arguments
11430    to the call.
11431
11432    Return NULL_TREE if no simplification was possible, otherwise return the
11433    simplified form of the call as a tree.
11434
11435    The simplified form may be a constant or other expression which
11436    computes the same value, but in a more efficient manner (including
11437    calls to other builtin functions).
11438
11439    The call may contain arguments which need to be evaluated, but
11440    which are not useful to determine the result of the call.  In
11441    this case we return a chain of COMPOUND_EXPRs.  The LHS of each
11442    COMPOUND_EXPR will be an argument which must be evaluated.
11443    COMPOUND_EXPRs are chained through their RHS.  The RHS of the last
11444    COMPOUND_EXPR in the chain will contain the tree for the simplified
11445    form of the builtin function call.  */
11446
11447 static tree
11448 fold_builtin_strcat (location_t loc ATTRIBUTE_UNUSED, tree dst, tree src)
11449 {
11450   if (!validate_arg (dst, POINTER_TYPE)
11451       || !validate_arg (src, POINTER_TYPE))
11452     return NULL_TREE;
11453   else
11454     {
11455       const char *p = c_getstr (src);
11456
11457       /* If the string length is zero, return the dst parameter.  */
11458       if (p && *p == '\0')
11459         return dst;
11460
11461       if (optimize_insn_for_speed_p ())
11462         {
11463           /* See if we can store by pieces into (dst + strlen(dst)).  */
11464           tree newdst, call;
11465           tree strlen_fn = implicit_built_in_decls[BUILT_IN_STRLEN];
11466           tree strcpy_fn = implicit_built_in_decls[BUILT_IN_STRCPY];
11467
11468           if (!strlen_fn || !strcpy_fn)
11469             return NULL_TREE;
11470
11471           /* If we don't have a movstr we don't want to emit an strcpy
11472              call.  We have to do that if the length of the source string
11473              isn't computable (in that case we can use memcpy probably
11474              later expanding to a sequence of mov instructions).  If we
11475              have movstr instructions we can emit strcpy calls.  */
11476           if (!HAVE_movstr)
11477             {
11478               tree len = c_strlen (src, 1);
11479               if (! len || TREE_SIDE_EFFECTS (len))
11480                 return NULL_TREE;
11481             }
11482
11483           /* Stabilize the argument list.  */
11484           dst = builtin_save_expr (dst);
11485
11486           /* Create strlen (dst).  */
11487           newdst = build_call_expr_loc (loc, strlen_fn, 1, dst);
11488           /* Create (dst p+ strlen (dst)).  */
11489
11490           newdst = fold_build2_loc (loc, POINTER_PLUS_EXPR,
11491                                 TREE_TYPE (dst), dst, newdst);
11492           newdst = builtin_save_expr (newdst);
11493
11494           call = build_call_expr_loc (loc, strcpy_fn, 2, newdst, src);
11495           return build2 (COMPOUND_EXPR, TREE_TYPE (dst), call, dst);
11496         }
11497       return NULL_TREE;
11498     }
11499 }
11500
11501 /* Simplify a call to the strncat builtin.  DST, SRC, and LEN are the
11502    arguments to the call.
11503
11504    Return NULL_TREE if no simplification was possible, otherwise return the
11505    simplified form of the call as a tree.
11506
11507    The simplified form may be a constant or other expression which
11508    computes the same value, but in a more efficient manner (including
11509    calls to other builtin functions).
11510
11511    The call may contain arguments which need to be evaluated, but
11512    which are not useful to determine the result of the call.  In
11513    this case we return a chain of COMPOUND_EXPRs.  The LHS of each
11514    COMPOUND_EXPR will be an argument which must be evaluated.
11515    COMPOUND_EXPRs are chained through their RHS.  The RHS of the last
11516    COMPOUND_EXPR in the chain will contain the tree for the simplified
11517    form of the builtin function call.  */
11518
11519 static tree
11520 fold_builtin_strncat (location_t loc, tree dst, tree src, tree len)
11521 {
11522   if (!validate_arg (dst, POINTER_TYPE)
11523       || !validate_arg (src, POINTER_TYPE)
11524       || !validate_arg (len, INTEGER_TYPE))
11525     return NULL_TREE;
11526   else
11527     {
11528       const char *p = c_getstr (src);
11529
11530       /* If the requested length is zero, or the src parameter string
11531          length is zero, return the dst parameter.  */
11532       if (integer_zerop (len) || (p && *p == '\0'))
11533         return omit_two_operands_loc (loc, TREE_TYPE (dst), dst, src, len);
11534
11535       /* If the requested len is greater than or equal to the string
11536          length, call strcat.  */
11537       if (TREE_CODE (len) == INTEGER_CST && p
11538           && compare_tree_int (len, strlen (p)) >= 0)
11539         {
11540           tree fn = implicit_built_in_decls[BUILT_IN_STRCAT];
11541
11542           /* If the replacement _DECL isn't initialized, don't do the
11543              transformation.  */
11544           if (!fn)
11545             return NULL_TREE;
11546
11547           return build_call_expr_loc (loc, fn, 2, dst, src);
11548         }
11549       return NULL_TREE;
11550     }
11551 }
11552
11553 /* Simplify a call to the strspn builtin.  S1 and S2 are the arguments
11554    to the call.
11555
11556    Return NULL_TREE if no simplification was possible, otherwise return the
11557    simplified form of the call as a tree.
11558
11559    The simplified form may be a constant or other expression which
11560    computes the same value, but in a more efficient manner (including
11561    calls to other builtin functions).
11562
11563    The call may contain arguments which need to be evaluated, but
11564    which are not useful to determine the result of the call.  In
11565    this case we return a chain of COMPOUND_EXPRs.  The LHS of each
11566    COMPOUND_EXPR will be an argument which must be evaluated.
11567    COMPOUND_EXPRs are chained through their RHS.  The RHS of the last
11568    COMPOUND_EXPR in the chain will contain the tree for the simplified
11569    form of the builtin function call.  */
11570
11571 static tree
11572 fold_builtin_strspn (location_t loc, tree s1, tree s2)
11573 {
11574   if (!validate_arg (s1, POINTER_TYPE)
11575       || !validate_arg (s2, POINTER_TYPE))
11576     return NULL_TREE;
11577   else
11578     {
11579       const char *p1 = c_getstr (s1), *p2 = c_getstr (s2);
11580
11581       /* If both arguments are constants, evaluate at compile-time.  */
11582       if (p1 && p2)
11583         {
11584           const size_t r = strspn (p1, p2);
11585           return size_int (r);
11586         }
11587
11588       /* If either argument is "", return NULL_TREE.  */
11589       if ((p1 && *p1 == '\0') || (p2 && *p2 == '\0'))
11590         /* Evaluate and ignore both arguments in case either one has
11591            side-effects.  */
11592         return omit_two_operands_loc (loc, size_type_node, size_zero_node,
11593                                   s1, s2);
11594       return NULL_TREE;
11595     }
11596 }
11597
11598 /* Simplify a call to the strcspn builtin.  S1 and S2 are the arguments
11599    to the call.
11600
11601    Return NULL_TREE if no simplification was possible, otherwise return the
11602    simplified form of the call as a tree.
11603
11604    The simplified form may be a constant or other expression which
11605    computes the same value, but in a more efficient manner (including
11606    calls to other builtin functions).
11607
11608    The call may contain arguments which need to be evaluated, but
11609    which are not useful to determine the result of the call.  In
11610    this case we return a chain of COMPOUND_EXPRs.  The LHS of each
11611    COMPOUND_EXPR will be an argument which must be evaluated.
11612    COMPOUND_EXPRs are chained through their RHS.  The RHS of the last
11613    COMPOUND_EXPR in the chain will contain the tree for the simplified
11614    form of the builtin function call.  */
11615
11616 static tree
11617 fold_builtin_strcspn (location_t loc, tree s1, tree s2)
11618 {
11619   if (!validate_arg (s1, POINTER_TYPE)
11620       || !validate_arg (s2, POINTER_TYPE))
11621     return NULL_TREE;
11622   else
11623     {
11624       const char *p1 = c_getstr (s1), *p2 = c_getstr (s2);
11625
11626       /* If both arguments are constants, evaluate at compile-time.  */
11627       if (p1 && p2)
11628         {
11629           const size_t r = strcspn (p1, p2);
11630           return size_int (r);
11631         }
11632
11633       /* If the first argument is "", return NULL_TREE.  */
11634       if (p1 && *p1 == '\0')
11635         {
11636           /* Evaluate and ignore argument s2 in case it has
11637              side-effects.  */
11638           return omit_one_operand_loc (loc, size_type_node,
11639                                    size_zero_node, s2);
11640         }
11641
11642       /* If the second argument is "", return __builtin_strlen(s1).  */
11643       if (p2 && *p2 == '\0')
11644         {
11645           tree fn = implicit_built_in_decls[BUILT_IN_STRLEN];
11646
11647           /* If the replacement _DECL isn't initialized, don't do the
11648              transformation.  */
11649           if (!fn)
11650             return NULL_TREE;
11651
11652           return build_call_expr_loc (loc, fn, 1, s1);
11653         }
11654       return NULL_TREE;
11655     }
11656 }
11657
11658 /* Fold a call to the fputs builtin.  ARG0 and ARG1 are the arguments
11659    to the call.  IGNORE is true if the value returned
11660    by the builtin will be ignored.  UNLOCKED is true is true if this
11661    actually a call to fputs_unlocked.  If LEN in non-NULL, it represents
11662    the known length of the string.  Return NULL_TREE if no simplification
11663    was possible.  */
11664
11665 tree
11666 fold_builtin_fputs (location_t loc, tree arg0, tree arg1,
11667                     bool ignore, bool unlocked, tree len)
11668 {
11669   /* If we're using an unlocked function, assume the other unlocked
11670      functions exist explicitly.  */
11671   tree const fn_fputc = unlocked ? built_in_decls[BUILT_IN_FPUTC_UNLOCKED]
11672     : implicit_built_in_decls[BUILT_IN_FPUTC];
11673   tree const fn_fwrite = unlocked ? built_in_decls[BUILT_IN_FWRITE_UNLOCKED]
11674     : implicit_built_in_decls[BUILT_IN_FWRITE];
11675
11676   /* If the return value is used, don't do the transformation.  */
11677   if (!ignore)
11678     return NULL_TREE;
11679
11680   /* Verify the arguments in the original call.  */
11681   if (!validate_arg (arg0, POINTER_TYPE)
11682       || !validate_arg (arg1, POINTER_TYPE))
11683     return NULL_TREE;
11684
11685   if (! len)
11686     len = c_strlen (arg0, 0);
11687
11688   /* Get the length of the string passed to fputs.  If the length
11689      can't be determined, punt.  */
11690   if (!len
11691       || TREE_CODE (len) != INTEGER_CST)
11692     return NULL_TREE;
11693
11694   switch (compare_tree_int (len, 1))
11695     {
11696     case -1: /* length is 0, delete the call entirely .  */
11697       return omit_one_operand_loc (loc, integer_type_node,
11698                                integer_zero_node, arg1);;
11699
11700     case 0: /* length is 1, call fputc.  */
11701       {
11702         const char *p = c_getstr (arg0);
11703
11704         if (p != NULL)
11705           {
11706             if (fn_fputc)
11707               return build_call_expr_loc (loc, fn_fputc, 2,
11708                                       build_int_cst (NULL_TREE, p[0]), arg1);
11709             else
11710               return NULL_TREE;
11711           }
11712       }
11713       /* FALLTHROUGH */
11714     case 1: /* length is greater than 1, call fwrite.  */
11715       {
11716         /* If optimizing for size keep fputs.  */
11717         if (optimize_function_for_size_p (cfun))
11718           return NULL_TREE;
11719         /* New argument list transforming fputs(string, stream) to
11720            fwrite(string, 1, len, stream).  */
11721         if (fn_fwrite)
11722           return build_call_expr_loc (loc, fn_fwrite, 4, arg0,
11723                                   size_one_node, len, arg1);
11724         else
11725           return NULL_TREE;
11726       }
11727     default:
11728       gcc_unreachable ();
11729     }
11730   return NULL_TREE;
11731 }
11732
11733 /* Fold the next_arg or va_start call EXP. Returns true if there was an error
11734    produced.  False otherwise.  This is done so that we don't output the error
11735    or warning twice or three times.  */
11736
11737 bool
11738 fold_builtin_next_arg (tree exp, bool va_start_p)
11739 {
11740   tree fntype = TREE_TYPE (current_function_decl);
11741   int nargs = call_expr_nargs (exp);
11742   tree arg;
11743
11744   if (!stdarg_p (fntype))
11745     {
11746       error ("%<va_start%> used in function with fixed args");
11747       return true;
11748     }
11749
11750   if (va_start_p)
11751     {
11752       if (va_start_p && (nargs != 2))
11753         {
11754           error ("wrong number of arguments to function %<va_start%>");
11755           return true;
11756         }
11757       arg = CALL_EXPR_ARG (exp, 1);
11758     }
11759   /* We use __builtin_va_start (ap, 0, 0) or __builtin_next_arg (0, 0)
11760      when we checked the arguments and if needed issued a warning.  */
11761   else
11762     {
11763       if (nargs == 0)
11764         {
11765           /* Evidently an out of date version of <stdarg.h>; can't validate
11766              va_start's second argument, but can still work as intended.  */
11767           warning (0, "%<__builtin_next_arg%> called without an argument");
11768           return true;
11769         }
11770       else if (nargs > 1)
11771         {
11772           error ("wrong number of arguments to function %<__builtin_next_arg%>");
11773           return true;
11774         }
11775       arg = CALL_EXPR_ARG (exp, 0);
11776     }
11777
11778   if (TREE_CODE (arg) == SSA_NAME)
11779     arg = SSA_NAME_VAR (arg);
11780
11781   /* We destructively modify the call to be __builtin_va_start (ap, 0)
11782      or __builtin_next_arg (0) the first time we see it, after checking
11783      the arguments and if needed issuing a warning.  */
11784   if (!integer_zerop (arg))
11785     {
11786       tree last_parm = tree_last (DECL_ARGUMENTS (current_function_decl));
11787
11788       /* Strip off all nops for the sake of the comparison.  This
11789          is not quite the same as STRIP_NOPS.  It does more.
11790          We must also strip off INDIRECT_EXPR for C++ reference
11791          parameters.  */
11792       while (CONVERT_EXPR_P (arg)
11793              || TREE_CODE (arg) == INDIRECT_REF)
11794         arg = TREE_OPERAND (arg, 0);
11795       if (arg != last_parm)
11796         {
11797           /* FIXME: Sometimes with the tree optimizers we can get the
11798              not the last argument even though the user used the last
11799              argument.  We just warn and set the arg to be the last
11800              argument so that we will get wrong-code because of
11801              it.  */
11802           warning (0, "second parameter of %<va_start%> not last named argument");
11803         }
11804
11805       /* Undefined by C99 7.15.1.4p4 (va_start):
11806          "If the parameter parmN is declared with the register storage
11807          class, with a function or array type, or with a type that is
11808          not compatible with the type that results after application of
11809          the default argument promotions, the behavior is undefined."
11810       */
11811       else if (DECL_REGISTER (arg))
11812         warning (0, "undefined behaviour when second parameter of "
11813                  "%<va_start%> is declared with %<register%> storage");
11814
11815       /* We want to verify the second parameter just once before the tree
11816          optimizers are run and then avoid keeping it in the tree,
11817          as otherwise we could warn even for correct code like:
11818          void foo (int i, ...)
11819          { va_list ap; i++; va_start (ap, i); va_end (ap); }  */
11820       if (va_start_p)
11821         CALL_EXPR_ARG (exp, 1) = integer_zero_node;
11822       else
11823         CALL_EXPR_ARG (exp, 0) = integer_zero_node;
11824     }
11825   return false;
11826 }
11827
11828
11829 /* Simplify a call to the sprintf builtin with arguments DEST, FMT, and ORIG.
11830    ORIG may be null if this is a 2-argument call.  We don't attempt to
11831    simplify calls with more than 3 arguments.
11832
11833    Return NULL_TREE if no simplification was possible, otherwise return the
11834    simplified form of the call as a tree.  If IGNORED is true, it means that
11835    the caller does not use the returned value of the function.  */
11836
11837 static tree
11838 fold_builtin_sprintf (location_t loc, tree dest, tree fmt,
11839                       tree orig, int ignored)
11840 {
11841   tree call, retval;
11842   const char *fmt_str = NULL;
11843
11844   /* Verify the required arguments in the original call.  We deal with two
11845      types of sprintf() calls: 'sprintf (str, fmt)' and
11846      'sprintf (dest, "%s", orig)'.  */
11847   if (!validate_arg (dest, POINTER_TYPE)
11848       || !validate_arg (fmt, POINTER_TYPE))
11849     return NULL_TREE;
11850   if (orig && !validate_arg (orig, POINTER_TYPE))
11851     return NULL_TREE;
11852
11853   /* Check whether the format is a literal string constant.  */
11854   fmt_str = c_getstr (fmt);
11855   if (fmt_str == NULL)
11856     return NULL_TREE;
11857
11858   call = NULL_TREE;
11859   retval = NULL_TREE;
11860
11861   if (!init_target_chars ())
11862     return NULL_TREE;
11863
11864   /* If the format doesn't contain % args or %%, use strcpy.  */
11865   if (strchr (fmt_str, target_percent) == NULL)
11866     {
11867       tree fn = implicit_built_in_decls[BUILT_IN_STRCPY];
11868
11869       if (!fn)
11870         return NULL_TREE;
11871
11872       /* Don't optimize sprintf (buf, "abc", ptr++).  */
11873       if (orig)
11874         return NULL_TREE;
11875
11876       /* Convert sprintf (str, fmt) into strcpy (str, fmt) when
11877          'format' is known to contain no % formats.  */
11878       call = build_call_expr_loc (loc, fn, 2, dest, fmt);
11879       if (!ignored)
11880         retval = build_int_cst (NULL_TREE, strlen (fmt_str));
11881     }
11882
11883   /* If the format is "%s", use strcpy if the result isn't used.  */
11884   else if (fmt_str && strcmp (fmt_str, target_percent_s) == 0)
11885     {
11886       tree fn;
11887       fn = implicit_built_in_decls[BUILT_IN_STRCPY];
11888
11889       if (!fn)
11890         return NULL_TREE;
11891
11892       /* Don't crash on sprintf (str1, "%s").  */
11893       if (!orig)
11894         return NULL_TREE;
11895
11896       /* Convert sprintf (str1, "%s", str2) into strcpy (str1, str2).  */
11897       if (!ignored)
11898         {
11899           retval = c_strlen (orig, 1);
11900           if (!retval || TREE_CODE (retval) != INTEGER_CST)
11901             return NULL_TREE;
11902         }
11903       call = build_call_expr_loc (loc, fn, 2, dest, orig);
11904     }
11905
11906   if (call && retval)
11907     {
11908       retval = fold_convert_loc
11909         (loc, TREE_TYPE (TREE_TYPE (implicit_built_in_decls[BUILT_IN_SPRINTF])),
11910          retval);
11911       return build2 (COMPOUND_EXPR, TREE_TYPE (retval), call, retval);
11912     }
11913   else
11914     return call;
11915 }
11916
11917 /* Expand a call EXP to __builtin_object_size.  */
11918
11919 rtx
11920 expand_builtin_object_size (tree exp)
11921 {
11922   tree ost;
11923   int object_size_type;
11924   tree fndecl = get_callee_fndecl (exp);
11925
11926   if (!validate_arglist (exp, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
11927     {
11928       error ("%Kfirst argument of %D must be a pointer, second integer constant",
11929              exp, fndecl);
11930       expand_builtin_trap ();
11931       return const0_rtx;
11932     }
11933
11934   ost = CALL_EXPR_ARG (exp, 1);
11935   STRIP_NOPS (ost);
11936
11937   if (TREE_CODE (ost) != INTEGER_CST
11938       || tree_int_cst_sgn (ost) < 0
11939       || compare_tree_int (ost, 3) > 0)
11940     {
11941       error ("%Klast argument of %D is not integer constant between 0 and 3",
11942              exp, fndecl);
11943       expand_builtin_trap ();
11944       return const0_rtx;
11945     }
11946
11947   object_size_type = tree_low_cst (ost, 0);
11948
11949   return object_size_type < 2 ? constm1_rtx : const0_rtx;
11950 }
11951
11952 /* Expand EXP, a call to the __mem{cpy,pcpy,move,set}_chk builtin.
11953    FCODE is the BUILT_IN_* to use.
11954    Return NULL_RTX if we failed; the caller should emit a normal call,
11955    otherwise try to get the result in TARGET, if convenient (and in
11956    mode MODE if that's convenient).  */
11957
11958 static rtx
11959 expand_builtin_memory_chk (tree exp, rtx target, enum machine_mode mode,
11960                            enum built_in_function fcode)
11961 {
11962   tree dest, src, len, size;
11963
11964   if (!validate_arglist (exp,
11965                          POINTER_TYPE,
11966                          fcode == BUILT_IN_MEMSET_CHK
11967                          ? INTEGER_TYPE : POINTER_TYPE,
11968                          INTEGER_TYPE, INTEGER_TYPE, VOID_TYPE))
11969     return NULL_RTX;
11970
11971   dest = CALL_EXPR_ARG (exp, 0);
11972   src = CALL_EXPR_ARG (exp, 1);
11973   len = CALL_EXPR_ARG (exp, 2);
11974   size = CALL_EXPR_ARG (exp, 3);
11975
11976   if (! host_integerp (size, 1))
11977     return NULL_RTX;
11978
11979   if (host_integerp (len, 1) || integer_all_onesp (size))
11980     {
11981       tree fn;
11982
11983       if (! integer_all_onesp (size) && tree_int_cst_lt (size, len))
11984         {
11985           warning_at (tree_nonartificial_location (exp),
11986                       0, "%Kcall to %D will always overflow destination buffer",
11987                       exp, get_callee_fndecl (exp));
11988           return NULL_RTX;
11989         }
11990
11991       fn = NULL_TREE;
11992       /* If __builtin_mem{cpy,pcpy,move,set}_chk is used, assume
11993          mem{cpy,pcpy,move,set} is available.  */
11994       switch (fcode)
11995         {
11996         case BUILT_IN_MEMCPY_CHK:
11997           fn = built_in_decls[BUILT_IN_MEMCPY];
11998           break;
11999         case BUILT_IN_MEMPCPY_CHK:
12000           fn = built_in_decls[BUILT_IN_MEMPCPY];
12001           break;
12002         case BUILT_IN_MEMMOVE_CHK:
12003           fn = built_in_decls[BUILT_IN_MEMMOVE];
12004           break;
12005         case BUILT_IN_MEMSET_CHK:
12006           fn = built_in_decls[BUILT_IN_MEMSET];
12007           break;
12008         default:
12009           break;
12010         }
12011
12012       if (! fn)
12013         return NULL_RTX;
12014
12015       fn = build_call_nofold_loc (EXPR_LOCATION (exp), fn, 3, dest, src, len);
12016       gcc_assert (TREE_CODE (fn) == CALL_EXPR);
12017       CALL_EXPR_TAILCALL (fn) = CALL_EXPR_TAILCALL (exp);
12018       return expand_expr (fn, target, mode, EXPAND_NORMAL);
12019     }
12020   else if (fcode == BUILT_IN_MEMSET_CHK)
12021     return NULL_RTX;
12022   else
12023     {
12024       unsigned int dest_align
12025         = get_pointer_alignment (dest, BIGGEST_ALIGNMENT);
12026
12027       /* If DEST is not a pointer type, call the normal function.  */
12028       if (dest_align == 0)
12029         return NULL_RTX;
12030
12031       /* If SRC and DEST are the same (and not volatile), do nothing.  */
12032       if (operand_equal_p (src, dest, 0))
12033         {
12034           tree expr;
12035
12036           if (fcode != BUILT_IN_MEMPCPY_CHK)
12037             {
12038               /* Evaluate and ignore LEN in case it has side-effects.  */
12039               expand_expr (len, const0_rtx, VOIDmode, EXPAND_NORMAL);
12040               return expand_expr (dest, target, mode, EXPAND_NORMAL);
12041             }
12042
12043           expr = fold_build2 (POINTER_PLUS_EXPR, TREE_TYPE (dest), dest, len);
12044           return expand_expr (expr, target, mode, EXPAND_NORMAL);
12045         }
12046
12047       /* __memmove_chk special case.  */
12048       if (fcode == BUILT_IN_MEMMOVE_CHK)
12049         {
12050           unsigned int src_align
12051             = get_pointer_alignment (src, BIGGEST_ALIGNMENT);
12052
12053           if (src_align == 0)
12054             return NULL_RTX;
12055
12056           /* If src is categorized for a readonly section we can use
12057              normal __memcpy_chk.  */
12058           if (readonly_data_expr (src))
12059             {
12060               tree fn = built_in_decls[BUILT_IN_MEMCPY_CHK];
12061               if (!fn)
12062                 return NULL_RTX;
12063               fn = build_call_nofold_loc (EXPR_LOCATION (exp), fn, 4,
12064                                           dest, src, len, size);
12065               gcc_assert (TREE_CODE (fn) == CALL_EXPR);
12066               CALL_EXPR_TAILCALL (fn) = CALL_EXPR_TAILCALL (exp);
12067               return expand_expr (fn, target, mode, EXPAND_NORMAL);
12068             }
12069         }
12070       return NULL_RTX;
12071     }
12072 }
12073
12074 /* Emit warning if a buffer overflow is detected at compile time.  */
12075
12076 static void
12077 maybe_emit_chk_warning (tree exp, enum built_in_function fcode)
12078 {
12079   int is_strlen = 0;
12080   tree len, size;
12081   location_t loc = tree_nonartificial_location (exp);
12082
12083   switch (fcode)
12084     {
12085     case BUILT_IN_STRCPY_CHK:
12086     case BUILT_IN_STPCPY_CHK:
12087     /* For __strcat_chk the warning will be emitted only if overflowing
12088        by at least strlen (dest) + 1 bytes.  */
12089     case BUILT_IN_STRCAT_CHK:
12090       len = CALL_EXPR_ARG (exp, 1);
12091       size = CALL_EXPR_ARG (exp, 2);
12092       is_strlen = 1;
12093       break;
12094     case BUILT_IN_STRNCAT_CHK:
12095     case BUILT_IN_STRNCPY_CHK:
12096       len = CALL_EXPR_ARG (exp, 2);
12097       size = CALL_EXPR_ARG (exp, 3);
12098       break;
12099     case BUILT_IN_SNPRINTF_CHK:
12100     case BUILT_IN_VSNPRINTF_CHK:
12101       len = CALL_EXPR_ARG (exp, 1);
12102       size = CALL_EXPR_ARG (exp, 3);
12103       break;
12104     default:
12105       gcc_unreachable ();
12106     }
12107
12108   if (!len || !size)
12109     return;
12110
12111   if (! host_integerp (size, 1) || integer_all_onesp (size))
12112     return;
12113
12114   if (is_strlen)
12115     {
12116       len = c_strlen (len, 1);
12117       if (! len || ! host_integerp (len, 1) || tree_int_cst_lt (len, size))
12118         return;
12119     }
12120   else if (fcode == BUILT_IN_STRNCAT_CHK)
12121     {
12122       tree src = CALL_EXPR_ARG (exp, 1);
12123       if (! src || ! host_integerp (len, 1) || tree_int_cst_lt (len, size))
12124         return;
12125       src = c_strlen (src, 1);
12126       if (! src || ! host_integerp (src, 1))
12127         {
12128           warning_at (loc, 0, "%Kcall to %D might overflow destination buffer",
12129                       exp, get_callee_fndecl (exp));
12130           return;
12131         }
12132       else if (tree_int_cst_lt (src, size))
12133         return;
12134     }
12135   else if (! host_integerp (len, 1) || ! tree_int_cst_lt (size, len))
12136     return;
12137
12138   warning_at (loc, 0, "%Kcall to %D will always overflow destination buffer",
12139               exp, get_callee_fndecl (exp));
12140 }
12141
12142 /* Emit warning if a buffer overflow is detected at compile time
12143    in __sprintf_chk/__vsprintf_chk calls.  */
12144
12145 static void
12146 maybe_emit_sprintf_chk_warning (tree exp, enum built_in_function fcode)
12147 {
12148   tree size, len, fmt;
12149   const char *fmt_str;
12150   int nargs = call_expr_nargs (exp);
12151
12152   /* Verify the required arguments in the original call.  */
12153
12154   if (nargs < 4)
12155     return;
12156   size = CALL_EXPR_ARG (exp, 2);
12157   fmt = CALL_EXPR_ARG (exp, 3);
12158
12159   if (! host_integerp (size, 1) || integer_all_onesp (size))
12160     return;
12161
12162   /* Check whether the format is a literal string constant.  */
12163   fmt_str = c_getstr (fmt);
12164   if (fmt_str == NULL)
12165     return;
12166
12167   if (!init_target_chars ())
12168     return;
12169
12170   /* If the format doesn't contain % args or %%, we know its size.  */
12171   if (strchr (fmt_str, target_percent) == 0)
12172     len = build_int_cstu (size_type_node, strlen (fmt_str));
12173   /* If the format is "%s" and first ... argument is a string literal,
12174      we know it too.  */
12175   else if (fcode == BUILT_IN_SPRINTF_CHK
12176            && strcmp (fmt_str, target_percent_s) == 0)
12177     {
12178       tree arg;
12179
12180       if (nargs < 5)
12181         return;
12182       arg = CALL_EXPR_ARG (exp, 4);
12183       if (! POINTER_TYPE_P (TREE_TYPE (arg)))
12184         return;
12185
12186       len = c_strlen (arg, 1);
12187       if (!len || ! host_integerp (len, 1))
12188         return;
12189     }
12190   else
12191     return;
12192
12193   if (! tree_int_cst_lt (len, size))
12194     warning_at (tree_nonartificial_location (exp),
12195                 0, "%Kcall to %D will always overflow destination buffer",
12196                 exp, get_callee_fndecl (exp));
12197 }
12198
12199 /* Emit warning if a free is called with address of a variable.  */
12200
12201 static void
12202 maybe_emit_free_warning (tree exp)
12203 {
12204   tree arg = CALL_EXPR_ARG (exp, 0);
12205
12206   STRIP_NOPS (arg);
12207   if (TREE_CODE (arg) != ADDR_EXPR)
12208     return;
12209
12210   arg = get_base_address (TREE_OPERAND (arg, 0));
12211   if (arg == NULL || INDIRECT_REF_P (arg) || TREE_CODE (arg) == MEM_REF)
12212     return;
12213
12214   if (SSA_VAR_P (arg))
12215     warning_at (tree_nonartificial_location (exp),
12216                 0, "%Kattempt to free a non-heap object %qD", exp, arg);
12217   else
12218     warning_at (tree_nonartificial_location (exp),
12219                 0, "%Kattempt to free a non-heap object", exp);
12220 }
12221
12222 /* Fold a call to __builtin_object_size with arguments PTR and OST,
12223    if possible.  */
12224
12225 tree
12226 fold_builtin_object_size (tree ptr, tree ost)
12227 {
12228   unsigned HOST_WIDE_INT bytes;
12229   int object_size_type;
12230
12231   if (!validate_arg (ptr, POINTER_TYPE)
12232       || !validate_arg (ost, INTEGER_TYPE))
12233     return NULL_TREE;
12234
12235   STRIP_NOPS (ost);
12236
12237   if (TREE_CODE (ost) != INTEGER_CST
12238       || tree_int_cst_sgn (ost) < 0
12239       || compare_tree_int (ost, 3) > 0)
12240     return NULL_TREE;
12241
12242   object_size_type = tree_low_cst (ost, 0);
12243
12244   /* __builtin_object_size doesn't evaluate side-effects in its arguments;
12245      if there are any side-effects, it returns (size_t) -1 for types 0 and 1
12246      and (size_t) 0 for types 2 and 3.  */
12247   if (TREE_SIDE_EFFECTS (ptr))
12248     return build_int_cst_type (size_type_node, object_size_type < 2 ? -1 : 0);
12249
12250   if (TREE_CODE (ptr) == ADDR_EXPR)
12251     {
12252       bytes = compute_builtin_object_size (ptr, object_size_type);
12253       if (double_int_fits_to_tree_p (size_type_node,
12254                                      uhwi_to_double_int (bytes)))
12255         return build_int_cstu (size_type_node, bytes);
12256     }
12257   else if (TREE_CODE (ptr) == SSA_NAME)
12258     {
12259       /* If object size is not known yet, delay folding until
12260        later.  Maybe subsequent passes will help determining
12261        it.  */
12262       bytes = compute_builtin_object_size (ptr, object_size_type);
12263       if (bytes != (unsigned HOST_WIDE_INT) (object_size_type < 2 ? -1 : 0)
12264           && double_int_fits_to_tree_p (size_type_node,
12265                                         uhwi_to_double_int (bytes)))
12266         return build_int_cstu (size_type_node, bytes);
12267     }
12268
12269   return NULL_TREE;
12270 }
12271
12272 /* Fold a call to the __mem{cpy,pcpy,move,set}_chk builtin.
12273    DEST, SRC, LEN, and SIZE are the arguments to the call.
12274    IGNORE is true, if return value can be ignored.  FCODE is the BUILT_IN_*
12275    code of the builtin.  If MAXLEN is not NULL, it is maximum length
12276    passed as third argument.  */
12277
12278 tree
12279 fold_builtin_memory_chk (location_t loc, tree fndecl,
12280                          tree dest, tree src, tree len, tree size,
12281                          tree maxlen, bool ignore,
12282                          enum built_in_function fcode)
12283 {
12284   tree fn;
12285
12286   if (!validate_arg (dest, POINTER_TYPE)
12287       || !validate_arg (src,
12288                         (fcode == BUILT_IN_MEMSET_CHK
12289                          ? INTEGER_TYPE : POINTER_TYPE))
12290       || !validate_arg (len, INTEGER_TYPE)
12291       || !validate_arg (size, INTEGER_TYPE))
12292     return NULL_TREE;
12293
12294   /* If SRC and DEST are the same (and not volatile), return DEST
12295      (resp. DEST+LEN for __mempcpy_chk).  */
12296   if (fcode != BUILT_IN_MEMSET_CHK && operand_equal_p (src, dest, 0))
12297     {
12298       if (fcode != BUILT_IN_MEMPCPY_CHK)
12299         return omit_one_operand_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)),
12300                                  dest, len);
12301       else
12302         {
12303           tree temp = fold_build2_loc (loc, POINTER_PLUS_EXPR, TREE_TYPE (dest),
12304                                    dest, len);
12305           return fold_convert_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)), temp);
12306         }
12307     }
12308
12309   if (! host_integerp (size, 1))
12310     return NULL_TREE;
12311
12312   if (! integer_all_onesp (size))
12313     {
12314       if (! host_integerp (len, 1))
12315         {
12316           /* If LEN is not constant, try MAXLEN too.
12317              For MAXLEN only allow optimizing into non-_ocs function
12318              if SIZE is >= MAXLEN, never convert to __ocs_fail ().  */
12319           if (maxlen == NULL_TREE || ! host_integerp (maxlen, 1))
12320             {
12321               if (fcode == BUILT_IN_MEMPCPY_CHK && ignore)
12322                 {
12323                   /* (void) __mempcpy_chk () can be optimized into
12324                      (void) __memcpy_chk ().  */
12325                   fn = built_in_decls[BUILT_IN_MEMCPY_CHK];
12326                   if (!fn)
12327                     return NULL_TREE;
12328
12329                   return build_call_expr_loc (loc, fn, 4, dest, src, len, size);
12330                 }
12331               return NULL_TREE;
12332             }
12333         }
12334       else
12335         maxlen = len;
12336
12337       if (tree_int_cst_lt (size, maxlen))
12338         return NULL_TREE;
12339     }
12340
12341   fn = NULL_TREE;
12342   /* If __builtin_mem{cpy,pcpy,move,set}_chk is used, assume
12343      mem{cpy,pcpy,move,set} is available.  */
12344   switch (fcode)
12345     {
12346     case BUILT_IN_MEMCPY_CHK:
12347       fn = built_in_decls[BUILT_IN_MEMCPY];
12348       break;
12349     case BUILT_IN_MEMPCPY_CHK:
12350       fn = built_in_decls[BUILT_IN_MEMPCPY];
12351       break;
12352     case BUILT_IN_MEMMOVE_CHK:
12353       fn = built_in_decls[BUILT_IN_MEMMOVE];
12354       break;
12355     case BUILT_IN_MEMSET_CHK:
12356       fn = built_in_decls[BUILT_IN_MEMSET];
12357       break;
12358     default:
12359       break;
12360     }
12361
12362   if (!fn)
12363     return NULL_TREE;
12364
12365   return build_call_expr_loc (loc, fn, 3, dest, src, len);
12366 }
12367
12368 /* Fold a call to the __st[rp]cpy_chk builtin.
12369    DEST, SRC, and SIZE are the arguments to the call.
12370    IGNORE is true if return value can be ignored.  FCODE is the BUILT_IN_*
12371    code of the builtin.  If MAXLEN is not NULL, it is maximum length of
12372    strings passed as second argument.  */
12373
12374 tree
12375 fold_builtin_stxcpy_chk (location_t loc, tree fndecl, tree dest,
12376                          tree src, tree size,
12377                          tree maxlen, bool ignore,
12378                          enum built_in_function fcode)
12379 {
12380   tree len, fn;
12381
12382   if (!validate_arg (dest, POINTER_TYPE)
12383       || !validate_arg (src, POINTER_TYPE)
12384       || !validate_arg (size, INTEGER_TYPE))
12385     return NULL_TREE;
12386
12387   /* If SRC and DEST are the same (and not volatile), return DEST.  */
12388   if (fcode == BUILT_IN_STRCPY_CHK && operand_equal_p (src, dest, 0))
12389     return fold_convert_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)), dest);
12390
12391   if (! host_integerp (size, 1))
12392     return NULL_TREE;
12393
12394   if (! integer_all_onesp (size))
12395     {
12396       len = c_strlen (src, 1);
12397       if (! len || ! host_integerp (len, 1))
12398         {
12399           /* If LEN is not constant, try MAXLEN too.
12400              For MAXLEN only allow optimizing into non-_ocs function
12401              if SIZE is >= MAXLEN, never convert to __ocs_fail ().  */
12402           if (maxlen == NULL_TREE || ! host_integerp (maxlen, 1))
12403             {
12404               if (fcode == BUILT_IN_STPCPY_CHK)
12405                 {
12406                   if (! ignore)
12407                     return NULL_TREE;
12408
12409                   /* If return value of __stpcpy_chk is ignored,
12410                      optimize into __strcpy_chk.  */
12411                   fn = built_in_decls[BUILT_IN_STRCPY_CHK];
12412                   if (!fn)
12413                     return NULL_TREE;
12414
12415                   return build_call_expr_loc (loc, fn, 3, dest, src, size);
12416                 }
12417
12418               if (! len || TREE_SIDE_EFFECTS (len))
12419                 return NULL_TREE;
12420
12421               /* If c_strlen returned something, but not a constant,
12422                  transform __strcpy_chk into __memcpy_chk.  */
12423               fn = built_in_decls[BUILT_IN_MEMCPY_CHK];
12424               if (!fn)
12425                 return NULL_TREE;
12426
12427               len = size_binop_loc (loc, PLUS_EXPR, len, ssize_int (1));
12428               return fold_convert_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)),
12429                                        build_call_expr_loc (loc, fn, 4,
12430                                                         dest, src, len, size));
12431             }
12432         }
12433       else
12434         maxlen = len;
12435
12436       if (! tree_int_cst_lt (maxlen, size))
12437         return NULL_TREE;
12438     }
12439
12440   /* If __builtin_st{r,p}cpy_chk is used, assume st{r,p}cpy is available.  */
12441   fn = built_in_decls[fcode == BUILT_IN_STPCPY_CHK
12442                       ? BUILT_IN_STPCPY : BUILT_IN_STRCPY];
12443   if (!fn)
12444     return NULL_TREE;
12445
12446   return build_call_expr_loc (loc, fn, 2, dest, src);
12447 }
12448
12449 /* Fold a call to the __strncpy_chk builtin.  DEST, SRC, LEN, and SIZE
12450    are the arguments to the call.  If MAXLEN is not NULL, it is maximum
12451    length passed as third argument.  */
12452
12453 tree
12454 fold_builtin_strncpy_chk (location_t loc, tree dest, tree src,
12455                           tree len, tree size, tree maxlen)
12456 {
12457   tree fn;
12458
12459   if (!validate_arg (dest, POINTER_TYPE)
12460       || !validate_arg (src, POINTER_TYPE)
12461       || !validate_arg (len, INTEGER_TYPE)
12462       || !validate_arg (size, INTEGER_TYPE))
12463     return NULL_TREE;
12464
12465   if (! host_integerp (size, 1))
12466     return NULL_TREE;
12467
12468   if (! integer_all_onesp (size))
12469     {
12470       if (! host_integerp (len, 1))
12471         {
12472           /* If LEN is not constant, try MAXLEN too.
12473              For MAXLEN only allow optimizing into non-_ocs function
12474              if SIZE is >= MAXLEN, never convert to __ocs_fail ().  */
12475           if (maxlen == NULL_TREE || ! host_integerp (maxlen, 1))
12476             return NULL_TREE;
12477         }
12478       else
12479         maxlen = len;
12480
12481       if (tree_int_cst_lt (size, maxlen))
12482         return NULL_TREE;
12483     }
12484
12485   /* If __builtin_strncpy_chk is used, assume strncpy is available.  */
12486   fn = built_in_decls[BUILT_IN_STRNCPY];
12487   if (!fn)
12488     return NULL_TREE;
12489
12490   return build_call_expr_loc (loc, fn, 3, dest, src, len);
12491 }
12492
12493 /* Fold a call to the __strcat_chk builtin FNDECL.  DEST, SRC, and SIZE
12494    are the arguments to the call.  */
12495
12496 static tree
12497 fold_builtin_strcat_chk (location_t loc, tree fndecl, tree dest,
12498                          tree src, tree size)
12499 {
12500   tree fn;
12501   const char *p;
12502
12503   if (!validate_arg (dest, POINTER_TYPE)
12504       || !validate_arg (src, POINTER_TYPE)
12505       || !validate_arg (size, INTEGER_TYPE))
12506     return NULL_TREE;
12507
12508   p = c_getstr (src);
12509   /* If the SRC parameter is "", return DEST.  */
12510   if (p && *p == '\0')
12511     return omit_one_operand_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)), dest, src);
12512
12513   if (! host_integerp (size, 1) || ! integer_all_onesp (size))
12514     return NULL_TREE;
12515
12516   /* If __builtin_strcat_chk is used, assume strcat is available.  */
12517   fn = built_in_decls[BUILT_IN_STRCAT];
12518   if (!fn)
12519     return NULL_TREE;
12520
12521   return build_call_expr_loc (loc, fn, 2, dest, src);
12522 }
12523
12524 /* Fold a call to the __strncat_chk builtin with arguments DEST, SRC,
12525    LEN, and SIZE.  */
12526
12527 static tree
12528 fold_builtin_strncat_chk (location_t loc, tree fndecl,
12529                           tree dest, tree src, tree len, tree size)
12530 {
12531   tree fn;
12532   const char *p;
12533
12534   if (!validate_arg (dest, POINTER_TYPE)
12535       || !validate_arg (src, POINTER_TYPE)
12536       || !validate_arg (size, INTEGER_TYPE)
12537       || !validate_arg (size, INTEGER_TYPE))
12538     return NULL_TREE;
12539
12540   p = c_getstr (src);
12541   /* If the SRC parameter is "" or if LEN is 0, return DEST.  */
12542   if (p && *p == '\0')
12543     return omit_one_operand_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)), dest, len);
12544   else if (integer_zerop (len))
12545     return omit_one_operand_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)), dest, src);
12546
12547   if (! host_integerp (size, 1))
12548     return NULL_TREE;
12549
12550   if (! integer_all_onesp (size))
12551     {
12552       tree src_len = c_strlen (src, 1);
12553       if (src_len
12554           && host_integerp (src_len, 1)
12555           && host_integerp (len, 1)
12556           && ! tree_int_cst_lt (len, src_len))
12557         {
12558           /* If LEN >= strlen (SRC), optimize into __strcat_chk.  */
12559           fn = built_in_decls[BUILT_IN_STRCAT_CHK];
12560           if (!fn)
12561             return NULL_TREE;
12562
12563           return build_call_expr_loc (loc, fn, 3, dest, src, size);
12564         }
12565       return NULL_TREE;
12566     }
12567
12568   /* If __builtin_strncat_chk is used, assume strncat is available.  */
12569   fn = built_in_decls[BUILT_IN_STRNCAT];
12570   if (!fn)
12571     return NULL_TREE;
12572
12573   return build_call_expr_loc (loc, fn, 3, dest, src, len);
12574 }
12575
12576 /* Fold a call EXP to __{,v}sprintf_chk having NARGS passed as ARGS.
12577    Return NULL_TREE if a normal call should be emitted rather than
12578    expanding the function inline.  FCODE is either BUILT_IN_SPRINTF_CHK
12579    or BUILT_IN_VSPRINTF_CHK.  */
12580
12581 static tree
12582 fold_builtin_sprintf_chk_1 (location_t loc, int nargs, tree *args,
12583                             enum built_in_function fcode)
12584 {
12585   tree dest, size, len, fn, fmt, flag;
12586   const char *fmt_str;
12587
12588   /* Verify the required arguments in the original call.  */
12589   if (nargs < 4)
12590     return NULL_TREE;
12591   dest = args[0];
12592   if (!validate_arg (dest, POINTER_TYPE))
12593     return NULL_TREE;
12594   flag = args[1];
12595   if (!validate_arg (flag, INTEGER_TYPE))
12596     return NULL_TREE;
12597   size = args[2];
12598   if (!validate_arg (size, INTEGER_TYPE))
12599     return NULL_TREE;
12600   fmt = args[3];
12601   if (!validate_arg (fmt, POINTER_TYPE))
12602     return NULL_TREE;
12603
12604   if (! host_integerp (size, 1))
12605     return NULL_TREE;
12606
12607   len = NULL_TREE;
12608
12609   if (!init_target_chars ())
12610     return NULL_TREE;
12611
12612   /* Check whether the format is a literal string constant.  */
12613   fmt_str = c_getstr (fmt);
12614   if (fmt_str != NULL)
12615     {
12616       /* If the format doesn't contain % args or %%, we know the size.  */
12617       if (strchr (fmt_str, target_percent) == 0)
12618         {
12619           if (fcode != BUILT_IN_SPRINTF_CHK || nargs == 4)
12620             len = build_int_cstu (size_type_node, strlen (fmt_str));
12621         }
12622       /* If the format is "%s" and first ... argument is a string literal,
12623          we know the size too.  */
12624       else if (fcode == BUILT_IN_SPRINTF_CHK
12625                && strcmp (fmt_str, target_percent_s) == 0)
12626         {
12627           tree arg;
12628
12629           if (nargs == 5)
12630             {
12631               arg = args[4];
12632               if (validate_arg (arg, POINTER_TYPE))
12633                 {
12634                   len = c_strlen (arg, 1);
12635                   if (! len || ! host_integerp (len, 1))
12636                     len = NULL_TREE;
12637                 }
12638             }
12639         }
12640     }
12641
12642   if (! integer_all_onesp (size))
12643     {
12644       if (! len || ! tree_int_cst_lt (len, size))
12645         return NULL_TREE;
12646     }
12647
12648   /* Only convert __{,v}sprintf_chk to {,v}sprintf if flag is 0
12649      or if format doesn't contain % chars or is "%s".  */
12650   if (! integer_zerop (flag))
12651     {
12652       if (fmt_str == NULL)
12653         return NULL_TREE;
12654       if (strchr (fmt_str, target_percent) != NULL
12655           && strcmp (fmt_str, target_percent_s))
12656         return NULL_TREE;
12657     }
12658
12659   /* If __builtin_{,v}sprintf_chk is used, assume {,v}sprintf is available.  */
12660   fn = built_in_decls[fcode == BUILT_IN_VSPRINTF_CHK
12661                       ? BUILT_IN_VSPRINTF : BUILT_IN_SPRINTF];
12662   if (!fn)
12663     return NULL_TREE;
12664
12665   return rewrite_call_expr_array (loc, nargs, args, 4, fn, 2, dest, fmt);
12666 }
12667
12668 /* Fold a call EXP to __{,v}sprintf_chk.  Return NULL_TREE if
12669    a normal call should be emitted rather than expanding the function
12670    inline.  FCODE is either BUILT_IN_SPRINTF_CHK or BUILT_IN_VSPRINTF_CHK.  */
12671
12672 static tree
12673 fold_builtin_sprintf_chk (location_t loc, tree exp,
12674                           enum built_in_function fcode)
12675 {
12676   return fold_builtin_sprintf_chk_1 (loc, call_expr_nargs (exp),
12677                                      CALL_EXPR_ARGP (exp), fcode);
12678 }
12679
12680 /* Fold a call EXP to {,v}snprintf having NARGS passed as ARGS.  Return
12681    NULL_TREE if a normal call should be emitted rather than expanding
12682    the function inline.  FCODE is either BUILT_IN_SNPRINTF_CHK or
12683    BUILT_IN_VSNPRINTF_CHK.  If MAXLEN is not NULL, it is maximum length
12684    passed as second argument.  */
12685
12686 static tree
12687 fold_builtin_snprintf_chk_1 (location_t loc, int nargs, tree *args,
12688                              tree maxlen, enum built_in_function fcode)
12689 {
12690   tree dest, size, len, fn, fmt, flag;
12691   const char *fmt_str;
12692
12693   /* Verify the required arguments in the original call.  */
12694   if (nargs < 5)
12695     return NULL_TREE;
12696   dest = args[0];
12697   if (!validate_arg (dest, POINTER_TYPE))
12698     return NULL_TREE;
12699   len = args[1];
12700   if (!validate_arg (len, INTEGER_TYPE))
12701     return NULL_TREE;
12702   flag = args[2];
12703   if (!validate_arg (flag, INTEGER_TYPE))
12704     return NULL_TREE;
12705   size = args[3];
12706   if (!validate_arg (size, INTEGER_TYPE))
12707     return NULL_TREE;
12708   fmt = args[4];
12709   if (!validate_arg (fmt, POINTER_TYPE))
12710     return NULL_TREE;
12711
12712   if (! host_integerp (size, 1))
12713     return NULL_TREE;
12714
12715   if (! integer_all_onesp (size))
12716     {
12717       if (! host_integerp (len, 1))
12718         {
12719           /* If LEN is not constant, try MAXLEN too.
12720              For MAXLEN only allow optimizing into non-_ocs function
12721              if SIZE is >= MAXLEN, never convert to __ocs_fail ().  */
12722           if (maxlen == NULL_TREE || ! host_integerp (maxlen, 1))
12723             return NULL_TREE;
12724         }
12725       else
12726         maxlen = len;
12727
12728       if (tree_int_cst_lt (size, maxlen))
12729         return NULL_TREE;
12730     }
12731
12732   if (!init_target_chars ())
12733     return NULL_TREE;
12734
12735   /* Only convert __{,v}snprintf_chk to {,v}snprintf if flag is 0
12736      or if format doesn't contain % chars or is "%s".  */
12737   if (! integer_zerop (flag))
12738     {
12739       fmt_str = c_getstr (fmt);
12740       if (fmt_str == NULL)
12741         return NULL_TREE;
12742       if (strchr (fmt_str, target_percent) != NULL
12743           && strcmp (fmt_str, target_percent_s))
12744         return NULL_TREE;
12745     }
12746
12747   /* If __builtin_{,v}snprintf_chk is used, assume {,v}snprintf is
12748      available.  */
12749   fn = built_in_decls[fcode == BUILT_IN_VSNPRINTF_CHK
12750                       ? BUILT_IN_VSNPRINTF : BUILT_IN_SNPRINTF];
12751   if (!fn)
12752     return NULL_TREE;
12753
12754   return rewrite_call_expr_array (loc, nargs, args, 5, fn, 3, dest, len, fmt);
12755 }
12756
12757 /* Fold a call EXP to {,v}snprintf.  Return NULL_TREE if
12758    a normal call should be emitted rather than expanding the function
12759    inline.  FCODE is either BUILT_IN_SNPRINTF_CHK or
12760    BUILT_IN_VSNPRINTF_CHK.  If MAXLEN is not NULL, it is maximum length
12761    passed as second argument.  */
12762
12763 tree
12764 fold_builtin_snprintf_chk (location_t loc, tree exp, tree maxlen,
12765                            enum built_in_function fcode)
12766 {
12767   return fold_builtin_snprintf_chk_1 (loc, call_expr_nargs (exp),
12768                                       CALL_EXPR_ARGP (exp), maxlen, fcode);
12769 }
12770
12771 /* Fold a call to the {,v}printf{,_unlocked} and __{,v}printf_chk builtins.
12772    FMT and ARG are the arguments to the call; we don't fold cases with
12773    more than 2 arguments, and ARG may be null if this is a 1-argument case.
12774
12775    Return NULL_TREE if no simplification was possible, otherwise return the
12776    simplified form of the call as a tree.  FCODE is the BUILT_IN_*
12777    code of the function to be simplified.  */
12778
12779 static tree
12780 fold_builtin_printf (location_t loc, tree fndecl, tree fmt,
12781                      tree arg, bool ignore,
12782                      enum built_in_function fcode)
12783 {
12784   tree fn_putchar, fn_puts, newarg, call = NULL_TREE;
12785   const char *fmt_str = NULL;
12786
12787   /* If the return value is used, don't do the transformation.  */
12788   if (! ignore)
12789     return NULL_TREE;
12790
12791   /* Verify the required arguments in the original call.  */
12792   if (!validate_arg (fmt, POINTER_TYPE))
12793     return NULL_TREE;
12794
12795   /* Check whether the format is a literal string constant.  */
12796   fmt_str = c_getstr (fmt);
12797   if (fmt_str == NULL)
12798     return NULL_TREE;
12799
12800   if (fcode == BUILT_IN_PRINTF_UNLOCKED)
12801     {
12802       /* If we're using an unlocked function, assume the other
12803          unlocked functions exist explicitly.  */
12804       fn_putchar = built_in_decls[BUILT_IN_PUTCHAR_UNLOCKED];
12805       fn_puts = built_in_decls[BUILT_IN_PUTS_UNLOCKED];
12806     }
12807   else
12808     {
12809       fn_putchar = implicit_built_in_decls[BUILT_IN_PUTCHAR];
12810       fn_puts = implicit_built_in_decls[BUILT_IN_PUTS];
12811     }
12812
12813   if (!init_target_chars ())
12814     return NULL_TREE;
12815
12816   if (strcmp (fmt_str, target_percent_s) == 0
12817       || strchr (fmt_str, target_percent) == NULL)
12818     {
12819       const char *str;
12820
12821       if (strcmp (fmt_str, target_percent_s) == 0)
12822         {
12823           if (fcode == BUILT_IN_VPRINTF || fcode == BUILT_IN_VPRINTF_CHK)
12824             return NULL_TREE;
12825
12826           if (!arg || !validate_arg (arg, POINTER_TYPE))
12827             return NULL_TREE;
12828
12829           str = c_getstr (arg);
12830           if (str == NULL)
12831             return NULL_TREE;
12832         }
12833       else
12834         {
12835           /* The format specifier doesn't contain any '%' characters.  */
12836           if (fcode != BUILT_IN_VPRINTF && fcode != BUILT_IN_VPRINTF_CHK
12837               && arg)
12838             return NULL_TREE;
12839           str = fmt_str;
12840         }
12841
12842       /* If the string was "", printf does nothing.  */
12843       if (str[0] == '\0')
12844         return build_int_cst (TREE_TYPE (TREE_TYPE (fndecl)), 0);
12845
12846       /* If the string has length of 1, call putchar.  */
12847       if (str[1] == '\0')
12848         {
12849           /* Given printf("c"), (where c is any one character,)
12850              convert "c"[0] to an int and pass that to the replacement
12851              function.  */
12852           newarg = build_int_cst (NULL_TREE, str[0]);
12853           if (fn_putchar)
12854             call = build_call_expr_loc (loc, fn_putchar, 1, newarg);
12855         }
12856       else
12857         {
12858           /* If the string was "string\n", call puts("string").  */
12859           size_t len = strlen (str);
12860           if ((unsigned char)str[len - 1] == target_newline)
12861             {
12862               /* Create a NUL-terminated string that's one char shorter
12863                  than the original, stripping off the trailing '\n'.  */
12864               char *newstr = XALLOCAVEC (char, len);
12865               memcpy (newstr, str, len - 1);
12866               newstr[len - 1] = 0;
12867
12868               newarg = build_string_literal (len, newstr);
12869               if (fn_puts)
12870                 call = build_call_expr_loc (loc, fn_puts, 1, newarg);
12871             }
12872           else
12873             /* We'd like to arrange to call fputs(string,stdout) here,
12874                but we need stdout and don't have a way to get it yet.  */
12875             return NULL_TREE;
12876         }
12877     }
12878
12879   /* The other optimizations can be done only on the non-va_list variants.  */
12880   else if (fcode == BUILT_IN_VPRINTF || fcode == BUILT_IN_VPRINTF_CHK)
12881     return NULL_TREE;
12882
12883   /* If the format specifier was "%s\n", call __builtin_puts(arg).  */
12884   else if (strcmp (fmt_str, target_percent_s_newline) == 0)
12885     {
12886       if (!arg || !validate_arg (arg, POINTER_TYPE))
12887         return NULL_TREE;
12888       if (fn_puts)
12889         call = build_call_expr_loc (loc, fn_puts, 1, arg);
12890     }
12891
12892   /* If the format specifier was "%c", call __builtin_putchar(arg).  */
12893   else if (strcmp (fmt_str, target_percent_c) == 0)
12894     {
12895       if (!arg || !validate_arg (arg, INTEGER_TYPE))
12896         return NULL_TREE;
12897       if (fn_putchar)
12898         call = build_call_expr_loc (loc, fn_putchar, 1, arg);
12899     }
12900
12901   if (!call)
12902     return NULL_TREE;
12903
12904   return fold_convert_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)), call);
12905 }
12906
12907 /* Fold a call to the {,v}fprintf{,_unlocked} and __{,v}printf_chk builtins.
12908    FP, FMT, and ARG are the arguments to the call.  We don't fold calls with
12909    more than 3 arguments, and ARG may be null in the 2-argument case.
12910
12911    Return NULL_TREE if no simplification was possible, otherwise return the
12912    simplified form of the call as a tree.  FCODE is the BUILT_IN_*
12913    code of the function to be simplified.  */
12914
12915 static tree
12916 fold_builtin_fprintf (location_t loc, tree fndecl, tree fp,
12917                       tree fmt, tree arg, bool ignore,
12918                       enum built_in_function fcode)
12919 {
12920   tree fn_fputc, fn_fputs, call = NULL_TREE;
12921   const char *fmt_str = NULL;
12922
12923   /* If the return value is used, don't do the transformation.  */
12924   if (! ignore)
12925     return NULL_TREE;
12926
12927   /* Verify the required arguments in the original call.  */
12928   if (!validate_arg (fp, POINTER_TYPE))
12929     return NULL_TREE;
12930   if (!validate_arg (fmt, POINTER_TYPE))
12931     return NULL_TREE;
12932
12933   /* Check whether the format is a literal string constant.  */
12934   fmt_str = c_getstr (fmt);
12935   if (fmt_str == NULL)
12936     return NULL_TREE;
12937
12938   if (fcode == BUILT_IN_FPRINTF_UNLOCKED)
12939     {
12940       /* If we're using an unlocked function, assume the other
12941          unlocked functions exist explicitly.  */
12942       fn_fputc = built_in_decls[BUILT_IN_FPUTC_UNLOCKED];
12943       fn_fputs = built_in_decls[BUILT_IN_FPUTS_UNLOCKED];
12944     }
12945   else
12946     {
12947       fn_fputc = implicit_built_in_decls[BUILT_IN_FPUTC];
12948       fn_fputs = implicit_built_in_decls[BUILT_IN_FPUTS];
12949     }
12950
12951   if (!init_target_chars ())
12952     return NULL_TREE;
12953
12954   /* If the format doesn't contain % args or %%, use strcpy.  */
12955   if (strchr (fmt_str, target_percent) == NULL)
12956     {
12957       if (fcode != BUILT_IN_VFPRINTF && fcode != BUILT_IN_VFPRINTF_CHK
12958           && arg)
12959         return NULL_TREE;
12960
12961       /* If the format specifier was "", fprintf does nothing.  */
12962       if (fmt_str[0] == '\0')
12963         {
12964           /* If FP has side-effects, just wait until gimplification is
12965              done.  */
12966           if (TREE_SIDE_EFFECTS (fp))
12967             return NULL_TREE;
12968
12969           return build_int_cst (TREE_TYPE (TREE_TYPE (fndecl)), 0);
12970         }
12971
12972       /* When "string" doesn't contain %, replace all cases of
12973          fprintf (fp, string) with fputs (string, fp).  The fputs
12974          builtin will take care of special cases like length == 1.  */
12975       if (fn_fputs)
12976         call = build_call_expr_loc (loc, fn_fputs, 2, fmt, fp);
12977     }
12978
12979   /* The other optimizations can be done only on the non-va_list variants.  */
12980   else if (fcode == BUILT_IN_VFPRINTF || fcode == BUILT_IN_VFPRINTF_CHK)
12981     return NULL_TREE;
12982
12983   /* If the format specifier was "%s", call __builtin_fputs (arg, fp).  */
12984   else if (strcmp (fmt_str, target_percent_s) == 0)
12985     {
12986       if (!arg || !validate_arg (arg, POINTER_TYPE))
12987         return NULL_TREE;
12988       if (fn_fputs)
12989         call = build_call_expr_loc (loc, fn_fputs, 2, arg, fp);
12990     }
12991
12992   /* If the format specifier was "%c", call __builtin_fputc (arg, fp).  */
12993   else if (strcmp (fmt_str, target_percent_c) == 0)
12994     {
12995       if (!arg || !validate_arg (arg, INTEGER_TYPE))
12996         return NULL_TREE;
12997       if (fn_fputc)
12998         call = build_call_expr_loc (loc, fn_fputc, 2, arg, fp);
12999     }
13000
13001   if (!call)
13002     return NULL_TREE;
13003   return fold_convert_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)), call);
13004 }
13005
13006 /* Initialize format string characters in the target charset.  */
13007
13008 static bool
13009 init_target_chars (void)
13010 {
13011   static bool init;
13012   if (!init)
13013     {
13014       target_newline = lang_hooks.to_target_charset ('\n');
13015       target_percent = lang_hooks.to_target_charset ('%');
13016       target_c = lang_hooks.to_target_charset ('c');
13017       target_s = lang_hooks.to_target_charset ('s');
13018       if (target_newline == 0 || target_percent == 0 || target_c == 0
13019           || target_s == 0)
13020         return false;
13021
13022       target_percent_c[0] = target_percent;
13023       target_percent_c[1] = target_c;
13024       target_percent_c[2] = '\0';
13025
13026       target_percent_s[0] = target_percent;
13027       target_percent_s[1] = target_s;
13028       target_percent_s[2] = '\0';
13029
13030       target_percent_s_newline[0] = target_percent;
13031       target_percent_s_newline[1] = target_s;
13032       target_percent_s_newline[2] = target_newline;
13033       target_percent_s_newline[3] = '\0';
13034
13035       init = true;
13036     }
13037   return true;
13038 }
13039
13040 /* Helper function for do_mpfr_arg*().  Ensure M is a normal number
13041    and no overflow/underflow occurred.  INEXACT is true if M was not
13042    exactly calculated.  TYPE is the tree type for the result.  This
13043    function assumes that you cleared the MPFR flags and then
13044    calculated M to see if anything subsequently set a flag prior to
13045    entering this function.  Return NULL_TREE if any checks fail.  */
13046
13047 static tree
13048 do_mpfr_ckconv (mpfr_srcptr m, tree type, int inexact)
13049 {
13050   /* Proceed iff we get a normal number, i.e. not NaN or Inf and no
13051      overflow/underflow occurred.  If -frounding-math, proceed iff the
13052      result of calling FUNC was exact.  */
13053   if (mpfr_number_p (m) && !mpfr_overflow_p () && !mpfr_underflow_p ()
13054       && (!flag_rounding_math || !inexact))
13055     {
13056       REAL_VALUE_TYPE rr;
13057
13058       real_from_mpfr (&rr, m, type, GMP_RNDN);
13059       /* Proceed iff GCC's REAL_VALUE_TYPE can hold the MPFR value,
13060          check for overflow/underflow.  If the REAL_VALUE_TYPE is zero
13061          but the mpft_t is not, then we underflowed in the
13062          conversion.  */
13063       if (real_isfinite (&rr)
13064           && (rr.cl == rvc_zero) == (mpfr_zero_p (m) != 0))
13065         {
13066           REAL_VALUE_TYPE rmode;
13067
13068           real_convert (&rmode, TYPE_MODE (type), &rr);
13069           /* Proceed iff the specified mode can hold the value.  */
13070           if (real_identical (&rmode, &rr))
13071             return build_real (type, rmode);
13072         }
13073     }
13074   return NULL_TREE;
13075 }
13076
13077 /* Helper function for do_mpc_arg*().  Ensure M is a normal complex
13078    number and no overflow/underflow occurred.  INEXACT is true if M
13079    was not exactly calculated.  TYPE is the tree type for the result.
13080    This function assumes that you cleared the MPFR flags and then
13081    calculated M to see if anything subsequently set a flag prior to
13082    entering this function.  Return NULL_TREE if any checks fail, if
13083    FORCE_CONVERT is true, then bypass the checks.  */
13084
13085 static tree
13086 do_mpc_ckconv (mpc_srcptr m, tree type, int inexact, int force_convert)
13087 {
13088   /* Proceed iff we get a normal number, i.e. not NaN or Inf and no
13089      overflow/underflow occurred.  If -frounding-math, proceed iff the
13090      result of calling FUNC was exact.  */
13091   if (force_convert
13092       || (mpfr_number_p (mpc_realref (m)) && mpfr_number_p (mpc_imagref (m))
13093           && !mpfr_overflow_p () && !mpfr_underflow_p ()
13094           && (!flag_rounding_math || !inexact)))
13095     {
13096       REAL_VALUE_TYPE re, im;
13097
13098       real_from_mpfr (&re, mpc_realref (m), TREE_TYPE (type), GMP_RNDN);
13099       real_from_mpfr (&im, mpc_imagref (m), TREE_TYPE (type), GMP_RNDN);
13100       /* Proceed iff GCC's REAL_VALUE_TYPE can hold the MPFR values,
13101          check for overflow/underflow.  If the REAL_VALUE_TYPE is zero
13102          but the mpft_t is not, then we underflowed in the
13103          conversion.  */
13104       if (force_convert
13105           || (real_isfinite (&re) && real_isfinite (&im)
13106               && (re.cl == rvc_zero) == (mpfr_zero_p (mpc_realref (m)) != 0)
13107               && (im.cl == rvc_zero) == (mpfr_zero_p (mpc_imagref (m)) != 0)))
13108         {
13109           REAL_VALUE_TYPE re_mode, im_mode;
13110
13111           real_convert (&re_mode, TYPE_MODE (TREE_TYPE (type)), &re);
13112           real_convert (&im_mode, TYPE_MODE (TREE_TYPE (type)), &im);
13113           /* Proceed iff the specified mode can hold the value.  */
13114           if (force_convert
13115               || (real_identical (&re_mode, &re)
13116                   && real_identical (&im_mode, &im)))
13117             return build_complex (type, build_real (TREE_TYPE (type), re_mode),
13118                                   build_real (TREE_TYPE (type), im_mode));
13119         }
13120     }
13121   return NULL_TREE;
13122 }
13123
13124 /* If argument ARG is a REAL_CST, call the one-argument mpfr function
13125    FUNC on it and return the resulting value as a tree with type TYPE.
13126    If MIN and/or MAX are not NULL, then the supplied ARG must be
13127    within those bounds.  If INCLUSIVE is true, then MIN/MAX are
13128    acceptable values, otherwise they are not.  The mpfr precision is
13129    set to the precision of TYPE.  We assume that function FUNC returns
13130    zero if the result could be calculated exactly within the requested
13131    precision.  */
13132
13133 static tree
13134 do_mpfr_arg1 (tree arg, tree type, int (*func)(mpfr_ptr, mpfr_srcptr, mp_rnd_t),
13135               const REAL_VALUE_TYPE *min, const REAL_VALUE_TYPE *max,
13136               bool inclusive)
13137 {
13138   tree result = NULL_TREE;
13139
13140   STRIP_NOPS (arg);
13141
13142   /* To proceed, MPFR must exactly represent the target floating point
13143      format, which only happens when the target base equals two.  */
13144   if (REAL_MODE_FORMAT (TYPE_MODE (type))->b == 2
13145       && TREE_CODE (arg) == REAL_CST && !TREE_OVERFLOW (arg))
13146     {
13147       const REAL_VALUE_TYPE *const ra = &TREE_REAL_CST (arg);
13148
13149       if (real_isfinite (ra)
13150           && (!min || real_compare (inclusive ? GE_EXPR: GT_EXPR , ra, min))
13151           && (!max || real_compare (inclusive ? LE_EXPR: LT_EXPR , ra, max)))
13152         {
13153           const struct real_format *fmt = REAL_MODE_FORMAT (TYPE_MODE (type));
13154           const int prec = fmt->p;
13155           const mp_rnd_t rnd = fmt->round_towards_zero? GMP_RNDZ : GMP_RNDN;
13156           int inexact;
13157           mpfr_t m;
13158
13159           mpfr_init2 (m, prec);
13160           mpfr_from_real (m, ra, GMP_RNDN);
13161           mpfr_clear_flags ();
13162           inexact = func (m, m, rnd);
13163           result = do_mpfr_ckconv (m, type, inexact);
13164           mpfr_clear (m);
13165         }
13166     }
13167
13168   return result;
13169 }
13170
13171 /* If argument ARG is a REAL_CST, call the two-argument mpfr function
13172    FUNC on it and return the resulting value as a tree with type TYPE.
13173    The mpfr precision is set to the precision of TYPE.  We assume that
13174    function FUNC returns zero if the result could be calculated
13175    exactly within the requested precision.  */
13176
13177 static tree
13178 do_mpfr_arg2 (tree arg1, tree arg2, tree type,
13179               int (*func)(mpfr_ptr, mpfr_srcptr, mpfr_srcptr, mp_rnd_t))
13180 {
13181   tree result = NULL_TREE;
13182
13183   STRIP_NOPS (arg1);
13184   STRIP_NOPS (arg2);
13185
13186   /* To proceed, MPFR must exactly represent the target floating point
13187      format, which only happens when the target base equals two.  */
13188   if (REAL_MODE_FORMAT (TYPE_MODE (type))->b == 2
13189       && TREE_CODE (arg1) == REAL_CST && !TREE_OVERFLOW (arg1)
13190       && TREE_CODE (arg2) == REAL_CST && !TREE_OVERFLOW (arg2))
13191     {
13192       const REAL_VALUE_TYPE *const ra1 = &TREE_REAL_CST (arg1);
13193       const REAL_VALUE_TYPE *const ra2 = &TREE_REAL_CST (arg2);
13194
13195       if (real_isfinite (ra1) && real_isfinite (ra2))
13196         {
13197           const struct real_format *fmt = REAL_MODE_FORMAT (TYPE_MODE (type));
13198           const int prec = fmt->p;
13199           const mp_rnd_t rnd = fmt->round_towards_zero? GMP_RNDZ : GMP_RNDN;
13200           int inexact;
13201           mpfr_t m1, m2;
13202
13203           mpfr_inits2 (prec, m1, m2, NULL);
13204           mpfr_from_real (m1, ra1, GMP_RNDN);
13205           mpfr_from_real (m2, ra2, GMP_RNDN);
13206           mpfr_clear_flags ();
13207           inexact = func (m1, m1, m2, rnd);
13208           result = do_mpfr_ckconv (m1, type, inexact);
13209           mpfr_clears (m1, m2, NULL);
13210         }
13211     }
13212
13213   return result;
13214 }
13215
13216 /* If argument ARG is a REAL_CST, call the three-argument mpfr function
13217    FUNC on it and return the resulting value as a tree with type TYPE.
13218    The mpfr precision is set to the precision of TYPE.  We assume that
13219    function FUNC returns zero if the result could be calculated
13220    exactly within the requested precision.  */
13221
13222 static tree
13223 do_mpfr_arg3 (tree arg1, tree arg2, tree arg3, tree type,
13224               int (*func)(mpfr_ptr, mpfr_srcptr, mpfr_srcptr, mpfr_srcptr, mp_rnd_t))
13225 {
13226   tree result = NULL_TREE;
13227
13228   STRIP_NOPS (arg1);
13229   STRIP_NOPS (arg2);
13230   STRIP_NOPS (arg3);
13231
13232   /* To proceed, MPFR must exactly represent the target floating point
13233      format, which only happens when the target base equals two.  */
13234   if (REAL_MODE_FORMAT (TYPE_MODE (type))->b == 2
13235       && TREE_CODE (arg1) == REAL_CST && !TREE_OVERFLOW (arg1)
13236       && TREE_CODE (arg2) == REAL_CST && !TREE_OVERFLOW (arg2)
13237       && TREE_CODE (arg3) == REAL_CST && !TREE_OVERFLOW (arg3))
13238     {
13239       const REAL_VALUE_TYPE *const ra1 = &TREE_REAL_CST (arg1);
13240       const REAL_VALUE_TYPE *const ra2 = &TREE_REAL_CST (arg2);
13241       const REAL_VALUE_TYPE *const ra3 = &TREE_REAL_CST (arg3);
13242
13243       if (real_isfinite (ra1) && real_isfinite (ra2) && real_isfinite (ra3))
13244         {
13245           const struct real_format *fmt = REAL_MODE_FORMAT (TYPE_MODE (type));
13246           const int prec = fmt->p;
13247           const mp_rnd_t rnd = fmt->round_towards_zero? GMP_RNDZ : GMP_RNDN;
13248           int inexact;
13249           mpfr_t m1, m2, m3;
13250
13251           mpfr_inits2 (prec, m1, m2, m3, NULL);
13252           mpfr_from_real (m1, ra1, GMP_RNDN);
13253           mpfr_from_real (m2, ra2, GMP_RNDN);
13254           mpfr_from_real (m3, ra3, GMP_RNDN);
13255           mpfr_clear_flags ();
13256           inexact = func (m1, m1, m2, m3, rnd);
13257           result = do_mpfr_ckconv (m1, type, inexact);
13258           mpfr_clears (m1, m2, m3, NULL);
13259         }
13260     }
13261
13262   return result;
13263 }
13264
13265 /* If argument ARG is a REAL_CST, call mpfr_sin_cos() on it and set
13266    the pointers *(ARG_SINP) and *(ARG_COSP) to the resulting values.
13267    If ARG_SINP and ARG_COSP are NULL then the result is returned
13268    as a complex value.
13269    The type is taken from the type of ARG and is used for setting the
13270    precision of the calculation and results.  */
13271
13272 static tree
13273 do_mpfr_sincos (tree arg, tree arg_sinp, tree arg_cosp)
13274 {
13275   tree const type = TREE_TYPE (arg);
13276   tree result = NULL_TREE;
13277
13278   STRIP_NOPS (arg);
13279
13280   /* To proceed, MPFR must exactly represent the target floating point
13281      format, which only happens when the target base equals two.  */
13282   if (REAL_MODE_FORMAT (TYPE_MODE (type))->b == 2
13283       && TREE_CODE (arg) == REAL_CST
13284       && !TREE_OVERFLOW (arg))
13285     {
13286       const REAL_VALUE_TYPE *const ra = &TREE_REAL_CST (arg);
13287
13288       if (real_isfinite (ra))
13289         {
13290           const struct real_format *fmt = REAL_MODE_FORMAT (TYPE_MODE (type));
13291           const int prec = fmt->p;
13292           const mp_rnd_t rnd = fmt->round_towards_zero? GMP_RNDZ : GMP_RNDN;
13293           tree result_s, result_c;
13294           int inexact;
13295           mpfr_t m, ms, mc;
13296
13297           mpfr_inits2 (prec, m, ms, mc, NULL);
13298           mpfr_from_real (m, ra, GMP_RNDN);
13299           mpfr_clear_flags ();
13300           inexact = mpfr_sin_cos (ms, mc, m, rnd);
13301           result_s = do_mpfr_ckconv (ms, type, inexact);
13302           result_c = do_mpfr_ckconv (mc, type, inexact);
13303           mpfr_clears (m, ms, mc, NULL);
13304           if (result_s && result_c)
13305             {
13306               /* If we are to return in a complex value do so.  */
13307               if (!arg_sinp && !arg_cosp)
13308                 return build_complex (build_complex_type (type),
13309                                       result_c, result_s);
13310
13311               /* Dereference the sin/cos pointer arguments.  */
13312               arg_sinp = build_fold_indirect_ref (arg_sinp);
13313               arg_cosp = build_fold_indirect_ref (arg_cosp);
13314               /* Proceed if valid pointer type were passed in.  */
13315               if (TYPE_MAIN_VARIANT (TREE_TYPE (arg_sinp)) == TYPE_MAIN_VARIANT (type)
13316                   && TYPE_MAIN_VARIANT (TREE_TYPE (arg_cosp)) == TYPE_MAIN_VARIANT (type))
13317                 {
13318                   /* Set the values. */
13319                   result_s = fold_build2 (MODIFY_EXPR, type, arg_sinp,
13320                                           result_s);
13321                   TREE_SIDE_EFFECTS (result_s) = 1;
13322                   result_c = fold_build2 (MODIFY_EXPR, type, arg_cosp,
13323                                           result_c);
13324                   TREE_SIDE_EFFECTS (result_c) = 1;
13325                   /* Combine the assignments into a compound expr.  */
13326                   result = non_lvalue (fold_build2 (COMPOUND_EXPR, type,
13327                                                     result_s, result_c));
13328                 }
13329             }
13330         }
13331     }
13332   return result;
13333 }
13334
13335 /* If argument ARG1 is an INTEGER_CST and ARG2 is a REAL_CST, call the
13336    two-argument mpfr order N Bessel function FUNC on them and return
13337    the resulting value as a tree with type TYPE.  The mpfr precision
13338    is set to the precision of TYPE.  We assume that function FUNC
13339    returns zero if the result could be calculated exactly within the
13340    requested precision.  */
13341 static tree
13342 do_mpfr_bessel_n (tree arg1, tree arg2, tree type,
13343                   int (*func)(mpfr_ptr, long, mpfr_srcptr, mp_rnd_t),
13344                   const REAL_VALUE_TYPE *min, bool inclusive)
13345 {
13346   tree result = NULL_TREE;
13347
13348   STRIP_NOPS (arg1);
13349   STRIP_NOPS (arg2);
13350
13351   /* To proceed, MPFR must exactly represent the target floating point
13352      format, which only happens when the target base equals two.  */
13353   if (REAL_MODE_FORMAT (TYPE_MODE (type))->b == 2
13354       && host_integerp (arg1, 0)
13355       && TREE_CODE (arg2) == REAL_CST && !TREE_OVERFLOW (arg2))
13356     {
13357       const HOST_WIDE_INT n = tree_low_cst(arg1, 0);
13358       const REAL_VALUE_TYPE *const ra = &TREE_REAL_CST (arg2);
13359
13360       if (n == (long)n
13361           && real_isfinite (ra)
13362           && (!min || real_compare (inclusive ? GE_EXPR: GT_EXPR , ra, min)))
13363         {
13364           const struct real_format *fmt = REAL_MODE_FORMAT (TYPE_MODE (type));
13365           const int prec = fmt->p;
13366           const mp_rnd_t rnd = fmt->round_towards_zero? GMP_RNDZ : GMP_RNDN;
13367           int inexact;
13368           mpfr_t m;
13369
13370           mpfr_init2 (m, prec);
13371           mpfr_from_real (m, ra, GMP_RNDN);
13372           mpfr_clear_flags ();
13373           inexact = func (m, n, m, rnd);
13374           result = do_mpfr_ckconv (m, type, inexact);
13375           mpfr_clear (m);
13376         }
13377     }
13378
13379   return result;
13380 }
13381
13382 /* If arguments ARG0 and ARG1 are REAL_CSTs, call mpfr_remquo() to set
13383    the pointer *(ARG_QUO) and return the result.  The type is taken
13384    from the type of ARG0 and is used for setting the precision of the
13385    calculation and results.  */
13386
13387 static tree
13388 do_mpfr_remquo (tree arg0, tree arg1, tree arg_quo)
13389 {
13390   tree const type = TREE_TYPE (arg0);
13391   tree result = NULL_TREE;
13392
13393   STRIP_NOPS (arg0);
13394   STRIP_NOPS (arg1);
13395
13396   /* To proceed, MPFR must exactly represent the target floating point
13397      format, which only happens when the target base equals two.  */
13398   if (REAL_MODE_FORMAT (TYPE_MODE (type))->b == 2
13399       && TREE_CODE (arg0) == REAL_CST && !TREE_OVERFLOW (arg0)
13400       && TREE_CODE (arg1) == REAL_CST && !TREE_OVERFLOW (arg1))
13401     {
13402       const REAL_VALUE_TYPE *const ra0 = TREE_REAL_CST_PTR (arg0);
13403       const REAL_VALUE_TYPE *const ra1 = TREE_REAL_CST_PTR (arg1);
13404
13405       if (real_isfinite (ra0) && real_isfinite (ra1))
13406         {
13407           const struct real_format *fmt = REAL_MODE_FORMAT (TYPE_MODE (type));
13408           const int prec = fmt->p;
13409           const mp_rnd_t rnd = fmt->round_towards_zero? GMP_RNDZ : GMP_RNDN;
13410           tree result_rem;
13411           long integer_quo;
13412           mpfr_t m0, m1;
13413
13414           mpfr_inits2 (prec, m0, m1, NULL);
13415           mpfr_from_real (m0, ra0, GMP_RNDN);
13416           mpfr_from_real (m1, ra1, GMP_RNDN);
13417           mpfr_clear_flags ();
13418           mpfr_remquo (m0, &integer_quo, m0, m1, rnd);
13419           /* Remquo is independent of the rounding mode, so pass
13420              inexact=0 to do_mpfr_ckconv().  */
13421           result_rem = do_mpfr_ckconv (m0, type, /*inexact=*/ 0);
13422           mpfr_clears (m0, m1, NULL);
13423           if (result_rem)
13424             {
13425               /* MPFR calculates quo in the host's long so it may
13426                  return more bits in quo than the target int can hold
13427                  if sizeof(host long) > sizeof(target int).  This can
13428                  happen even for native compilers in LP64 mode.  In
13429                  these cases, modulo the quo value with the largest
13430                  number that the target int can hold while leaving one
13431                  bit for the sign.  */
13432               if (sizeof (integer_quo) * CHAR_BIT > INT_TYPE_SIZE)
13433                 integer_quo %= (long)(1UL << (INT_TYPE_SIZE - 1));
13434
13435               /* Dereference the quo pointer argument.  */
13436               arg_quo = build_fold_indirect_ref (arg_quo);
13437               /* Proceed iff a valid pointer type was passed in.  */
13438               if (TYPE_MAIN_VARIANT (TREE_TYPE (arg_quo)) == integer_type_node)
13439                 {
13440                   /* Set the value. */
13441                   tree result_quo = fold_build2 (MODIFY_EXPR,
13442                                                  TREE_TYPE (arg_quo), arg_quo,
13443                                                  build_int_cst (NULL, integer_quo));
13444                   TREE_SIDE_EFFECTS (result_quo) = 1;
13445                   /* Combine the quo assignment with the rem.  */
13446                   result = non_lvalue (fold_build2 (COMPOUND_EXPR, type,
13447                                                     result_quo, result_rem));
13448                 }
13449             }
13450         }
13451     }
13452   return result;
13453 }
13454
13455 /* If ARG is a REAL_CST, call mpfr_lgamma() on it and return the
13456    resulting value as a tree with type TYPE.  The mpfr precision is
13457    set to the precision of TYPE.  We assume that this mpfr function
13458    returns zero if the result could be calculated exactly within the
13459    requested precision.  In addition, the integer pointer represented
13460    by ARG_SG will be dereferenced and set to the appropriate signgam
13461    (-1,1) value.  */
13462
13463 static tree
13464 do_mpfr_lgamma_r (tree arg, tree arg_sg, tree type)
13465 {
13466   tree result = NULL_TREE;
13467
13468   STRIP_NOPS (arg);
13469
13470   /* To proceed, MPFR must exactly represent the target floating point
13471      format, which only happens when the target base equals two.  Also
13472      verify ARG is a constant and that ARG_SG is an int pointer.  */
13473   if (REAL_MODE_FORMAT (TYPE_MODE (type))->b == 2
13474       && TREE_CODE (arg) == REAL_CST && !TREE_OVERFLOW (arg)
13475       && TREE_CODE (TREE_TYPE (arg_sg)) == POINTER_TYPE
13476       && TYPE_MAIN_VARIANT (TREE_TYPE (TREE_TYPE (arg_sg))) == integer_type_node)
13477     {
13478       const REAL_VALUE_TYPE *const ra = TREE_REAL_CST_PTR (arg);
13479
13480       /* In addition to NaN and Inf, the argument cannot be zero or a
13481          negative integer.  */
13482       if (real_isfinite (ra)
13483           && ra->cl != rvc_zero
13484           && !(real_isneg(ra) && real_isinteger(ra, TYPE_MODE (type))))
13485         {
13486           const struct real_format *fmt = REAL_MODE_FORMAT (TYPE_MODE (type));
13487           const int prec = fmt->p;
13488           const mp_rnd_t rnd = fmt->round_towards_zero? GMP_RNDZ : GMP_RNDN;
13489           int inexact, sg;
13490           mpfr_t m;
13491           tree result_lg;
13492
13493           mpfr_init2 (m, prec);
13494           mpfr_from_real (m, ra, GMP_RNDN);
13495           mpfr_clear_flags ();
13496           inexact = mpfr_lgamma (m, &sg, m, rnd);
13497           result_lg = do_mpfr_ckconv (m, type, inexact);
13498           mpfr_clear (m);
13499           if (result_lg)
13500             {
13501               tree result_sg;
13502
13503               /* Dereference the arg_sg pointer argument.  */
13504               arg_sg = build_fold_indirect_ref (arg_sg);
13505               /* Assign the signgam value into *arg_sg. */
13506               result_sg = fold_build2 (MODIFY_EXPR,
13507                                        TREE_TYPE (arg_sg), arg_sg,
13508                                        build_int_cst (NULL, sg));
13509               TREE_SIDE_EFFECTS (result_sg) = 1;
13510               /* Combine the signgam assignment with the lgamma result.  */
13511               result = non_lvalue (fold_build2 (COMPOUND_EXPR, type,
13512                                                 result_sg, result_lg));
13513             }
13514         }
13515     }
13516
13517   return result;
13518 }
13519
13520 /* If argument ARG is a COMPLEX_CST, call the one-argument mpc
13521    function FUNC on it and return the resulting value as a tree with
13522    type TYPE.  The mpfr precision is set to the precision of TYPE.  We
13523    assume that function FUNC returns zero if the result could be
13524    calculated exactly within the requested precision.  */
13525
13526 static tree
13527 do_mpc_arg1 (tree arg, tree type, int (*func)(mpc_ptr, mpc_srcptr, mpc_rnd_t))
13528 {
13529   tree result = NULL_TREE;
13530
13531   STRIP_NOPS (arg);
13532
13533   /* To proceed, MPFR must exactly represent the target floating point
13534      format, which only happens when the target base equals two.  */
13535   if (TREE_CODE (arg) == COMPLEX_CST && !TREE_OVERFLOW (arg)
13536       && TREE_CODE (TREE_TYPE (TREE_TYPE (arg))) == REAL_TYPE
13537       && REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (TREE_TYPE (arg))))->b == 2)
13538     {
13539       const REAL_VALUE_TYPE *const re = TREE_REAL_CST_PTR (TREE_REALPART (arg));
13540       const REAL_VALUE_TYPE *const im = TREE_REAL_CST_PTR (TREE_IMAGPART (arg));
13541
13542       if (real_isfinite (re) && real_isfinite (im))
13543         {
13544           const struct real_format *const fmt =
13545             REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (type)));
13546           const int prec = fmt->p;
13547           const mp_rnd_t rnd = fmt->round_towards_zero ? GMP_RNDZ : GMP_RNDN;
13548           const mpc_rnd_t crnd = fmt->round_towards_zero ? MPC_RNDZZ : MPC_RNDNN;
13549           int inexact;
13550           mpc_t m;
13551
13552           mpc_init2 (m, prec);
13553           mpfr_from_real (mpc_realref(m), re, rnd);
13554           mpfr_from_real (mpc_imagref(m), im, rnd);
13555           mpfr_clear_flags ();
13556           inexact = func (m, m, crnd);
13557           result = do_mpc_ckconv (m, type, inexact, /*force_convert=*/ 0);
13558           mpc_clear (m);
13559         }
13560     }
13561
13562   return result;
13563 }
13564
13565 /* If arguments ARG0 and ARG1 are a COMPLEX_CST, call the two-argument
13566    mpc function FUNC on it and return the resulting value as a tree
13567    with type TYPE.  The mpfr precision is set to the precision of
13568    TYPE.  We assume that function FUNC returns zero if the result
13569    could be calculated exactly within the requested precision.  If
13570    DO_NONFINITE is true, then fold expressions containing Inf or NaN
13571    in the arguments and/or results.  */
13572
13573 tree
13574 do_mpc_arg2 (tree arg0, tree arg1, tree type, int do_nonfinite,
13575              int (*func)(mpc_ptr, mpc_srcptr, mpc_srcptr, mpc_rnd_t))
13576 {
13577   tree result = NULL_TREE;
13578
13579   STRIP_NOPS (arg0);
13580   STRIP_NOPS (arg1);
13581
13582   /* To proceed, MPFR must exactly represent the target floating point
13583      format, which only happens when the target base equals two.  */
13584   if (TREE_CODE (arg0) == COMPLEX_CST && !TREE_OVERFLOW (arg0)
13585       && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE
13586       && TREE_CODE (arg1) == COMPLEX_CST && !TREE_OVERFLOW (arg1)
13587       && TREE_CODE (TREE_TYPE (TREE_TYPE (arg1))) == REAL_TYPE
13588       && REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (TREE_TYPE (arg0))))->b == 2)
13589     {
13590       const REAL_VALUE_TYPE *const re0 = TREE_REAL_CST_PTR (TREE_REALPART (arg0));
13591       const REAL_VALUE_TYPE *const im0 = TREE_REAL_CST_PTR (TREE_IMAGPART (arg0));
13592       const REAL_VALUE_TYPE *const re1 = TREE_REAL_CST_PTR (TREE_REALPART (arg1));
13593       const REAL_VALUE_TYPE *const im1 = TREE_REAL_CST_PTR (TREE_IMAGPART (arg1));
13594
13595       if (do_nonfinite
13596           || (real_isfinite (re0) && real_isfinite (im0)
13597               && real_isfinite (re1) && real_isfinite (im1)))
13598         {
13599           const struct real_format *const fmt =
13600             REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (type)));
13601           const int prec = fmt->p;
13602           const mp_rnd_t rnd = fmt->round_towards_zero ? GMP_RNDZ : GMP_RNDN;
13603           const mpc_rnd_t crnd = fmt->round_towards_zero ? MPC_RNDZZ : MPC_RNDNN;
13604           int inexact;
13605           mpc_t m0, m1;
13606
13607           mpc_init2 (m0, prec);
13608           mpc_init2 (m1, prec);
13609           mpfr_from_real (mpc_realref(m0), re0, rnd);
13610           mpfr_from_real (mpc_imagref(m0), im0, rnd);
13611           mpfr_from_real (mpc_realref(m1), re1, rnd);
13612           mpfr_from_real (mpc_imagref(m1), im1, rnd);
13613           mpfr_clear_flags ();
13614           inexact = func (m0, m0, m1, crnd);
13615           result = do_mpc_ckconv (m0, type, inexact, do_nonfinite);
13616           mpc_clear (m0);
13617           mpc_clear (m1);
13618         }
13619     }
13620
13621   return result;
13622 }
13623
13624 /* Fold a call STMT to __{,v}sprintf_chk.  Return NULL_TREE if
13625    a normal call should be emitted rather than expanding the function
13626    inline.  FCODE is either BUILT_IN_SPRINTF_CHK or BUILT_IN_VSPRINTF_CHK.  */
13627
13628 static tree
13629 gimple_fold_builtin_sprintf_chk (gimple stmt, enum built_in_function fcode)
13630 {
13631   int nargs = gimple_call_num_args (stmt);
13632
13633   return fold_builtin_sprintf_chk_1 (gimple_location (stmt), nargs,
13634                                      (nargs > 0
13635                                       ? gimple_call_arg_ptr (stmt, 0)
13636                                       : &error_mark_node), fcode);
13637 }
13638
13639 /* Fold a call STMT to {,v}snprintf.  Return NULL_TREE if
13640    a normal call should be emitted rather than expanding the function
13641    inline.  FCODE is either BUILT_IN_SNPRINTF_CHK or
13642    BUILT_IN_VSNPRINTF_CHK.  If MAXLEN is not NULL, it is maximum length
13643    passed as second argument.  */
13644
13645 tree
13646 gimple_fold_builtin_snprintf_chk (gimple stmt, tree maxlen,
13647                                   enum built_in_function fcode)
13648 {
13649   int nargs = gimple_call_num_args (stmt);
13650
13651   return fold_builtin_snprintf_chk_1 (gimple_location (stmt), nargs,
13652                                       (nargs > 0
13653                                        ? gimple_call_arg_ptr (stmt, 0)
13654                                        : &error_mark_node), maxlen, fcode);
13655 }
13656
13657 /* Builtins with folding operations that operate on "..." arguments
13658    need special handling; we need to store the arguments in a convenient
13659    data structure before attempting any folding.  Fortunately there are
13660    only a few builtins that fall into this category.  FNDECL is the
13661    function, EXP is the CALL_EXPR for the call, and IGNORE is true if the
13662    result of the function call is ignored.  */
13663
13664 static tree
13665 gimple_fold_builtin_varargs (tree fndecl, gimple stmt,
13666                              bool ignore ATTRIBUTE_UNUSED)
13667 {
13668   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
13669   tree ret = NULL_TREE;
13670
13671   switch (fcode)
13672     {
13673     case BUILT_IN_SPRINTF_CHK:
13674     case BUILT_IN_VSPRINTF_CHK:
13675       ret = gimple_fold_builtin_sprintf_chk (stmt, fcode);
13676       break;
13677
13678     case BUILT_IN_SNPRINTF_CHK:
13679     case BUILT_IN_VSNPRINTF_CHK:
13680       ret = gimple_fold_builtin_snprintf_chk (stmt, NULL_TREE, fcode);
13681
13682     default:
13683       break;
13684     }
13685   if (ret)
13686     {
13687       ret = build1 (NOP_EXPR, TREE_TYPE (ret), ret);
13688       TREE_NO_WARNING (ret) = 1;
13689       return ret;
13690     }
13691   return NULL_TREE;
13692 }
13693
13694 /* A wrapper function for builtin folding that prevents warnings for
13695    "statement without effect" and the like, caused by removing the
13696    call node earlier than the warning is generated.  */
13697
13698 tree
13699 fold_call_stmt (gimple stmt, bool ignore)
13700 {
13701   tree ret = NULL_TREE;
13702   tree fndecl = gimple_call_fndecl (stmt);
13703   location_t loc = gimple_location (stmt);
13704   if (fndecl
13705       && TREE_CODE (fndecl) == FUNCTION_DECL
13706       && DECL_BUILT_IN (fndecl)
13707       && !gimple_call_va_arg_pack_p (stmt))
13708     {
13709       int nargs = gimple_call_num_args (stmt);
13710       tree *args = (nargs > 0
13711                     ? gimple_call_arg_ptr (stmt, 0)
13712                     : &error_mark_node);
13713
13714       if (avoid_folding_inline_builtin (fndecl))
13715         return NULL_TREE;
13716       if (DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_MD)
13717         {
13718           return targetm.fold_builtin (fndecl, nargs, args, ignore);
13719         }
13720       else
13721         {
13722           if (nargs <= MAX_ARGS_TO_FOLD_BUILTIN)
13723             ret = fold_builtin_n (loc, fndecl, args, nargs, ignore);
13724           if (!ret)
13725             ret = gimple_fold_builtin_varargs (fndecl, stmt, ignore);
13726           if (ret)
13727             {
13728               /* Propagate location information from original call to
13729                  expansion of builtin.  Otherwise things like
13730                  maybe_emit_chk_warning, that operate on the expansion
13731                  of a builtin, will use the wrong location information.  */
13732               if (gimple_has_location (stmt))
13733                 {
13734                   tree realret = ret;
13735                   if (TREE_CODE (ret) == NOP_EXPR)
13736                     realret = TREE_OPERAND (ret, 0);
13737                   if (CAN_HAVE_LOCATION_P (realret)
13738                       && !EXPR_HAS_LOCATION (realret))
13739                     SET_EXPR_LOCATION (realret, loc);
13740                   return realret;
13741                 }
13742               return ret;
13743             }
13744         }
13745     }
13746   return NULL_TREE;
13747 }
13748
13749 /* Look up the function in built_in_decls that corresponds to DECL
13750    and set ASMSPEC as its user assembler name.  DECL must be a
13751    function decl that declares a builtin.  */
13752
13753 void
13754 set_builtin_user_assembler_name (tree decl, const char *asmspec)
13755 {
13756   tree builtin;
13757   gcc_assert (TREE_CODE (decl) == FUNCTION_DECL
13758               && DECL_BUILT_IN_CLASS (decl) == BUILT_IN_NORMAL
13759               && asmspec != 0);
13760
13761   builtin = built_in_decls [DECL_FUNCTION_CODE (decl)];
13762   set_user_assembler_name (builtin, asmspec);
13763   switch (DECL_FUNCTION_CODE (decl))
13764     {
13765     case BUILT_IN_MEMCPY:
13766       init_block_move_fn (asmspec);
13767       memcpy_libfunc = set_user_assembler_libfunc ("memcpy", asmspec);
13768       break;
13769     case BUILT_IN_MEMSET:
13770       init_block_clear_fn (asmspec);
13771       memset_libfunc = set_user_assembler_libfunc ("memset", asmspec);
13772       break;
13773     case BUILT_IN_MEMMOVE:
13774       memmove_libfunc = set_user_assembler_libfunc ("memmove", asmspec);
13775       break;
13776     case BUILT_IN_MEMCMP:
13777       memcmp_libfunc = set_user_assembler_libfunc ("memcmp", asmspec);
13778       break;
13779     case BUILT_IN_ABORT:
13780       abort_libfunc = set_user_assembler_libfunc ("abort", asmspec);
13781       break;
13782     case BUILT_IN_FFS:
13783       if (INT_TYPE_SIZE < BITS_PER_WORD)
13784         {
13785           set_user_assembler_libfunc ("ffs", asmspec);
13786           set_optab_libfunc (ffs_optab, mode_for_size (INT_TYPE_SIZE,
13787                                                        MODE_INT, 0), "ffs");
13788         }
13789       break;
13790     default:
13791       break;
13792     }
13793 }
13794
13795 /* Return true if DECL is a builtin that expands to a constant or similarly
13796    simple code.  */
13797 bool
13798 is_simple_builtin (tree decl)
13799 {
13800   if (decl && DECL_BUILT_IN_CLASS (decl) == BUILT_IN_NORMAL)
13801     switch (DECL_FUNCTION_CODE (decl))
13802       {
13803         /* Builtins that expand to constants.  */
13804       case BUILT_IN_CONSTANT_P:
13805       case BUILT_IN_EXPECT:
13806       case BUILT_IN_OBJECT_SIZE:
13807       case BUILT_IN_UNREACHABLE:
13808         /* Simple register moves or loads from stack.  */
13809       case BUILT_IN_RETURN_ADDRESS:
13810       case BUILT_IN_EXTRACT_RETURN_ADDR:
13811       case BUILT_IN_FROB_RETURN_ADDR:
13812       case BUILT_IN_RETURN:
13813       case BUILT_IN_AGGREGATE_INCOMING_ADDRESS:
13814       case BUILT_IN_FRAME_ADDRESS:
13815       case BUILT_IN_VA_END:
13816       case BUILT_IN_STACK_SAVE:
13817       case BUILT_IN_STACK_RESTORE:
13818         /* Exception state returns or moves registers around.  */
13819       case BUILT_IN_EH_FILTER:
13820       case BUILT_IN_EH_POINTER:
13821       case BUILT_IN_EH_COPY_VALUES:
13822         return true;
13823
13824       default:
13825         return false;
13826       }
13827
13828   return false;
13829 }
13830
13831 /* Return true if DECL is a builtin that is not expensive, i.e., they are
13832    most probably expanded inline into reasonably simple code.  This is a
13833    superset of is_simple_builtin.  */
13834 bool
13835 is_inexpensive_builtin (tree decl)
13836 {
13837   if (!decl)
13838     return false;
13839   else if (DECL_BUILT_IN_CLASS (decl) == BUILT_IN_MD)
13840     return true;
13841   else if (DECL_BUILT_IN_CLASS (decl) == BUILT_IN_NORMAL)
13842     switch (DECL_FUNCTION_CODE (decl))
13843       {
13844       case BUILT_IN_ABS:
13845       case BUILT_IN_ALLOCA:
13846       case BUILT_IN_BSWAP32:
13847       case BUILT_IN_BSWAP64:
13848       case BUILT_IN_CLZ:
13849       case BUILT_IN_CLZIMAX:
13850       case BUILT_IN_CLZL:
13851       case BUILT_IN_CLZLL:
13852       case BUILT_IN_CTZ:
13853       case BUILT_IN_CTZIMAX:
13854       case BUILT_IN_CTZL:
13855       case BUILT_IN_CTZLL:
13856       case BUILT_IN_FFS:
13857       case BUILT_IN_FFSIMAX:
13858       case BUILT_IN_FFSL:
13859       case BUILT_IN_FFSLL:
13860       case BUILT_IN_IMAXABS:
13861       case BUILT_IN_FINITE:
13862       case BUILT_IN_FINITEF:
13863       case BUILT_IN_FINITEL:
13864       case BUILT_IN_FINITED32:
13865       case BUILT_IN_FINITED64:
13866       case BUILT_IN_FINITED128:
13867       case BUILT_IN_FPCLASSIFY:
13868       case BUILT_IN_ISFINITE:
13869       case BUILT_IN_ISINF_SIGN:
13870       case BUILT_IN_ISINF:
13871       case BUILT_IN_ISINFF:
13872       case BUILT_IN_ISINFL:
13873       case BUILT_IN_ISINFD32:
13874       case BUILT_IN_ISINFD64:
13875       case BUILT_IN_ISINFD128:
13876       case BUILT_IN_ISNAN:
13877       case BUILT_IN_ISNANF:
13878       case BUILT_IN_ISNANL:
13879       case BUILT_IN_ISNAND32:
13880       case BUILT_IN_ISNAND64:
13881       case BUILT_IN_ISNAND128:
13882       case BUILT_IN_ISNORMAL:
13883       case BUILT_IN_ISGREATER:
13884       case BUILT_IN_ISGREATEREQUAL:
13885       case BUILT_IN_ISLESS:
13886       case BUILT_IN_ISLESSEQUAL:
13887       case BUILT_IN_ISLESSGREATER:
13888       case BUILT_IN_ISUNORDERED:
13889       case BUILT_IN_VA_ARG_PACK:
13890       case BUILT_IN_VA_ARG_PACK_LEN:
13891       case BUILT_IN_VA_COPY:
13892       case BUILT_IN_TRAP:
13893       case BUILT_IN_SAVEREGS:
13894       case BUILT_IN_POPCOUNTL:
13895       case BUILT_IN_POPCOUNTLL:
13896       case BUILT_IN_POPCOUNTIMAX:
13897       case BUILT_IN_POPCOUNT:
13898       case BUILT_IN_PARITYL:
13899       case BUILT_IN_PARITYLL:
13900       case BUILT_IN_PARITYIMAX:
13901       case BUILT_IN_PARITY:
13902       case BUILT_IN_LABS:
13903       case BUILT_IN_LLABS:
13904       case BUILT_IN_PREFETCH:
13905         return true;
13906
13907       default:
13908         return is_simple_builtin (decl);
13909       }
13910
13911   return false;
13912 }