OSDN Git Service

* c-common.h (c_tree_chain_next): New static inline function.
[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, 2011
4    Free Software Foundation, Inc.
5
6 This file is part of GCC.
7
8 GCC is free software; you can redistribute it and/or modify it under
9 the terms of the GNU General Public License as published by the Free
10 Software Foundation; either version 3, or (at your option) any later
11 version.
12
13 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
14 WARRANTY; without even the implied warranty of MERCHANTABILITY or
15 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
16 for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with GCC; see the file COPYING3.  If not see
20 <http://www.gnu.org/licenses/>.  */
21
22 #include "config.h"
23 #include "system.h"
24 #include "coretypes.h"
25 #include "tm.h"
26 #include "machmode.h"
27 #include "rtl.h"
28 #include "tree.h"
29 #include "realmpfr.h"
30 #include "gimple.h"
31 #include "flags.h"
32 #include "regs.h"
33 #include "hard-reg-set.h"
34 #include "except.h"
35 #include "function.h"
36 #include "insn-config.h"
37 #include "expr.h"
38 #include "optabs.h"
39 #include "libfuncs.h"
40 #include "recog.h"
41 #include "output.h"
42 #include "typeclass.h"
43 #include "predict.h"
44 #include "tm_p.h"
45 #include "target.h"
46 #include "langhooks.h"
47 #include "basic-block.h"
48 #include "tree-mudflap.h"
49 #include "tree-flow.h"
50 #include "value-prof.h"
51 #include "diagnostic-core.h"
52 #include "builtins.h"
53
54
55 #ifndef PAD_VARARGS_DOWN
56 #define PAD_VARARGS_DOWN BYTES_BIG_ENDIAN
57 #endif
58 static tree do_mpc_arg1 (tree, tree, int (*)(mpc_ptr, mpc_srcptr, mpc_rnd_t));
59
60 struct target_builtins default_target_builtins;
61 #if SWITCHABLE_TARGET
62 struct target_builtins *this_target_builtins = &default_target_builtins;
63 #endif
64
65 /* Define the names of the builtin function types and codes.  */
66 const char *const built_in_class_names[4]
67   = {"NOT_BUILT_IN", "BUILT_IN_FRONTEND", "BUILT_IN_MD", "BUILT_IN_NORMAL"};
68
69 #define DEF_BUILTIN(X, N, C, T, LT, B, F, NA, AT, IM, COND) #X,
70 const char * built_in_names[(int) END_BUILTINS] =
71 {
72 #include "builtins.def"
73 };
74 #undef DEF_BUILTIN
75
76 /* Setup an array of _DECL trees, make sure each element is
77    initialized to NULL_TREE.  */
78 tree built_in_decls[(int) END_BUILTINS];
79 /* Declarations used when constructing the builtin implicitly in the compiler.
80    It may be NULL_TREE when this is invalid (for instance runtime is not
81    required to implement the function call in all cases).  */
82 tree implicit_built_in_decls[(int) END_BUILTINS];
83
84 static const char *c_getstr (tree);
85 static rtx c_readstr (const char *, enum machine_mode);
86 static int target_char_cast (tree, char *);
87 static rtx get_memory_rtx (tree, tree);
88 static int apply_args_size (void);
89 static int apply_result_size (void);
90 #if defined (HAVE_untyped_call) || defined (HAVE_untyped_return)
91 static rtx result_vector (int, rtx);
92 #endif
93 static void expand_builtin_update_setjmp_buf (rtx);
94 static void expand_builtin_prefetch (tree);
95 static rtx expand_builtin_apply_args (void);
96 static rtx expand_builtin_apply_args_1 (void);
97 static rtx expand_builtin_apply (rtx, rtx, rtx);
98 static void expand_builtin_return (rtx);
99 static enum type_class type_to_class (tree);
100 static rtx expand_builtin_classify_type (tree);
101 static void expand_errno_check (tree, rtx);
102 static rtx expand_builtin_mathfn (tree, rtx, rtx);
103 static rtx expand_builtin_mathfn_2 (tree, rtx, rtx);
104 static rtx expand_builtin_mathfn_3 (tree, rtx, rtx);
105 static rtx expand_builtin_mathfn_ternary (tree, rtx, rtx);
106 static rtx expand_builtin_interclass_mathfn (tree, rtx);
107 static rtx expand_builtin_sincos (tree);
108 static rtx expand_builtin_cexpi (tree, rtx);
109 static rtx expand_builtin_int_roundingfn (tree, rtx);
110 static rtx expand_builtin_int_roundingfn_2 (tree, rtx);
111 static rtx expand_builtin_next_arg (void);
112 static rtx expand_builtin_va_start (tree);
113 static rtx expand_builtin_va_end (tree);
114 static rtx expand_builtin_va_copy (tree);
115 static rtx expand_builtin_memcmp (tree, rtx, enum machine_mode);
116 static rtx expand_builtin_strcmp (tree, rtx);
117 static rtx expand_builtin_strncmp (tree, rtx, enum machine_mode);
118 static rtx builtin_memcpy_read_str (void *, HOST_WIDE_INT, enum machine_mode);
119 static rtx expand_builtin_memcpy (tree, rtx);
120 static rtx expand_builtin_mempcpy (tree, rtx, enum machine_mode);
121 static rtx expand_builtin_mempcpy_args (tree, tree, tree, rtx,
122                                         enum machine_mode, int);
123 static rtx expand_builtin_strcpy (tree, rtx);
124 static rtx expand_builtin_strcpy_args (tree, tree, rtx);
125 static rtx expand_builtin_stpcpy (tree, rtx, enum machine_mode);
126 static rtx expand_builtin_strncpy (tree, rtx);
127 static rtx builtin_memset_gen_str (void *, HOST_WIDE_INT, enum machine_mode);
128 static rtx expand_builtin_memset (tree, rtx, enum machine_mode);
129 static rtx expand_builtin_memset_args (tree, tree, tree, rtx, enum machine_mode, tree);
130 static rtx expand_builtin_bzero (tree);
131 static rtx expand_builtin_strlen (tree, rtx, enum machine_mode);
132 static rtx expand_builtin_alloca (tree, bool);
133 static rtx expand_builtin_unop (enum machine_mode, tree, rtx, rtx, optab);
134 static rtx expand_builtin_frame_address (tree, tree);
135 static tree stabilize_va_list_loc (location_t, tree, int);
136 static rtx expand_builtin_expect (tree, rtx);
137 static tree fold_builtin_constant_p (tree);
138 static tree fold_builtin_expect (location_t, tree, tree);
139 static tree fold_builtin_classify_type (tree);
140 static tree fold_builtin_strlen (location_t, tree, tree);
141 static tree fold_builtin_inf (location_t, tree, int);
142 static tree fold_builtin_nan (tree, tree, int);
143 static tree rewrite_call_expr (location_t, tree, int, tree, int, ...);
144 static bool validate_arg (const_tree, enum tree_code code);
145 static bool integer_valued_real_p (tree);
146 static tree fold_trunc_transparent_mathfn (location_t, tree, tree);
147 static bool readonly_data_expr (tree);
148 static rtx expand_builtin_fabs (tree, rtx, rtx);
149 static rtx expand_builtin_signbit (tree, rtx);
150 static tree fold_builtin_sqrt (location_t, tree, tree);
151 static tree fold_builtin_cbrt (location_t, tree, tree);
152 static tree fold_builtin_pow (location_t, tree, tree, tree, tree);
153 static tree fold_builtin_powi (location_t, tree, tree, tree, tree);
154 static tree fold_builtin_cos (location_t, tree, tree, tree);
155 static tree fold_builtin_cosh (location_t, tree, tree, tree);
156 static tree fold_builtin_tan (tree, tree);
157 static tree fold_builtin_trunc (location_t, tree, tree);
158 static tree fold_builtin_floor (location_t, tree, tree);
159 static tree fold_builtin_ceil (location_t, tree, tree);
160 static tree fold_builtin_round (location_t, tree, tree);
161 static tree fold_builtin_int_roundingfn (location_t, tree, tree);
162 static tree fold_builtin_bitop (tree, tree);
163 static tree fold_builtin_memory_op (location_t, tree, tree, tree, tree, bool, int);
164 static tree fold_builtin_strchr (location_t, tree, tree, tree);
165 static tree fold_builtin_memchr (location_t, tree, tree, tree, tree);
166 static tree fold_builtin_memcmp (location_t, tree, tree, tree);
167 static tree fold_builtin_strcmp (location_t, tree, tree);
168 static tree fold_builtin_strncmp (location_t, tree, tree, tree);
169 static tree fold_builtin_signbit (location_t, tree, tree);
170 static tree fold_builtin_copysign (location_t, tree, tree, tree, tree);
171 static tree fold_builtin_isascii (location_t, tree);
172 static tree fold_builtin_toascii (location_t, tree);
173 static tree fold_builtin_isdigit (location_t, tree);
174 static tree fold_builtin_fabs (location_t, tree, tree);
175 static tree fold_builtin_abs (location_t, tree, tree);
176 static tree fold_builtin_unordered_cmp (location_t, tree, tree, tree, enum tree_code,
177                                         enum tree_code);
178 static tree fold_builtin_n (location_t, tree, tree *, int, bool);
179 static tree fold_builtin_0 (location_t, tree, bool);
180 static tree fold_builtin_1 (location_t, tree, tree, bool);
181 static tree fold_builtin_2 (location_t, tree, tree, tree, bool);
182 static tree fold_builtin_3 (location_t, tree, tree, tree, tree, bool);
183 static tree fold_builtin_4 (location_t, tree, tree, tree, tree, tree, bool);
184 static tree fold_builtin_varargs (location_t, tree, tree, bool);
185
186 static tree fold_builtin_strpbrk (location_t, tree, tree, tree);
187 static tree fold_builtin_strstr (location_t, tree, tree, tree);
188 static tree fold_builtin_strrchr (location_t, tree, tree, tree);
189 static tree fold_builtin_strcat (location_t, tree, tree);
190 static tree fold_builtin_strncat (location_t, tree, tree, tree);
191 static tree fold_builtin_strspn (location_t, tree, tree);
192 static tree fold_builtin_strcspn (location_t, tree, tree);
193 static tree fold_builtin_sprintf (location_t, tree, tree, tree, int);
194 static tree fold_builtin_snprintf (location_t, tree, tree, tree, tree, int);
195
196 static rtx expand_builtin_object_size (tree);
197 static rtx expand_builtin_memory_chk (tree, rtx, enum machine_mode,
198                                       enum built_in_function);
199 static void maybe_emit_chk_warning (tree, enum built_in_function);
200 static void maybe_emit_sprintf_chk_warning (tree, enum built_in_function);
201 static void maybe_emit_free_warning (tree);
202 static tree fold_builtin_object_size (tree, tree);
203 static tree fold_builtin_strcat_chk (location_t, tree, tree, tree, tree);
204 static tree fold_builtin_strncat_chk (location_t, tree, tree, tree, tree, tree);
205 static tree fold_builtin_sprintf_chk (location_t, tree, enum built_in_function);
206 static tree fold_builtin_printf (location_t, tree, tree, tree, bool, enum built_in_function);
207 static tree fold_builtin_fprintf (location_t, tree, tree, tree, tree, bool,
208                                   enum built_in_function);
209 static bool init_target_chars (void);
210
211 static unsigned HOST_WIDE_INT target_newline;
212 static unsigned HOST_WIDE_INT target_percent;
213 static unsigned HOST_WIDE_INT target_c;
214 static unsigned HOST_WIDE_INT target_s;
215 static char target_percent_c[3];
216 static char target_percent_s[3];
217 static char target_percent_s_newline[4];
218 static tree do_mpfr_arg1 (tree, tree, int (*)(mpfr_ptr, mpfr_srcptr, mp_rnd_t),
219                           const REAL_VALUE_TYPE *, const REAL_VALUE_TYPE *, bool);
220 static tree do_mpfr_arg2 (tree, tree, tree,
221                           int (*)(mpfr_ptr, mpfr_srcptr, mpfr_srcptr, mp_rnd_t));
222 static tree do_mpfr_arg3 (tree, tree, tree, tree,
223                           int (*)(mpfr_ptr, mpfr_srcptr, mpfr_srcptr, mpfr_srcptr, mp_rnd_t));
224 static tree do_mpfr_sincos (tree, tree, tree);
225 static tree do_mpfr_bessel_n (tree, tree, tree,
226                               int (*)(mpfr_ptr, long, mpfr_srcptr, mp_rnd_t),
227                               const REAL_VALUE_TYPE *, bool);
228 static tree do_mpfr_remquo (tree, tree, tree);
229 static tree do_mpfr_lgamma_r (tree, tree, tree);
230
231 /* Return true if NAME starts with __builtin_ or __sync_.  */
232
233 bool
234 is_builtin_name (const char *name)
235 {
236   if (strncmp (name, "__builtin_", 10) == 0)
237     return true;
238   if (strncmp (name, "__sync_", 7) == 0)
239     return true;
240   return false;
241 }
242
243
244 /* Return true if DECL is a function symbol representing a built-in.  */
245
246 bool
247 is_builtin_fn (tree decl)
248 {
249   return TREE_CODE (decl) == FUNCTION_DECL && DECL_BUILT_IN (decl);
250 }
251
252
253 /* Return true if NODE should be considered for inline expansion regardless
254    of the optimization level.  This means whenever a function is invoked with
255    its "internal" name, which normally contains the prefix "__builtin".  */
256
257 static bool
258 called_as_built_in (tree node)
259 {
260   /* Note that we must use DECL_NAME, not DECL_ASSEMBLER_NAME_SET_P since
261      we want the name used to call the function, not the name it
262      will have. */
263   const char *name = IDENTIFIER_POINTER (DECL_NAME (node));
264   return is_builtin_name (name);
265 }
266
267 /* Return the alignment in bits of EXP, an object.
268    Don't return more than MAX_ALIGN no matter what.  */
269
270 unsigned int
271 get_object_alignment_1 (tree exp, unsigned HOST_WIDE_INT *bitposp)
272 {
273   HOST_WIDE_INT bitsize, bitpos;
274   tree offset;
275   enum machine_mode mode;
276   int unsignedp, volatilep;
277   unsigned int align, inner;
278
279   /* Get the innermost object and the constant (bitpos) and possibly
280      variable (offset) offset of the access.  */
281   exp = get_inner_reference (exp, &bitsize, &bitpos, &offset,
282                              &mode, &unsignedp, &volatilep, true);
283
284   /* Extract alignment information from the innermost object and
285      possibly adjust bitpos and offset.  */
286   if (TREE_CODE (exp) == CONST_DECL)
287     exp = DECL_INITIAL (exp);
288   if (DECL_P (exp)
289       && TREE_CODE (exp) != LABEL_DECL)
290     align = DECL_ALIGN (exp);
291   else if (CONSTANT_CLASS_P (exp))
292     {
293       align = TYPE_ALIGN (TREE_TYPE (exp));
294 #ifdef CONSTANT_ALIGNMENT
295       align = (unsigned)CONSTANT_ALIGNMENT (exp, align);
296 #endif
297     }
298   else if (TREE_CODE (exp) == VIEW_CONVERT_EXPR)
299     align = TYPE_ALIGN (TREE_TYPE (exp));
300   else if (TREE_CODE (exp) == INDIRECT_REF)
301     align = TYPE_ALIGN (TREE_TYPE (exp));
302   else if (TREE_CODE (exp) == MEM_REF)
303     {
304       tree addr = TREE_OPERAND (exp, 0);
305       struct ptr_info_def *pi;
306       if (TREE_CODE (addr) == BIT_AND_EXPR
307           && TREE_CODE (TREE_OPERAND (addr, 1)) == INTEGER_CST)
308         {
309           align = (TREE_INT_CST_LOW (TREE_OPERAND (addr, 1))
310                     & -TREE_INT_CST_LOW (TREE_OPERAND (addr, 1)));
311           align *= BITS_PER_UNIT;
312           addr = TREE_OPERAND (addr, 0);
313         }
314       else
315         align = BITS_PER_UNIT;
316       if (TREE_CODE (addr) == SSA_NAME
317           && (pi = SSA_NAME_PTR_INFO (addr)))
318         {
319           bitpos += (pi->misalign * BITS_PER_UNIT) & ~(align - 1);
320           align = MAX (pi->align * BITS_PER_UNIT, align);
321         }
322       else if (TREE_CODE (addr) == ADDR_EXPR)
323         align = MAX (align, get_object_alignment (TREE_OPERAND (addr, 0), ~0U));
324       bitpos += mem_ref_offset (exp).low * BITS_PER_UNIT;
325     }
326   else if (TREE_CODE (exp) == TARGET_MEM_REF)
327     {
328       struct ptr_info_def *pi;
329       tree addr = TMR_BASE (exp);
330       if (TREE_CODE (addr) == BIT_AND_EXPR
331           && TREE_CODE (TREE_OPERAND (addr, 1)) == INTEGER_CST)
332         {
333           align = (TREE_INT_CST_LOW (TREE_OPERAND (addr, 1))
334                    & -TREE_INT_CST_LOW (TREE_OPERAND (addr, 1)));
335           align *= BITS_PER_UNIT;
336           addr = TREE_OPERAND (addr, 0);
337         }
338       else
339         align = BITS_PER_UNIT;
340       if (TREE_CODE (addr) == SSA_NAME
341           && (pi = SSA_NAME_PTR_INFO (addr)))
342         {
343           bitpos += (pi->misalign * BITS_PER_UNIT) & ~(align - 1);
344           align = MAX (pi->align * BITS_PER_UNIT, align);
345         }
346       else if (TREE_CODE (addr) == ADDR_EXPR)
347         align = MAX (align, get_object_alignment (TREE_OPERAND (addr, 0), ~0U));
348       if (TMR_OFFSET (exp))
349         bitpos += TREE_INT_CST_LOW (TMR_OFFSET (exp)) * BITS_PER_UNIT;
350       if (TMR_INDEX (exp) && TMR_STEP (exp))
351         {
352           unsigned HOST_WIDE_INT step = TREE_INT_CST_LOW (TMR_STEP (exp));
353           align = MIN (align, (step & -step) * BITS_PER_UNIT);
354         }
355       else if (TMR_INDEX (exp))
356         align = BITS_PER_UNIT;
357       if (TMR_INDEX2 (exp))
358         align = BITS_PER_UNIT;
359     }
360   else
361     align = BITS_PER_UNIT;
362
363   /* If there is a non-constant offset part extract the maximum
364      alignment that can prevail.  */
365   inner = ~0U;
366   while (offset)
367     {
368       tree next_offset;
369
370       if (TREE_CODE (offset) == PLUS_EXPR)
371         {
372           next_offset = TREE_OPERAND (offset, 0);
373           offset = TREE_OPERAND (offset, 1);
374         }
375       else
376         next_offset = NULL;
377       if (host_integerp (offset, 1))
378         {
379           /* Any overflow in calculating offset_bits won't change
380              the alignment.  */
381           unsigned offset_bits
382             = ((unsigned) tree_low_cst (offset, 1) * BITS_PER_UNIT);
383
384           if (offset_bits)
385             inner = MIN (inner, (offset_bits & -offset_bits));
386         }
387       else if (TREE_CODE (offset) == MULT_EXPR
388                && host_integerp (TREE_OPERAND (offset, 1), 1))
389         {
390           /* Any overflow in calculating offset_factor won't change
391              the alignment.  */
392           unsigned offset_factor
393             = ((unsigned) tree_low_cst (TREE_OPERAND (offset, 1), 1)
394                * BITS_PER_UNIT);
395
396           if (offset_factor)
397             inner = MIN (inner, (offset_factor & -offset_factor));
398         }
399       else
400         {
401           inner = MIN (inner, BITS_PER_UNIT);
402           break;
403         }
404       offset = next_offset;
405     }
406
407   /* Alignment is innermost object alignment adjusted by the constant
408      and non-constant offset parts.  */
409   align = MIN (align, inner);
410   bitpos = bitpos & (align - 1);
411
412   *bitposp = bitpos;
413   return align;
414 }
415
416 /* Return the alignment in bits of EXP, an object.
417    Don't return more than MAX_ALIGN no matter what.  */
418
419 unsigned int
420 get_object_alignment (tree exp, unsigned int max_align)
421 {
422   unsigned HOST_WIDE_INT bitpos = 0;
423   unsigned int align;
424
425   align = get_object_alignment_1 (exp, &bitpos);
426
427   /* align and bitpos now specify known low bits of the pointer.
428      ptr & (align - 1) == bitpos.  */
429
430   if (bitpos != 0)
431     align = (bitpos & -bitpos);
432
433   return MIN (align, max_align);
434 }
435
436 /* Returns true iff we can trust that alignment information has been
437    calculated properly.  */
438
439 bool
440 can_trust_pointer_alignment (void)
441 {
442   /* We rely on TER to compute accurate alignment information.  */
443   return (optimize && flag_tree_ter);
444 }
445
446 /* Return the alignment in bits of EXP, a pointer valued expression.
447    But don't return more than MAX_ALIGN no matter what.
448    The alignment returned is, by default, the alignment of the thing that
449    EXP points to.  If it is not a POINTER_TYPE, 0 is returned.
450
451    Otherwise, look at the expression to see if we can do better, i.e., if the
452    expression is actually pointing at an object whose alignment is tighter.  */
453
454 unsigned int
455 get_pointer_alignment (tree exp, unsigned int max_align)
456 {
457   STRIP_NOPS (exp);
458
459   if (TREE_CODE (exp) == ADDR_EXPR)
460     return get_object_alignment (TREE_OPERAND (exp, 0), max_align);
461   else if (TREE_CODE (exp) == SSA_NAME
462            && POINTER_TYPE_P (TREE_TYPE (exp)))
463     {
464       struct ptr_info_def *pi = SSA_NAME_PTR_INFO (exp);
465       unsigned align;
466       if (!pi)
467         return BITS_PER_UNIT;
468       if (pi->misalign != 0)
469         align = (pi->misalign & -pi->misalign);
470       else
471         align = pi->align;
472       return MIN (max_align, align * BITS_PER_UNIT);
473     }
474
475   return POINTER_TYPE_P (TREE_TYPE (exp)) ? BITS_PER_UNIT : 0;
476 }
477
478 /* Compute the length of a C string.  TREE_STRING_LENGTH is not the right
479    way, because it could contain a zero byte in the middle.
480    TREE_STRING_LENGTH is the size of the character array, not the string.
481
482    ONLY_VALUE should be nonzero if the result is not going to be emitted
483    into the instruction stream and zero if it is going to be expanded.
484    E.g. with i++ ? "foo" : "bar", if ONLY_VALUE is nonzero, constant 3
485    is returned, otherwise NULL, since
486    len = c_strlen (src, 1); if (len) expand_expr (len, ...); would not
487    evaluate the side-effects.
488
489    The value returned is of type `ssizetype'.
490
491    Unfortunately, string_constant can't access the values of const char
492    arrays with initializers, so neither can we do so here.  */
493
494 tree
495 c_strlen (tree src, int only_value)
496 {
497   tree offset_node;
498   HOST_WIDE_INT offset;
499   int max;
500   const char *ptr;
501   location_t loc;
502
503   STRIP_NOPS (src);
504   if (TREE_CODE (src) == COND_EXPR
505       && (only_value || !TREE_SIDE_EFFECTS (TREE_OPERAND (src, 0))))
506     {
507       tree len1, len2;
508
509       len1 = c_strlen (TREE_OPERAND (src, 1), only_value);
510       len2 = c_strlen (TREE_OPERAND (src, 2), only_value);
511       if (tree_int_cst_equal (len1, len2))
512         return len1;
513     }
514
515   if (TREE_CODE (src) == COMPOUND_EXPR
516       && (only_value || !TREE_SIDE_EFFECTS (TREE_OPERAND (src, 0))))
517     return c_strlen (TREE_OPERAND (src, 1), only_value);
518
519   loc = EXPR_LOC_OR_HERE (src);
520
521   src = string_constant (src, &offset_node);
522   if (src == 0)
523     return NULL_TREE;
524
525   max = TREE_STRING_LENGTH (src) - 1;
526   ptr = TREE_STRING_POINTER (src);
527
528   if (offset_node && TREE_CODE (offset_node) != INTEGER_CST)
529     {
530       /* If the string has an internal zero byte (e.g., "foo\0bar"), we can't
531          compute the offset to the following null if we don't know where to
532          start searching for it.  */
533       int i;
534
535       for (i = 0; i < max; i++)
536         if (ptr[i] == 0)
537           return NULL_TREE;
538
539       /* We don't know the starting offset, but we do know that the string
540          has no internal zero bytes.  We can assume that the offset falls
541          within the bounds of the string; otherwise, the programmer deserves
542          what he gets.  Subtract the offset from the length of the string,
543          and return that.  This would perhaps not be valid if we were dealing
544          with named arrays in addition to literal string constants.  */
545
546       return size_diffop_loc (loc, size_int (max), offset_node);
547     }
548
549   /* We have a known offset into the string.  Start searching there for
550      a null character if we can represent it as a single HOST_WIDE_INT.  */
551   if (offset_node == 0)
552     offset = 0;
553   else if (! host_integerp (offset_node, 0))
554     offset = -1;
555   else
556     offset = tree_low_cst (offset_node, 0);
557
558   /* If the offset is known to be out of bounds, warn, and call strlen at
559      runtime.  */
560   if (offset < 0 || offset > max)
561     {
562      /* Suppress multiple warnings for propagated constant strings.  */
563       if (! TREE_NO_WARNING (src))
564         {
565           warning_at (loc, 0, "offset outside bounds of constant string");
566           TREE_NO_WARNING (src) = 1;
567         }
568       return NULL_TREE;
569     }
570
571   /* Use strlen to search for the first zero byte.  Since any strings
572      constructed with build_string will have nulls appended, we win even
573      if we get handed something like (char[4])"abcd".
574
575      Since OFFSET is our starting index into the string, no further
576      calculation is needed.  */
577   return ssize_int (strlen (ptr + offset));
578 }
579
580 /* Return a char pointer for a C string if it is a string constant
581    or sum of string constant and integer constant.  */
582
583 static const char *
584 c_getstr (tree src)
585 {
586   tree offset_node;
587
588   src = string_constant (src, &offset_node);
589   if (src == 0)
590     return 0;
591
592   if (offset_node == 0)
593     return TREE_STRING_POINTER (src);
594   else if (!host_integerp (offset_node, 1)
595            || compare_tree_int (offset_node, TREE_STRING_LENGTH (src) - 1) > 0)
596     return 0;
597
598   return TREE_STRING_POINTER (src) + tree_low_cst (offset_node, 1);
599 }
600
601 /* Return a CONST_INT or CONST_DOUBLE corresponding to target reading
602    GET_MODE_BITSIZE (MODE) bits from string constant STR.  */
603
604 static rtx
605 c_readstr (const char *str, enum machine_mode mode)
606 {
607   HOST_WIDE_INT c[2];
608   HOST_WIDE_INT ch;
609   unsigned int i, j;
610
611   gcc_assert (GET_MODE_CLASS (mode) == MODE_INT);
612
613   c[0] = 0;
614   c[1] = 0;
615   ch = 1;
616   for (i = 0; i < GET_MODE_SIZE (mode); i++)
617     {
618       j = i;
619       if (WORDS_BIG_ENDIAN)
620         j = GET_MODE_SIZE (mode) - i - 1;
621       if (BYTES_BIG_ENDIAN != WORDS_BIG_ENDIAN
622           && GET_MODE_SIZE (mode) >= UNITS_PER_WORD)
623         j = j + UNITS_PER_WORD - 2 * (j % UNITS_PER_WORD) - 1;
624       j *= BITS_PER_UNIT;
625       gcc_assert (j < 2 * HOST_BITS_PER_WIDE_INT);
626
627       if (ch)
628         ch = (unsigned char) str[i];
629       c[j / HOST_BITS_PER_WIDE_INT] |= ch << (j % HOST_BITS_PER_WIDE_INT);
630     }
631   return immed_double_const (c[0], c[1], mode);
632 }
633
634 /* Cast a target constant CST to target CHAR and if that value fits into
635    host char type, return zero and put that value into variable pointed to by
636    P.  */
637
638 static int
639 target_char_cast (tree cst, char *p)
640 {
641   unsigned HOST_WIDE_INT val, hostval;
642
643   if (TREE_CODE (cst) != INTEGER_CST
644       || CHAR_TYPE_SIZE > HOST_BITS_PER_WIDE_INT)
645     return 1;
646
647   val = TREE_INT_CST_LOW (cst);
648   if (CHAR_TYPE_SIZE < HOST_BITS_PER_WIDE_INT)
649     val &= (((unsigned HOST_WIDE_INT) 1) << CHAR_TYPE_SIZE) - 1;
650
651   hostval = val;
652   if (HOST_BITS_PER_CHAR < HOST_BITS_PER_WIDE_INT)
653     hostval &= (((unsigned HOST_WIDE_INT) 1) << HOST_BITS_PER_CHAR) - 1;
654
655   if (val != hostval)
656     return 1;
657
658   *p = hostval;
659   return 0;
660 }
661
662 /* Similar to save_expr, but assumes that arbitrary code is not executed
663    in between the multiple evaluations.  In particular, we assume that a
664    non-addressable local variable will not be modified.  */
665
666 static tree
667 builtin_save_expr (tree exp)
668 {
669   if (TREE_CODE (exp) == SSA_NAME
670       || (TREE_ADDRESSABLE (exp) == 0
671           && (TREE_CODE (exp) == PARM_DECL
672               || (TREE_CODE (exp) == VAR_DECL && !TREE_STATIC (exp)))))
673     return exp;
674
675   return save_expr (exp);
676 }
677
678 /* Given TEM, a pointer to a stack frame, follow the dynamic chain COUNT
679    times to get the address of either a higher stack frame, or a return
680    address located within it (depending on FNDECL_CODE).  */
681
682 static rtx
683 expand_builtin_return_addr (enum built_in_function fndecl_code, int count)
684 {
685   int i;
686
687 #ifdef INITIAL_FRAME_ADDRESS_RTX
688   rtx tem = INITIAL_FRAME_ADDRESS_RTX;
689 #else
690   rtx tem;
691
692   /* For a zero count with __builtin_return_address, we don't care what
693      frame address we return, because target-specific definitions will
694      override us.  Therefore frame pointer elimination is OK, and using
695      the soft frame pointer is OK.
696
697      For a nonzero count, or a zero count with __builtin_frame_address,
698      we require a stable offset from the current frame pointer to the
699      previous one, so we must use the hard frame pointer, and
700      we must disable frame pointer elimination.  */
701   if (count == 0 && fndecl_code == BUILT_IN_RETURN_ADDRESS)
702     tem = frame_pointer_rtx;
703   else
704     {
705       tem = hard_frame_pointer_rtx;
706
707       /* Tell reload not to eliminate the frame pointer.  */
708       crtl->accesses_prior_frames = 1;
709     }
710 #endif
711
712   /* Some machines need special handling before we can access
713      arbitrary frames.  For example, on the SPARC, we must first flush
714      all register windows to the stack.  */
715 #ifdef SETUP_FRAME_ADDRESSES
716   if (count > 0)
717     SETUP_FRAME_ADDRESSES ();
718 #endif
719
720   /* On the SPARC, the return address is not in the frame, it is in a
721      register.  There is no way to access it off of the current frame
722      pointer, but it can be accessed off the previous frame pointer by
723      reading the value from the register window save area.  */
724 #ifdef RETURN_ADDR_IN_PREVIOUS_FRAME
725   if (fndecl_code == BUILT_IN_RETURN_ADDRESS)
726     count--;
727 #endif
728
729   /* Scan back COUNT frames to the specified frame.  */
730   for (i = 0; i < count; i++)
731     {
732       /* Assume the dynamic chain pointer is in the word that the
733          frame address points to, unless otherwise specified.  */
734 #ifdef DYNAMIC_CHAIN_ADDRESS
735       tem = DYNAMIC_CHAIN_ADDRESS (tem);
736 #endif
737       tem = memory_address (Pmode, tem);
738       tem = gen_frame_mem (Pmode, tem);
739       tem = copy_to_reg (tem);
740     }
741
742   /* For __builtin_frame_address, return what we've got.  But, on
743      the SPARC for example, we may have to add a bias.  */
744   if (fndecl_code == BUILT_IN_FRAME_ADDRESS)
745 #ifdef FRAME_ADDR_RTX
746     return FRAME_ADDR_RTX (tem);
747 #else
748     return tem;
749 #endif
750
751   /* For __builtin_return_address, get the return address from that frame.  */
752 #ifdef RETURN_ADDR_RTX
753   tem = RETURN_ADDR_RTX (count, tem);
754 #else
755   tem = memory_address (Pmode,
756                         plus_constant (tem, GET_MODE_SIZE (Pmode)));
757   tem = gen_frame_mem (Pmode, tem);
758 #endif
759   return tem;
760 }
761
762 /* Alias set used for setjmp buffer.  */
763 static alias_set_type setjmp_alias_set = -1;
764
765 /* Construct the leading half of a __builtin_setjmp call.  Control will
766    return to RECEIVER_LABEL.  This is also called directly by the SJLJ
767    exception handling code.  */
768
769 void
770 expand_builtin_setjmp_setup (rtx buf_addr, rtx receiver_label)
771 {
772   enum machine_mode sa_mode = STACK_SAVEAREA_MODE (SAVE_NONLOCAL);
773   rtx stack_save;
774   rtx mem;
775
776   if (setjmp_alias_set == -1)
777     setjmp_alias_set = new_alias_set ();
778
779   buf_addr = convert_memory_address (Pmode, buf_addr);
780
781   buf_addr = force_reg (Pmode, force_operand (buf_addr, NULL_RTX));
782
783   /* We store the frame pointer and the address of receiver_label in
784      the buffer and use the rest of it for the stack save area, which
785      is machine-dependent.  */
786
787   mem = gen_rtx_MEM (Pmode, buf_addr);
788   set_mem_alias_set (mem, setjmp_alias_set);
789   emit_move_insn (mem, targetm.builtin_setjmp_frame_value ());
790
791   mem = gen_rtx_MEM (Pmode, plus_constant (buf_addr, GET_MODE_SIZE (Pmode))),
792   set_mem_alias_set (mem, setjmp_alias_set);
793
794   emit_move_insn (validize_mem (mem),
795                   force_reg (Pmode, gen_rtx_LABEL_REF (Pmode, receiver_label)));
796
797   stack_save = gen_rtx_MEM (sa_mode,
798                             plus_constant (buf_addr,
799                                            2 * GET_MODE_SIZE (Pmode)));
800   set_mem_alias_set (stack_save, setjmp_alias_set);
801   emit_stack_save (SAVE_NONLOCAL, &stack_save);
802
803   /* If there is further processing to do, do it.  */
804 #ifdef HAVE_builtin_setjmp_setup
805   if (HAVE_builtin_setjmp_setup)
806     emit_insn (gen_builtin_setjmp_setup (buf_addr));
807 #endif
808
809   /* We have a nonlocal label.   */
810   cfun->has_nonlocal_label = 1;
811 }
812
813 /* Construct the trailing part of a __builtin_setjmp call.  This is
814    also called directly by the SJLJ exception handling code.  */
815
816 void
817 expand_builtin_setjmp_receiver (rtx receiver_label ATTRIBUTE_UNUSED)
818 {
819   rtx chain;
820
821   /* Clobber the FP when we get here, so we have to make sure it's
822      marked as used by this function.  */
823   emit_use (hard_frame_pointer_rtx);
824
825   /* Mark the static chain as clobbered here so life information
826      doesn't get messed up for it.  */
827   chain = targetm.calls.static_chain (current_function_decl, true);
828   if (chain && REG_P (chain))
829     emit_clobber (chain);
830
831   /* Now put in the code to restore the frame pointer, and argument
832      pointer, if needed.  */
833 #ifdef HAVE_nonlocal_goto
834   if (! HAVE_nonlocal_goto)
835 #endif
836     {
837       emit_move_insn (virtual_stack_vars_rtx, hard_frame_pointer_rtx);
838       /* This might change the hard frame pointer in ways that aren't
839          apparent to early optimization passes, so force a clobber.  */
840       emit_clobber (hard_frame_pointer_rtx);
841     }
842
843 #if !HARD_FRAME_POINTER_IS_ARG_POINTER
844   if (fixed_regs[ARG_POINTER_REGNUM])
845     {
846 #ifdef ELIMINABLE_REGS
847       size_t i;
848       static const struct elims {const int from, to;} elim_regs[] = ELIMINABLE_REGS;
849
850       for (i = 0; i < ARRAY_SIZE (elim_regs); i++)
851         if (elim_regs[i].from == ARG_POINTER_REGNUM
852             && elim_regs[i].to == HARD_FRAME_POINTER_REGNUM)
853           break;
854
855       if (i == ARRAY_SIZE (elim_regs))
856 #endif
857         {
858           /* Now restore our arg pointer from the address at which it
859              was saved in our stack frame.  */
860           emit_move_insn (crtl->args.internal_arg_pointer,
861                           copy_to_reg (get_arg_pointer_save_area ()));
862         }
863     }
864 #endif
865
866 #ifdef HAVE_builtin_setjmp_receiver
867   if (HAVE_builtin_setjmp_receiver)
868     emit_insn (gen_builtin_setjmp_receiver (receiver_label));
869   else
870 #endif
871 #ifdef HAVE_nonlocal_goto_receiver
872     if (HAVE_nonlocal_goto_receiver)
873       emit_insn (gen_nonlocal_goto_receiver ());
874     else
875 #endif
876       { /* Nothing */ }
877
878   /* We must not allow the code we just generated to be reordered by
879      scheduling.  Specifically, the update of the frame pointer must
880      happen immediately, not later.  */
881   emit_insn (gen_blockage ());
882 }
883
884 /* __builtin_longjmp is passed a pointer to an array of five words (not
885    all will be used on all machines).  It operates similarly to the C
886    library function of the same name, but is more efficient.  Much of
887    the code below is copied from the handling of non-local gotos.  */
888
889 static void
890 expand_builtin_longjmp (rtx buf_addr, rtx value)
891 {
892   rtx fp, lab, stack, insn, last;
893   enum machine_mode sa_mode = STACK_SAVEAREA_MODE (SAVE_NONLOCAL);
894
895   /* DRAP is needed for stack realign if longjmp is expanded to current
896      function  */
897   if (SUPPORTS_STACK_ALIGNMENT)
898     crtl->need_drap = true;
899
900   if (setjmp_alias_set == -1)
901     setjmp_alias_set = new_alias_set ();
902
903   buf_addr = convert_memory_address (Pmode, buf_addr);
904
905   buf_addr = force_reg (Pmode, buf_addr);
906
907   /* We require that the user must pass a second argument of 1, because
908      that is what builtin_setjmp will return.  */
909   gcc_assert (value == const1_rtx);
910
911   last = get_last_insn ();
912 #ifdef HAVE_builtin_longjmp
913   if (HAVE_builtin_longjmp)
914     emit_insn (gen_builtin_longjmp (buf_addr));
915   else
916 #endif
917     {
918       fp = gen_rtx_MEM (Pmode, buf_addr);
919       lab = gen_rtx_MEM (Pmode, plus_constant (buf_addr,
920                                                GET_MODE_SIZE (Pmode)));
921
922       stack = gen_rtx_MEM (sa_mode, plus_constant (buf_addr,
923                                                    2 * GET_MODE_SIZE (Pmode)));
924       set_mem_alias_set (fp, setjmp_alias_set);
925       set_mem_alias_set (lab, setjmp_alias_set);
926       set_mem_alias_set (stack, setjmp_alias_set);
927
928       /* Pick up FP, label, and SP from the block and jump.  This code is
929          from expand_goto in stmt.c; see there for detailed comments.  */
930 #ifdef HAVE_nonlocal_goto
931       if (HAVE_nonlocal_goto)
932         /* We have to pass a value to the nonlocal_goto pattern that will
933            get copied into the static_chain pointer, but it does not matter
934            what that value is, because builtin_setjmp does not use it.  */
935         emit_insn (gen_nonlocal_goto (value, lab, stack, fp));
936       else
937 #endif
938         {
939           lab = copy_to_reg (lab);
940
941           emit_clobber (gen_rtx_MEM (BLKmode, gen_rtx_SCRATCH (VOIDmode)));
942           emit_clobber (gen_rtx_MEM (BLKmode, hard_frame_pointer_rtx));
943
944           emit_move_insn (hard_frame_pointer_rtx, fp);
945           emit_stack_restore (SAVE_NONLOCAL, stack);
946
947           emit_use (hard_frame_pointer_rtx);
948           emit_use (stack_pointer_rtx);
949           emit_indirect_jump (lab);
950         }
951     }
952
953   /* Search backwards and mark the jump insn as a non-local goto.
954      Note that this precludes the use of __builtin_longjmp to a
955      __builtin_setjmp target in the same function.  However, we've
956      already cautioned the user that these functions are for
957      internal exception handling use only.  */
958   for (insn = get_last_insn (); insn; insn = PREV_INSN (insn))
959     {
960       gcc_assert (insn != last);
961
962       if (JUMP_P (insn))
963         {
964           add_reg_note (insn, REG_NON_LOCAL_GOTO, const0_rtx);
965           break;
966         }
967       else if (CALL_P (insn))
968         break;
969     }
970 }
971
972 /* Expand a call to __builtin_nonlocal_goto.  We're passed the target label
973    and the address of the save area.  */
974
975 static rtx
976 expand_builtin_nonlocal_goto (tree exp)
977 {
978   tree t_label, t_save_area;
979   rtx r_label, r_save_area, r_fp, r_sp, insn;
980
981   if (!validate_arglist (exp, POINTER_TYPE, POINTER_TYPE, VOID_TYPE))
982     return NULL_RTX;
983
984   t_label = CALL_EXPR_ARG (exp, 0);
985   t_save_area = CALL_EXPR_ARG (exp, 1);
986
987   r_label = expand_normal (t_label);
988   r_label = convert_memory_address (Pmode, r_label);
989   r_save_area = expand_normal (t_save_area);
990   r_save_area = convert_memory_address (Pmode, r_save_area);
991   /* Copy the address of the save location to a register just in case it was
992      based on the frame pointer.   */
993   r_save_area = copy_to_reg (r_save_area);
994   r_fp = gen_rtx_MEM (Pmode, r_save_area);
995   r_sp = gen_rtx_MEM (STACK_SAVEAREA_MODE (SAVE_NONLOCAL),
996                       plus_constant (r_save_area, GET_MODE_SIZE (Pmode)));
997
998   crtl->has_nonlocal_goto = 1;
999
1000 #ifdef HAVE_nonlocal_goto
1001   /* ??? We no longer need to pass the static chain value, afaik.  */
1002   if (HAVE_nonlocal_goto)
1003     emit_insn (gen_nonlocal_goto (const0_rtx, r_label, r_sp, r_fp));
1004   else
1005 #endif
1006     {
1007       r_label = copy_to_reg (r_label);
1008
1009       emit_clobber (gen_rtx_MEM (BLKmode, gen_rtx_SCRATCH (VOIDmode)));
1010       emit_clobber (gen_rtx_MEM (BLKmode, hard_frame_pointer_rtx));
1011
1012       /* Restore frame pointer for containing function.  */
1013       emit_move_insn (hard_frame_pointer_rtx, r_fp);
1014       emit_stack_restore (SAVE_NONLOCAL, r_sp);
1015
1016       /* USE of hard_frame_pointer_rtx added for consistency;
1017          not clear if really needed.  */
1018       emit_use (hard_frame_pointer_rtx);
1019       emit_use (stack_pointer_rtx);
1020
1021       /* If the architecture is using a GP register, we must
1022          conservatively assume that the target function makes use of it.
1023          The prologue of functions with nonlocal gotos must therefore
1024          initialize the GP register to the appropriate value, and we
1025          must then make sure that this value is live at the point
1026          of the jump.  (Note that this doesn't necessarily apply
1027          to targets with a nonlocal_goto pattern; they are free
1028          to implement it in their own way.  Note also that this is
1029          a no-op if the GP register is a global invariant.)  */
1030       if ((unsigned) PIC_OFFSET_TABLE_REGNUM != INVALID_REGNUM
1031           && fixed_regs[PIC_OFFSET_TABLE_REGNUM])
1032         emit_use (pic_offset_table_rtx);
1033
1034       emit_indirect_jump (r_label);
1035     }
1036
1037   /* Search backwards to the jump insn and mark it as a
1038      non-local goto.  */
1039   for (insn = get_last_insn (); insn; insn = PREV_INSN (insn))
1040     {
1041       if (JUMP_P (insn))
1042         {
1043           add_reg_note (insn, REG_NON_LOCAL_GOTO, const0_rtx);
1044           break;
1045         }
1046       else if (CALL_P (insn))
1047         break;
1048     }
1049
1050   return const0_rtx;
1051 }
1052
1053 /* __builtin_update_setjmp_buf is passed a pointer to an array of five words
1054    (not all will be used on all machines) that was passed to __builtin_setjmp.
1055    It updates the stack pointer in that block to correspond to the current
1056    stack pointer.  */
1057
1058 static void
1059 expand_builtin_update_setjmp_buf (rtx buf_addr)
1060 {
1061   enum machine_mode sa_mode = STACK_SAVEAREA_MODE (SAVE_NONLOCAL);
1062   rtx stack_save
1063     = gen_rtx_MEM (sa_mode,
1064                    memory_address
1065                    (sa_mode,
1066                     plus_constant (buf_addr, 2 * GET_MODE_SIZE (Pmode))));
1067
1068   emit_stack_save (SAVE_NONLOCAL, &stack_save);
1069 }
1070
1071 /* Expand a call to __builtin_prefetch.  For a target that does not support
1072    data prefetch, evaluate the memory address argument in case it has side
1073    effects.  */
1074
1075 static void
1076 expand_builtin_prefetch (tree exp)
1077 {
1078   tree arg0, arg1, arg2;
1079   int nargs;
1080   rtx op0, op1, op2;
1081
1082   if (!validate_arglist (exp, POINTER_TYPE, 0))
1083     return;
1084
1085   arg0 = CALL_EXPR_ARG (exp, 0);
1086
1087   /* Arguments 1 and 2 are optional; argument 1 (read/write) defaults to
1088      zero (read) and argument 2 (locality) defaults to 3 (high degree of
1089      locality).  */
1090   nargs = call_expr_nargs (exp);
1091   if (nargs > 1)
1092     arg1 = CALL_EXPR_ARG (exp, 1);
1093   else
1094     arg1 = integer_zero_node;
1095   if (nargs > 2)
1096     arg2 = CALL_EXPR_ARG (exp, 2);
1097   else
1098     arg2 = integer_three_node;
1099
1100   /* Argument 0 is an address.  */
1101   op0 = expand_expr (arg0, NULL_RTX, Pmode, EXPAND_NORMAL);
1102
1103   /* Argument 1 (read/write flag) must be a compile-time constant int.  */
1104   if (TREE_CODE (arg1) != INTEGER_CST)
1105     {
1106       error ("second argument to %<__builtin_prefetch%> must be a constant");
1107       arg1 = integer_zero_node;
1108     }
1109   op1 = expand_normal (arg1);
1110   /* Argument 1 must be either zero or one.  */
1111   if (INTVAL (op1) != 0 && INTVAL (op1) != 1)
1112     {
1113       warning (0, "invalid second argument to %<__builtin_prefetch%>;"
1114                " using zero");
1115       op1 = const0_rtx;
1116     }
1117
1118   /* Argument 2 (locality) must be a compile-time constant int.  */
1119   if (TREE_CODE (arg2) != INTEGER_CST)
1120     {
1121       error ("third argument to %<__builtin_prefetch%> must be a constant");
1122       arg2 = integer_zero_node;
1123     }
1124   op2 = expand_normal (arg2);
1125   /* Argument 2 must be 0, 1, 2, or 3.  */
1126   if (INTVAL (op2) < 0 || INTVAL (op2) > 3)
1127     {
1128       warning (0, "invalid third argument to %<__builtin_prefetch%>; using zero");
1129       op2 = const0_rtx;
1130     }
1131
1132 #ifdef HAVE_prefetch
1133   if (HAVE_prefetch)
1134     {
1135       struct expand_operand ops[3];
1136
1137       create_address_operand (&ops[0], op0);
1138       create_integer_operand (&ops[1], INTVAL (op1));
1139       create_integer_operand (&ops[2], INTVAL (op2));
1140       if (maybe_expand_insn (CODE_FOR_prefetch, 3, ops))
1141         return;
1142     }
1143 #endif
1144
1145   /* Don't do anything with direct references to volatile memory, but
1146      generate code to handle other side effects.  */
1147   if (!MEM_P (op0) && side_effects_p (op0))
1148     emit_insn (op0);
1149 }
1150
1151 /* Get a MEM rtx for expression EXP which is the address of an operand
1152    to be used in a string instruction (cmpstrsi, movmemsi, ..).  LEN is
1153    the maximum length of the block of memory that might be accessed or
1154    NULL if unknown.  */
1155
1156 static rtx
1157 get_memory_rtx (tree exp, tree len)
1158 {
1159   tree orig_exp = exp;
1160   rtx addr, mem;
1161   HOST_WIDE_INT off;
1162
1163   /* When EXP is not resolved SAVE_EXPR, MEM_ATTRS can be still derived
1164      from its expression, for expr->a.b only <variable>.a.b is recorded.  */
1165   if (TREE_CODE (exp) == SAVE_EXPR && !SAVE_EXPR_RESOLVED_P (exp))
1166     exp = TREE_OPERAND (exp, 0);
1167
1168   addr = expand_expr (orig_exp, NULL_RTX, ptr_mode, EXPAND_NORMAL);
1169   mem = gen_rtx_MEM (BLKmode, memory_address (BLKmode, addr));
1170
1171   /* Get an expression we can use to find the attributes to assign to MEM.
1172      If it is an ADDR_EXPR, use the operand.  Otherwise, dereference it if
1173      we can.  First remove any nops.  */
1174   while (CONVERT_EXPR_P (exp)
1175          && POINTER_TYPE_P (TREE_TYPE (TREE_OPERAND (exp, 0))))
1176     exp = TREE_OPERAND (exp, 0);
1177
1178   off = 0;
1179   if (TREE_CODE (exp) == POINTER_PLUS_EXPR
1180       && TREE_CODE (TREE_OPERAND (exp, 0)) == ADDR_EXPR
1181       && host_integerp (TREE_OPERAND (exp, 1), 0)
1182       && (off = tree_low_cst (TREE_OPERAND (exp, 1), 0)) > 0)
1183     exp = TREE_OPERAND (TREE_OPERAND (exp, 0), 0);
1184   else if (TREE_CODE (exp) == ADDR_EXPR)
1185     exp = TREE_OPERAND (exp, 0);
1186   else if (POINTER_TYPE_P (TREE_TYPE (exp)))
1187     exp = build1 (INDIRECT_REF, TREE_TYPE (TREE_TYPE (exp)), exp);
1188   else
1189     exp = NULL;
1190
1191   /* Honor attributes derived from exp, except for the alias set
1192      (as builtin stringops may alias with anything) and the size
1193      (as stringops may access multiple array elements).  */
1194   if (exp)
1195     {
1196       set_mem_attributes (mem, exp, 0);
1197
1198       if (off)
1199         mem = adjust_automodify_address_nv (mem, BLKmode, NULL, off);
1200
1201       /* Allow the string and memory builtins to overflow from one
1202          field into another, see http://gcc.gnu.org/PR23561.
1203          Thus avoid COMPONENT_REFs in MEM_EXPR unless we know the whole
1204          memory accessed by the string or memory builtin will fit
1205          within the field.  */
1206       if (MEM_EXPR (mem) && TREE_CODE (MEM_EXPR (mem)) == COMPONENT_REF)
1207         {
1208           tree mem_expr = MEM_EXPR (mem);
1209           HOST_WIDE_INT offset = -1, length = -1;
1210           tree inner = exp;
1211
1212           while (TREE_CODE (inner) == ARRAY_REF
1213                  || CONVERT_EXPR_P (inner)
1214                  || TREE_CODE (inner) == VIEW_CONVERT_EXPR
1215                  || TREE_CODE (inner) == SAVE_EXPR)
1216             inner = TREE_OPERAND (inner, 0);
1217
1218           gcc_assert (TREE_CODE (inner) == COMPONENT_REF);
1219
1220           if (MEM_OFFSET (mem)
1221               && CONST_INT_P (MEM_OFFSET (mem)))
1222             offset = INTVAL (MEM_OFFSET (mem));
1223
1224           if (offset >= 0 && len && host_integerp (len, 0))
1225             length = tree_low_cst (len, 0);
1226
1227           while (TREE_CODE (inner) == COMPONENT_REF)
1228             {
1229               tree field = TREE_OPERAND (inner, 1);
1230               gcc_assert (TREE_CODE (mem_expr) == COMPONENT_REF);
1231               gcc_assert (field == TREE_OPERAND (mem_expr, 1));
1232
1233               /* Bitfields are generally not byte-addressable.  */
1234               gcc_assert (!DECL_BIT_FIELD (field)
1235                           || ((tree_low_cst (DECL_FIELD_BIT_OFFSET (field), 1)
1236                                % BITS_PER_UNIT) == 0
1237                               && host_integerp (DECL_SIZE (field), 0)
1238                               && (TREE_INT_CST_LOW (DECL_SIZE (field))
1239                                   % BITS_PER_UNIT) == 0));
1240
1241               /* If we can prove that the memory starting at XEXP (mem, 0) and
1242                  ending at XEXP (mem, 0) + LENGTH will fit into this field, we
1243                  can keep the COMPONENT_REF in MEM_EXPR.  But be careful with
1244                  fields without DECL_SIZE_UNIT like flexible array members.  */
1245               if (length >= 0
1246                   && DECL_SIZE_UNIT (field)
1247                   && host_integerp (DECL_SIZE_UNIT (field), 0))
1248                 {
1249                   HOST_WIDE_INT size
1250                     = TREE_INT_CST_LOW (DECL_SIZE_UNIT (field));
1251                   if (offset <= size
1252                       && length <= size
1253                       && offset + length <= size)
1254                     break;
1255                 }
1256
1257               if (offset >= 0
1258                   && host_integerp (DECL_FIELD_OFFSET (field), 0))
1259                 offset += TREE_INT_CST_LOW (DECL_FIELD_OFFSET (field))
1260                           + tree_low_cst (DECL_FIELD_BIT_OFFSET (field), 1)
1261                             / BITS_PER_UNIT;
1262               else
1263                 {
1264                   offset = -1;
1265                   length = -1;
1266                 }
1267
1268               mem_expr = TREE_OPERAND (mem_expr, 0);
1269               inner = TREE_OPERAND (inner, 0);
1270             }
1271
1272           if (mem_expr == NULL)
1273             offset = -1;
1274           if (mem_expr != MEM_EXPR (mem))
1275             {
1276               set_mem_expr (mem, mem_expr);
1277               set_mem_offset (mem, offset >= 0 ? GEN_INT (offset) : NULL_RTX);
1278             }
1279         }
1280       set_mem_alias_set (mem, 0);
1281       set_mem_size (mem, NULL_RTX);
1282     }
1283
1284   return mem;
1285 }
1286 \f
1287 /* Built-in functions to perform an untyped call and return.  */
1288
1289 #define apply_args_mode \
1290   (this_target_builtins->x_apply_args_mode)
1291 #define apply_result_mode \
1292   (this_target_builtins->x_apply_result_mode)
1293
1294 /* Return the size required for the block returned by __builtin_apply_args,
1295    and initialize apply_args_mode.  */
1296
1297 static int
1298 apply_args_size (void)
1299 {
1300   static int size = -1;
1301   int align;
1302   unsigned int regno;
1303   enum machine_mode mode;
1304
1305   /* The values computed by this function never change.  */
1306   if (size < 0)
1307     {
1308       /* The first value is the incoming arg-pointer.  */
1309       size = GET_MODE_SIZE (Pmode);
1310
1311       /* The second value is the structure value address unless this is
1312          passed as an "invisible" first argument.  */
1313       if (targetm.calls.struct_value_rtx (cfun ? TREE_TYPE (cfun->decl) : 0, 0))
1314         size += GET_MODE_SIZE (Pmode);
1315
1316       for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
1317         if (FUNCTION_ARG_REGNO_P (regno))
1318           {
1319             mode = targetm.calls.get_raw_arg_mode (regno);
1320
1321             gcc_assert (mode != VOIDmode);
1322
1323             align = GET_MODE_ALIGNMENT (mode) / BITS_PER_UNIT;
1324             if (size % align != 0)
1325               size = CEIL (size, align) * align;
1326             size += GET_MODE_SIZE (mode);
1327             apply_args_mode[regno] = mode;
1328           }
1329         else
1330           {
1331             apply_args_mode[regno] = VOIDmode;
1332           }
1333     }
1334   return size;
1335 }
1336
1337 /* Return the size required for the block returned by __builtin_apply,
1338    and initialize apply_result_mode.  */
1339
1340 static int
1341 apply_result_size (void)
1342 {
1343   static int size = -1;
1344   int align, regno;
1345   enum machine_mode mode;
1346
1347   /* The values computed by this function never change.  */
1348   if (size < 0)
1349     {
1350       size = 0;
1351
1352       for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
1353         if (targetm.calls.function_value_regno_p (regno))
1354           {
1355             mode = targetm.calls.get_raw_result_mode (regno);
1356
1357             gcc_assert (mode != VOIDmode);
1358
1359             align = GET_MODE_ALIGNMENT (mode) / BITS_PER_UNIT;
1360             if (size % align != 0)
1361               size = CEIL (size, align) * align;
1362             size += GET_MODE_SIZE (mode);
1363             apply_result_mode[regno] = mode;
1364           }
1365         else
1366           apply_result_mode[regno] = VOIDmode;
1367
1368       /* Allow targets that use untyped_call and untyped_return to override
1369          the size so that machine-specific information can be stored here.  */
1370 #ifdef APPLY_RESULT_SIZE
1371       size = APPLY_RESULT_SIZE;
1372 #endif
1373     }
1374   return size;
1375 }
1376
1377 #if defined (HAVE_untyped_call) || defined (HAVE_untyped_return)
1378 /* Create a vector describing the result block RESULT.  If SAVEP is true,
1379    the result block is used to save the values; otherwise it is used to
1380    restore the values.  */
1381
1382 static rtx
1383 result_vector (int savep, rtx result)
1384 {
1385   int regno, size, align, nelts;
1386   enum machine_mode mode;
1387   rtx reg, mem;
1388   rtx *savevec = XALLOCAVEC (rtx, FIRST_PSEUDO_REGISTER);
1389
1390   size = nelts = 0;
1391   for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
1392     if ((mode = apply_result_mode[regno]) != VOIDmode)
1393       {
1394         align = GET_MODE_ALIGNMENT (mode) / BITS_PER_UNIT;
1395         if (size % align != 0)
1396           size = CEIL (size, align) * align;
1397         reg = gen_rtx_REG (mode, savep ? regno : INCOMING_REGNO (regno));
1398         mem = adjust_address (result, mode, size);
1399         savevec[nelts++] = (savep
1400                             ? gen_rtx_SET (VOIDmode, mem, reg)
1401                             : gen_rtx_SET (VOIDmode, reg, mem));
1402         size += GET_MODE_SIZE (mode);
1403       }
1404   return gen_rtx_PARALLEL (VOIDmode, gen_rtvec_v (nelts, savevec));
1405 }
1406 #endif /* HAVE_untyped_call or HAVE_untyped_return */
1407
1408 /* Save the state required to perform an untyped call with the same
1409    arguments as were passed to the current function.  */
1410
1411 static rtx
1412 expand_builtin_apply_args_1 (void)
1413 {
1414   rtx registers, tem;
1415   int size, align, regno;
1416   enum machine_mode mode;
1417   rtx struct_incoming_value = targetm.calls.struct_value_rtx (cfun ? TREE_TYPE (cfun->decl) : 0, 1);
1418
1419   /* Create a block where the arg-pointer, structure value address,
1420      and argument registers can be saved.  */
1421   registers = assign_stack_local (BLKmode, apply_args_size (), -1);
1422
1423   /* Walk past the arg-pointer and structure value address.  */
1424   size = GET_MODE_SIZE (Pmode);
1425   if (targetm.calls.struct_value_rtx (cfun ? TREE_TYPE (cfun->decl) : 0, 0))
1426     size += GET_MODE_SIZE (Pmode);
1427
1428   /* Save each register used in calling a function to the block.  */
1429   for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
1430     if ((mode = apply_args_mode[regno]) != VOIDmode)
1431       {
1432         align = GET_MODE_ALIGNMENT (mode) / BITS_PER_UNIT;
1433         if (size % align != 0)
1434           size = CEIL (size, align) * align;
1435
1436         tem = gen_rtx_REG (mode, INCOMING_REGNO (regno));
1437
1438         emit_move_insn (adjust_address (registers, mode, size), tem);
1439         size += GET_MODE_SIZE (mode);
1440       }
1441
1442   /* Save the arg pointer to the block.  */
1443   tem = copy_to_reg (crtl->args.internal_arg_pointer);
1444 #ifdef STACK_GROWS_DOWNWARD
1445   /* We need the pointer as the caller actually passed them to us, not
1446      as we might have pretended they were passed.  Make sure it's a valid
1447      operand, as emit_move_insn isn't expected to handle a PLUS.  */
1448   tem
1449     = force_operand (plus_constant (tem, crtl->args.pretend_args_size),
1450                      NULL_RTX);
1451 #endif
1452   emit_move_insn (adjust_address (registers, Pmode, 0), tem);
1453
1454   size = GET_MODE_SIZE (Pmode);
1455
1456   /* Save the structure value address unless this is passed as an
1457      "invisible" first argument.  */
1458   if (struct_incoming_value)
1459     {
1460       emit_move_insn (adjust_address (registers, Pmode, size),
1461                       copy_to_reg (struct_incoming_value));
1462       size += GET_MODE_SIZE (Pmode);
1463     }
1464
1465   /* Return the address of the block.  */
1466   return copy_addr_to_reg (XEXP (registers, 0));
1467 }
1468
1469 /* __builtin_apply_args returns block of memory allocated on
1470    the stack into which is stored the arg pointer, structure
1471    value address, static chain, and all the registers that might
1472    possibly be used in performing a function call.  The code is
1473    moved to the start of the function so the incoming values are
1474    saved.  */
1475
1476 static rtx
1477 expand_builtin_apply_args (void)
1478 {
1479   /* Don't do __builtin_apply_args more than once in a function.
1480      Save the result of the first call and reuse it.  */
1481   if (apply_args_value != 0)
1482     return apply_args_value;
1483   {
1484     /* When this function is called, it means that registers must be
1485        saved on entry to this function.  So we migrate the
1486        call to the first insn of this function.  */
1487     rtx temp;
1488     rtx seq;
1489
1490     start_sequence ();
1491     temp = expand_builtin_apply_args_1 ();
1492     seq = get_insns ();
1493     end_sequence ();
1494
1495     apply_args_value = temp;
1496
1497     /* Put the insns after the NOTE that starts the function.
1498        If this is inside a start_sequence, make the outer-level insn
1499        chain current, so the code is placed at the start of the
1500        function.  If internal_arg_pointer is a non-virtual pseudo,
1501        it needs to be placed after the function that initializes
1502        that pseudo.  */
1503     push_topmost_sequence ();
1504     if (REG_P (crtl->args.internal_arg_pointer)
1505         && REGNO (crtl->args.internal_arg_pointer) > LAST_VIRTUAL_REGISTER)
1506       emit_insn_before (seq, parm_birth_insn);
1507     else
1508       emit_insn_before (seq, NEXT_INSN (entry_of_function ()));
1509     pop_topmost_sequence ();
1510     return temp;
1511   }
1512 }
1513
1514 /* Perform an untyped call and save the state required to perform an
1515    untyped return of whatever value was returned by the given function.  */
1516
1517 static rtx
1518 expand_builtin_apply (rtx function, rtx arguments, rtx argsize)
1519 {
1520   int size, align, regno;
1521   enum machine_mode mode;
1522   rtx incoming_args, result, reg, dest, src, call_insn;
1523   rtx old_stack_level = 0;
1524   rtx call_fusage = 0;
1525   rtx struct_value = targetm.calls.struct_value_rtx (cfun ? TREE_TYPE (cfun->decl) : 0, 0);
1526
1527   arguments = convert_memory_address (Pmode, arguments);
1528
1529   /* Create a block where the return registers can be saved.  */
1530   result = assign_stack_local (BLKmode, apply_result_size (), -1);
1531
1532   /* Fetch the arg pointer from the ARGUMENTS block.  */
1533   incoming_args = gen_reg_rtx (Pmode);
1534   emit_move_insn (incoming_args, gen_rtx_MEM (Pmode, arguments));
1535 #ifndef STACK_GROWS_DOWNWARD
1536   incoming_args = expand_simple_binop (Pmode, MINUS, incoming_args, argsize,
1537                                        incoming_args, 0, OPTAB_LIB_WIDEN);
1538 #endif
1539
1540   /* Push a new argument block and copy the arguments.  Do not allow
1541      the (potential) memcpy call below to interfere with our stack
1542      manipulations.  */
1543   do_pending_stack_adjust ();
1544   NO_DEFER_POP;
1545
1546   /* Save the stack with nonlocal if available.  */
1547 #ifdef HAVE_save_stack_nonlocal
1548   if (HAVE_save_stack_nonlocal)
1549     emit_stack_save (SAVE_NONLOCAL, &old_stack_level);
1550   else
1551 #endif
1552     emit_stack_save (SAVE_BLOCK, &old_stack_level);
1553
1554   /* Allocate a block of memory onto the stack and copy the memory
1555      arguments to the outgoing arguments address.  We can pass TRUE
1556      as the 4th argument because we just saved the stack pointer
1557      and will restore it right after the call.  */
1558   allocate_dynamic_stack_space (argsize, 0, BIGGEST_ALIGNMENT, true);
1559
1560   /* Set DRAP flag to true, even though allocate_dynamic_stack_space
1561      may have already set current_function_calls_alloca to true.
1562      current_function_calls_alloca won't be set if argsize is zero,
1563      so we have to guarantee need_drap is true here.  */
1564   if (SUPPORTS_STACK_ALIGNMENT)
1565     crtl->need_drap = true;
1566
1567   dest = virtual_outgoing_args_rtx;
1568 #ifndef STACK_GROWS_DOWNWARD
1569   if (CONST_INT_P (argsize))
1570     dest = plus_constant (dest, -INTVAL (argsize));
1571   else
1572     dest = gen_rtx_PLUS (Pmode, dest, negate_rtx (Pmode, argsize));
1573 #endif
1574   dest = gen_rtx_MEM (BLKmode, dest);
1575   set_mem_align (dest, PARM_BOUNDARY);
1576   src = gen_rtx_MEM (BLKmode, incoming_args);
1577   set_mem_align (src, PARM_BOUNDARY);
1578   emit_block_move (dest, src, argsize, BLOCK_OP_NORMAL);
1579
1580   /* Refer to the argument block.  */
1581   apply_args_size ();
1582   arguments = gen_rtx_MEM (BLKmode, arguments);
1583   set_mem_align (arguments, PARM_BOUNDARY);
1584
1585   /* Walk past the arg-pointer and structure value address.  */
1586   size = GET_MODE_SIZE (Pmode);
1587   if (struct_value)
1588     size += GET_MODE_SIZE (Pmode);
1589
1590   /* Restore each of the registers previously saved.  Make USE insns
1591      for each of these registers for use in making the call.  */
1592   for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
1593     if ((mode = apply_args_mode[regno]) != VOIDmode)
1594       {
1595         align = GET_MODE_ALIGNMENT (mode) / BITS_PER_UNIT;
1596         if (size % align != 0)
1597           size = CEIL (size, align) * align;
1598         reg = gen_rtx_REG (mode, regno);
1599         emit_move_insn (reg, adjust_address (arguments, mode, size));
1600         use_reg (&call_fusage, reg);
1601         size += GET_MODE_SIZE (mode);
1602       }
1603
1604   /* Restore the structure value address unless this is passed as an
1605      "invisible" first argument.  */
1606   size = GET_MODE_SIZE (Pmode);
1607   if (struct_value)
1608     {
1609       rtx value = gen_reg_rtx (Pmode);
1610       emit_move_insn (value, adjust_address (arguments, Pmode, size));
1611       emit_move_insn (struct_value, value);
1612       if (REG_P (struct_value))
1613         use_reg (&call_fusage, struct_value);
1614       size += GET_MODE_SIZE (Pmode);
1615     }
1616
1617   /* All arguments and registers used for the call are set up by now!  */
1618   function = prepare_call_address (NULL, function, NULL, &call_fusage, 0, 0);
1619
1620   /* Ensure address is valid.  SYMBOL_REF is already valid, so no need,
1621      and we don't want to load it into a register as an optimization,
1622      because prepare_call_address already did it if it should be done.  */
1623   if (GET_CODE (function) != SYMBOL_REF)
1624     function = memory_address (FUNCTION_MODE, function);
1625
1626   /* Generate the actual call instruction and save the return value.  */
1627 #ifdef HAVE_untyped_call
1628   if (HAVE_untyped_call)
1629     emit_call_insn (gen_untyped_call (gen_rtx_MEM (FUNCTION_MODE, function),
1630                                       result, result_vector (1, result)));
1631   else
1632 #endif
1633 #ifdef HAVE_call_value
1634   if (HAVE_call_value)
1635     {
1636       rtx valreg = 0;
1637
1638       /* Locate the unique return register.  It is not possible to
1639          express a call that sets more than one return register using
1640          call_value; use untyped_call for that.  In fact, untyped_call
1641          only needs to save the return registers in the given block.  */
1642       for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
1643         if ((mode = apply_result_mode[regno]) != VOIDmode)
1644           {
1645             gcc_assert (!valreg); /* HAVE_untyped_call required.  */
1646
1647             valreg = gen_rtx_REG (mode, regno);
1648           }
1649
1650       emit_call_insn (GEN_CALL_VALUE (valreg,
1651                                       gen_rtx_MEM (FUNCTION_MODE, function),
1652                                       const0_rtx, NULL_RTX, const0_rtx));
1653
1654       emit_move_insn (adjust_address (result, GET_MODE (valreg), 0), valreg);
1655     }
1656   else
1657 #endif
1658     gcc_unreachable ();
1659
1660   /* Find the CALL insn we just emitted, and attach the register usage
1661      information.  */
1662   call_insn = last_call_insn ();
1663   add_function_usage_to (call_insn, call_fusage);
1664
1665   /* Restore the stack.  */
1666 #ifdef HAVE_save_stack_nonlocal
1667   if (HAVE_save_stack_nonlocal)
1668     emit_stack_restore (SAVE_NONLOCAL, old_stack_level);
1669   else
1670 #endif
1671     emit_stack_restore (SAVE_BLOCK, old_stack_level);
1672
1673   OK_DEFER_POP;
1674
1675   /* Return the address of the result block.  */
1676   result = copy_addr_to_reg (XEXP (result, 0));
1677   return convert_memory_address (ptr_mode, result);
1678 }
1679
1680 /* Perform an untyped return.  */
1681
1682 static void
1683 expand_builtin_return (rtx result)
1684 {
1685   int size, align, regno;
1686   enum machine_mode mode;
1687   rtx reg;
1688   rtx call_fusage = 0;
1689
1690   result = convert_memory_address (Pmode, result);
1691
1692   apply_result_size ();
1693   result = gen_rtx_MEM (BLKmode, result);
1694
1695 #ifdef HAVE_untyped_return
1696   if (HAVE_untyped_return)
1697     {
1698       emit_jump_insn (gen_untyped_return (result, result_vector (0, result)));
1699       emit_barrier ();
1700       return;
1701     }
1702 #endif
1703
1704   /* Restore the return value and note that each value is used.  */
1705   size = 0;
1706   for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
1707     if ((mode = apply_result_mode[regno]) != VOIDmode)
1708       {
1709         align = GET_MODE_ALIGNMENT (mode) / BITS_PER_UNIT;
1710         if (size % align != 0)
1711           size = CEIL (size, align) * align;
1712         reg = gen_rtx_REG (mode, INCOMING_REGNO (regno));
1713         emit_move_insn (reg, adjust_address (result, mode, size));
1714
1715         push_to_sequence (call_fusage);
1716         emit_use (reg);
1717         call_fusage = get_insns ();
1718         end_sequence ();
1719         size += GET_MODE_SIZE (mode);
1720       }
1721
1722   /* Put the USE insns before the return.  */
1723   emit_insn (call_fusage);
1724
1725   /* Return whatever values was restored by jumping directly to the end
1726      of the function.  */
1727   expand_naked_return ();
1728 }
1729
1730 /* Used by expand_builtin_classify_type and fold_builtin_classify_type.  */
1731
1732 static enum type_class
1733 type_to_class (tree type)
1734 {
1735   switch (TREE_CODE (type))
1736     {
1737     case VOID_TYPE:        return void_type_class;
1738     case INTEGER_TYPE:     return integer_type_class;
1739     case ENUMERAL_TYPE:    return enumeral_type_class;
1740     case BOOLEAN_TYPE:     return boolean_type_class;
1741     case POINTER_TYPE:     return pointer_type_class;
1742     case REFERENCE_TYPE:   return reference_type_class;
1743     case OFFSET_TYPE:      return offset_type_class;
1744     case REAL_TYPE:        return real_type_class;
1745     case COMPLEX_TYPE:     return complex_type_class;
1746     case FUNCTION_TYPE:    return function_type_class;
1747     case METHOD_TYPE:      return method_type_class;
1748     case RECORD_TYPE:      return record_type_class;
1749     case UNION_TYPE:
1750     case QUAL_UNION_TYPE:  return union_type_class;
1751     case ARRAY_TYPE:       return (TYPE_STRING_FLAG (type)
1752                                    ? string_type_class : array_type_class);
1753     case LANG_TYPE:        return lang_type_class;
1754     default:               return no_type_class;
1755     }
1756 }
1757
1758 /* Expand a call EXP to __builtin_classify_type.  */
1759
1760 static rtx
1761 expand_builtin_classify_type (tree exp)
1762 {
1763   if (call_expr_nargs (exp))
1764     return GEN_INT (type_to_class (TREE_TYPE (CALL_EXPR_ARG (exp, 0))));
1765   return GEN_INT (no_type_class);
1766 }
1767
1768 /* This helper macro, meant to be used in mathfn_built_in below,
1769    determines which among a set of three builtin math functions is
1770    appropriate for a given type mode.  The `F' and `L' cases are
1771    automatically generated from the `double' case.  */
1772 #define CASE_MATHFN(BUILT_IN_MATHFN) \
1773   case BUILT_IN_MATHFN: case BUILT_IN_MATHFN##F: case BUILT_IN_MATHFN##L: \
1774   fcode = BUILT_IN_MATHFN; fcodef = BUILT_IN_MATHFN##F ; \
1775   fcodel = BUILT_IN_MATHFN##L ; break;
1776 /* Similar to above, but appends _R after any F/L suffix.  */
1777 #define CASE_MATHFN_REENT(BUILT_IN_MATHFN) \
1778   case BUILT_IN_MATHFN##_R: case BUILT_IN_MATHFN##F_R: case BUILT_IN_MATHFN##L_R: \
1779   fcode = BUILT_IN_MATHFN##_R; fcodef = BUILT_IN_MATHFN##F_R ; \
1780   fcodel = BUILT_IN_MATHFN##L_R ; break;
1781
1782 /* Return mathematic function equivalent to FN but operating directly
1783    on TYPE, if available.  If IMPLICIT is true find the function in
1784    implicit_built_in_decls[], otherwise use built_in_decls[].  If we
1785    can't do the conversion, return zero.  */
1786
1787 static tree
1788 mathfn_built_in_1 (tree type, enum built_in_function fn, bool implicit)
1789 {
1790   tree const *const fn_arr
1791     = implicit ? implicit_built_in_decls : built_in_decls;
1792   enum built_in_function fcode, fcodef, fcodel;
1793
1794   switch (fn)
1795     {
1796       CASE_MATHFN (BUILT_IN_ACOS)
1797       CASE_MATHFN (BUILT_IN_ACOSH)
1798       CASE_MATHFN (BUILT_IN_ASIN)
1799       CASE_MATHFN (BUILT_IN_ASINH)
1800       CASE_MATHFN (BUILT_IN_ATAN)
1801       CASE_MATHFN (BUILT_IN_ATAN2)
1802       CASE_MATHFN (BUILT_IN_ATANH)
1803       CASE_MATHFN (BUILT_IN_CBRT)
1804       CASE_MATHFN (BUILT_IN_CEIL)
1805       CASE_MATHFN (BUILT_IN_CEXPI)
1806       CASE_MATHFN (BUILT_IN_COPYSIGN)
1807       CASE_MATHFN (BUILT_IN_COS)
1808       CASE_MATHFN (BUILT_IN_COSH)
1809       CASE_MATHFN (BUILT_IN_DREM)
1810       CASE_MATHFN (BUILT_IN_ERF)
1811       CASE_MATHFN (BUILT_IN_ERFC)
1812       CASE_MATHFN (BUILT_IN_EXP)
1813       CASE_MATHFN (BUILT_IN_EXP10)
1814       CASE_MATHFN (BUILT_IN_EXP2)
1815       CASE_MATHFN (BUILT_IN_EXPM1)
1816       CASE_MATHFN (BUILT_IN_FABS)
1817       CASE_MATHFN (BUILT_IN_FDIM)
1818       CASE_MATHFN (BUILT_IN_FLOOR)
1819       CASE_MATHFN (BUILT_IN_FMA)
1820       CASE_MATHFN (BUILT_IN_FMAX)
1821       CASE_MATHFN (BUILT_IN_FMIN)
1822       CASE_MATHFN (BUILT_IN_FMOD)
1823       CASE_MATHFN (BUILT_IN_FREXP)
1824       CASE_MATHFN (BUILT_IN_GAMMA)
1825       CASE_MATHFN_REENT (BUILT_IN_GAMMA) /* GAMMA_R */
1826       CASE_MATHFN (BUILT_IN_HUGE_VAL)
1827       CASE_MATHFN (BUILT_IN_HYPOT)
1828       CASE_MATHFN (BUILT_IN_ILOGB)
1829       CASE_MATHFN (BUILT_IN_INF)
1830       CASE_MATHFN (BUILT_IN_ISINF)
1831       CASE_MATHFN (BUILT_IN_J0)
1832       CASE_MATHFN (BUILT_IN_J1)
1833       CASE_MATHFN (BUILT_IN_JN)
1834       CASE_MATHFN (BUILT_IN_LCEIL)
1835       CASE_MATHFN (BUILT_IN_LDEXP)
1836       CASE_MATHFN (BUILT_IN_LFLOOR)
1837       CASE_MATHFN (BUILT_IN_LGAMMA)
1838       CASE_MATHFN_REENT (BUILT_IN_LGAMMA) /* LGAMMA_R */
1839       CASE_MATHFN (BUILT_IN_LLCEIL)
1840       CASE_MATHFN (BUILT_IN_LLFLOOR)
1841       CASE_MATHFN (BUILT_IN_LLRINT)
1842       CASE_MATHFN (BUILT_IN_LLROUND)
1843       CASE_MATHFN (BUILT_IN_LOG)
1844       CASE_MATHFN (BUILT_IN_LOG10)
1845       CASE_MATHFN (BUILT_IN_LOG1P)
1846       CASE_MATHFN (BUILT_IN_LOG2)
1847       CASE_MATHFN (BUILT_IN_LOGB)
1848       CASE_MATHFN (BUILT_IN_LRINT)
1849       CASE_MATHFN (BUILT_IN_LROUND)
1850       CASE_MATHFN (BUILT_IN_MODF)
1851       CASE_MATHFN (BUILT_IN_NAN)
1852       CASE_MATHFN (BUILT_IN_NANS)
1853       CASE_MATHFN (BUILT_IN_NEARBYINT)
1854       CASE_MATHFN (BUILT_IN_NEXTAFTER)
1855       CASE_MATHFN (BUILT_IN_NEXTTOWARD)
1856       CASE_MATHFN (BUILT_IN_POW)
1857       CASE_MATHFN (BUILT_IN_POWI)
1858       CASE_MATHFN (BUILT_IN_POW10)
1859       CASE_MATHFN (BUILT_IN_REMAINDER)
1860       CASE_MATHFN (BUILT_IN_REMQUO)
1861       CASE_MATHFN (BUILT_IN_RINT)
1862       CASE_MATHFN (BUILT_IN_ROUND)
1863       CASE_MATHFN (BUILT_IN_SCALB)
1864       CASE_MATHFN (BUILT_IN_SCALBLN)
1865       CASE_MATHFN (BUILT_IN_SCALBN)
1866       CASE_MATHFN (BUILT_IN_SIGNBIT)
1867       CASE_MATHFN (BUILT_IN_SIGNIFICAND)
1868       CASE_MATHFN (BUILT_IN_SIN)
1869       CASE_MATHFN (BUILT_IN_SINCOS)
1870       CASE_MATHFN (BUILT_IN_SINH)
1871       CASE_MATHFN (BUILT_IN_SQRT)
1872       CASE_MATHFN (BUILT_IN_TAN)
1873       CASE_MATHFN (BUILT_IN_TANH)
1874       CASE_MATHFN (BUILT_IN_TGAMMA)
1875       CASE_MATHFN (BUILT_IN_TRUNC)
1876       CASE_MATHFN (BUILT_IN_Y0)
1877       CASE_MATHFN (BUILT_IN_Y1)
1878       CASE_MATHFN (BUILT_IN_YN)
1879
1880       default:
1881         return NULL_TREE;
1882       }
1883
1884   if (TYPE_MAIN_VARIANT (type) == double_type_node)
1885     return fn_arr[fcode];
1886   else if (TYPE_MAIN_VARIANT (type) == float_type_node)
1887     return fn_arr[fcodef];
1888   else if (TYPE_MAIN_VARIANT (type) == long_double_type_node)
1889     return fn_arr[fcodel];
1890   else
1891     return NULL_TREE;
1892 }
1893
1894 /* Like mathfn_built_in_1(), but always use the implicit array.  */
1895
1896 tree
1897 mathfn_built_in (tree type, enum built_in_function fn)
1898 {
1899   return mathfn_built_in_1 (type, fn, /*implicit=*/ 1);
1900 }
1901
1902 /* If errno must be maintained, expand the RTL to check if the result,
1903    TARGET, of a built-in function call, EXP, is NaN, and if so set
1904    errno to EDOM.  */
1905
1906 static void
1907 expand_errno_check (tree exp, rtx target)
1908 {
1909   rtx lab = gen_label_rtx ();
1910
1911   /* Test the result; if it is NaN, set errno=EDOM because
1912      the argument was not in the domain.  */
1913   do_compare_rtx_and_jump (target, target, EQ, 0, GET_MODE (target),
1914                            NULL_RTX, NULL_RTX, lab,
1915                            /* The jump is very likely.  */
1916                            REG_BR_PROB_BASE - (REG_BR_PROB_BASE / 2000 - 1));
1917
1918 #ifdef TARGET_EDOM
1919   /* If this built-in doesn't throw an exception, set errno directly.  */
1920   if (TREE_NOTHROW (TREE_OPERAND (CALL_EXPR_FN (exp), 0)))
1921     {
1922 #ifdef GEN_ERRNO_RTX
1923       rtx errno_rtx = GEN_ERRNO_RTX;
1924 #else
1925       rtx errno_rtx
1926           = gen_rtx_MEM (word_mode, gen_rtx_SYMBOL_REF (Pmode, "errno"));
1927 #endif
1928       emit_move_insn (errno_rtx, GEN_INT (TARGET_EDOM));
1929       emit_label (lab);
1930       return;
1931     }
1932 #endif
1933
1934   /* Make sure the library call isn't expanded as a tail call.  */
1935   CALL_EXPR_TAILCALL (exp) = 0;
1936
1937   /* We can't set errno=EDOM directly; let the library call do it.
1938      Pop the arguments right away in case the call gets deleted.  */
1939   NO_DEFER_POP;
1940   expand_call (exp, target, 0);
1941   OK_DEFER_POP;
1942   emit_label (lab);
1943 }
1944
1945 /* Expand a call to one of the builtin math functions (sqrt, exp, or log).
1946    Return NULL_RTX if a normal call should be emitted rather than expanding
1947    the function in-line.  EXP is the expression that is a call to the builtin
1948    function; if convenient, the result should be placed in TARGET.
1949    SUBTARGET may be used as the target for computing one of EXP's operands.  */
1950
1951 static rtx
1952 expand_builtin_mathfn (tree exp, rtx target, rtx subtarget)
1953 {
1954   optab builtin_optab;
1955   rtx op0, insns;
1956   tree fndecl = get_callee_fndecl (exp);
1957   enum machine_mode mode;
1958   bool errno_set = false;
1959   tree arg;
1960
1961   if (!validate_arglist (exp, REAL_TYPE, VOID_TYPE))
1962     return NULL_RTX;
1963
1964   arg = CALL_EXPR_ARG (exp, 0);
1965
1966   switch (DECL_FUNCTION_CODE (fndecl))
1967     {
1968     CASE_FLT_FN (BUILT_IN_SQRT):
1969       errno_set = ! tree_expr_nonnegative_p (arg);
1970       builtin_optab = sqrt_optab;
1971       break;
1972     CASE_FLT_FN (BUILT_IN_EXP):
1973       errno_set = true; builtin_optab = exp_optab; break;
1974     CASE_FLT_FN (BUILT_IN_EXP10):
1975     CASE_FLT_FN (BUILT_IN_POW10):
1976       errno_set = true; builtin_optab = exp10_optab; break;
1977     CASE_FLT_FN (BUILT_IN_EXP2):
1978       errno_set = true; builtin_optab = exp2_optab; break;
1979     CASE_FLT_FN (BUILT_IN_EXPM1):
1980       errno_set = true; builtin_optab = expm1_optab; break;
1981     CASE_FLT_FN (BUILT_IN_LOGB):
1982       errno_set = true; builtin_optab = logb_optab; break;
1983     CASE_FLT_FN (BUILT_IN_LOG):
1984       errno_set = true; builtin_optab = log_optab; break;
1985     CASE_FLT_FN (BUILT_IN_LOG10):
1986       errno_set = true; builtin_optab = log10_optab; break;
1987     CASE_FLT_FN (BUILT_IN_LOG2):
1988       errno_set = true; builtin_optab = log2_optab; break;
1989     CASE_FLT_FN (BUILT_IN_LOG1P):
1990       errno_set = true; builtin_optab = log1p_optab; break;
1991     CASE_FLT_FN (BUILT_IN_ASIN):
1992       builtin_optab = asin_optab; break;
1993     CASE_FLT_FN (BUILT_IN_ACOS):
1994       builtin_optab = acos_optab; break;
1995     CASE_FLT_FN (BUILT_IN_TAN):
1996       builtin_optab = tan_optab; break;
1997     CASE_FLT_FN (BUILT_IN_ATAN):
1998       builtin_optab = atan_optab; break;
1999     CASE_FLT_FN (BUILT_IN_FLOOR):
2000       builtin_optab = floor_optab; break;
2001     CASE_FLT_FN (BUILT_IN_CEIL):
2002       builtin_optab = ceil_optab; break;
2003     CASE_FLT_FN (BUILT_IN_TRUNC):
2004       builtin_optab = btrunc_optab; break;
2005     CASE_FLT_FN (BUILT_IN_ROUND):
2006       builtin_optab = round_optab; break;
2007     CASE_FLT_FN (BUILT_IN_NEARBYINT):
2008       builtin_optab = nearbyint_optab;
2009       if (flag_trapping_math)
2010         break;
2011       /* Else fallthrough and expand as rint.  */
2012     CASE_FLT_FN (BUILT_IN_RINT):
2013       builtin_optab = rint_optab; break;
2014     CASE_FLT_FN (BUILT_IN_SIGNIFICAND):
2015       builtin_optab = significand_optab; break;
2016     default:
2017       gcc_unreachable ();
2018     }
2019
2020   /* Make a suitable register to place result in.  */
2021   mode = TYPE_MODE (TREE_TYPE (exp));
2022
2023   if (! flag_errno_math || ! HONOR_NANS (mode))
2024     errno_set = false;
2025
2026   /* Before working hard, check whether the instruction is available.  */
2027   if (optab_handler (builtin_optab, mode) != CODE_FOR_nothing
2028       && (!errno_set || !optimize_insn_for_size_p ()))
2029     {
2030       target = gen_reg_rtx (mode);
2031
2032       /* Wrap the computation of the argument in a SAVE_EXPR, as we may
2033          need to expand the argument again.  This way, we will not perform
2034          side-effects more the once.  */
2035       CALL_EXPR_ARG (exp, 0) = arg = builtin_save_expr (arg);
2036
2037       op0 = expand_expr (arg, subtarget, VOIDmode, EXPAND_NORMAL);
2038
2039       start_sequence ();
2040
2041       /* Compute into TARGET.
2042          Set TARGET to wherever the result comes back.  */
2043       target = expand_unop (mode, builtin_optab, op0, target, 0);
2044
2045       if (target != 0)
2046         {
2047           if (errno_set)
2048             expand_errno_check (exp, target);
2049
2050           /* Output the entire sequence.  */
2051           insns = get_insns ();
2052           end_sequence ();
2053           emit_insn (insns);
2054           return target;
2055         }
2056
2057       /* If we were unable to expand via the builtin, stop the sequence
2058          (without outputting the insns) and call to the library function
2059          with the stabilized argument list.  */
2060       end_sequence ();
2061     }
2062
2063   return expand_call (exp, target, target == const0_rtx);
2064 }
2065
2066 /* Expand a call to the builtin binary math functions (pow and atan2).
2067    Return NULL_RTX if a normal call should be emitted rather than expanding the
2068    function in-line.  EXP is the expression that is a call to the builtin
2069    function; if convenient, the result should be placed in TARGET.
2070    SUBTARGET may be used as the target for computing one of EXP's
2071    operands.  */
2072
2073 static rtx
2074 expand_builtin_mathfn_2 (tree exp, rtx target, rtx subtarget)
2075 {
2076   optab builtin_optab;
2077   rtx op0, op1, insns;
2078   int op1_type = REAL_TYPE;
2079   tree fndecl = get_callee_fndecl (exp);
2080   tree arg0, arg1;
2081   enum machine_mode mode;
2082   bool errno_set = true;
2083
2084   switch (DECL_FUNCTION_CODE (fndecl))
2085     {
2086     CASE_FLT_FN (BUILT_IN_SCALBN):
2087     CASE_FLT_FN (BUILT_IN_SCALBLN):
2088     CASE_FLT_FN (BUILT_IN_LDEXP):
2089       op1_type = INTEGER_TYPE;
2090     default:
2091       break;
2092     }
2093
2094   if (!validate_arglist (exp, REAL_TYPE, op1_type, VOID_TYPE))
2095     return NULL_RTX;
2096
2097   arg0 = CALL_EXPR_ARG (exp, 0);
2098   arg1 = CALL_EXPR_ARG (exp, 1);
2099
2100   switch (DECL_FUNCTION_CODE (fndecl))
2101     {
2102     CASE_FLT_FN (BUILT_IN_POW):
2103       builtin_optab = pow_optab; break;
2104     CASE_FLT_FN (BUILT_IN_ATAN2):
2105       builtin_optab = atan2_optab; break;
2106     CASE_FLT_FN (BUILT_IN_SCALB):
2107       if (REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (exp)))->b != 2)
2108         return 0;
2109       builtin_optab = scalb_optab; break;
2110     CASE_FLT_FN (BUILT_IN_SCALBN):
2111     CASE_FLT_FN (BUILT_IN_SCALBLN):
2112       if (REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (exp)))->b != 2)
2113         return 0;
2114     /* Fall through... */
2115     CASE_FLT_FN (BUILT_IN_LDEXP):
2116       builtin_optab = ldexp_optab; break;
2117     CASE_FLT_FN (BUILT_IN_FMOD):
2118       builtin_optab = fmod_optab; break;
2119     CASE_FLT_FN (BUILT_IN_REMAINDER):
2120     CASE_FLT_FN (BUILT_IN_DREM):
2121       builtin_optab = remainder_optab; break;
2122     default:
2123       gcc_unreachable ();
2124     }
2125
2126   /* Make a suitable register to place result in.  */
2127   mode = TYPE_MODE (TREE_TYPE (exp));
2128
2129   /* Before working hard, check whether the instruction is available.  */
2130   if (optab_handler (builtin_optab, mode) == CODE_FOR_nothing)
2131     return NULL_RTX;
2132
2133   target = gen_reg_rtx (mode);
2134
2135   if (! flag_errno_math || ! HONOR_NANS (mode))
2136     errno_set = false;
2137
2138   if (errno_set && optimize_insn_for_size_p ())
2139     return 0;
2140
2141   /* Always stabilize the argument list.  */
2142   CALL_EXPR_ARG (exp, 0) = arg0 = builtin_save_expr (arg0);
2143   CALL_EXPR_ARG (exp, 1) = arg1 = builtin_save_expr (arg1);
2144
2145   op0 = expand_expr (arg0, subtarget, VOIDmode, EXPAND_NORMAL);
2146   op1 = expand_normal (arg1);
2147
2148   start_sequence ();
2149
2150   /* Compute into TARGET.
2151      Set TARGET to wherever the result comes back.  */
2152   target = expand_binop (mode, builtin_optab, op0, op1,
2153                          target, 0, OPTAB_DIRECT);
2154
2155   /* If we were unable to expand via the builtin, stop the sequence
2156      (without outputting the insns) and call to the library function
2157      with the stabilized argument list.  */
2158   if (target == 0)
2159     {
2160       end_sequence ();
2161       return expand_call (exp, target, target == const0_rtx);
2162     }
2163
2164   if (errno_set)
2165     expand_errno_check (exp, target);
2166
2167   /* Output the entire sequence.  */
2168   insns = get_insns ();
2169   end_sequence ();
2170   emit_insn (insns);
2171
2172   return target;
2173 }
2174
2175 /* Expand a call to the builtin trinary math functions (fma).
2176    Return NULL_RTX if a normal call should be emitted rather than expanding the
2177    function in-line.  EXP is the expression that is a call to the builtin
2178    function; if convenient, the result should be placed in TARGET.
2179    SUBTARGET may be used as the target for computing one of EXP's
2180    operands.  */
2181
2182 static rtx
2183 expand_builtin_mathfn_ternary (tree exp, rtx target, rtx subtarget)
2184 {
2185   optab builtin_optab;
2186   rtx op0, op1, op2, insns;
2187   tree fndecl = get_callee_fndecl (exp);
2188   tree arg0, arg1, arg2;
2189   enum machine_mode mode;
2190
2191   if (!validate_arglist (exp, REAL_TYPE, REAL_TYPE, REAL_TYPE, VOID_TYPE))
2192     return NULL_RTX;
2193
2194   arg0 = CALL_EXPR_ARG (exp, 0);
2195   arg1 = CALL_EXPR_ARG (exp, 1);
2196   arg2 = CALL_EXPR_ARG (exp, 2);
2197
2198   switch (DECL_FUNCTION_CODE (fndecl))
2199     {
2200     CASE_FLT_FN (BUILT_IN_FMA):
2201       builtin_optab = fma_optab; break;
2202     default:
2203       gcc_unreachable ();
2204     }
2205
2206   /* Make a suitable register to place result in.  */
2207   mode = TYPE_MODE (TREE_TYPE (exp));
2208
2209   /* Before working hard, check whether the instruction is available.  */
2210   if (optab_handler (builtin_optab, mode) == CODE_FOR_nothing)
2211     return NULL_RTX;
2212
2213   target = gen_reg_rtx (mode);
2214
2215   /* Always stabilize the argument list.  */
2216   CALL_EXPR_ARG (exp, 0) = arg0 = builtin_save_expr (arg0);
2217   CALL_EXPR_ARG (exp, 1) = arg1 = builtin_save_expr (arg1);
2218   CALL_EXPR_ARG (exp, 2) = arg2 = builtin_save_expr (arg2);
2219
2220   op0 = expand_expr (arg0, subtarget, VOIDmode, EXPAND_NORMAL);
2221   op1 = expand_normal (arg1);
2222   op2 = expand_normal (arg2);
2223
2224   start_sequence ();
2225
2226   /* Compute into TARGET.
2227      Set TARGET to wherever the result comes back.  */
2228   target = expand_ternary_op (mode, builtin_optab, op0, op1, op2,
2229                               target, 0);
2230
2231   /* If we were unable to expand via the builtin, stop the sequence
2232      (without outputting the insns) and call to the library function
2233      with the stabilized argument list.  */
2234   if (target == 0)
2235     {
2236       end_sequence ();
2237       return expand_call (exp, target, target == const0_rtx);
2238     }
2239
2240   /* Output the entire sequence.  */
2241   insns = get_insns ();
2242   end_sequence ();
2243   emit_insn (insns);
2244
2245   return target;
2246 }
2247
2248 /* Expand a call to the builtin sin and cos math functions.
2249    Return NULL_RTX if a normal call should be emitted rather than expanding the
2250    function in-line.  EXP is the expression that is a call to the builtin
2251    function; if convenient, the result should be placed in TARGET.
2252    SUBTARGET may be used as the target for computing one of EXP's
2253    operands.  */
2254
2255 static rtx
2256 expand_builtin_mathfn_3 (tree exp, rtx target, rtx subtarget)
2257 {
2258   optab builtin_optab;
2259   rtx op0, insns;
2260   tree fndecl = get_callee_fndecl (exp);
2261   enum machine_mode mode;
2262   tree arg;
2263
2264   if (!validate_arglist (exp, REAL_TYPE, VOID_TYPE))
2265     return NULL_RTX;
2266
2267   arg = CALL_EXPR_ARG (exp, 0);
2268
2269   switch (DECL_FUNCTION_CODE (fndecl))
2270     {
2271     CASE_FLT_FN (BUILT_IN_SIN):
2272     CASE_FLT_FN (BUILT_IN_COS):
2273       builtin_optab = sincos_optab; break;
2274     default:
2275       gcc_unreachable ();
2276     }
2277
2278   /* Make a suitable register to place result in.  */
2279   mode = TYPE_MODE (TREE_TYPE (exp));
2280
2281   /* Check if sincos insn is available, otherwise fallback
2282      to sin or cos insn.  */
2283   if (optab_handler (builtin_optab, mode) == CODE_FOR_nothing)
2284     switch (DECL_FUNCTION_CODE (fndecl))
2285       {
2286       CASE_FLT_FN (BUILT_IN_SIN):
2287         builtin_optab = sin_optab; break;
2288       CASE_FLT_FN (BUILT_IN_COS):
2289         builtin_optab = cos_optab; break;
2290       default:
2291         gcc_unreachable ();
2292       }
2293
2294   /* Before working hard, check whether the instruction is available.  */
2295   if (optab_handler (builtin_optab, mode) != CODE_FOR_nothing)
2296     {
2297       target = gen_reg_rtx (mode);
2298
2299       /* Wrap the computation of the argument in a SAVE_EXPR, as we may
2300          need to expand the argument again.  This way, we will not perform
2301          side-effects more the once.  */
2302       CALL_EXPR_ARG (exp, 0) = arg = builtin_save_expr (arg);
2303
2304       op0 = expand_expr (arg, subtarget, VOIDmode, EXPAND_NORMAL);
2305
2306       start_sequence ();
2307
2308       /* Compute into TARGET.
2309          Set TARGET to wherever the result comes back.  */
2310       if (builtin_optab == sincos_optab)
2311         {
2312           int result;
2313
2314           switch (DECL_FUNCTION_CODE (fndecl))
2315             {
2316             CASE_FLT_FN (BUILT_IN_SIN):
2317               result = expand_twoval_unop (builtin_optab, op0, 0, target, 0);
2318               break;
2319             CASE_FLT_FN (BUILT_IN_COS):
2320               result = expand_twoval_unop (builtin_optab, op0, target, 0, 0);
2321               break;
2322             default:
2323               gcc_unreachable ();
2324             }
2325           gcc_assert (result);
2326         }
2327       else
2328         {
2329           target = expand_unop (mode, builtin_optab, op0, target, 0);
2330         }
2331
2332       if (target != 0)
2333         {
2334           /* Output the entire sequence.  */
2335           insns = get_insns ();
2336           end_sequence ();
2337           emit_insn (insns);
2338           return target;
2339         }
2340
2341       /* If we were unable to expand via the builtin, stop the sequence
2342          (without outputting the insns) and call to the library function
2343          with the stabilized argument list.  */
2344       end_sequence ();
2345     }
2346
2347   target = expand_call (exp, target, target == const0_rtx);
2348
2349   return target;
2350 }
2351
2352 /* Given an interclass math builtin decl FNDECL and it's argument ARG
2353    return an RTL instruction code that implements the functionality.
2354    If that isn't possible or available return CODE_FOR_nothing.  */
2355
2356 static enum insn_code
2357 interclass_mathfn_icode (tree arg, tree fndecl)
2358 {
2359   bool errno_set = false;
2360   optab builtin_optab = 0;
2361   enum machine_mode mode;
2362
2363   switch (DECL_FUNCTION_CODE (fndecl))
2364     {
2365     CASE_FLT_FN (BUILT_IN_ILOGB):
2366       errno_set = true; builtin_optab = ilogb_optab; break;
2367     CASE_FLT_FN (BUILT_IN_ISINF):
2368       builtin_optab = isinf_optab; break;
2369     case BUILT_IN_ISNORMAL:
2370     case BUILT_IN_ISFINITE:
2371     CASE_FLT_FN (BUILT_IN_FINITE):
2372     case BUILT_IN_FINITED32:
2373     case BUILT_IN_FINITED64:
2374     case BUILT_IN_FINITED128:
2375     case BUILT_IN_ISINFD32:
2376     case BUILT_IN_ISINFD64:
2377     case BUILT_IN_ISINFD128:
2378       /* These builtins have no optabs (yet).  */
2379       break;
2380     default:
2381       gcc_unreachable ();
2382     }
2383
2384   /* There's no easy way to detect the case we need to set EDOM.  */
2385   if (flag_errno_math && errno_set)
2386     return CODE_FOR_nothing;
2387
2388   /* Optab mode depends on the mode of the input argument.  */
2389   mode = TYPE_MODE (TREE_TYPE (arg));
2390
2391   if (builtin_optab)
2392     return optab_handler (builtin_optab, mode);
2393   return CODE_FOR_nothing;
2394 }
2395
2396 /* Expand a call to one of the builtin math functions that operate on
2397    floating point argument and output an integer result (ilogb, isinf,
2398    isnan, etc).
2399    Return 0 if a normal call should be emitted rather than expanding the
2400    function in-line.  EXP is the expression that is a call to the builtin
2401    function; if convenient, the result should be placed in TARGET.  */
2402
2403 static rtx
2404 expand_builtin_interclass_mathfn (tree exp, rtx target)
2405 {
2406   enum insn_code icode = CODE_FOR_nothing;
2407   rtx op0;
2408   tree fndecl = get_callee_fndecl (exp);
2409   enum machine_mode mode;
2410   tree arg;
2411
2412   if (!validate_arglist (exp, REAL_TYPE, VOID_TYPE))
2413     return NULL_RTX;
2414
2415   arg = CALL_EXPR_ARG (exp, 0);
2416   icode = interclass_mathfn_icode (arg, fndecl);
2417   mode = TYPE_MODE (TREE_TYPE (arg));
2418
2419   if (icode != CODE_FOR_nothing)
2420     {
2421       struct expand_operand ops[1];
2422       rtx last = get_last_insn ();
2423       tree orig_arg = arg;
2424
2425       /* Wrap the computation of the argument in a SAVE_EXPR, as we may
2426          need to expand the argument again.  This way, we will not perform
2427          side-effects more the once.  */
2428       CALL_EXPR_ARG (exp, 0) = arg = builtin_save_expr (arg);
2429
2430       op0 = expand_expr (arg, NULL_RTX, VOIDmode, EXPAND_NORMAL);
2431
2432       if (mode != GET_MODE (op0))
2433         op0 = convert_to_mode (mode, op0, 0);
2434
2435       create_output_operand (&ops[0], target, TYPE_MODE (TREE_TYPE (exp)));
2436       if (maybe_legitimize_operands (icode, 0, 1, ops)
2437           && maybe_emit_unop_insn (icode, ops[0].value, op0, UNKNOWN))
2438         return ops[0].value;
2439
2440       delete_insns_since (last);
2441       CALL_EXPR_ARG (exp, 0) = orig_arg;
2442     }
2443
2444   return NULL_RTX;
2445 }
2446
2447 /* Expand a call to the builtin sincos math function.
2448    Return NULL_RTX if a normal call should be emitted rather than expanding the
2449    function in-line.  EXP is the expression that is a call to the builtin
2450    function.  */
2451
2452 static rtx
2453 expand_builtin_sincos (tree exp)
2454 {
2455   rtx op0, op1, op2, target1, target2;
2456   enum machine_mode mode;
2457   tree arg, sinp, cosp;
2458   int result;
2459   location_t loc = EXPR_LOCATION (exp);
2460   tree alias_type, alias_off;
2461
2462   if (!validate_arglist (exp, REAL_TYPE,
2463                          POINTER_TYPE, POINTER_TYPE, VOID_TYPE))
2464     return NULL_RTX;
2465
2466   arg = CALL_EXPR_ARG (exp, 0);
2467   sinp = CALL_EXPR_ARG (exp, 1);
2468   cosp = CALL_EXPR_ARG (exp, 2);
2469
2470   /* Make a suitable register to place result in.  */
2471   mode = TYPE_MODE (TREE_TYPE (arg));
2472
2473   /* Check if sincos insn is available, otherwise emit the call.  */
2474   if (optab_handler (sincos_optab, mode) == CODE_FOR_nothing)
2475     return NULL_RTX;
2476
2477   target1 = gen_reg_rtx (mode);
2478   target2 = gen_reg_rtx (mode);
2479
2480   op0 = expand_normal (arg);
2481   alias_type = build_pointer_type_for_mode (TREE_TYPE (arg), ptr_mode, true);
2482   alias_off = build_int_cst (alias_type, 0);
2483   op1 = expand_normal (fold_build2_loc (loc, MEM_REF, TREE_TYPE (arg),
2484                                         sinp, alias_off));
2485   op2 = expand_normal (fold_build2_loc (loc, MEM_REF, TREE_TYPE (arg),
2486                                         cosp, alias_off));
2487
2488   /* Compute into target1 and target2.
2489      Set TARGET to wherever the result comes back.  */
2490   result = expand_twoval_unop (sincos_optab, op0, target2, target1, 0);
2491   gcc_assert (result);
2492
2493   /* Move target1 and target2 to the memory locations indicated
2494      by op1 and op2.  */
2495   emit_move_insn (op1, target1);
2496   emit_move_insn (op2, target2);
2497
2498   return const0_rtx;
2499 }
2500
2501 /* Expand a call to the internal cexpi builtin to the sincos math function.
2502    EXP is the expression that is a call to the builtin function; if convenient,
2503    the result should be placed in TARGET.  */
2504
2505 static rtx
2506 expand_builtin_cexpi (tree exp, rtx target)
2507 {
2508   tree fndecl = get_callee_fndecl (exp);
2509   tree arg, type;
2510   enum machine_mode mode;
2511   rtx op0, op1, op2;
2512   location_t loc = EXPR_LOCATION (exp);
2513
2514   if (!validate_arglist (exp, REAL_TYPE, VOID_TYPE))
2515     return NULL_RTX;
2516
2517   arg = CALL_EXPR_ARG (exp, 0);
2518   type = TREE_TYPE (arg);
2519   mode = TYPE_MODE (TREE_TYPE (arg));
2520
2521   /* Try expanding via a sincos optab, fall back to emitting a libcall
2522      to sincos or cexp.  We are sure we have sincos or cexp because cexpi
2523      is only generated from sincos, cexp or if we have either of them.  */
2524   if (optab_handler (sincos_optab, mode) != CODE_FOR_nothing)
2525     {
2526       op1 = gen_reg_rtx (mode);
2527       op2 = gen_reg_rtx (mode);
2528
2529       op0 = expand_expr (arg, NULL_RTX, VOIDmode, EXPAND_NORMAL);
2530
2531       /* Compute into op1 and op2.  */
2532       expand_twoval_unop (sincos_optab, op0, op2, op1, 0);
2533     }
2534   else if (TARGET_HAS_SINCOS)
2535     {
2536       tree call, fn = NULL_TREE;
2537       tree top1, top2;
2538       rtx op1a, op2a;
2539
2540       if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPIF)
2541         fn = built_in_decls[BUILT_IN_SINCOSF];
2542       else if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPI)
2543         fn = built_in_decls[BUILT_IN_SINCOS];
2544       else if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPIL)
2545         fn = built_in_decls[BUILT_IN_SINCOSL];
2546       else
2547         gcc_unreachable ();
2548
2549       op1 = assign_temp (TREE_TYPE (arg), 0, 1, 1);
2550       op2 = assign_temp (TREE_TYPE (arg), 0, 1, 1);
2551       op1a = copy_to_mode_reg (Pmode, XEXP (op1, 0));
2552       op2a = copy_to_mode_reg (Pmode, XEXP (op2, 0));
2553       top1 = make_tree (build_pointer_type (TREE_TYPE (arg)), op1a);
2554       top2 = make_tree (build_pointer_type (TREE_TYPE (arg)), op2a);
2555
2556       /* Make sure not to fold the sincos call again.  */
2557       call = build1 (ADDR_EXPR, build_pointer_type (TREE_TYPE (fn)), fn);
2558       expand_normal (build_call_nary (TREE_TYPE (TREE_TYPE (fn)),
2559                                       call, 3, arg, top1, top2));
2560     }
2561   else
2562     {
2563       tree call, fn = NULL_TREE, narg;
2564       tree ctype = build_complex_type (type);
2565
2566       if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPIF)
2567         fn = built_in_decls[BUILT_IN_CEXPF];
2568       else if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPI)
2569         fn = built_in_decls[BUILT_IN_CEXP];
2570       else if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPIL)
2571         fn = built_in_decls[BUILT_IN_CEXPL];
2572       else
2573         gcc_unreachable ();
2574
2575       /* If we don't have a decl for cexp create one.  This is the
2576          friendliest fallback if the user calls __builtin_cexpi
2577          without full target C99 function support.  */
2578       if (fn == NULL_TREE)
2579         {
2580           tree fntype;
2581           const char *name = NULL;
2582
2583           if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPIF)
2584             name = "cexpf";
2585           else if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPI)
2586             name = "cexp";
2587           else if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPIL)
2588             name = "cexpl";
2589
2590           fntype = build_function_type_list (ctype, ctype, NULL_TREE);
2591           fn = build_fn_decl (name, fntype);
2592         }
2593
2594       narg = fold_build2_loc (loc, COMPLEX_EXPR, ctype,
2595                           build_real (type, dconst0), arg);
2596
2597       /* Make sure not to fold the cexp call again.  */
2598       call = build1 (ADDR_EXPR, build_pointer_type (TREE_TYPE (fn)), fn);
2599       return expand_expr (build_call_nary (ctype, call, 1, narg),
2600                           target, VOIDmode, EXPAND_NORMAL);
2601     }
2602
2603   /* Now build the proper return type.  */
2604   return expand_expr (build2 (COMPLEX_EXPR, build_complex_type (type),
2605                               make_tree (TREE_TYPE (arg), op2),
2606                               make_tree (TREE_TYPE (arg), op1)),
2607                       target, VOIDmode, EXPAND_NORMAL);
2608 }
2609
2610 /* Conveniently construct a function call expression.  FNDECL names the
2611    function to be called, N is the number of arguments, and the "..."
2612    parameters are the argument expressions.  Unlike build_call_exr
2613    this doesn't fold the call, hence it will always return a CALL_EXPR.  */
2614
2615 static tree
2616 build_call_nofold_loc (location_t loc, tree fndecl, int n, ...)
2617 {
2618   va_list ap;
2619   tree fntype = TREE_TYPE (fndecl);
2620   tree fn = build1 (ADDR_EXPR, build_pointer_type (fntype), fndecl);
2621
2622   va_start (ap, n);
2623   fn = build_call_valist (TREE_TYPE (fntype), fn, n, ap);
2624   va_end (ap);
2625   SET_EXPR_LOCATION (fn, loc);
2626   return fn;
2627 }
2628
2629 /* Expand a call to one of the builtin rounding functions gcc defines
2630    as an extension (lfloor and lceil).  As these are gcc extensions we
2631    do not need to worry about setting errno to EDOM.
2632    If expanding via optab fails, lower expression to (int)(floor(x)).
2633    EXP is the expression that is a call to the builtin function;
2634    if convenient, the result should be placed in TARGET.  */
2635
2636 static rtx
2637 expand_builtin_int_roundingfn (tree exp, rtx target)
2638 {
2639   convert_optab builtin_optab;
2640   rtx op0, insns, tmp;
2641   tree fndecl = get_callee_fndecl (exp);
2642   enum built_in_function fallback_fn;
2643   tree fallback_fndecl;
2644   enum machine_mode mode;
2645   tree arg;
2646
2647   if (!validate_arglist (exp, REAL_TYPE, VOID_TYPE))
2648     gcc_unreachable ();
2649
2650   arg = CALL_EXPR_ARG (exp, 0);
2651
2652   switch (DECL_FUNCTION_CODE (fndecl))
2653     {
2654     CASE_FLT_FN (BUILT_IN_LCEIL):
2655     CASE_FLT_FN (BUILT_IN_LLCEIL):
2656       builtin_optab = lceil_optab;
2657       fallback_fn = BUILT_IN_CEIL;
2658       break;
2659
2660     CASE_FLT_FN (BUILT_IN_LFLOOR):
2661     CASE_FLT_FN (BUILT_IN_LLFLOOR):
2662       builtin_optab = lfloor_optab;
2663       fallback_fn = BUILT_IN_FLOOR;
2664       break;
2665
2666     default:
2667       gcc_unreachable ();
2668     }
2669
2670   /* Make a suitable register to place result in.  */
2671   mode = TYPE_MODE (TREE_TYPE (exp));
2672
2673   target = gen_reg_rtx (mode);
2674
2675   /* Wrap the computation of the argument in a SAVE_EXPR, as we may
2676      need to expand the argument again.  This way, we will not perform
2677      side-effects more the once.  */
2678   CALL_EXPR_ARG (exp, 0) = arg = builtin_save_expr (arg);
2679
2680   op0 = expand_expr (arg, NULL, VOIDmode, EXPAND_NORMAL);
2681
2682   start_sequence ();
2683
2684   /* Compute into TARGET.  */
2685   if (expand_sfix_optab (target, op0, builtin_optab))
2686     {
2687       /* Output the entire sequence.  */
2688       insns = get_insns ();
2689       end_sequence ();
2690       emit_insn (insns);
2691       return target;
2692     }
2693
2694   /* If we were unable to expand via the builtin, stop the sequence
2695      (without outputting the insns).  */
2696   end_sequence ();
2697
2698   /* Fall back to floating point rounding optab.  */
2699   fallback_fndecl = mathfn_built_in (TREE_TYPE (arg), fallback_fn);
2700
2701   /* For non-C99 targets we may end up without a fallback fndecl here
2702      if the user called __builtin_lfloor directly.  In this case emit
2703      a call to the floor/ceil variants nevertheless.  This should result
2704      in the best user experience for not full C99 targets.  */
2705   if (fallback_fndecl == NULL_TREE)
2706     {
2707       tree fntype;
2708       const char *name = NULL;
2709
2710       switch (DECL_FUNCTION_CODE (fndecl))
2711         {
2712         case BUILT_IN_LCEIL:
2713         case BUILT_IN_LLCEIL:
2714           name = "ceil";
2715           break;
2716         case BUILT_IN_LCEILF:
2717         case BUILT_IN_LLCEILF:
2718           name = "ceilf";
2719           break;
2720         case BUILT_IN_LCEILL:
2721         case BUILT_IN_LLCEILL:
2722           name = "ceill";
2723           break;
2724         case BUILT_IN_LFLOOR:
2725         case BUILT_IN_LLFLOOR:
2726           name = "floor";
2727           break;
2728         case BUILT_IN_LFLOORF:
2729         case BUILT_IN_LLFLOORF:
2730           name = "floorf";
2731           break;
2732         case BUILT_IN_LFLOORL:
2733         case BUILT_IN_LLFLOORL:
2734           name = "floorl";
2735           break;
2736         default:
2737           gcc_unreachable ();
2738         }
2739
2740       fntype = build_function_type_list (TREE_TYPE (arg),
2741                                          TREE_TYPE (arg), NULL_TREE);
2742       fallback_fndecl = build_fn_decl (name, fntype);
2743     }
2744
2745   exp = build_call_nofold_loc (EXPR_LOCATION (exp), fallback_fndecl, 1, arg);
2746
2747   tmp = expand_normal (exp);
2748
2749   /* Truncate the result of floating point optab to integer
2750      via expand_fix ().  */
2751   target = gen_reg_rtx (mode);
2752   expand_fix (target, tmp, 0);
2753
2754   return target;
2755 }
2756
2757 /* Expand a call to one of the builtin math functions doing integer
2758    conversion (lrint).
2759    Return 0 if a normal call should be emitted rather than expanding the
2760    function in-line.  EXP is the expression that is a call to the builtin
2761    function; if convenient, the result should be placed in TARGET.  */
2762
2763 static rtx
2764 expand_builtin_int_roundingfn_2 (tree exp, rtx target)
2765 {
2766   convert_optab builtin_optab;
2767   rtx op0, insns;
2768   tree fndecl = get_callee_fndecl (exp);
2769   tree arg;
2770   enum machine_mode mode;
2771
2772   /* There's no easy way to detect the case we need to set EDOM.  */
2773   if (flag_errno_math)
2774     return NULL_RTX;
2775
2776   if (!validate_arglist (exp, REAL_TYPE, VOID_TYPE))
2777      gcc_unreachable ();
2778
2779   arg = CALL_EXPR_ARG (exp, 0);
2780
2781   switch (DECL_FUNCTION_CODE (fndecl))
2782     {
2783     CASE_FLT_FN (BUILT_IN_LRINT):
2784     CASE_FLT_FN (BUILT_IN_LLRINT):
2785       builtin_optab = lrint_optab; break;
2786     CASE_FLT_FN (BUILT_IN_LROUND):
2787     CASE_FLT_FN (BUILT_IN_LLROUND):
2788       builtin_optab = lround_optab; break;
2789     default:
2790       gcc_unreachable ();
2791     }
2792
2793   /* Make a suitable register to place result in.  */
2794   mode = TYPE_MODE (TREE_TYPE (exp));
2795
2796   target = gen_reg_rtx (mode);
2797
2798   /* Wrap the computation of the argument in a SAVE_EXPR, as we may
2799      need to expand the argument again.  This way, we will not perform
2800      side-effects more the once.  */
2801   CALL_EXPR_ARG (exp, 0) = arg = builtin_save_expr (arg);
2802
2803   op0 = expand_expr (arg, NULL, VOIDmode, EXPAND_NORMAL);
2804
2805   start_sequence ();
2806
2807   if (expand_sfix_optab (target, op0, builtin_optab))
2808     {
2809       /* Output the entire sequence.  */
2810       insns = get_insns ();
2811       end_sequence ();
2812       emit_insn (insns);
2813       return target;
2814     }
2815
2816   /* If we were unable to expand via the builtin, stop the sequence
2817      (without outputting the insns) and call to the library function
2818      with the stabilized argument list.  */
2819   end_sequence ();
2820
2821   target = expand_call (exp, target, target == const0_rtx);
2822
2823   return target;
2824 }
2825
2826 /* Expand a call to the powi built-in mathematical function.  Return NULL_RTX if
2827    a normal call should be emitted rather than expanding the function
2828    in-line.  EXP is the expression that is a call to the builtin
2829    function; if convenient, the result should be placed in TARGET.  */
2830
2831 static rtx
2832 expand_builtin_powi (tree exp, rtx target)
2833 {
2834   tree arg0, arg1;
2835   rtx op0, op1;
2836   enum machine_mode mode;
2837   enum machine_mode mode2;
2838
2839   if (! validate_arglist (exp, REAL_TYPE, INTEGER_TYPE, VOID_TYPE))
2840     return NULL_RTX;
2841
2842   arg0 = CALL_EXPR_ARG (exp, 0);
2843   arg1 = CALL_EXPR_ARG (exp, 1);
2844   mode = TYPE_MODE (TREE_TYPE (exp));
2845
2846   /* Emit a libcall to libgcc.  */
2847
2848   /* Mode of the 2nd argument must match that of an int.  */
2849   mode2 = mode_for_size (INT_TYPE_SIZE, MODE_INT, 0);
2850
2851   if (target == NULL_RTX)
2852     target = gen_reg_rtx (mode);
2853
2854   op0 = expand_expr (arg0, NULL_RTX, mode, EXPAND_NORMAL);
2855   if (GET_MODE (op0) != mode)
2856     op0 = convert_to_mode (mode, op0, 0);
2857   op1 = expand_expr (arg1, NULL_RTX, mode2, EXPAND_NORMAL);
2858   if (GET_MODE (op1) != mode2)
2859     op1 = convert_to_mode (mode2, op1, 0);
2860
2861   target = emit_library_call_value (optab_libfunc (powi_optab, mode),
2862                                     target, LCT_CONST, mode, 2,
2863                                     op0, mode, op1, mode2);
2864
2865   return target;
2866 }
2867
2868 /* Expand expression EXP which is a call to the strlen builtin.  Return
2869    NULL_RTX if we failed the caller should emit a normal call, otherwise
2870    try to get the result in TARGET, if convenient.  */
2871
2872 static rtx
2873 expand_builtin_strlen (tree exp, rtx target,
2874                        enum machine_mode target_mode)
2875 {
2876   if (!validate_arglist (exp, POINTER_TYPE, VOID_TYPE))
2877     return NULL_RTX;
2878   else
2879     {
2880       struct expand_operand ops[4];
2881       rtx pat;
2882       tree len;
2883       tree src = CALL_EXPR_ARG (exp, 0);
2884       rtx src_reg, before_strlen;
2885       enum machine_mode insn_mode = target_mode;
2886       enum insn_code icode = CODE_FOR_nothing;
2887       unsigned int align;
2888
2889       /* If the length can be computed at compile-time, return it.  */
2890       len = c_strlen (src, 0);
2891       if (len)
2892         return expand_expr (len, target, target_mode, EXPAND_NORMAL);
2893
2894       /* If the length can be computed at compile-time and is constant
2895          integer, but there are side-effects in src, evaluate
2896          src for side-effects, then return len.
2897          E.g. x = strlen (i++ ? "xfoo" + 1 : "bar");
2898          can be optimized into: i++; x = 3;  */
2899       len = c_strlen (src, 1);
2900       if (len && TREE_CODE (len) == INTEGER_CST)
2901         {
2902           expand_expr (src, const0_rtx, VOIDmode, EXPAND_NORMAL);
2903           return expand_expr (len, target, target_mode, EXPAND_NORMAL);
2904         }
2905
2906       align = get_pointer_alignment (src, BIGGEST_ALIGNMENT) / BITS_PER_UNIT;
2907
2908       /* If SRC is not a pointer type, don't do this operation inline.  */
2909       if (align == 0)
2910         return NULL_RTX;
2911
2912       /* Bail out if we can't compute strlen in the right mode.  */
2913       while (insn_mode != VOIDmode)
2914         {
2915           icode = optab_handler (strlen_optab, insn_mode);
2916           if (icode != CODE_FOR_nothing)
2917             break;
2918
2919           insn_mode = GET_MODE_WIDER_MODE (insn_mode);
2920         }
2921       if (insn_mode == VOIDmode)
2922         return NULL_RTX;
2923
2924       /* Make a place to hold the source address.  We will not expand
2925          the actual source until we are sure that the expansion will
2926          not fail -- there are trees that cannot be expanded twice.  */
2927       src_reg = gen_reg_rtx (Pmode);
2928
2929       /* Mark the beginning of the strlen sequence so we can emit the
2930          source operand later.  */
2931       before_strlen = get_last_insn ();
2932
2933       create_output_operand (&ops[0], target, insn_mode);
2934       create_fixed_operand (&ops[1], gen_rtx_MEM (BLKmode, src_reg));
2935       create_integer_operand (&ops[2], 0);
2936       create_integer_operand (&ops[3], align);
2937       if (!maybe_expand_insn (icode, 4, ops))
2938         return NULL_RTX;
2939
2940       /* Now that we are assured of success, expand the source.  */
2941       start_sequence ();
2942       pat = expand_expr (src, src_reg, Pmode, EXPAND_NORMAL);
2943       if (pat != src_reg)
2944         {
2945 #ifdef POINTERS_EXTEND_UNSIGNED
2946           if (GET_MODE (pat) != Pmode)
2947             pat = convert_to_mode (Pmode, pat,
2948                                    POINTERS_EXTEND_UNSIGNED);
2949 #endif
2950           emit_move_insn (src_reg, pat);
2951         }
2952       pat = get_insns ();
2953       end_sequence ();
2954
2955       if (before_strlen)
2956         emit_insn_after (pat, before_strlen);
2957       else
2958         emit_insn_before (pat, get_insns ());
2959
2960       /* Return the value in the proper mode for this function.  */
2961       if (GET_MODE (ops[0].value) == target_mode)
2962         target = ops[0].value;
2963       else if (target != 0)
2964         convert_move (target, ops[0].value, 0);
2965       else
2966         target = convert_to_mode (target_mode, ops[0].value, 0);
2967
2968       return target;
2969     }
2970 }
2971
2972 /* Callback routine for store_by_pieces.  Read GET_MODE_BITSIZE (MODE)
2973    bytes from constant string DATA + OFFSET and return it as target
2974    constant.  */
2975
2976 static rtx
2977 builtin_memcpy_read_str (void *data, HOST_WIDE_INT offset,
2978                          enum machine_mode mode)
2979 {
2980   const char *str = (const char *) data;
2981
2982   gcc_assert (offset >= 0
2983               && ((unsigned HOST_WIDE_INT) offset + GET_MODE_SIZE (mode)
2984                   <= strlen (str) + 1));
2985
2986   return c_readstr (str + offset, mode);
2987 }
2988
2989 /* Expand a call EXP to the memcpy builtin.
2990    Return NULL_RTX if we failed, the caller should emit a normal call,
2991    otherwise try to get the result in TARGET, if convenient (and in
2992    mode MODE if that's convenient).  */
2993
2994 static rtx
2995 expand_builtin_memcpy (tree exp, rtx target)
2996 {
2997   if (!validate_arglist (exp,
2998                          POINTER_TYPE, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
2999     return NULL_RTX;
3000   else
3001     {
3002       tree dest = CALL_EXPR_ARG (exp, 0);
3003       tree src = CALL_EXPR_ARG (exp, 1);
3004       tree len = CALL_EXPR_ARG (exp, 2);
3005       const char *src_str;
3006       unsigned int src_align = get_pointer_alignment (src, BIGGEST_ALIGNMENT);
3007       unsigned int dest_align
3008         = get_pointer_alignment (dest, BIGGEST_ALIGNMENT);
3009       rtx dest_mem, src_mem, dest_addr, len_rtx;
3010       HOST_WIDE_INT expected_size = -1;
3011       unsigned int expected_align = 0;
3012
3013       /* If DEST is not a pointer type, call the normal function.  */
3014       if (dest_align == 0)
3015         return NULL_RTX;
3016
3017       /* If either SRC is not a pointer type, don't do this
3018          operation in-line.  */
3019       if (src_align == 0)
3020         return NULL_RTX;
3021
3022       if (currently_expanding_gimple_stmt)
3023         stringop_block_profile (currently_expanding_gimple_stmt,
3024                                 &expected_align, &expected_size);
3025
3026       if (expected_align < dest_align)
3027         expected_align = dest_align;
3028       dest_mem = get_memory_rtx (dest, len);
3029       set_mem_align (dest_mem, dest_align);
3030       len_rtx = expand_normal (len);
3031       src_str = c_getstr (src);
3032
3033       /* If SRC is a string constant and block move would be done
3034          by pieces, we can avoid loading the string from memory
3035          and only stored the computed constants.  */
3036       if (src_str
3037           && CONST_INT_P (len_rtx)
3038           && (unsigned HOST_WIDE_INT) INTVAL (len_rtx) <= strlen (src_str) + 1
3039           && can_store_by_pieces (INTVAL (len_rtx), builtin_memcpy_read_str,
3040                                   CONST_CAST (char *, src_str),
3041                                   dest_align, false))
3042         {
3043           dest_mem = store_by_pieces (dest_mem, INTVAL (len_rtx),
3044                                       builtin_memcpy_read_str,
3045                                       CONST_CAST (char *, src_str),
3046                                       dest_align, false, 0);
3047           dest_mem = force_operand (XEXP (dest_mem, 0), target);
3048           dest_mem = convert_memory_address (ptr_mode, dest_mem);
3049           return dest_mem;
3050         }
3051
3052       src_mem = get_memory_rtx (src, len);
3053       set_mem_align (src_mem, src_align);
3054
3055       /* Copy word part most expediently.  */
3056       dest_addr = emit_block_move_hints (dest_mem, src_mem, len_rtx,
3057                                          CALL_EXPR_TAILCALL (exp)
3058                                          ? BLOCK_OP_TAILCALL : BLOCK_OP_NORMAL,
3059                                          expected_align, expected_size);
3060
3061       if (dest_addr == 0)
3062         {
3063           dest_addr = force_operand (XEXP (dest_mem, 0), target);
3064           dest_addr = convert_memory_address (ptr_mode, dest_addr);
3065         }
3066       return dest_addr;
3067     }
3068 }
3069
3070 /* Expand a call EXP to the mempcpy builtin.
3071    Return NULL_RTX if we failed; the caller should emit a normal call,
3072    otherwise try to get the result in TARGET, if convenient (and in
3073    mode MODE if that's convenient).  If ENDP is 0 return the
3074    destination pointer, if ENDP is 1 return the end pointer ala
3075    mempcpy, and if ENDP is 2 return the end pointer minus one ala
3076    stpcpy.  */
3077
3078 static rtx
3079 expand_builtin_mempcpy (tree exp, rtx target, enum machine_mode mode)
3080 {
3081   if (!validate_arglist (exp,
3082                          POINTER_TYPE, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
3083     return NULL_RTX;
3084   else
3085     {
3086       tree dest = CALL_EXPR_ARG (exp, 0);
3087       tree src = CALL_EXPR_ARG (exp, 1);
3088       tree len = CALL_EXPR_ARG (exp, 2);
3089       return expand_builtin_mempcpy_args (dest, src, len,
3090                                           target, mode, /*endp=*/ 1);
3091     }
3092 }
3093
3094 /* Helper function to do the actual work for expand_builtin_mempcpy.  The
3095    arguments to the builtin_mempcpy call DEST, SRC, and LEN are broken out
3096    so that this can also be called without constructing an actual CALL_EXPR.
3097    The other arguments and return value are the same as for
3098    expand_builtin_mempcpy.  */
3099
3100 static rtx
3101 expand_builtin_mempcpy_args (tree dest, tree src, tree len,
3102                              rtx target, enum machine_mode mode, int endp)
3103 {
3104     /* If return value is ignored, transform mempcpy into memcpy.  */
3105   if (target == const0_rtx && implicit_built_in_decls[BUILT_IN_MEMCPY])
3106     {
3107       tree fn = implicit_built_in_decls[BUILT_IN_MEMCPY];
3108       tree result = build_call_nofold_loc (UNKNOWN_LOCATION, fn, 3,
3109                                            dest, src, len);
3110       return expand_expr (result, target, mode, EXPAND_NORMAL);
3111     }
3112   else
3113     {
3114       const char *src_str;
3115       unsigned int src_align = get_pointer_alignment (src, BIGGEST_ALIGNMENT);
3116       unsigned int dest_align
3117         = get_pointer_alignment (dest, BIGGEST_ALIGNMENT);
3118       rtx dest_mem, src_mem, len_rtx;
3119
3120       /* If either SRC or DEST is not a pointer type, don't do this
3121          operation in-line.  */
3122       if (dest_align == 0 || src_align == 0)
3123         return NULL_RTX;
3124
3125       /* If LEN is not constant, call the normal function.  */
3126       if (! host_integerp (len, 1))
3127         return NULL_RTX;
3128
3129       len_rtx = expand_normal (len);
3130       src_str = c_getstr (src);
3131
3132       /* If SRC is a string constant and block move would be done
3133          by pieces, we can avoid loading the string from memory
3134          and only stored the computed constants.  */
3135       if (src_str
3136           && CONST_INT_P (len_rtx)
3137           && (unsigned HOST_WIDE_INT) INTVAL (len_rtx) <= strlen (src_str) + 1
3138           && can_store_by_pieces (INTVAL (len_rtx), builtin_memcpy_read_str,
3139                                   CONST_CAST (char *, src_str),
3140                                   dest_align, false))
3141         {
3142           dest_mem = get_memory_rtx (dest, len);
3143           set_mem_align (dest_mem, dest_align);
3144           dest_mem = store_by_pieces (dest_mem, INTVAL (len_rtx),
3145                                       builtin_memcpy_read_str,
3146                                       CONST_CAST (char *, src_str),
3147                                       dest_align, false, endp);
3148           dest_mem = force_operand (XEXP (dest_mem, 0), NULL_RTX);
3149           dest_mem = convert_memory_address (ptr_mode, dest_mem);
3150           return dest_mem;
3151         }
3152
3153       if (CONST_INT_P (len_rtx)
3154           && can_move_by_pieces (INTVAL (len_rtx),
3155                                  MIN (dest_align, src_align)))
3156         {
3157           dest_mem = get_memory_rtx (dest, len);
3158           set_mem_align (dest_mem, dest_align);
3159           src_mem = get_memory_rtx (src, len);
3160           set_mem_align (src_mem, src_align);
3161           dest_mem = move_by_pieces (dest_mem, src_mem, INTVAL (len_rtx),
3162                                      MIN (dest_align, src_align), endp);
3163           dest_mem = force_operand (XEXP (dest_mem, 0), NULL_RTX);
3164           dest_mem = convert_memory_address (ptr_mode, dest_mem);
3165           return dest_mem;
3166         }
3167
3168       return NULL_RTX;
3169     }
3170 }
3171
3172 #ifndef HAVE_movstr
3173 # define HAVE_movstr 0
3174 # define CODE_FOR_movstr CODE_FOR_nothing
3175 #endif
3176
3177 /* Expand into a movstr instruction, if one is available.  Return NULL_RTX if
3178    we failed, the caller should emit a normal call, otherwise try to
3179    get the result in TARGET, if convenient.  If ENDP is 0 return the
3180    destination pointer, if ENDP is 1 return the end pointer ala
3181    mempcpy, and if ENDP is 2 return the end pointer minus one ala
3182    stpcpy.  */
3183
3184 static rtx
3185 expand_movstr (tree dest, tree src, rtx target, int endp)
3186 {
3187   struct expand_operand ops[3];
3188   rtx dest_mem;
3189   rtx src_mem;
3190
3191   if (!HAVE_movstr)
3192     return NULL_RTX;
3193
3194   dest_mem = get_memory_rtx (dest, NULL);
3195   src_mem = get_memory_rtx (src, NULL);
3196   if (!endp)
3197     {
3198       target = force_reg (Pmode, XEXP (dest_mem, 0));
3199       dest_mem = replace_equiv_address (dest_mem, target);
3200     }
3201
3202   create_output_operand (&ops[0], endp ? target : NULL_RTX, Pmode);
3203   create_fixed_operand (&ops[1], dest_mem);
3204   create_fixed_operand (&ops[2], src_mem);
3205   expand_insn (CODE_FOR_movstr, 3, ops);
3206
3207   if (endp && target != const0_rtx)
3208     {
3209       target = ops[0].value;
3210       /* movstr is supposed to set end to the address of the NUL
3211          terminator.  If the caller requested a mempcpy-like return value,
3212          adjust it.  */
3213       if (endp == 1)
3214         {
3215           rtx tem = plus_constant (gen_lowpart (GET_MODE (target), target), 1);
3216           emit_move_insn (target, force_operand (tem, NULL_RTX));
3217         }
3218     }
3219   return target;
3220 }
3221
3222 /* Expand expression EXP, which is a call to the strcpy builtin.  Return
3223    NULL_RTX if we failed the caller should emit a normal call, otherwise
3224    try to get the result in TARGET, if convenient (and in mode MODE if that's
3225    convenient).  */
3226
3227 static rtx
3228 expand_builtin_strcpy (tree exp, rtx target)
3229 {
3230   if (validate_arglist (exp, POINTER_TYPE, POINTER_TYPE, VOID_TYPE))
3231    {
3232      tree dest = CALL_EXPR_ARG (exp, 0);
3233      tree src = CALL_EXPR_ARG (exp, 1);
3234      return expand_builtin_strcpy_args (dest, src, target);
3235    }
3236    return NULL_RTX;
3237 }
3238
3239 /* Helper function to do the actual work for expand_builtin_strcpy.  The
3240    arguments to the builtin_strcpy call DEST and SRC are broken out
3241    so that this can also be called without constructing an actual CALL_EXPR.
3242    The other arguments and return value are the same as for
3243    expand_builtin_strcpy.  */
3244
3245 static rtx
3246 expand_builtin_strcpy_args (tree dest, tree src, rtx target)
3247 {
3248   return expand_movstr (dest, src, target, /*endp=*/0);
3249 }
3250
3251 /* Expand a call EXP to the stpcpy builtin.
3252    Return NULL_RTX if we failed the caller should emit a normal call,
3253    otherwise try to get the result in TARGET, if convenient (and in
3254    mode MODE if that's convenient).  */
3255
3256 static rtx
3257 expand_builtin_stpcpy (tree exp, rtx target, enum machine_mode mode)
3258 {
3259   tree dst, src;
3260   location_t loc = EXPR_LOCATION (exp);
3261
3262   if (!validate_arglist (exp, POINTER_TYPE, POINTER_TYPE, VOID_TYPE))
3263     return NULL_RTX;
3264
3265   dst = CALL_EXPR_ARG (exp, 0);
3266   src = CALL_EXPR_ARG (exp, 1);
3267
3268   /* If return value is ignored, transform stpcpy into strcpy.  */
3269   if (target == const0_rtx && implicit_built_in_decls[BUILT_IN_STRCPY])
3270     {
3271       tree fn = implicit_built_in_decls[BUILT_IN_STRCPY];
3272       tree result = build_call_nofold_loc (loc, fn, 2, dst, src);
3273       return expand_expr (result, target, mode, EXPAND_NORMAL);
3274     }
3275   else
3276     {
3277       tree len, lenp1;
3278       rtx ret;
3279
3280       /* Ensure we get an actual string whose length can be evaluated at
3281          compile-time, not an expression containing a string.  This is
3282          because the latter will potentially produce pessimized code
3283          when used to produce the return value.  */
3284       if (! c_getstr (src) || ! (len = c_strlen (src, 0)))
3285         return expand_movstr (dst, src, target, /*endp=*/2);
3286
3287       lenp1 = size_binop_loc (loc, PLUS_EXPR, len, ssize_int (1));
3288       ret = expand_builtin_mempcpy_args (dst, src, lenp1,
3289                                          target, mode, /*endp=*/2);
3290
3291       if (ret)
3292         return ret;
3293
3294       if (TREE_CODE (len) == INTEGER_CST)
3295         {
3296           rtx len_rtx = expand_normal (len);
3297
3298           if (CONST_INT_P (len_rtx))
3299             {
3300               ret = expand_builtin_strcpy_args (dst, src, target);
3301
3302               if (ret)
3303                 {
3304                   if (! target)
3305                     {
3306                       if (mode != VOIDmode)
3307                         target = gen_reg_rtx (mode);
3308                       else
3309                         target = gen_reg_rtx (GET_MODE (ret));
3310                     }
3311                   if (GET_MODE (target) != GET_MODE (ret))
3312                     ret = gen_lowpart (GET_MODE (target), ret);
3313
3314                   ret = plus_constant (ret, INTVAL (len_rtx));
3315                   ret = emit_move_insn (target, force_operand (ret, NULL_RTX));
3316                   gcc_assert (ret);
3317
3318                   return target;
3319                 }
3320             }
3321         }
3322
3323       return expand_movstr (dst, src, target, /*endp=*/2);
3324     }
3325 }
3326
3327 /* Callback routine for store_by_pieces.  Read GET_MODE_BITSIZE (MODE)
3328    bytes from constant string DATA + OFFSET and return it as target
3329    constant.  */
3330
3331 rtx
3332 builtin_strncpy_read_str (void *data, HOST_WIDE_INT offset,
3333                           enum machine_mode mode)
3334 {
3335   const char *str = (const char *) data;
3336
3337   if ((unsigned HOST_WIDE_INT) offset > strlen (str))
3338     return const0_rtx;
3339
3340   return c_readstr (str + offset, mode);
3341 }
3342
3343 /* Expand expression EXP, which is a call to the strncpy builtin.  Return
3344    NULL_RTX if we failed the caller should emit a normal call.  */
3345
3346 static rtx
3347 expand_builtin_strncpy (tree exp, rtx target)
3348 {
3349   location_t loc = EXPR_LOCATION (exp);
3350
3351   if (validate_arglist (exp,
3352                         POINTER_TYPE, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
3353     {
3354       tree dest = CALL_EXPR_ARG (exp, 0);
3355       tree src = CALL_EXPR_ARG (exp, 1);
3356       tree len = CALL_EXPR_ARG (exp, 2);
3357       tree slen = c_strlen (src, 1);
3358
3359       /* We must be passed a constant len and src parameter.  */
3360       if (!host_integerp (len, 1) || !slen || !host_integerp (slen, 1))
3361         return NULL_RTX;
3362
3363       slen = size_binop_loc (loc, PLUS_EXPR, slen, ssize_int (1));
3364
3365       /* We're required to pad with trailing zeros if the requested
3366          len is greater than strlen(s2)+1.  In that case try to
3367          use store_by_pieces, if it fails, punt.  */
3368       if (tree_int_cst_lt (slen, len))
3369         {
3370           unsigned int dest_align
3371             = get_pointer_alignment (dest, BIGGEST_ALIGNMENT);
3372           const char *p = c_getstr (src);
3373           rtx dest_mem;
3374
3375           if (!p || dest_align == 0 || !host_integerp (len, 1)
3376               || !can_store_by_pieces (tree_low_cst (len, 1),
3377                                        builtin_strncpy_read_str,
3378                                        CONST_CAST (char *, p),
3379                                        dest_align, false))
3380             return NULL_RTX;
3381
3382           dest_mem = get_memory_rtx (dest, len);
3383           store_by_pieces (dest_mem, tree_low_cst (len, 1),
3384                            builtin_strncpy_read_str,
3385                            CONST_CAST (char *, p), dest_align, false, 0);
3386           dest_mem = force_operand (XEXP (dest_mem, 0), target);
3387           dest_mem = convert_memory_address (ptr_mode, dest_mem);
3388           return dest_mem;
3389         }
3390     }
3391   return NULL_RTX;
3392 }
3393
3394 /* Callback routine for store_by_pieces.  Read GET_MODE_BITSIZE (MODE)
3395    bytes from constant string DATA + OFFSET and return it as target
3396    constant.  */
3397
3398 rtx
3399 builtin_memset_read_str (void *data, HOST_WIDE_INT offset ATTRIBUTE_UNUSED,
3400                          enum machine_mode mode)
3401 {
3402   const char *c = (const char *) data;
3403   char *p = XALLOCAVEC (char, GET_MODE_SIZE (mode));
3404
3405   memset (p, *c, GET_MODE_SIZE (mode));
3406
3407   return c_readstr (p, mode);
3408 }
3409
3410 /* Callback routine for store_by_pieces.  Return the RTL of a register
3411    containing GET_MODE_SIZE (MODE) consecutive copies of the unsigned
3412    char value given in the RTL register data.  For example, if mode is
3413    4 bytes wide, return the RTL for 0x01010101*data.  */
3414
3415 static rtx
3416 builtin_memset_gen_str (void *data, HOST_WIDE_INT offset ATTRIBUTE_UNUSED,
3417                         enum machine_mode mode)
3418 {
3419   rtx target, coeff;
3420   size_t size;
3421   char *p;
3422
3423   size = GET_MODE_SIZE (mode);
3424   if (size == 1)
3425     return (rtx) data;
3426
3427   p = XALLOCAVEC (char, size);
3428   memset (p, 1, size);
3429   coeff = c_readstr (p, mode);
3430
3431   target = convert_to_mode (mode, (rtx) data, 1);
3432   target = expand_mult (mode, target, coeff, NULL_RTX, 1);
3433   return force_reg (mode, target);
3434 }
3435
3436 /* Expand expression EXP, which is a call to the memset builtin.  Return
3437    NULL_RTX if we failed the caller should emit a normal call, otherwise
3438    try to get the result in TARGET, if convenient (and in mode MODE if that's
3439    convenient).  */
3440
3441 static rtx
3442 expand_builtin_memset (tree exp, rtx target, enum machine_mode mode)
3443 {
3444   if (!validate_arglist (exp,
3445                          POINTER_TYPE, INTEGER_TYPE, INTEGER_TYPE, VOID_TYPE))
3446     return NULL_RTX;
3447   else
3448     {
3449       tree dest = CALL_EXPR_ARG (exp, 0);
3450       tree val = CALL_EXPR_ARG (exp, 1);
3451       tree len = CALL_EXPR_ARG (exp, 2);
3452       return expand_builtin_memset_args (dest, val, len, target, mode, exp);
3453     }
3454 }
3455
3456 /* Helper function to do the actual work for expand_builtin_memset.  The
3457    arguments to the builtin_memset call DEST, VAL, and LEN are broken out
3458    so that this can also be called without constructing an actual CALL_EXPR.
3459    The other arguments and return value are the same as for
3460    expand_builtin_memset.  */
3461
3462 static rtx
3463 expand_builtin_memset_args (tree dest, tree val, tree len,
3464                             rtx target, enum machine_mode mode, tree orig_exp)
3465 {
3466   tree fndecl, fn;
3467   enum built_in_function fcode;
3468   enum machine_mode val_mode;
3469   char c;
3470   unsigned int dest_align;
3471   rtx dest_mem, dest_addr, len_rtx;
3472   HOST_WIDE_INT expected_size = -1;
3473   unsigned int expected_align = 0;
3474
3475   dest_align = get_pointer_alignment (dest, BIGGEST_ALIGNMENT);
3476
3477   /* If DEST is not a pointer type, don't do this operation in-line.  */
3478   if (dest_align == 0)
3479     return NULL_RTX;
3480
3481   if (currently_expanding_gimple_stmt)
3482     stringop_block_profile (currently_expanding_gimple_stmt,
3483                             &expected_align, &expected_size);
3484
3485   if (expected_align < dest_align)
3486     expected_align = dest_align;
3487
3488   /* If the LEN parameter is zero, return DEST.  */
3489   if (integer_zerop (len))
3490     {
3491       /* Evaluate and ignore VAL in case it has side-effects.  */
3492       expand_expr (val, const0_rtx, VOIDmode, EXPAND_NORMAL);
3493       return expand_expr (dest, target, mode, EXPAND_NORMAL);
3494     }
3495
3496   /* Stabilize the arguments in case we fail.  */
3497   dest = builtin_save_expr (dest);
3498   val = builtin_save_expr (val);
3499   len = builtin_save_expr (len);
3500
3501   len_rtx = expand_normal (len);
3502   dest_mem = get_memory_rtx (dest, len);
3503   val_mode = TYPE_MODE (unsigned_char_type_node);
3504
3505   if (TREE_CODE (val) != INTEGER_CST)
3506     {
3507       rtx val_rtx;
3508
3509       val_rtx = expand_normal (val);
3510       val_rtx = convert_to_mode (val_mode, val_rtx, 0);
3511
3512       /* Assume that we can memset by pieces if we can store
3513        * the coefficients by pieces (in the required modes).
3514        * We can't pass builtin_memset_gen_str as that emits RTL.  */
3515       c = 1;
3516       if (host_integerp (len, 1)
3517           && can_store_by_pieces (tree_low_cst (len, 1),
3518                                   builtin_memset_read_str, &c, dest_align,
3519                                   true))
3520         {
3521           val_rtx = force_reg (val_mode, val_rtx);
3522           store_by_pieces (dest_mem, tree_low_cst (len, 1),
3523                            builtin_memset_gen_str, val_rtx, dest_align,
3524                            true, 0);
3525         }
3526       else if (!set_storage_via_setmem (dest_mem, len_rtx, val_rtx,
3527                                         dest_align, expected_align,
3528                                         expected_size))
3529         goto do_libcall;
3530
3531       dest_mem = force_operand (XEXP (dest_mem, 0), NULL_RTX);
3532       dest_mem = convert_memory_address (ptr_mode, dest_mem);
3533       return dest_mem;
3534     }
3535
3536   if (target_char_cast (val, &c))
3537     goto do_libcall;
3538
3539   if (c)
3540     {
3541       if (host_integerp (len, 1)
3542           && can_store_by_pieces (tree_low_cst (len, 1),
3543                                   builtin_memset_read_str, &c, dest_align,
3544                                   true))
3545         store_by_pieces (dest_mem, tree_low_cst (len, 1),
3546                          builtin_memset_read_str, &c, dest_align, true, 0);
3547       else if (!set_storage_via_setmem (dest_mem, len_rtx,
3548                                         gen_int_mode (c, val_mode),
3549                                         dest_align, expected_align,
3550                                         expected_size))
3551         goto do_libcall;
3552
3553       dest_mem = force_operand (XEXP (dest_mem, 0), NULL_RTX);
3554       dest_mem = convert_memory_address (ptr_mode, dest_mem);
3555       return dest_mem;
3556     }
3557
3558   set_mem_align (dest_mem, dest_align);
3559   dest_addr = clear_storage_hints (dest_mem, len_rtx,
3560                                    CALL_EXPR_TAILCALL (orig_exp)
3561                                    ? BLOCK_OP_TAILCALL : BLOCK_OP_NORMAL,
3562                                    expected_align, expected_size);
3563
3564   if (dest_addr == 0)
3565     {
3566       dest_addr = force_operand (XEXP (dest_mem, 0), NULL_RTX);
3567       dest_addr = convert_memory_address (ptr_mode, dest_addr);
3568     }
3569
3570   return dest_addr;
3571
3572  do_libcall:
3573   fndecl = get_callee_fndecl (orig_exp);
3574   fcode = DECL_FUNCTION_CODE (fndecl);
3575   if (fcode == BUILT_IN_MEMSET)
3576     fn = build_call_nofold_loc (EXPR_LOCATION (orig_exp), fndecl, 3,
3577                                 dest, val, len);
3578   else if (fcode == BUILT_IN_BZERO)
3579     fn = build_call_nofold_loc (EXPR_LOCATION (orig_exp), fndecl, 2,
3580                                 dest, len);
3581   else
3582     gcc_unreachable ();
3583   gcc_assert (TREE_CODE (fn) == CALL_EXPR);
3584   CALL_EXPR_TAILCALL (fn) = CALL_EXPR_TAILCALL (orig_exp);
3585   return expand_call (fn, target, target == const0_rtx);
3586 }
3587
3588 /* Expand expression EXP, which is a call to the bzero builtin.  Return
3589    NULL_RTX if we failed the caller should emit a normal call.  */
3590
3591 static rtx
3592 expand_builtin_bzero (tree exp)
3593 {
3594   tree dest, size;
3595   location_t loc = EXPR_LOCATION (exp);
3596
3597   if (!validate_arglist (exp, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
3598     return NULL_RTX;
3599
3600   dest = CALL_EXPR_ARG (exp, 0);
3601   size = CALL_EXPR_ARG (exp, 1);
3602
3603   /* New argument list transforming bzero(ptr x, int y) to
3604      memset(ptr x, int 0, size_t y).   This is done this way
3605      so that if it isn't expanded inline, we fallback to
3606      calling bzero instead of memset.  */
3607
3608   return expand_builtin_memset_args (dest, integer_zero_node,
3609                                      fold_convert_loc (loc, sizetype, size),
3610                                      const0_rtx, VOIDmode, exp);
3611 }
3612
3613 /* Expand expression EXP, which is a call to the memcmp built-in function.
3614    Return NULL_RTX if we failed and the
3615    caller should emit a normal call, otherwise try to get the result in
3616    TARGET, if convenient (and in mode MODE, if that's convenient).  */
3617
3618 static rtx
3619 expand_builtin_memcmp (tree exp, ATTRIBUTE_UNUSED rtx target,
3620                        ATTRIBUTE_UNUSED enum machine_mode mode)
3621 {
3622   location_t loc ATTRIBUTE_UNUSED = EXPR_LOCATION (exp);
3623
3624   if (!validate_arglist (exp,
3625                          POINTER_TYPE, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
3626     return NULL_RTX;
3627
3628 #if defined HAVE_cmpmemsi || defined HAVE_cmpstrnsi
3629   {
3630     rtx arg1_rtx, arg2_rtx, arg3_rtx;
3631     rtx result;
3632     rtx insn;
3633     tree arg1 = CALL_EXPR_ARG (exp, 0);
3634     tree arg2 = CALL_EXPR_ARG (exp, 1);
3635     tree len = CALL_EXPR_ARG (exp, 2);
3636
3637     unsigned int arg1_align
3638       = get_pointer_alignment (arg1, BIGGEST_ALIGNMENT) / BITS_PER_UNIT;
3639     unsigned int arg2_align
3640       = get_pointer_alignment (arg2, BIGGEST_ALIGNMENT) / BITS_PER_UNIT;
3641     enum machine_mode insn_mode;
3642
3643 #ifdef HAVE_cmpmemsi
3644     if (HAVE_cmpmemsi)
3645       insn_mode = insn_data[(int) CODE_FOR_cmpmemsi].operand[0].mode;
3646     else
3647 #endif
3648 #ifdef HAVE_cmpstrnsi
3649     if (HAVE_cmpstrnsi)
3650       insn_mode = insn_data[(int) CODE_FOR_cmpstrnsi].operand[0].mode;
3651     else
3652 #endif
3653       return NULL_RTX;
3654
3655     /* If we don't have POINTER_TYPE, call the function.  */
3656     if (arg1_align == 0 || arg2_align == 0)
3657       return NULL_RTX;
3658
3659     /* Make a place to write the result of the instruction.  */
3660     result = target;
3661     if (! (result != 0
3662            && REG_P (result) && GET_MODE (result) == insn_mode
3663            && REGNO (result) >= FIRST_PSEUDO_REGISTER))
3664       result = gen_reg_rtx (insn_mode);
3665
3666     arg1_rtx = get_memory_rtx (arg1, len);
3667     arg2_rtx = get_memory_rtx (arg2, len);
3668     arg3_rtx = expand_normal (fold_convert_loc (loc, sizetype, len));
3669
3670     /* Set MEM_SIZE as appropriate.  */
3671     if (CONST_INT_P (arg3_rtx))
3672       {
3673         set_mem_size (arg1_rtx, arg3_rtx);
3674         set_mem_size (arg2_rtx, arg3_rtx);
3675       }
3676
3677 #ifdef HAVE_cmpmemsi
3678     if (HAVE_cmpmemsi)
3679       insn = gen_cmpmemsi (result, arg1_rtx, arg2_rtx, arg3_rtx,
3680                            GEN_INT (MIN (arg1_align, arg2_align)));
3681     else
3682 #endif
3683 #ifdef HAVE_cmpstrnsi
3684     if (HAVE_cmpstrnsi)
3685       insn = gen_cmpstrnsi (result, arg1_rtx, arg2_rtx, arg3_rtx,
3686                             GEN_INT (MIN (arg1_align, arg2_align)));
3687     else
3688 #endif
3689       gcc_unreachable ();
3690
3691     if (insn)
3692       emit_insn (insn);
3693     else
3694       emit_library_call_value (memcmp_libfunc, result, LCT_PURE,
3695                                TYPE_MODE (integer_type_node), 3,
3696                                XEXP (arg1_rtx, 0), Pmode,
3697                                XEXP (arg2_rtx, 0), Pmode,
3698                                convert_to_mode (TYPE_MODE (sizetype), arg3_rtx,
3699                                                 TYPE_UNSIGNED (sizetype)),
3700                                TYPE_MODE (sizetype));
3701
3702     /* Return the value in the proper mode for this function.  */
3703     mode = TYPE_MODE (TREE_TYPE (exp));
3704     if (GET_MODE (result) == mode)
3705       return result;
3706     else if (target != 0)
3707       {
3708         convert_move (target, result, 0);
3709         return target;
3710       }
3711     else
3712       return convert_to_mode (mode, result, 0);
3713   }
3714 #endif
3715
3716   return NULL_RTX;
3717 }
3718
3719 /* Expand expression EXP, which is a call to the strcmp builtin.  Return NULL_RTX
3720    if we failed the caller should emit a normal call, otherwise try to get
3721    the result in TARGET, if convenient.  */
3722
3723 static rtx
3724 expand_builtin_strcmp (tree exp, ATTRIBUTE_UNUSED rtx target)
3725 {
3726   if (!validate_arglist (exp, POINTER_TYPE, POINTER_TYPE, VOID_TYPE))
3727     return NULL_RTX;
3728
3729 #if defined HAVE_cmpstrsi || defined HAVE_cmpstrnsi
3730   if (direct_optab_handler (cmpstr_optab, SImode) != CODE_FOR_nothing
3731       || direct_optab_handler (cmpstrn_optab, SImode) != CODE_FOR_nothing)
3732     {
3733       rtx arg1_rtx, arg2_rtx;
3734       rtx result, insn = NULL_RTX;
3735       tree fndecl, fn;
3736       tree arg1 = CALL_EXPR_ARG (exp, 0);
3737       tree arg2 = CALL_EXPR_ARG (exp, 1);
3738
3739       unsigned int arg1_align
3740         = get_pointer_alignment (arg1, BIGGEST_ALIGNMENT) / BITS_PER_UNIT;
3741       unsigned int arg2_align
3742         = get_pointer_alignment (arg2, BIGGEST_ALIGNMENT) / BITS_PER_UNIT;
3743
3744       /* If we don't have POINTER_TYPE, call the function.  */
3745       if (arg1_align == 0 || arg2_align == 0)
3746         return NULL_RTX;
3747
3748       /* Stabilize the arguments in case gen_cmpstr(n)si fail.  */
3749       arg1 = builtin_save_expr (arg1);
3750       arg2 = builtin_save_expr (arg2);
3751
3752       arg1_rtx = get_memory_rtx (arg1, NULL);
3753       arg2_rtx = get_memory_rtx (arg2, NULL);
3754
3755 #ifdef HAVE_cmpstrsi
3756       /* Try to call cmpstrsi.  */
3757       if (HAVE_cmpstrsi)
3758         {
3759           enum machine_mode insn_mode
3760             = insn_data[(int) CODE_FOR_cmpstrsi].operand[0].mode;
3761
3762           /* Make a place to write the result of the instruction.  */
3763           result = target;
3764           if (! (result != 0
3765                  && REG_P (result) && GET_MODE (result) == insn_mode
3766                  && REGNO (result) >= FIRST_PSEUDO_REGISTER))
3767             result = gen_reg_rtx (insn_mode);
3768
3769           insn = gen_cmpstrsi (result, arg1_rtx, arg2_rtx,
3770                                GEN_INT (MIN (arg1_align, arg2_align)));
3771         }
3772 #endif
3773 #ifdef HAVE_cmpstrnsi
3774       /* Try to determine at least one length and call cmpstrnsi.  */
3775       if (!insn && HAVE_cmpstrnsi)
3776         {
3777           tree len;
3778           rtx arg3_rtx;
3779
3780           enum machine_mode insn_mode
3781             = insn_data[(int) CODE_FOR_cmpstrnsi].operand[0].mode;
3782           tree len1 = c_strlen (arg1, 1);
3783           tree len2 = c_strlen (arg2, 1);
3784
3785           if (len1)
3786             len1 = size_binop (PLUS_EXPR, ssize_int (1), len1);
3787           if (len2)
3788             len2 = size_binop (PLUS_EXPR, ssize_int (1), len2);
3789
3790           /* If we don't have a constant length for the first, use the length
3791              of the second, if we know it.  We don't require a constant for
3792              this case; some cost analysis could be done if both are available
3793              but neither is constant.  For now, assume they're equally cheap,
3794              unless one has side effects.  If both strings have constant lengths,
3795              use the smaller.  */
3796
3797           if (!len1)
3798             len = len2;
3799           else if (!len2)
3800             len = len1;
3801           else if (TREE_SIDE_EFFECTS (len1))
3802             len = len2;
3803           else if (TREE_SIDE_EFFECTS (len2))
3804             len = len1;
3805           else if (TREE_CODE (len1) != INTEGER_CST)
3806             len = len2;
3807           else if (TREE_CODE (len2) != INTEGER_CST)
3808             len = len1;
3809           else if (tree_int_cst_lt (len1, len2))
3810             len = len1;
3811           else
3812             len = len2;
3813
3814           /* If both arguments have side effects, we cannot optimize.  */
3815           if (!len || TREE_SIDE_EFFECTS (len))
3816             goto do_libcall;
3817
3818           arg3_rtx = expand_normal (len);
3819
3820           /* Make a place to write the result of the instruction.  */
3821           result = target;
3822           if (! (result != 0
3823                  && REG_P (result) && GET_MODE (result) == insn_mode
3824                  && REGNO (result) >= FIRST_PSEUDO_REGISTER))
3825             result = gen_reg_rtx (insn_mode);
3826
3827           insn = gen_cmpstrnsi (result, arg1_rtx, arg2_rtx, arg3_rtx,
3828                                 GEN_INT (MIN (arg1_align, arg2_align)));
3829         }
3830 #endif
3831
3832       if (insn)
3833         {
3834           enum machine_mode mode;
3835           emit_insn (insn);
3836
3837           /* Return the value in the proper mode for this function.  */
3838           mode = TYPE_MODE (TREE_TYPE (exp));
3839           if (GET_MODE (result) == mode)
3840             return result;
3841           if (target == 0)
3842             return convert_to_mode (mode, result, 0);
3843           convert_move (target, result, 0);
3844           return target;
3845         }
3846
3847       /* Expand the library call ourselves using a stabilized argument
3848          list to avoid re-evaluating the function's arguments twice.  */
3849 #ifdef HAVE_cmpstrnsi
3850     do_libcall:
3851 #endif
3852       fndecl = get_callee_fndecl (exp);
3853       fn = build_call_nofold_loc (EXPR_LOCATION (exp), fndecl, 2, arg1, arg2);
3854       gcc_assert (TREE_CODE (fn) == CALL_EXPR);
3855       CALL_EXPR_TAILCALL (fn) = CALL_EXPR_TAILCALL (exp);
3856       return expand_call (fn, target, target == const0_rtx);
3857     }
3858 #endif
3859   return NULL_RTX;
3860 }
3861
3862 /* Expand expression EXP, which is a call to the strncmp builtin. Return
3863    NULL_RTX if we failed the caller should emit a normal call, otherwise try to get
3864    the result in TARGET, if convenient.  */
3865
3866 static rtx
3867 expand_builtin_strncmp (tree exp, ATTRIBUTE_UNUSED rtx target,
3868                         ATTRIBUTE_UNUSED enum machine_mode mode)
3869 {
3870   location_t loc ATTRIBUTE_UNUSED = EXPR_LOCATION (exp);
3871
3872   if (!validate_arglist (exp,
3873                          POINTER_TYPE, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
3874     return NULL_RTX;
3875
3876   /* If c_strlen can determine an expression for one of the string
3877      lengths, and it doesn't have side effects, then emit cmpstrnsi
3878      using length MIN(strlen(string)+1, arg3).  */
3879 #ifdef HAVE_cmpstrnsi
3880   if (HAVE_cmpstrnsi)
3881   {
3882     tree len, len1, len2;
3883     rtx arg1_rtx, arg2_rtx, arg3_rtx;
3884     rtx result, insn;
3885     tree fndecl, fn;
3886     tree arg1 = CALL_EXPR_ARG (exp, 0);
3887     tree arg2 = CALL_EXPR_ARG (exp, 1);
3888     tree arg3 = CALL_EXPR_ARG (exp, 2);
3889
3890     unsigned int arg1_align
3891       = get_pointer_alignment (arg1, BIGGEST_ALIGNMENT) / BITS_PER_UNIT;
3892     unsigned int arg2_align
3893       = get_pointer_alignment (arg2, BIGGEST_ALIGNMENT) / BITS_PER_UNIT;
3894     enum machine_mode insn_mode
3895       = insn_data[(int) CODE_FOR_cmpstrnsi].operand[0].mode;
3896
3897     len1 = c_strlen (arg1, 1);
3898     len2 = c_strlen (arg2, 1);
3899
3900     if (len1)
3901       len1 = size_binop_loc (loc, PLUS_EXPR, ssize_int (1), len1);
3902     if (len2)
3903       len2 = size_binop_loc (loc, PLUS_EXPR, ssize_int (1), len2);
3904
3905     /* If we don't have a constant length for the first, use the length
3906        of the second, if we know it.  We don't require a constant for
3907        this case; some cost analysis could be done if both are available
3908        but neither is constant.  For now, assume they're equally cheap,
3909        unless one has side effects.  If both strings have constant lengths,
3910        use the smaller.  */
3911
3912     if (!len1)
3913       len = len2;
3914     else if (!len2)
3915       len = len1;
3916     else if (TREE_SIDE_EFFECTS (len1))
3917       len = len2;
3918     else if (TREE_SIDE_EFFECTS (len2))
3919       len = len1;
3920     else if (TREE_CODE (len1) != INTEGER_CST)
3921       len = len2;
3922     else if (TREE_CODE (len2) != INTEGER_CST)
3923       len = len1;
3924     else if (tree_int_cst_lt (len1, len2))
3925       len = len1;
3926     else
3927       len = len2;
3928
3929     /* If both arguments have side effects, we cannot optimize.  */
3930     if (!len || TREE_SIDE_EFFECTS (len))
3931       return NULL_RTX;
3932
3933     /* The actual new length parameter is MIN(len,arg3).  */
3934     len = fold_build2_loc (loc, MIN_EXPR, TREE_TYPE (len), len,
3935                        fold_convert_loc (loc, TREE_TYPE (len), arg3));
3936
3937     /* If we don't have POINTER_TYPE, call the function.  */
3938     if (arg1_align == 0 || arg2_align == 0)
3939       return NULL_RTX;
3940
3941     /* Make a place to write the result of the instruction.  */
3942     result = target;
3943     if (! (result != 0
3944            && REG_P (result) && GET_MODE (result) == insn_mode
3945            && REGNO (result) >= FIRST_PSEUDO_REGISTER))
3946       result = gen_reg_rtx (insn_mode);
3947
3948     /* Stabilize the arguments in case gen_cmpstrnsi fails.  */
3949     arg1 = builtin_save_expr (arg1);
3950     arg2 = builtin_save_expr (arg2);
3951     len = builtin_save_expr (len);
3952
3953     arg1_rtx = get_memory_rtx (arg1, len);
3954     arg2_rtx = get_memory_rtx (arg2, len);
3955     arg3_rtx = expand_normal (len);
3956     insn = gen_cmpstrnsi (result, arg1_rtx, arg2_rtx, arg3_rtx,
3957                           GEN_INT (MIN (arg1_align, arg2_align)));
3958     if (insn)
3959       {
3960         emit_insn (insn);
3961
3962         /* Return the value in the proper mode for this function.  */
3963         mode = TYPE_MODE (TREE_TYPE (exp));
3964         if (GET_MODE (result) == mode)
3965           return result;
3966         if (target == 0)
3967           return convert_to_mode (mode, result, 0);
3968         convert_move (target, result, 0);
3969         return target;
3970       }
3971
3972     /* Expand the library call ourselves using a stabilized argument
3973        list to avoid re-evaluating the function's arguments twice.  */
3974     fndecl = get_callee_fndecl (exp);
3975     fn = build_call_nofold_loc (EXPR_LOCATION (exp), fndecl, 3,
3976                                 arg1, arg2, len);
3977     gcc_assert (TREE_CODE (fn) == CALL_EXPR);
3978     CALL_EXPR_TAILCALL (fn) = CALL_EXPR_TAILCALL (exp);
3979     return expand_call (fn, target, target == const0_rtx);
3980   }
3981 #endif
3982   return NULL_RTX;
3983 }
3984
3985 /* Expand a call to __builtin_saveregs, generating the result in TARGET,
3986    if that's convenient.  */
3987
3988 rtx
3989 expand_builtin_saveregs (void)
3990 {
3991   rtx val, seq;
3992
3993   /* Don't do __builtin_saveregs more than once in a function.
3994      Save the result of the first call and reuse it.  */
3995   if (saveregs_value != 0)
3996     return saveregs_value;
3997
3998   /* When this function is called, it means that registers must be
3999      saved on entry to this function.  So we migrate the call to the
4000      first insn of this function.  */
4001
4002   start_sequence ();
4003
4004   /* Do whatever the machine needs done in this case.  */
4005   val = targetm.calls.expand_builtin_saveregs ();
4006
4007   seq = get_insns ();
4008   end_sequence ();
4009
4010   saveregs_value = val;
4011
4012   /* Put the insns after the NOTE that starts the function.  If this
4013      is inside a start_sequence, make the outer-level insn chain current, so
4014      the code is placed at the start of the function.  */
4015   push_topmost_sequence ();
4016   emit_insn_after (seq, entry_of_function ());
4017   pop_topmost_sequence ();
4018
4019   return val;
4020 }
4021
4022 /* Expand a call to __builtin_next_arg.  */
4023
4024 static rtx
4025 expand_builtin_next_arg (void)
4026 {
4027   /* Checking arguments is already done in fold_builtin_next_arg
4028      that must be called before this function.  */
4029   return expand_binop (ptr_mode, add_optab,
4030                        crtl->args.internal_arg_pointer,
4031                        crtl->args.arg_offset_rtx,
4032                        NULL_RTX, 0, OPTAB_LIB_WIDEN);
4033 }
4034
4035 /* Make it easier for the backends by protecting the valist argument
4036    from multiple evaluations.  */
4037
4038 static tree
4039 stabilize_va_list_loc (location_t loc, tree valist, int needs_lvalue)
4040 {
4041   tree vatype = targetm.canonical_va_list_type (TREE_TYPE (valist));
4042
4043   /* The current way of determining the type of valist is completely
4044      bogus.  We should have the information on the va builtin instead.  */
4045   if (!vatype)
4046     vatype = targetm.fn_abi_va_list (cfun->decl);
4047
4048   if (TREE_CODE (vatype) == ARRAY_TYPE)
4049     {
4050       if (TREE_SIDE_EFFECTS (valist))
4051         valist = save_expr (valist);
4052
4053       /* For this case, the backends will be expecting a pointer to
4054          vatype, but it's possible we've actually been given an array
4055          (an actual TARGET_CANONICAL_VA_LIST_TYPE (valist)).
4056          So fix it.  */
4057       if (TREE_CODE (TREE_TYPE (valist)) == ARRAY_TYPE)
4058         {
4059           tree p1 = build_pointer_type (TREE_TYPE (vatype));
4060           valist = build_fold_addr_expr_with_type_loc (loc, valist, p1);
4061         }
4062     }
4063   else
4064     {
4065       tree pt = build_pointer_type (vatype);
4066
4067       if (! needs_lvalue)
4068         {
4069           if (! TREE_SIDE_EFFECTS (valist))
4070             return valist;
4071
4072           valist = fold_build1_loc (loc, ADDR_EXPR, pt, valist);
4073           TREE_SIDE_EFFECTS (valist) = 1;
4074         }
4075
4076       if (TREE_SIDE_EFFECTS (valist))
4077         valist = save_expr (valist);
4078       valist = fold_build2_loc (loc, MEM_REF,
4079                                 vatype, valist, build_int_cst (pt, 0));
4080     }
4081
4082   return valist;
4083 }
4084
4085 /* The "standard" definition of va_list is void*.  */
4086
4087 tree
4088 std_build_builtin_va_list (void)
4089 {
4090   return ptr_type_node;
4091 }
4092
4093 /* The "standard" abi va_list is va_list_type_node.  */
4094
4095 tree
4096 std_fn_abi_va_list (tree fndecl ATTRIBUTE_UNUSED)
4097 {
4098   return va_list_type_node;
4099 }
4100
4101 /* The "standard" type of va_list is va_list_type_node.  */
4102
4103 tree
4104 std_canonical_va_list_type (tree type)
4105 {
4106   tree wtype, htype;
4107
4108   if (INDIRECT_REF_P (type))
4109     type = TREE_TYPE (type);
4110   else if (POINTER_TYPE_P (type) && POINTER_TYPE_P (TREE_TYPE(type)))
4111     type = TREE_TYPE (type);
4112   wtype = va_list_type_node;
4113   htype = type;
4114   /* Treat structure va_list types.  */
4115   if (TREE_CODE (wtype) == RECORD_TYPE && POINTER_TYPE_P (htype))
4116     htype = TREE_TYPE (htype);
4117   else if (TREE_CODE (wtype) == ARRAY_TYPE)
4118     {
4119       /* If va_list is an array type, the argument may have decayed
4120          to a pointer type, e.g. by being passed to another function.
4121          In that case, unwrap both types so that we can compare the
4122          underlying records.  */
4123       if (TREE_CODE (htype) == ARRAY_TYPE
4124           || POINTER_TYPE_P (htype))
4125         {
4126           wtype = TREE_TYPE (wtype);
4127           htype = TREE_TYPE (htype);
4128         }
4129     }
4130   if (TYPE_MAIN_VARIANT (wtype) == TYPE_MAIN_VARIANT (htype))
4131     return va_list_type_node;
4132
4133   return NULL_TREE;
4134 }
4135
4136 /* The "standard" implementation of va_start: just assign `nextarg' to
4137    the variable.  */
4138
4139 void
4140 std_expand_builtin_va_start (tree valist, rtx nextarg)
4141 {
4142   rtx va_r = expand_expr (valist, NULL_RTX, VOIDmode, EXPAND_WRITE);
4143   convert_move (va_r, nextarg, 0);
4144 }
4145
4146 /* Expand EXP, a call to __builtin_va_start.  */
4147
4148 static rtx
4149 expand_builtin_va_start (tree exp)
4150 {
4151   rtx nextarg;
4152   tree valist;
4153   location_t loc = EXPR_LOCATION (exp);
4154
4155   if (call_expr_nargs (exp) < 2)
4156     {
4157       error_at (loc, "too few arguments to function %<va_start%>");
4158       return const0_rtx;
4159     }
4160
4161   if (fold_builtin_next_arg (exp, true))
4162     return const0_rtx;
4163
4164   nextarg = expand_builtin_next_arg ();
4165   valist = stabilize_va_list_loc (loc, CALL_EXPR_ARG (exp, 0), 1);
4166
4167   if (targetm.expand_builtin_va_start)
4168     targetm.expand_builtin_va_start (valist, nextarg);
4169   else
4170     std_expand_builtin_va_start (valist, nextarg);
4171
4172   return const0_rtx;
4173 }
4174
4175 /* The "standard" implementation of va_arg: read the value from the
4176    current (padded) address and increment by the (padded) size.  */
4177
4178 tree
4179 std_gimplify_va_arg_expr (tree valist, tree type, gimple_seq *pre_p,
4180                           gimple_seq *post_p)
4181 {
4182   tree addr, t, type_size, rounded_size, valist_tmp;
4183   unsigned HOST_WIDE_INT align, boundary;
4184   bool indirect;
4185
4186 #ifdef ARGS_GROW_DOWNWARD
4187   /* All of the alignment and movement below is for args-grow-up machines.
4188      As of 2004, there are only 3 ARGS_GROW_DOWNWARD targets, and they all
4189      implement their own specialized gimplify_va_arg_expr routines.  */
4190   gcc_unreachable ();
4191 #endif
4192
4193   indirect = pass_by_reference (NULL, TYPE_MODE (type), type, false);
4194   if (indirect)
4195     type = build_pointer_type (type);
4196
4197   align = PARM_BOUNDARY / BITS_PER_UNIT;
4198   boundary = targetm.calls.function_arg_boundary (TYPE_MODE (type), type);
4199
4200   /* When we align parameter on stack for caller, if the parameter
4201      alignment is beyond MAX_SUPPORTED_STACK_ALIGNMENT, it will be
4202      aligned at MAX_SUPPORTED_STACK_ALIGNMENT.  We will match callee
4203      here with caller.  */
4204   if (boundary > MAX_SUPPORTED_STACK_ALIGNMENT)
4205     boundary = MAX_SUPPORTED_STACK_ALIGNMENT;
4206
4207   boundary /= BITS_PER_UNIT;
4208
4209   /* Hoist the valist value into a temporary for the moment.  */
4210   valist_tmp = get_initialized_tmp_var (valist, pre_p, NULL);
4211
4212   /* va_list pointer is aligned to PARM_BOUNDARY.  If argument actually
4213      requires greater alignment, we must perform dynamic alignment.  */
4214   if (boundary > align
4215       && !integer_zerop (TYPE_SIZE (type)))
4216     {
4217       t = build2 (MODIFY_EXPR, TREE_TYPE (valist), valist_tmp,
4218                   fold_build2 (POINTER_PLUS_EXPR,
4219                                TREE_TYPE (valist),
4220                                valist_tmp, size_int (boundary - 1)));
4221       gimplify_and_add (t, pre_p);
4222
4223       t = fold_convert (sizetype, valist_tmp);
4224       t = build2 (MODIFY_EXPR, TREE_TYPE (valist), valist_tmp,
4225                   fold_convert (TREE_TYPE (valist),
4226                                 fold_build2 (BIT_AND_EXPR, sizetype, t,
4227                                              size_int (-boundary))));
4228       gimplify_and_add (t, pre_p);
4229     }
4230   else
4231     boundary = align;
4232
4233   /* If the actual alignment is less than the alignment of the type,
4234      adjust the type accordingly so that we don't assume strict alignment
4235      when dereferencing the pointer.  */
4236   boundary *= BITS_PER_UNIT;
4237   if (boundary < TYPE_ALIGN (type))
4238     {
4239       type = build_variant_type_copy (type);
4240       TYPE_ALIGN (type) = boundary;
4241     }
4242
4243   /* Compute the rounded size of the type.  */
4244   type_size = size_in_bytes (type);
4245   rounded_size = round_up (type_size, align);
4246
4247   /* Reduce rounded_size so it's sharable with the postqueue.  */
4248   gimplify_expr (&rounded_size, pre_p, post_p, is_gimple_val, fb_rvalue);
4249
4250   /* Get AP.  */
4251   addr = valist_tmp;
4252   if (PAD_VARARGS_DOWN && !integer_zerop (rounded_size))
4253     {
4254       /* Small args are padded downward.  */
4255       t = fold_build2_loc (input_location, GT_EXPR, sizetype,
4256                        rounded_size, size_int (align));
4257       t = fold_build3 (COND_EXPR, sizetype, t, size_zero_node,
4258                        size_binop (MINUS_EXPR, rounded_size, type_size));
4259       addr = fold_build2 (POINTER_PLUS_EXPR,
4260                           TREE_TYPE (addr), addr, t);
4261     }
4262
4263   /* Compute new value for AP.  */
4264   t = build2 (POINTER_PLUS_EXPR, TREE_TYPE (valist), valist_tmp, rounded_size);
4265   t = build2 (MODIFY_EXPR, TREE_TYPE (valist), valist, t);
4266   gimplify_and_add (t, pre_p);
4267
4268   addr = fold_convert (build_pointer_type (type), addr);
4269
4270   if (indirect)
4271     addr = build_va_arg_indirect_ref (addr);
4272
4273   return build_va_arg_indirect_ref (addr);
4274 }
4275
4276 /* Build an indirect-ref expression over the given TREE, which represents a
4277    piece of a va_arg() expansion.  */
4278 tree
4279 build_va_arg_indirect_ref (tree addr)
4280 {
4281   addr = build_simple_mem_ref_loc (EXPR_LOCATION (addr), addr);
4282
4283   if (flag_mudflap) /* Don't instrument va_arg INDIRECT_REF.  */
4284     mf_mark (addr);
4285
4286   return addr;
4287 }
4288
4289 /* Return a dummy expression of type TYPE in order to keep going after an
4290    error.  */
4291
4292 static tree
4293 dummy_object (tree type)
4294 {
4295   tree t = build_int_cst (build_pointer_type (type), 0);
4296   return build2 (MEM_REF, type, t, t);
4297 }
4298
4299 /* Gimplify __builtin_va_arg, aka VA_ARG_EXPR, which is not really a
4300    builtin function, but a very special sort of operator.  */
4301
4302 enum gimplify_status
4303 gimplify_va_arg_expr (tree *expr_p, gimple_seq *pre_p, gimple_seq *post_p)
4304 {
4305   tree promoted_type, have_va_type;
4306   tree valist = TREE_OPERAND (*expr_p, 0);
4307   tree type = TREE_TYPE (*expr_p);
4308   tree t;
4309   location_t loc = EXPR_LOCATION (*expr_p);
4310
4311   /* Verify that valist is of the proper type.  */
4312   have_va_type = TREE_TYPE (valist);
4313   if (have_va_type == error_mark_node)
4314     return GS_ERROR;
4315   have_va_type = targetm.canonical_va_list_type (have_va_type);
4316
4317   if (have_va_type == NULL_TREE)
4318     {
4319       error_at (loc, "first argument to %<va_arg%> not of type %<va_list%>");
4320       return GS_ERROR;
4321     }
4322
4323   /* Generate a diagnostic for requesting data of a type that cannot
4324      be passed through `...' due to type promotion at the call site.  */
4325   if ((promoted_type = lang_hooks.types.type_promotes_to (type))
4326            != type)
4327     {
4328       static bool gave_help;
4329       bool warned;
4330
4331       /* Unfortunately, this is merely undefined, rather than a constraint
4332          violation, so we cannot make this an error.  If this call is never
4333          executed, the program is still strictly conforming.  */
4334       warned = warning_at (loc, 0,
4335                            "%qT is promoted to %qT when passed through %<...%>",
4336                            type, promoted_type);
4337       if (!gave_help && warned)
4338         {
4339           gave_help = true;
4340           inform (loc, "(so you should pass %qT not %qT to %<va_arg%>)",
4341                   promoted_type, type);
4342         }
4343
4344       /* We can, however, treat "undefined" any way we please.
4345          Call abort to encourage the user to fix the program.  */
4346       if (warned)
4347         inform (loc, "if this code is reached, the program will abort");
4348       /* Before the abort, allow the evaluation of the va_list
4349          expression to exit or longjmp.  */
4350       gimplify_and_add (valist, pre_p);
4351       t = build_call_expr_loc (loc,
4352                                implicit_built_in_decls[BUILT_IN_TRAP], 0);
4353       gimplify_and_add (t, pre_p);
4354
4355       /* This is dead code, but go ahead and finish so that the
4356          mode of the result comes out right.  */
4357       *expr_p = dummy_object (type);
4358       return GS_ALL_DONE;
4359     }
4360   else
4361     {
4362       /* Make it easier for the backends by protecting the valist argument
4363          from multiple evaluations.  */
4364       if (TREE_CODE (have_va_type) == ARRAY_TYPE)
4365         {
4366           /* For this case, the backends will be expecting a pointer to
4367              TREE_TYPE (abi), but it's possible we've
4368              actually been given an array (an actual TARGET_FN_ABI_VA_LIST).
4369              So fix it.  */
4370           if (TREE_CODE (TREE_TYPE (valist)) == ARRAY_TYPE)
4371             {
4372               tree p1 = build_pointer_type (TREE_TYPE (have_va_type));
4373               valist = fold_convert_loc (loc, p1,
4374                                          build_fold_addr_expr_loc (loc, valist));
4375             }
4376
4377           gimplify_expr (&valist, pre_p, post_p, is_gimple_val, fb_rvalue);
4378         }
4379       else
4380         gimplify_expr (&valist, pre_p, post_p, is_gimple_min_lval, fb_lvalue);
4381
4382       if (!targetm.gimplify_va_arg_expr)
4383         /* FIXME: Once most targets are converted we should merely
4384            assert this is non-null.  */
4385         return GS_ALL_DONE;
4386
4387       *expr_p = targetm.gimplify_va_arg_expr (valist, type, pre_p, post_p);
4388       return GS_OK;
4389     }
4390 }
4391
4392 /* Expand EXP, a call to __builtin_va_end.  */
4393
4394 static rtx
4395 expand_builtin_va_end (tree exp)
4396 {
4397   tree valist = CALL_EXPR_ARG (exp, 0);
4398
4399   /* Evaluate for side effects, if needed.  I hate macros that don't
4400      do that.  */
4401   if (TREE_SIDE_EFFECTS (valist))
4402     expand_expr (valist, const0_rtx, VOIDmode, EXPAND_NORMAL);
4403
4404   return const0_rtx;
4405 }
4406
4407 /* Expand EXP, a call to __builtin_va_copy.  We do this as a
4408    builtin rather than just as an assignment in stdarg.h because of the
4409    nastiness of array-type va_list types.  */
4410
4411 static rtx
4412 expand_builtin_va_copy (tree exp)
4413 {
4414   tree dst, src, t;
4415   location_t loc = EXPR_LOCATION (exp);
4416
4417   dst = CALL_EXPR_ARG (exp, 0);
4418   src = CALL_EXPR_ARG (exp, 1);
4419
4420   dst = stabilize_va_list_loc (loc, dst, 1);
4421   src = stabilize_va_list_loc (loc, src, 0);
4422
4423   gcc_assert (cfun != NULL && cfun->decl != NULL_TREE);
4424
4425   if (TREE_CODE (targetm.fn_abi_va_list (cfun->decl)) != ARRAY_TYPE)
4426     {
4427       t = build2 (MODIFY_EXPR, targetm.fn_abi_va_list (cfun->decl), dst, src);
4428       TREE_SIDE_EFFECTS (t) = 1;
4429       expand_expr (t, const0_rtx, VOIDmode, EXPAND_NORMAL);
4430     }
4431   else
4432     {
4433       rtx dstb, srcb, size;
4434
4435       /* Evaluate to pointers.  */
4436       dstb = expand_expr (dst, NULL_RTX, Pmode, EXPAND_NORMAL);
4437       srcb = expand_expr (src, NULL_RTX, Pmode, EXPAND_NORMAL);
4438       size = expand_expr (TYPE_SIZE_UNIT (targetm.fn_abi_va_list (cfun->decl)),
4439                   NULL_RTX, VOIDmode, EXPAND_NORMAL);
4440
4441       dstb = convert_memory_address (Pmode, dstb);
4442       srcb = convert_memory_address (Pmode, srcb);
4443
4444       /* "Dereference" to BLKmode memories.  */
4445       dstb = gen_rtx_MEM (BLKmode, dstb);
4446       set_mem_alias_set (dstb, get_alias_set (TREE_TYPE (TREE_TYPE (dst))));
4447       set_mem_align (dstb, TYPE_ALIGN (targetm.fn_abi_va_list (cfun->decl)));
4448       srcb = gen_rtx_MEM (BLKmode, srcb);
4449       set_mem_alias_set (srcb, get_alias_set (TREE_TYPE (TREE_TYPE (src))));
4450       set_mem_align (srcb, TYPE_ALIGN (targetm.fn_abi_va_list (cfun->decl)));
4451
4452       /* Copy.  */
4453       emit_block_move (dstb, srcb, size, BLOCK_OP_NORMAL);
4454     }
4455
4456   return const0_rtx;
4457 }
4458
4459 /* Expand a call to one of the builtin functions __builtin_frame_address or
4460    __builtin_return_address.  */
4461
4462 static rtx
4463 expand_builtin_frame_address (tree fndecl, tree exp)
4464 {
4465   /* The argument must be a nonnegative integer constant.
4466      It counts the number of frames to scan up the stack.
4467      The value is the return address saved in that frame.  */
4468   if (call_expr_nargs (exp) == 0)
4469     /* Warning about missing arg was already issued.  */
4470     return const0_rtx;
4471   else if (! host_integerp (CALL_EXPR_ARG (exp, 0), 1))
4472     {
4473       if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_FRAME_ADDRESS)
4474         error ("invalid argument to %<__builtin_frame_address%>");
4475       else
4476         error ("invalid argument to %<__builtin_return_address%>");
4477       return const0_rtx;
4478     }
4479   else
4480     {
4481       rtx tem
4482         = expand_builtin_return_addr (DECL_FUNCTION_CODE (fndecl),
4483                                       tree_low_cst (CALL_EXPR_ARG (exp, 0), 1));
4484
4485       /* Some ports cannot access arbitrary stack frames.  */
4486       if (tem == NULL)
4487         {
4488           if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_FRAME_ADDRESS)
4489             warning (0, "unsupported argument to %<__builtin_frame_address%>");
4490           else
4491             warning (0, "unsupported argument to %<__builtin_return_address%>");
4492           return const0_rtx;
4493         }
4494
4495       /* For __builtin_frame_address, return what we've got.  */
4496       if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_FRAME_ADDRESS)
4497         return tem;
4498
4499       if (!REG_P (tem)
4500           && ! CONSTANT_P (tem))
4501         tem = copy_to_mode_reg (Pmode, tem);
4502       return tem;
4503     }
4504 }
4505
4506 /* Expand EXP, a call to the alloca builtin.  Return NULL_RTX if we
4507    failed and the caller should emit a normal call.  CANNOT_ACCUMULATE
4508    is the same as for allocate_dynamic_stack_space.  */
4509
4510 static rtx
4511 expand_builtin_alloca (tree exp, bool cannot_accumulate)
4512 {
4513   rtx op0;
4514   rtx result;
4515
4516   /* Emit normal call if marked not-inlineable.  */
4517   if (CALL_CANNOT_INLINE_P (exp))
4518     return NULL_RTX;
4519
4520   if (!validate_arglist (exp, INTEGER_TYPE, VOID_TYPE))
4521     return NULL_RTX;
4522
4523   /* Compute the argument.  */
4524   op0 = expand_normal (CALL_EXPR_ARG (exp, 0));
4525
4526   /* Allocate the desired space.  */
4527   result = allocate_dynamic_stack_space (op0, 0, BIGGEST_ALIGNMENT,
4528                                          cannot_accumulate);
4529   result = convert_memory_address (ptr_mode, result);
4530
4531   return result;
4532 }
4533
4534 /* Expand a call to a bswap builtin with argument ARG0.  MODE
4535    is the mode to expand with.  */
4536
4537 static rtx
4538 expand_builtin_bswap (tree exp, rtx target, rtx subtarget)
4539 {
4540   enum machine_mode mode;
4541   tree arg;
4542   rtx op0;
4543
4544   if (!validate_arglist (exp, INTEGER_TYPE, VOID_TYPE))
4545     return NULL_RTX;
4546
4547   arg = CALL_EXPR_ARG (exp, 0);
4548   mode = TYPE_MODE (TREE_TYPE (arg));
4549   op0 = expand_expr (arg, subtarget, VOIDmode, EXPAND_NORMAL);
4550
4551   target = expand_unop (mode, bswap_optab, op0, target, 1);
4552
4553   gcc_assert (target);
4554
4555   return convert_to_mode (mode, target, 0);
4556 }
4557
4558 /* Expand a call to a unary builtin in EXP.
4559    Return NULL_RTX if a normal call should be emitted rather than expanding the
4560    function in-line.  If convenient, the result should be placed in TARGET.
4561    SUBTARGET may be used as the target for computing one of EXP's operands.  */
4562
4563 static rtx
4564 expand_builtin_unop (enum machine_mode target_mode, tree exp, rtx target,
4565                      rtx subtarget, optab op_optab)
4566 {
4567   rtx op0;
4568
4569   if (!validate_arglist (exp, INTEGER_TYPE, VOID_TYPE))
4570     return NULL_RTX;
4571
4572   /* Compute the argument.  */
4573   op0 = expand_expr (CALL_EXPR_ARG (exp, 0),
4574                      (subtarget
4575                       && (TYPE_MODE (TREE_TYPE (CALL_EXPR_ARG (exp, 0)))
4576                           == GET_MODE (subtarget))) ? subtarget : NULL_RTX,
4577                      VOIDmode, EXPAND_NORMAL);
4578   /* Compute op, into TARGET if possible.
4579      Set TARGET to wherever the result comes back.  */
4580   target = expand_unop (TYPE_MODE (TREE_TYPE (CALL_EXPR_ARG (exp, 0))),
4581                         op_optab, op0, target, op_optab != clrsb_optab);
4582   gcc_assert (target);
4583
4584   return convert_to_mode (target_mode, target, 0);
4585 }
4586
4587 /* Expand a call to __builtin_expect.  We just return our argument
4588    as the builtin_expect semantic should've been already executed by
4589    tree branch prediction pass. */
4590
4591 static rtx
4592 expand_builtin_expect (tree exp, rtx target)
4593 {
4594   tree arg;
4595
4596   if (call_expr_nargs (exp) < 2)
4597     return const0_rtx;
4598   arg = CALL_EXPR_ARG (exp, 0);
4599
4600   target = expand_expr (arg, target, VOIDmode, EXPAND_NORMAL);
4601   /* When guessing was done, the hints should be already stripped away.  */
4602   gcc_assert (!flag_guess_branch_prob
4603               || optimize == 0 || seen_error ());
4604   return target;
4605 }
4606
4607 /* Expand a call to __builtin_assume_aligned.  We just return our first
4608    argument as the builtin_assume_aligned semantic should've been already
4609    executed by CCP.  */
4610
4611 static rtx
4612 expand_builtin_assume_aligned (tree exp, rtx target)
4613 {
4614   if (call_expr_nargs (exp) < 2)
4615     return const0_rtx;
4616   target = expand_expr (CALL_EXPR_ARG (exp, 0), target, VOIDmode,
4617                         EXPAND_NORMAL);
4618   gcc_assert (!TREE_SIDE_EFFECTS (CALL_EXPR_ARG (exp, 1))
4619               && (call_expr_nargs (exp) < 3
4620                   || !TREE_SIDE_EFFECTS (CALL_EXPR_ARG (exp, 2))));
4621   return target;
4622 }
4623
4624 void
4625 expand_builtin_trap (void)
4626 {
4627 #ifdef HAVE_trap
4628   if (HAVE_trap)
4629     emit_insn (gen_trap ());
4630   else
4631 #endif
4632     emit_library_call (abort_libfunc, LCT_NORETURN, VOIDmode, 0);
4633   emit_barrier ();
4634 }
4635
4636 /* Expand a call to __builtin_unreachable.  We do nothing except emit
4637    a barrier saying that control flow will not pass here.
4638
4639    It is the responsibility of the program being compiled to ensure
4640    that control flow does never reach __builtin_unreachable.  */
4641 static void
4642 expand_builtin_unreachable (void)
4643 {
4644   emit_barrier ();
4645 }
4646
4647 /* Expand EXP, a call to fabs, fabsf or fabsl.
4648    Return NULL_RTX if a normal call should be emitted rather than expanding
4649    the function inline.  If convenient, the result should be placed
4650    in TARGET.  SUBTARGET may be used as the target for computing
4651    the operand.  */
4652
4653 static rtx
4654 expand_builtin_fabs (tree exp, rtx target, rtx subtarget)
4655 {
4656   enum machine_mode mode;
4657   tree arg;
4658   rtx op0;
4659
4660   if (!validate_arglist (exp, REAL_TYPE, VOID_TYPE))
4661     return NULL_RTX;
4662
4663   arg = CALL_EXPR_ARG (exp, 0);
4664   CALL_EXPR_ARG (exp, 0) = arg = builtin_save_expr (arg);
4665   mode = TYPE_MODE (TREE_TYPE (arg));
4666   op0 = expand_expr (arg, subtarget, VOIDmode, EXPAND_NORMAL);
4667   return expand_abs (mode, op0, target, 0, safe_from_p (target, arg, 1));
4668 }
4669
4670 /* Expand EXP, a call to copysign, copysignf, or copysignl.
4671    Return NULL is a normal call should be emitted rather than expanding the
4672    function inline.  If convenient, the result should be placed in TARGET.
4673    SUBTARGET may be used as the target for computing the operand.  */
4674
4675 static rtx
4676 expand_builtin_copysign (tree exp, rtx target, rtx subtarget)
4677 {
4678   rtx op0, op1;
4679   tree arg;
4680
4681   if (!validate_arglist (exp, REAL_TYPE, REAL_TYPE, VOID_TYPE))
4682     return NULL_RTX;
4683
4684   arg = CALL_EXPR_ARG (exp, 0);
4685   op0 = expand_expr (arg, subtarget, VOIDmode, EXPAND_NORMAL);
4686
4687   arg = CALL_EXPR_ARG (exp, 1);
4688   op1 = expand_normal (arg);
4689
4690   return expand_copysign (op0, op1, target);
4691 }
4692
4693 /* Create a new constant string literal and return a char* pointer to it.
4694    The STRING_CST value is the LEN characters at STR.  */
4695 tree
4696 build_string_literal (int len, const char *str)
4697 {
4698   tree t, elem, index, type;
4699
4700   t = build_string (len, str);
4701   elem = build_type_variant (char_type_node, 1, 0);
4702   index = build_index_type (size_int (len - 1));
4703   type = build_array_type (elem, index);
4704   TREE_TYPE (t) = type;
4705   TREE_CONSTANT (t) = 1;
4706   TREE_READONLY (t) = 1;
4707   TREE_STATIC (t) = 1;
4708
4709   type = build_pointer_type (elem);
4710   t = build1 (ADDR_EXPR, type,
4711               build4 (ARRAY_REF, elem,
4712                       t, integer_zero_node, NULL_TREE, NULL_TREE));
4713   return t;
4714 }
4715
4716 /* Expand a call to __builtin___clear_cache.  */
4717
4718 static rtx
4719 expand_builtin___clear_cache (tree exp ATTRIBUTE_UNUSED)
4720 {
4721 #ifndef HAVE_clear_cache
4722 #ifdef CLEAR_INSN_CACHE
4723   /* There is no "clear_cache" insn, and __clear_cache() in libgcc
4724      does something.  Just do the default expansion to a call to
4725      __clear_cache().  */
4726   return NULL_RTX;
4727 #else
4728   /* There is no "clear_cache" insn, and __clear_cache() in libgcc
4729      does nothing.  There is no need to call it.  Do nothing.  */
4730   return const0_rtx;
4731 #endif /* CLEAR_INSN_CACHE */
4732 #else
4733   /* We have a "clear_cache" insn, and it will handle everything.  */
4734   tree begin, end;
4735   rtx begin_rtx, end_rtx;
4736
4737   /* We must not expand to a library call.  If we did, any
4738      fallback library function in libgcc that might contain a call to
4739      __builtin___clear_cache() would recurse infinitely.  */
4740   if (!validate_arglist (exp, POINTER_TYPE, POINTER_TYPE, VOID_TYPE))
4741     {
4742       error ("both arguments to %<__builtin___clear_cache%> must be pointers");
4743       return const0_rtx;
4744     }
4745
4746   if (HAVE_clear_cache)
4747     {
4748       struct expand_operand ops[2];
4749
4750       begin = CALL_EXPR_ARG (exp, 0);
4751       begin_rtx = expand_expr (begin, NULL_RTX, Pmode, EXPAND_NORMAL);
4752
4753       end = CALL_EXPR_ARG (exp, 1);
4754       end_rtx = expand_expr (end, NULL_RTX, Pmode, EXPAND_NORMAL);
4755
4756       create_address_operand (&ops[0], begin_rtx);
4757       create_address_operand (&ops[1], end_rtx);
4758       if (maybe_expand_insn (CODE_FOR_clear_cache, 2, ops))
4759         return const0_rtx;
4760     }
4761   return const0_rtx;
4762 #endif /* HAVE_clear_cache */
4763 }
4764
4765 /* Given a trampoline address, make sure it satisfies TRAMPOLINE_ALIGNMENT.  */
4766
4767 static rtx
4768 round_trampoline_addr (rtx tramp)
4769 {
4770   rtx temp, addend, mask;
4771
4772   /* If we don't need too much alignment, we'll have been guaranteed
4773      proper alignment by get_trampoline_type.  */
4774   if (TRAMPOLINE_ALIGNMENT <= STACK_BOUNDARY)
4775     return tramp;
4776
4777   /* Round address up to desired boundary.  */
4778   temp = gen_reg_rtx (Pmode);
4779   addend = GEN_INT (TRAMPOLINE_ALIGNMENT / BITS_PER_UNIT - 1);
4780   mask = GEN_INT (-TRAMPOLINE_ALIGNMENT / BITS_PER_UNIT);
4781
4782   temp  = expand_simple_binop (Pmode, PLUS, tramp, addend,
4783                                temp, 0, OPTAB_LIB_WIDEN);
4784   tramp = expand_simple_binop (Pmode, AND, temp, mask,
4785                                temp, 0, OPTAB_LIB_WIDEN);
4786
4787   return tramp;
4788 }
4789
4790 static rtx
4791 expand_builtin_init_trampoline (tree exp)
4792 {
4793   tree t_tramp, t_func, t_chain;
4794   rtx m_tramp, r_tramp, r_chain, tmp;
4795
4796   if (!validate_arglist (exp, POINTER_TYPE, POINTER_TYPE,
4797                          POINTER_TYPE, VOID_TYPE))
4798     return NULL_RTX;
4799
4800   t_tramp = CALL_EXPR_ARG (exp, 0);
4801   t_func = CALL_EXPR_ARG (exp, 1);
4802   t_chain = CALL_EXPR_ARG (exp, 2);
4803
4804   r_tramp = expand_normal (t_tramp);
4805   m_tramp = gen_rtx_MEM (BLKmode, r_tramp);
4806   MEM_NOTRAP_P (m_tramp) = 1;
4807
4808   /* The TRAMP argument should be the address of a field within the
4809      local function's FRAME decl.  Let's see if we can fill in the
4810      to fill in the MEM_ATTRs for this memory.  */
4811   if (TREE_CODE (t_tramp) == ADDR_EXPR)
4812     set_mem_attributes_minus_bitpos (m_tramp, TREE_OPERAND (t_tramp, 0),
4813                                      true, 0);
4814
4815   tmp = round_trampoline_addr (r_tramp);
4816   if (tmp != r_tramp)
4817     {
4818       m_tramp = change_address (m_tramp, BLKmode, tmp);
4819       set_mem_align (m_tramp, TRAMPOLINE_ALIGNMENT);
4820       set_mem_size (m_tramp, GEN_INT (TRAMPOLINE_SIZE));
4821     }
4822
4823   /* The FUNC argument should be the address of the nested function.
4824      Extract the actual function decl to pass to the hook.  */
4825   gcc_assert (TREE_CODE (t_func) == ADDR_EXPR);
4826   t_func = TREE_OPERAND (t_func, 0);
4827   gcc_assert (TREE_CODE (t_func) == FUNCTION_DECL);
4828
4829   r_chain = expand_normal (t_chain);
4830
4831   /* Generate insns to initialize the trampoline.  */
4832   targetm.calls.trampoline_init (m_tramp, t_func, r_chain);
4833
4834   trampolines_created = 1;
4835
4836   warning_at (DECL_SOURCE_LOCATION (t_func), OPT_Wtrampolines,
4837               "trampoline generated for nested function %qD", t_func);
4838
4839   return const0_rtx;
4840 }
4841
4842 static rtx
4843 expand_builtin_adjust_trampoline (tree exp)
4844 {
4845   rtx tramp;
4846
4847   if (!validate_arglist (exp, POINTER_TYPE, VOID_TYPE))
4848     return NULL_RTX;
4849
4850   tramp = expand_normal (CALL_EXPR_ARG (exp, 0));
4851   tramp = round_trampoline_addr (tramp);
4852   if (targetm.calls.trampoline_adjust_address)
4853     tramp = targetm.calls.trampoline_adjust_address (tramp);
4854
4855   return tramp;
4856 }
4857
4858 /* Expand the call EXP to the built-in signbit, signbitf or signbitl
4859    function.  The function first checks whether the back end provides
4860    an insn to implement signbit for the respective mode.  If not, it
4861    checks whether the floating point format of the value is such that
4862    the sign bit can be extracted.  If that is not the case, the
4863    function returns NULL_RTX to indicate that a normal call should be
4864    emitted rather than expanding the function in-line.  EXP is the
4865    expression that is a call to the builtin function; if convenient,
4866    the result should be placed in TARGET.  */
4867 static rtx
4868 expand_builtin_signbit (tree exp, rtx target)
4869 {
4870   const struct real_format *fmt;
4871   enum machine_mode fmode, imode, rmode;
4872   tree arg;
4873   int word, bitpos;
4874   enum insn_code icode;
4875   rtx temp;
4876   location_t loc = EXPR_LOCATION (exp);
4877
4878   if (!validate_arglist (exp, REAL_TYPE, VOID_TYPE))
4879     return NULL_RTX;
4880
4881   arg = CALL_EXPR_ARG (exp, 0);
4882   fmode = TYPE_MODE (TREE_TYPE (arg));
4883   rmode = TYPE_MODE (TREE_TYPE (exp));
4884   fmt = REAL_MODE_FORMAT (fmode);
4885
4886   arg = builtin_save_expr (arg);
4887
4888   /* Expand the argument yielding a RTX expression. */
4889   temp = expand_normal (arg);
4890
4891   /* Check if the back end provides an insn that handles signbit for the
4892      argument's mode. */
4893   icode = optab_handler (signbit_optab, fmode);
4894   if (icode != CODE_FOR_nothing)
4895     {
4896       rtx last = get_last_insn ();
4897       target = gen_reg_rtx (TYPE_MODE (TREE_TYPE (exp)));
4898       if (maybe_emit_unop_insn (icode, target, temp, UNKNOWN))
4899         return target;
4900       delete_insns_since (last);
4901     }
4902
4903   /* For floating point formats without a sign bit, implement signbit
4904      as "ARG < 0.0".  */
4905   bitpos = fmt->signbit_ro;
4906   if (bitpos < 0)
4907   {
4908     /* But we can't do this if the format supports signed zero.  */
4909     if (fmt->has_signed_zero && HONOR_SIGNED_ZEROS (fmode))
4910       return NULL_RTX;
4911
4912     arg = fold_build2_loc (loc, LT_EXPR, TREE_TYPE (exp), arg,
4913                        build_real (TREE_TYPE (arg), dconst0));
4914     return expand_expr (arg, target, VOIDmode, EXPAND_NORMAL);
4915   }
4916
4917   if (GET_MODE_SIZE (fmode) <= UNITS_PER_WORD)
4918     {
4919       imode = int_mode_for_mode (fmode);
4920       if (imode == BLKmode)
4921         return NULL_RTX;
4922       temp = gen_lowpart (imode, temp);
4923     }
4924   else
4925     {
4926       imode = word_mode;
4927       /* Handle targets with different FP word orders.  */
4928       if (FLOAT_WORDS_BIG_ENDIAN)
4929         word = (GET_MODE_BITSIZE (fmode) - bitpos) / BITS_PER_WORD;
4930       else
4931         word = bitpos / BITS_PER_WORD;
4932       temp = operand_subword_force (temp, word, fmode);
4933       bitpos = bitpos % BITS_PER_WORD;
4934     }
4935
4936   /* Force the intermediate word_mode (or narrower) result into a
4937      register.  This avoids attempting to create paradoxical SUBREGs
4938      of floating point modes below.  */
4939   temp = force_reg (imode, temp);
4940
4941   /* If the bitpos is within the "result mode" lowpart, the operation
4942      can be implement with a single bitwise AND.  Otherwise, we need
4943      a right shift and an AND.  */
4944
4945   if (bitpos < GET_MODE_BITSIZE (rmode))
4946     {
4947       double_int mask = double_int_setbit (double_int_zero, bitpos);
4948
4949       if (GET_MODE_SIZE (imode) > GET_MODE_SIZE (rmode))
4950         temp = gen_lowpart (rmode, temp);
4951       temp = expand_binop (rmode, and_optab, temp,
4952                            immed_double_int_const (mask, rmode),
4953                            NULL_RTX, 1, OPTAB_LIB_WIDEN);
4954     }
4955   else
4956     {
4957       /* Perform a logical right shift to place the signbit in the least
4958          significant bit, then truncate the result to the desired mode
4959          and mask just this bit.  */
4960       temp = expand_shift (RSHIFT_EXPR, imode, temp, bitpos, NULL_RTX, 1);
4961       temp = gen_lowpart (rmode, temp);
4962       temp = expand_binop (rmode, and_optab, temp, const1_rtx,
4963                            NULL_RTX, 1, OPTAB_LIB_WIDEN);
4964     }
4965
4966   return temp;
4967 }
4968
4969 /* Expand fork or exec calls.  TARGET is the desired target of the
4970    call.  EXP is the call. FN is the
4971    identificator of the actual function.  IGNORE is nonzero if the
4972    value is to be ignored.  */
4973
4974 static rtx
4975 expand_builtin_fork_or_exec (tree fn, tree exp, rtx target, int ignore)
4976 {
4977   tree id, decl;
4978   tree call;
4979
4980   /* If we are not profiling, just call the function.  */
4981   if (!profile_arc_flag)
4982     return NULL_RTX;
4983
4984   /* Otherwise call the wrapper.  This should be equivalent for the rest of
4985      compiler, so the code does not diverge, and the wrapper may run the
4986      code necessary for keeping the profiling sane.  */
4987
4988   switch (DECL_FUNCTION_CODE (fn))
4989     {
4990     case BUILT_IN_FORK:
4991       id = get_identifier ("__gcov_fork");
4992       break;
4993
4994     case BUILT_IN_EXECL:
4995       id = get_identifier ("__gcov_execl");
4996       break;
4997
4998     case BUILT_IN_EXECV:
4999       id = get_identifier ("__gcov_execv");
5000       break;
5001
5002     case BUILT_IN_EXECLP:
5003       id = get_identifier ("__gcov_execlp");
5004       break;
5005
5006     case BUILT_IN_EXECLE:
5007       id = get_identifier ("__gcov_execle");
5008       break;
5009
5010     case BUILT_IN_EXECVP:
5011       id = get_identifier ("__gcov_execvp");
5012       break;
5013
5014     case BUILT_IN_EXECVE:
5015       id = get_identifier ("__gcov_execve");
5016       break;
5017
5018     default:
5019       gcc_unreachable ();
5020     }
5021
5022   decl = build_decl (DECL_SOURCE_LOCATION (fn),
5023                      FUNCTION_DECL, id, TREE_TYPE (fn));
5024   DECL_EXTERNAL (decl) = 1;
5025   TREE_PUBLIC (decl) = 1;
5026   DECL_ARTIFICIAL (decl) = 1;
5027   TREE_NOTHROW (decl) = 1;
5028   DECL_VISIBILITY (decl) = VISIBILITY_DEFAULT;
5029   DECL_VISIBILITY_SPECIFIED (decl) = 1;
5030   call = rewrite_call_expr (EXPR_LOCATION (exp), exp, 0, decl, 0);
5031   return expand_call (call, target, ignore);
5032  }
5033
5034
5035 \f
5036 /* Reconstitute a mode for a __sync intrinsic operation.  Since the type of
5037    the pointer in these functions is void*, the tree optimizers may remove
5038    casts.  The mode computed in expand_builtin isn't reliable either, due
5039    to __sync_bool_compare_and_swap.
5040
5041    FCODE_DIFF should be fcode - base, where base is the FOO_1 code for the
5042    group of builtins.  This gives us log2 of the mode size.  */
5043
5044 static inline enum machine_mode
5045 get_builtin_sync_mode (int fcode_diff)
5046 {
5047   /* The size is not negotiable, so ask not to get BLKmode in return
5048      if the target indicates that a smaller size would be better.  */
5049   return mode_for_size (BITS_PER_UNIT << fcode_diff, MODE_INT, 0);
5050 }
5051
5052 /* Expand the memory expression LOC and return the appropriate memory operand
5053    for the builtin_sync operations.  */
5054
5055 static rtx
5056 get_builtin_sync_mem (tree loc, enum machine_mode mode)
5057 {
5058   rtx addr, mem;
5059
5060   addr = expand_expr (loc, NULL_RTX, ptr_mode, EXPAND_SUM);
5061   addr = convert_memory_address (Pmode, addr);
5062
5063   /* Note that we explicitly do not want any alias information for this
5064      memory, so that we kill all other live memories.  Otherwise we don't
5065      satisfy the full barrier semantics of the intrinsic.  */
5066   mem = validize_mem (gen_rtx_MEM (mode, addr));
5067
5068   /* The alignment needs to be at least according to that of the mode.  */
5069   set_mem_align (mem, MAX (GET_MODE_ALIGNMENT (mode),
5070                            get_pointer_alignment (loc, BIGGEST_ALIGNMENT)));
5071   set_mem_alias_set (mem, ALIAS_SET_MEMORY_BARRIER);
5072   MEM_VOLATILE_P (mem) = 1;
5073
5074   return mem;
5075 }
5076
5077 /* Expand the __sync_xxx_and_fetch and __sync_fetch_and_xxx intrinsics.
5078    EXP is the CALL_EXPR.  CODE is the rtx code
5079    that corresponds to the arithmetic or logical operation from the name;
5080    an exception here is that NOT actually means NAND.  TARGET is an optional
5081    place for us to store the results; AFTER is true if this is the
5082    fetch_and_xxx form.  IGNORE is true if we don't actually care about
5083    the result of the operation at all.  */
5084
5085 static rtx
5086 expand_builtin_sync_operation (enum machine_mode mode, tree exp,
5087                                enum rtx_code code, bool after,
5088                                rtx target, bool ignore)
5089 {
5090   rtx val, mem;
5091   enum machine_mode old_mode;
5092   location_t loc = EXPR_LOCATION (exp);
5093
5094   if (code == NOT && warn_sync_nand)
5095     {
5096       tree fndecl = get_callee_fndecl (exp);
5097       enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
5098
5099       static bool warned_f_a_n, warned_n_a_f;
5100
5101       switch (fcode)
5102         {
5103         case BUILT_IN_SYNC_FETCH_AND_NAND_1:
5104         case BUILT_IN_SYNC_FETCH_AND_NAND_2:
5105         case BUILT_IN_SYNC_FETCH_AND_NAND_4:
5106         case BUILT_IN_SYNC_FETCH_AND_NAND_8:
5107         case BUILT_IN_SYNC_FETCH_AND_NAND_16:
5108
5109           if (warned_f_a_n)
5110             break;
5111
5112           fndecl = implicit_built_in_decls[BUILT_IN_SYNC_FETCH_AND_NAND_N];
5113           inform (loc, "%qD changed semantics in GCC 4.4", fndecl);
5114           warned_f_a_n = true;
5115           break;
5116
5117         case BUILT_IN_SYNC_NAND_AND_FETCH_1:
5118         case BUILT_IN_SYNC_NAND_AND_FETCH_2:
5119         case BUILT_IN_SYNC_NAND_AND_FETCH_4:
5120         case BUILT_IN_SYNC_NAND_AND_FETCH_8:
5121         case BUILT_IN_SYNC_NAND_AND_FETCH_16:
5122
5123           if (warned_n_a_f)
5124             break;
5125
5126           fndecl = implicit_built_in_decls[BUILT_IN_SYNC_NAND_AND_FETCH_N];
5127           inform (loc, "%qD changed semantics in GCC 4.4", fndecl);
5128           warned_n_a_f = true;
5129           break;
5130
5131         default:
5132           gcc_unreachable ();
5133         }
5134     }
5135
5136   /* Expand the operands.  */
5137   mem = get_builtin_sync_mem (CALL_EXPR_ARG (exp, 0), mode);
5138
5139   val = expand_expr (CALL_EXPR_ARG (exp, 1), NULL_RTX, mode, EXPAND_NORMAL);
5140   /* If VAL is promoted to a wider mode, convert it back to MODE.  Take care
5141      of CONST_INTs, where we know the old_mode only from the call argument.  */
5142   old_mode = GET_MODE (val);
5143   if (old_mode == VOIDmode)
5144     old_mode = TYPE_MODE (TREE_TYPE (CALL_EXPR_ARG (exp, 1)));
5145   val = convert_modes (mode, old_mode, val, 1);
5146
5147   if (ignore)
5148     return expand_sync_operation (mem, val, code);
5149   else
5150     return expand_sync_fetch_operation (mem, val, code, after, target);
5151 }
5152
5153 /* Expand the __sync_val_compare_and_swap and __sync_bool_compare_and_swap
5154    intrinsics. EXP is the CALL_EXPR.  IS_BOOL is
5155    true if this is the boolean form.  TARGET is a place for us to store the
5156    results; this is NOT optional if IS_BOOL is true.  */
5157
5158 static rtx
5159 expand_builtin_compare_and_swap (enum machine_mode mode, tree exp,
5160                                  bool is_bool, rtx target)
5161 {
5162   rtx old_val, new_val, mem;
5163   enum machine_mode old_mode;
5164
5165   /* Expand the operands.  */
5166   mem = get_builtin_sync_mem (CALL_EXPR_ARG (exp, 0), mode);
5167
5168
5169   old_val = expand_expr (CALL_EXPR_ARG (exp, 1), NULL_RTX,
5170                          mode, EXPAND_NORMAL);
5171   /* If VAL is promoted to a wider mode, convert it back to MODE.  Take care
5172      of CONST_INTs, where we know the old_mode only from the call argument.  */
5173   old_mode = GET_MODE (old_val);
5174   if (old_mode == VOIDmode)
5175     old_mode = TYPE_MODE (TREE_TYPE (CALL_EXPR_ARG (exp, 1)));
5176   old_val = convert_modes (mode, old_mode, old_val, 1);
5177
5178   new_val = expand_expr (CALL_EXPR_ARG (exp, 2), NULL_RTX,
5179                          mode, EXPAND_NORMAL);
5180   /* If VAL is promoted to a wider mode, convert it back to MODE.  Take care
5181      of CONST_INTs, where we know the old_mode only from the call argument.  */
5182   old_mode = GET_MODE (new_val);
5183   if (old_mode == VOIDmode)
5184     old_mode = TYPE_MODE (TREE_TYPE (CALL_EXPR_ARG (exp, 2)));
5185   new_val = convert_modes (mode, old_mode, new_val, 1);
5186
5187   if (is_bool)
5188     return expand_bool_compare_and_swap (mem, old_val, new_val, target);
5189   else
5190     return expand_val_compare_and_swap (mem, old_val, new_val, target);
5191 }
5192
5193 /* Expand the __sync_lock_test_and_set intrinsic.  Note that the most
5194    general form is actually an atomic exchange, and some targets only
5195    support a reduced form with the second argument being a constant 1.
5196    EXP is the CALL_EXPR; TARGET is an optional place for us to store
5197    the results.  */
5198
5199 static rtx
5200 expand_builtin_sync_lock_test_and_set (enum machine_mode mode, tree exp,
5201                                   rtx target)
5202 {
5203   rtx val, mem;
5204   enum machine_mode old_mode;
5205
5206   /* Expand the operands.  */
5207   mem = get_builtin_sync_mem (CALL_EXPR_ARG (exp, 0), mode);
5208   val = expand_expr (CALL_EXPR_ARG (exp, 1), NULL_RTX, mode, EXPAND_NORMAL);
5209   /* If VAL is promoted to a wider mode, convert it back to MODE.  Take care
5210      of CONST_INTs, where we know the old_mode only from the call argument.  */
5211   old_mode = GET_MODE (val);
5212   if (old_mode == VOIDmode)
5213     old_mode = TYPE_MODE (TREE_TYPE (CALL_EXPR_ARG (exp, 1)));
5214   val = convert_modes (mode, old_mode, val, 1);
5215
5216   return expand_sync_lock_test_and_set (mem, val, target);
5217 }
5218
5219 /* Expand the __sync_synchronize intrinsic.  */
5220
5221 static void
5222 expand_builtin_sync_synchronize (void)
5223 {
5224   gimple x;
5225   VEC (tree, gc) *v_clobbers;
5226
5227 #ifdef HAVE_memory_barrier
5228   if (HAVE_memory_barrier)
5229     {
5230       emit_insn (gen_memory_barrier ());
5231       return;
5232     }
5233 #endif
5234
5235   if (synchronize_libfunc != NULL_RTX)
5236     {
5237       emit_library_call (synchronize_libfunc, LCT_NORMAL, VOIDmode, 0);
5238       return;
5239     }
5240
5241   /* If no explicit memory barrier instruction is available, create an
5242      empty asm stmt with a memory clobber.  */
5243   v_clobbers = VEC_alloc (tree, gc, 1);
5244   VEC_quick_push (tree, v_clobbers,
5245                   tree_cons (NULL, build_string (6, "memory"), NULL));
5246   x = gimple_build_asm_vec ("", NULL, NULL, v_clobbers, NULL);
5247   gimple_asm_set_volatile (x, true);
5248   expand_asm_stmt (x);
5249 }
5250
5251 /* Expand the __sync_lock_release intrinsic.  EXP is the CALL_EXPR.  */
5252
5253 static void
5254 expand_builtin_sync_lock_release (enum machine_mode mode, tree exp)
5255 {
5256   struct expand_operand ops[2];
5257   enum insn_code icode;
5258   rtx mem;
5259
5260   /* Expand the operands.  */
5261   mem = get_builtin_sync_mem (CALL_EXPR_ARG (exp, 0), mode);
5262
5263   /* If there is an explicit operation in the md file, use it.  */
5264   icode = direct_optab_handler (sync_lock_release_optab, mode);
5265   if (icode != CODE_FOR_nothing)
5266     {
5267       create_fixed_operand (&ops[0], mem);
5268       create_input_operand (&ops[1], const0_rtx, mode);
5269       if (maybe_expand_insn (icode, 2, ops))
5270         return;
5271     }
5272
5273   /* Otherwise we can implement this operation by emitting a barrier
5274      followed by a store of zero.  */
5275   expand_builtin_sync_synchronize ();
5276   emit_move_insn (mem, const0_rtx);
5277 }
5278 \f
5279 /* Expand an expression EXP that calls a built-in function,
5280    with result going to TARGET if that's convenient
5281    (and in mode MODE if that's convenient).
5282    SUBTARGET may be used as the target for computing one of EXP's operands.
5283    IGNORE is nonzero if the value is to be ignored.  */
5284
5285 rtx
5286 expand_builtin (tree exp, rtx target, rtx subtarget, enum machine_mode mode,
5287                 int ignore)
5288 {
5289   tree fndecl = get_callee_fndecl (exp);
5290   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
5291   enum machine_mode target_mode = TYPE_MODE (TREE_TYPE (exp));
5292   int flags;
5293
5294   if (DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_MD)
5295     return targetm.expand_builtin (exp, target, subtarget, mode, ignore);
5296
5297   /* When not optimizing, generate calls to library functions for a certain
5298      set of builtins.  */
5299   if (!optimize
5300       && !called_as_built_in (fndecl)
5301       && DECL_ASSEMBLER_NAME_SET_P (fndecl)
5302       && fcode != BUILT_IN_ALLOCA
5303       && fcode != BUILT_IN_FREE)
5304     return expand_call (exp, target, ignore);
5305
5306   /* The built-in function expanders test for target == const0_rtx
5307      to determine whether the function's result will be ignored.  */
5308   if (ignore)
5309     target = const0_rtx;
5310
5311   /* If the result of a pure or const built-in function is ignored, and
5312      none of its arguments are volatile, we can avoid expanding the
5313      built-in call and just evaluate the arguments for side-effects.  */
5314   if (target == const0_rtx
5315       && ((flags = flags_from_decl_or_type (fndecl)) & (ECF_CONST | ECF_PURE))
5316       && !(flags & ECF_LOOPING_CONST_OR_PURE))
5317     {
5318       bool volatilep = false;
5319       tree arg;
5320       call_expr_arg_iterator iter;
5321
5322       FOR_EACH_CALL_EXPR_ARG (arg, iter, exp)
5323         if (TREE_THIS_VOLATILE (arg))
5324           {
5325             volatilep = true;
5326             break;
5327           }
5328
5329       if (! volatilep)
5330         {
5331           FOR_EACH_CALL_EXPR_ARG (arg, iter, exp)
5332             expand_expr (arg, const0_rtx, VOIDmode, EXPAND_NORMAL);
5333           return const0_rtx;
5334         }
5335     }
5336
5337   switch (fcode)
5338     {
5339     CASE_FLT_FN (BUILT_IN_FABS):
5340       target = expand_builtin_fabs (exp, target, subtarget);
5341       if (target)
5342         return target;
5343       break;
5344
5345     CASE_FLT_FN (BUILT_IN_COPYSIGN):
5346       target = expand_builtin_copysign (exp, target, subtarget);
5347       if (target)
5348         return target;
5349       break;
5350
5351       /* Just do a normal library call if we were unable to fold
5352          the values.  */
5353     CASE_FLT_FN (BUILT_IN_CABS):
5354       break;
5355
5356     CASE_FLT_FN (BUILT_IN_EXP):
5357     CASE_FLT_FN (BUILT_IN_EXP10):
5358     CASE_FLT_FN (BUILT_IN_POW10):
5359     CASE_FLT_FN (BUILT_IN_EXP2):
5360     CASE_FLT_FN (BUILT_IN_EXPM1):
5361     CASE_FLT_FN (BUILT_IN_LOGB):
5362     CASE_FLT_FN (BUILT_IN_LOG):
5363     CASE_FLT_FN (BUILT_IN_LOG10):
5364     CASE_FLT_FN (BUILT_IN_LOG2):
5365     CASE_FLT_FN (BUILT_IN_LOG1P):
5366     CASE_FLT_FN (BUILT_IN_TAN):
5367     CASE_FLT_FN (BUILT_IN_ASIN):
5368     CASE_FLT_FN (BUILT_IN_ACOS):
5369     CASE_FLT_FN (BUILT_IN_ATAN):
5370     CASE_FLT_FN (BUILT_IN_SIGNIFICAND):
5371       /* Treat these like sqrt only if unsafe math optimizations are allowed,
5372          because of possible accuracy problems.  */
5373       if (! flag_unsafe_math_optimizations)
5374         break;
5375     CASE_FLT_FN (BUILT_IN_SQRT):
5376     CASE_FLT_FN (BUILT_IN_FLOOR):
5377     CASE_FLT_FN (BUILT_IN_CEIL):
5378     CASE_FLT_FN (BUILT_IN_TRUNC):
5379     CASE_FLT_FN (BUILT_IN_ROUND):
5380     CASE_FLT_FN (BUILT_IN_NEARBYINT):
5381     CASE_FLT_FN (BUILT_IN_RINT):
5382       target = expand_builtin_mathfn (exp, target, subtarget);
5383       if (target)
5384         return target;
5385       break;
5386
5387     CASE_FLT_FN (BUILT_IN_FMA):
5388       target = expand_builtin_mathfn_ternary (exp, target, subtarget);
5389       if (target)
5390         return target;
5391       break;
5392
5393     CASE_FLT_FN (BUILT_IN_ILOGB):
5394       if (! flag_unsafe_math_optimizations)
5395         break;
5396     CASE_FLT_FN (BUILT_IN_ISINF):
5397     CASE_FLT_FN (BUILT_IN_FINITE):
5398     case BUILT_IN_ISFINITE:
5399     case BUILT_IN_ISNORMAL:
5400       target = expand_builtin_interclass_mathfn (exp, target);
5401       if (target)
5402         return target;
5403       break;
5404
5405     CASE_FLT_FN (BUILT_IN_LCEIL):
5406     CASE_FLT_FN (BUILT_IN_LLCEIL):
5407     CASE_FLT_FN (BUILT_IN_LFLOOR):
5408     CASE_FLT_FN (BUILT_IN_LLFLOOR):
5409       target = expand_builtin_int_roundingfn (exp, target);
5410       if (target)
5411         return target;
5412       break;
5413
5414     CASE_FLT_FN (BUILT_IN_LRINT):
5415     CASE_FLT_FN (BUILT_IN_LLRINT):
5416     CASE_FLT_FN (BUILT_IN_LROUND):
5417     CASE_FLT_FN (BUILT_IN_LLROUND):
5418       target = expand_builtin_int_roundingfn_2 (exp, target);
5419       if (target)
5420         return target;
5421       break;
5422
5423     CASE_FLT_FN (BUILT_IN_POWI):
5424       target = expand_builtin_powi (exp, target);
5425       if (target)
5426         return target;
5427       break;
5428
5429     CASE_FLT_FN (BUILT_IN_ATAN2):
5430     CASE_FLT_FN (BUILT_IN_LDEXP):
5431     CASE_FLT_FN (BUILT_IN_SCALB):
5432     CASE_FLT_FN (BUILT_IN_SCALBN):
5433     CASE_FLT_FN (BUILT_IN_SCALBLN):
5434       if (! flag_unsafe_math_optimizations)
5435         break;
5436
5437     CASE_FLT_FN (BUILT_IN_FMOD):
5438     CASE_FLT_FN (BUILT_IN_REMAINDER):
5439     CASE_FLT_FN (BUILT_IN_DREM):
5440     CASE_FLT_FN (BUILT_IN_POW):
5441       target = expand_builtin_mathfn_2 (exp, target, subtarget);
5442       if (target)
5443         return target;
5444       break;
5445
5446     CASE_FLT_FN (BUILT_IN_CEXPI):
5447       target = expand_builtin_cexpi (exp, target);
5448       gcc_assert (target);
5449       return target;
5450
5451     CASE_FLT_FN (BUILT_IN_SIN):
5452     CASE_FLT_FN (BUILT_IN_COS):
5453       if (! flag_unsafe_math_optimizations)
5454         break;
5455       target = expand_builtin_mathfn_3 (exp, target, subtarget);
5456       if (target)
5457         return target;
5458       break;
5459
5460     CASE_FLT_FN (BUILT_IN_SINCOS):
5461       if (! flag_unsafe_math_optimizations)
5462         break;
5463       target = expand_builtin_sincos (exp);
5464       if (target)
5465         return target;
5466       break;
5467
5468     case BUILT_IN_APPLY_ARGS:
5469       return expand_builtin_apply_args ();
5470
5471       /* __builtin_apply (FUNCTION, ARGUMENTS, ARGSIZE) invokes
5472          FUNCTION with a copy of the parameters described by
5473          ARGUMENTS, and ARGSIZE.  It returns a block of memory
5474          allocated on the stack into which is stored all the registers
5475          that might possibly be used for returning the result of a
5476          function.  ARGUMENTS is the value returned by
5477          __builtin_apply_args.  ARGSIZE is the number of bytes of
5478          arguments that must be copied.  ??? How should this value be
5479          computed?  We'll also need a safe worst case value for varargs
5480          functions.  */
5481     case BUILT_IN_APPLY:
5482       if (!validate_arglist (exp, POINTER_TYPE,
5483                              POINTER_TYPE, INTEGER_TYPE, VOID_TYPE)
5484           && !validate_arglist (exp, REFERENCE_TYPE,
5485                                 POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
5486         return const0_rtx;
5487       else
5488         {
5489           rtx ops[3];
5490
5491           ops[0] = expand_normal (CALL_EXPR_ARG (exp, 0));
5492           ops[1] = expand_normal (CALL_EXPR_ARG (exp, 1));
5493           ops[2] = expand_normal (CALL_EXPR_ARG (exp, 2));
5494
5495           return expand_builtin_apply (ops[0], ops[1], ops[2]);
5496         }
5497
5498       /* __builtin_return (RESULT) causes the function to return the
5499          value described by RESULT.  RESULT is address of the block of
5500          memory returned by __builtin_apply.  */
5501     case BUILT_IN_RETURN:
5502       if (validate_arglist (exp, POINTER_TYPE, VOID_TYPE))
5503         expand_builtin_return (expand_normal (CALL_EXPR_ARG (exp, 0)));
5504       return const0_rtx;
5505
5506     case BUILT_IN_SAVEREGS:
5507       return expand_builtin_saveregs ();
5508
5509     case BUILT_IN_VA_ARG_PACK:
5510       /* All valid uses of __builtin_va_arg_pack () are removed during
5511          inlining.  */
5512       error ("%Kinvalid use of %<__builtin_va_arg_pack ()%>", exp);
5513       return const0_rtx;
5514
5515     case BUILT_IN_VA_ARG_PACK_LEN:
5516       /* All valid uses of __builtin_va_arg_pack_len () are removed during
5517          inlining.  */
5518       error ("%Kinvalid use of %<__builtin_va_arg_pack_len ()%>", exp);
5519       return const0_rtx;
5520
5521       /* Return the address of the first anonymous stack arg.  */
5522     case BUILT_IN_NEXT_ARG:
5523       if (fold_builtin_next_arg (exp, false))
5524         return const0_rtx;
5525       return expand_builtin_next_arg ();
5526
5527     case BUILT_IN_CLEAR_CACHE:
5528       target = expand_builtin___clear_cache (exp);
5529       if (target)
5530         return target;
5531       break;
5532
5533     case BUILT_IN_CLASSIFY_TYPE:
5534       return expand_builtin_classify_type (exp);
5535
5536     case BUILT_IN_CONSTANT_P:
5537       return const0_rtx;
5538
5539     case BUILT_IN_FRAME_ADDRESS:
5540     case BUILT_IN_RETURN_ADDRESS:
5541       return expand_builtin_frame_address (fndecl, exp);
5542
5543     /* Returns the address of the area where the structure is returned.
5544        0 otherwise.  */
5545     case BUILT_IN_AGGREGATE_INCOMING_ADDRESS:
5546       if (call_expr_nargs (exp) != 0
5547           || ! AGGREGATE_TYPE_P (TREE_TYPE (TREE_TYPE (current_function_decl)))
5548           || !MEM_P (DECL_RTL (DECL_RESULT (current_function_decl))))
5549         return const0_rtx;
5550       else
5551         return XEXP (DECL_RTL (DECL_RESULT (current_function_decl)), 0);
5552
5553     case BUILT_IN_ALLOCA:
5554       /* If the allocation stems from the declaration of a variable-sized
5555          object, it cannot accumulate.  */
5556       target = expand_builtin_alloca (exp, CALL_ALLOCA_FOR_VAR_P (exp));
5557       if (target)
5558         return target;
5559       break;
5560
5561     case BUILT_IN_STACK_SAVE:
5562       return expand_stack_save ();
5563
5564     case BUILT_IN_STACK_RESTORE:
5565       expand_stack_restore (CALL_EXPR_ARG (exp, 0));
5566       return const0_rtx;
5567
5568     case BUILT_IN_BSWAP32:
5569     case BUILT_IN_BSWAP64:
5570       target = expand_builtin_bswap (exp, target, subtarget);
5571
5572       if (target)
5573         return target;
5574       break;
5575
5576     CASE_INT_FN (BUILT_IN_FFS):
5577     case BUILT_IN_FFSIMAX:
5578       target = expand_builtin_unop (target_mode, exp, target,
5579                                     subtarget, ffs_optab);
5580       if (target)
5581         return target;
5582       break;
5583
5584     CASE_INT_FN (BUILT_IN_CLZ):
5585     case BUILT_IN_CLZIMAX:
5586       target = expand_builtin_unop (target_mode, exp, target,
5587                                     subtarget, clz_optab);
5588       if (target)
5589         return target;
5590       break;
5591
5592     CASE_INT_FN (BUILT_IN_CTZ):
5593     case BUILT_IN_CTZIMAX:
5594       target = expand_builtin_unop (target_mode, exp, target,
5595                                     subtarget, ctz_optab);
5596       if (target)
5597         return target;
5598       break;
5599
5600     CASE_INT_FN (BUILT_IN_CLRSB):
5601     case BUILT_IN_CLRSBIMAX:
5602       target = expand_builtin_unop (target_mode, exp, target,
5603                                     subtarget, clrsb_optab);
5604       if (target)
5605         return target;
5606       break;
5607
5608     CASE_INT_FN (BUILT_IN_POPCOUNT):
5609     case BUILT_IN_POPCOUNTIMAX:
5610       target = expand_builtin_unop (target_mode, exp, target,
5611                                     subtarget, popcount_optab);
5612       if (target)
5613         return target;
5614       break;
5615
5616     CASE_INT_FN (BUILT_IN_PARITY):
5617     case BUILT_IN_PARITYIMAX:
5618       target = expand_builtin_unop (target_mode, exp, target,
5619                                     subtarget, parity_optab);
5620       if (target)
5621         return target;
5622       break;
5623
5624     case BUILT_IN_STRLEN:
5625       target = expand_builtin_strlen (exp, target, target_mode);
5626       if (target)
5627         return target;
5628       break;
5629
5630     case BUILT_IN_STRCPY:
5631       target = expand_builtin_strcpy (exp, target);
5632       if (target)
5633         return target;
5634       break;
5635
5636     case BUILT_IN_STRNCPY:
5637       target = expand_builtin_strncpy (exp, target);
5638       if (target)
5639         return target;
5640       break;
5641
5642     case BUILT_IN_STPCPY:
5643       target = expand_builtin_stpcpy (exp, target, mode);
5644       if (target)
5645         return target;
5646       break;
5647
5648     case BUILT_IN_MEMCPY:
5649       target = expand_builtin_memcpy (exp, target);
5650       if (target)
5651         return target;
5652       break;
5653
5654     case BUILT_IN_MEMPCPY:
5655       target = expand_builtin_mempcpy (exp, target, mode);
5656       if (target)
5657         return target;
5658       break;
5659
5660     case BUILT_IN_MEMSET:
5661       target = expand_builtin_memset (exp, target, mode);
5662       if (target)
5663         return target;
5664       break;
5665
5666     case BUILT_IN_BZERO:
5667       target = expand_builtin_bzero (exp);
5668       if (target)
5669         return target;
5670       break;
5671
5672     case BUILT_IN_STRCMP:
5673       target = expand_builtin_strcmp (exp, target);
5674       if (target)
5675         return target;
5676       break;
5677
5678     case BUILT_IN_STRNCMP:
5679       target = expand_builtin_strncmp (exp, target, mode);
5680       if (target)
5681         return target;
5682       break;
5683
5684     case BUILT_IN_BCMP:
5685     case BUILT_IN_MEMCMP:
5686       target = expand_builtin_memcmp (exp, target, mode);
5687       if (target)
5688         return target;
5689       break;
5690
5691     case BUILT_IN_SETJMP:
5692       /* This should have been lowered to the builtins below.  */
5693       gcc_unreachable ();
5694
5695     case BUILT_IN_SETJMP_SETUP:
5696       /* __builtin_setjmp_setup is passed a pointer to an array of five words
5697           and the receiver label.  */
5698       if (validate_arglist (exp, POINTER_TYPE, POINTER_TYPE, VOID_TYPE))
5699         {
5700           rtx buf_addr = expand_expr (CALL_EXPR_ARG (exp, 0), subtarget,
5701                                       VOIDmode, EXPAND_NORMAL);
5702           tree label = TREE_OPERAND (CALL_EXPR_ARG (exp, 1), 0);
5703           rtx label_r = label_rtx (label);
5704
5705           /* This is copied from the handling of non-local gotos.  */
5706           expand_builtin_setjmp_setup (buf_addr, label_r);
5707           nonlocal_goto_handler_labels
5708             = gen_rtx_EXPR_LIST (VOIDmode, label_r,
5709                                  nonlocal_goto_handler_labels);
5710           /* ??? Do not let expand_label treat us as such since we would
5711              not want to be both on the list of non-local labels and on
5712              the list of forced labels.  */
5713           FORCED_LABEL (label) = 0;
5714           return const0_rtx;
5715         }
5716       break;
5717
5718     case BUILT_IN_SETJMP_DISPATCHER:
5719        /* __builtin_setjmp_dispatcher is passed the dispatcher label.  */
5720       if (validate_arglist (exp, POINTER_TYPE, VOID_TYPE))
5721         {
5722           tree label = TREE_OPERAND (CALL_EXPR_ARG (exp, 0), 0);
5723           rtx label_r = label_rtx (label);
5724
5725           /* Remove the dispatcher label from the list of non-local labels
5726              since the receiver labels have been added to it above.  */
5727           remove_node_from_expr_list (label_r, &nonlocal_goto_handler_labels);
5728           return const0_rtx;
5729         }
5730       break;
5731
5732     case BUILT_IN_SETJMP_RECEIVER:
5733        /* __builtin_setjmp_receiver is passed the receiver label.  */
5734       if (validate_arglist (exp, POINTER_TYPE, VOID_TYPE))
5735         {
5736           tree label = TREE_OPERAND (CALL_EXPR_ARG (exp, 0), 0);
5737           rtx label_r = label_rtx (label);
5738
5739           expand_builtin_setjmp_receiver (label_r);
5740           return const0_rtx;
5741         }
5742       break;
5743
5744       /* __builtin_longjmp is passed a pointer to an array of five words.
5745          It's similar to the C library longjmp function but works with
5746          __builtin_setjmp above.  */
5747     case BUILT_IN_LONGJMP:
5748       if (validate_arglist (exp, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
5749         {
5750           rtx buf_addr = expand_expr (CALL_EXPR_ARG (exp, 0), subtarget,
5751                                       VOIDmode, EXPAND_NORMAL);
5752           rtx value = expand_normal (CALL_EXPR_ARG (exp, 1));
5753
5754           if (value != const1_rtx)
5755             {
5756               error ("%<__builtin_longjmp%> second argument must be 1");
5757               return const0_rtx;
5758             }
5759
5760           expand_builtin_longjmp (buf_addr, value);
5761           return const0_rtx;
5762         }
5763       break;
5764
5765     case BUILT_IN_NONLOCAL_GOTO:
5766       target = expand_builtin_nonlocal_goto (exp);
5767       if (target)
5768         return target;
5769       break;
5770
5771       /* This updates the setjmp buffer that is its argument with the value
5772          of the current stack pointer.  */
5773     case BUILT_IN_UPDATE_SETJMP_BUF:
5774       if (validate_arglist (exp, POINTER_TYPE, VOID_TYPE))
5775         {
5776           rtx buf_addr
5777             = expand_normal (CALL_EXPR_ARG (exp, 0));
5778
5779           expand_builtin_update_setjmp_buf (buf_addr);
5780           return const0_rtx;
5781         }
5782       break;
5783
5784     case BUILT_IN_TRAP:
5785       expand_builtin_trap ();
5786       return const0_rtx;
5787
5788     case BUILT_IN_UNREACHABLE:
5789       expand_builtin_unreachable ();
5790       return const0_rtx;
5791
5792     CASE_FLT_FN (BUILT_IN_SIGNBIT):
5793     case BUILT_IN_SIGNBITD32:
5794     case BUILT_IN_SIGNBITD64:
5795     case BUILT_IN_SIGNBITD128:
5796       target = expand_builtin_signbit (exp, target);
5797       if (target)
5798         return target;
5799       break;
5800
5801       /* Various hooks for the DWARF 2 __throw routine.  */
5802     case BUILT_IN_UNWIND_INIT:
5803       expand_builtin_unwind_init ();
5804       return const0_rtx;
5805     case BUILT_IN_DWARF_CFA:
5806       return virtual_cfa_rtx;
5807 #ifdef DWARF2_UNWIND_INFO
5808     case BUILT_IN_DWARF_SP_COLUMN:
5809       return expand_builtin_dwarf_sp_column ();
5810     case BUILT_IN_INIT_DWARF_REG_SIZES:
5811       expand_builtin_init_dwarf_reg_sizes (CALL_EXPR_ARG (exp, 0));
5812       return const0_rtx;
5813 #endif
5814     case BUILT_IN_FROB_RETURN_ADDR:
5815       return expand_builtin_frob_return_addr (CALL_EXPR_ARG (exp, 0));
5816     case BUILT_IN_EXTRACT_RETURN_ADDR:
5817       return expand_builtin_extract_return_addr (CALL_EXPR_ARG (exp, 0));
5818     case BUILT_IN_EH_RETURN:
5819       expand_builtin_eh_return (CALL_EXPR_ARG (exp, 0),
5820                                 CALL_EXPR_ARG (exp, 1));
5821       return const0_rtx;
5822 #ifdef EH_RETURN_DATA_REGNO
5823     case BUILT_IN_EH_RETURN_DATA_REGNO:
5824       return expand_builtin_eh_return_data_regno (exp);
5825 #endif
5826     case BUILT_IN_EXTEND_POINTER:
5827       return expand_builtin_extend_pointer (CALL_EXPR_ARG (exp, 0));
5828     case BUILT_IN_EH_POINTER:
5829       return expand_builtin_eh_pointer (exp);
5830     case BUILT_IN_EH_FILTER:
5831       return expand_builtin_eh_filter (exp);
5832     case BUILT_IN_EH_COPY_VALUES:
5833       return expand_builtin_eh_copy_values (exp);
5834
5835     case BUILT_IN_VA_START:
5836       return expand_builtin_va_start (exp);
5837     case BUILT_IN_VA_END:
5838       return expand_builtin_va_end (exp);
5839     case BUILT_IN_VA_COPY:
5840       return expand_builtin_va_copy (exp);
5841     case BUILT_IN_EXPECT:
5842       return expand_builtin_expect (exp, target);
5843     case BUILT_IN_ASSUME_ALIGNED:
5844       return expand_builtin_assume_aligned (exp, target);
5845     case BUILT_IN_PREFETCH:
5846       expand_builtin_prefetch (exp);
5847       return const0_rtx;
5848
5849     case BUILT_IN_INIT_TRAMPOLINE:
5850       return expand_builtin_init_trampoline (exp);
5851     case BUILT_IN_ADJUST_TRAMPOLINE:
5852       return expand_builtin_adjust_trampoline (exp);
5853
5854     case BUILT_IN_FORK:
5855     case BUILT_IN_EXECL:
5856     case BUILT_IN_EXECV:
5857     case BUILT_IN_EXECLP:
5858     case BUILT_IN_EXECLE:
5859     case BUILT_IN_EXECVP:
5860     case BUILT_IN_EXECVE:
5861       target = expand_builtin_fork_or_exec (fndecl, exp, target, ignore);
5862       if (target)
5863         return target;
5864       break;
5865
5866     case BUILT_IN_SYNC_FETCH_AND_ADD_1:
5867     case BUILT_IN_SYNC_FETCH_AND_ADD_2:
5868     case BUILT_IN_SYNC_FETCH_AND_ADD_4:
5869     case BUILT_IN_SYNC_FETCH_AND_ADD_8:
5870     case BUILT_IN_SYNC_FETCH_AND_ADD_16:
5871       mode = get_builtin_sync_mode (fcode - BUILT_IN_SYNC_FETCH_AND_ADD_1);
5872       target = expand_builtin_sync_operation (mode, exp, PLUS,
5873                                               false, target, ignore);
5874       if (target)
5875         return target;
5876       break;
5877
5878     case BUILT_IN_SYNC_FETCH_AND_SUB_1:
5879     case BUILT_IN_SYNC_FETCH_AND_SUB_2:
5880     case BUILT_IN_SYNC_FETCH_AND_SUB_4:
5881     case BUILT_IN_SYNC_FETCH_AND_SUB_8:
5882     case BUILT_IN_SYNC_FETCH_AND_SUB_16:
5883       mode = get_builtin_sync_mode (fcode - BUILT_IN_SYNC_FETCH_AND_SUB_1);
5884       target = expand_builtin_sync_operation (mode, exp, MINUS,
5885                                               false, target, ignore);
5886       if (target)
5887         return target;
5888       break;
5889
5890     case BUILT_IN_SYNC_FETCH_AND_OR_1:
5891     case BUILT_IN_SYNC_FETCH_AND_OR_2:
5892     case BUILT_IN_SYNC_FETCH_AND_OR_4:
5893     case BUILT_IN_SYNC_FETCH_AND_OR_8:
5894     case BUILT_IN_SYNC_FETCH_AND_OR_16:
5895       mode = get_builtin_sync_mode (fcode - BUILT_IN_SYNC_FETCH_AND_OR_1);
5896       target = expand_builtin_sync_operation (mode, exp, IOR,
5897                                               false, target, ignore);
5898       if (target)
5899         return target;
5900       break;
5901
5902     case BUILT_IN_SYNC_FETCH_AND_AND_1:
5903     case BUILT_IN_SYNC_FETCH_AND_AND_2:
5904     case BUILT_IN_SYNC_FETCH_AND_AND_4:
5905     case BUILT_IN_SYNC_FETCH_AND_AND_8:
5906     case BUILT_IN_SYNC_FETCH_AND_AND_16:
5907       mode = get_builtin_sync_mode (fcode - BUILT_IN_SYNC_FETCH_AND_AND_1);
5908       target = expand_builtin_sync_operation (mode, exp, AND,
5909                                               false, target, ignore);
5910       if (target)
5911         return target;
5912       break;
5913
5914     case BUILT_IN_SYNC_FETCH_AND_XOR_1:
5915     case BUILT_IN_SYNC_FETCH_AND_XOR_2:
5916     case BUILT_IN_SYNC_FETCH_AND_XOR_4:
5917     case BUILT_IN_SYNC_FETCH_AND_XOR_8:
5918     case BUILT_IN_SYNC_FETCH_AND_XOR_16:
5919       mode = get_builtin_sync_mode (fcode - BUILT_IN_SYNC_FETCH_AND_XOR_1);
5920       target = expand_builtin_sync_operation (mode, exp, XOR,
5921                                               false, target, ignore);
5922       if (target)
5923         return target;
5924       break;
5925
5926     case BUILT_IN_SYNC_FETCH_AND_NAND_1:
5927     case BUILT_IN_SYNC_FETCH_AND_NAND_2:
5928     case BUILT_IN_SYNC_FETCH_AND_NAND_4:
5929     case BUILT_IN_SYNC_FETCH_AND_NAND_8:
5930     case BUILT_IN_SYNC_FETCH_AND_NAND_16:
5931       mode = get_builtin_sync_mode (fcode - BUILT_IN_SYNC_FETCH_AND_NAND_1);
5932       target = expand_builtin_sync_operation (mode, exp, NOT,
5933                                               false, target, ignore);
5934       if (target)
5935         return target;
5936       break;
5937
5938     case BUILT_IN_SYNC_ADD_AND_FETCH_1:
5939     case BUILT_IN_SYNC_ADD_AND_FETCH_2:
5940     case BUILT_IN_SYNC_ADD_AND_FETCH_4:
5941     case BUILT_IN_SYNC_ADD_AND_FETCH_8:
5942     case BUILT_IN_SYNC_ADD_AND_FETCH_16:
5943       mode = get_builtin_sync_mode (fcode - BUILT_IN_SYNC_ADD_AND_FETCH_1);
5944       target = expand_builtin_sync_operation (mode, exp, PLUS,
5945                                               true, target, ignore);
5946       if (target)
5947         return target;
5948       break;
5949
5950     case BUILT_IN_SYNC_SUB_AND_FETCH_1:
5951     case BUILT_IN_SYNC_SUB_AND_FETCH_2:
5952     case BUILT_IN_SYNC_SUB_AND_FETCH_4:
5953     case BUILT_IN_SYNC_SUB_AND_FETCH_8:
5954     case BUILT_IN_SYNC_SUB_AND_FETCH_16:
5955       mode = get_builtin_sync_mode (fcode - BUILT_IN_SYNC_SUB_AND_FETCH_1);
5956       target = expand_builtin_sync_operation (mode, exp, MINUS,
5957                                               true, target, ignore);
5958       if (target)
5959         return target;
5960       break;
5961
5962     case BUILT_IN_SYNC_OR_AND_FETCH_1:
5963     case BUILT_IN_SYNC_OR_AND_FETCH_2:
5964     case BUILT_IN_SYNC_OR_AND_FETCH_4:
5965     case BUILT_IN_SYNC_OR_AND_FETCH_8:
5966     case BUILT_IN_SYNC_OR_AND_FETCH_16:
5967       mode = get_builtin_sync_mode (fcode - BUILT_IN_SYNC_OR_AND_FETCH_1);
5968       target = expand_builtin_sync_operation (mode, exp, IOR,
5969                                               true, target, ignore);
5970       if (target)
5971         return target;
5972       break;
5973
5974     case BUILT_IN_SYNC_AND_AND_FETCH_1:
5975     case BUILT_IN_SYNC_AND_AND_FETCH_2:
5976     case BUILT_IN_SYNC_AND_AND_FETCH_4:
5977     case BUILT_IN_SYNC_AND_AND_FETCH_8:
5978     case BUILT_IN_SYNC_AND_AND_FETCH_16:
5979       mode = get_builtin_sync_mode (fcode - BUILT_IN_SYNC_AND_AND_FETCH_1);
5980       target = expand_builtin_sync_operation (mode, exp, AND,
5981                                               true, target, ignore);
5982       if (target)
5983         return target;
5984       break;
5985
5986     case BUILT_IN_SYNC_XOR_AND_FETCH_1:
5987     case BUILT_IN_SYNC_XOR_AND_FETCH_2:
5988     case BUILT_IN_SYNC_XOR_AND_FETCH_4:
5989     case BUILT_IN_SYNC_XOR_AND_FETCH_8:
5990     case BUILT_IN_SYNC_XOR_AND_FETCH_16:
5991       mode = get_builtin_sync_mode (fcode - BUILT_IN_SYNC_XOR_AND_FETCH_1);
5992       target = expand_builtin_sync_operation (mode, exp, XOR,
5993                                               true, target, ignore);
5994       if (target)
5995         return target;
5996       break;
5997
5998     case BUILT_IN_SYNC_NAND_AND_FETCH_1:
5999     case BUILT_IN_SYNC_NAND_AND_FETCH_2:
6000     case BUILT_IN_SYNC_NAND_AND_FETCH_4:
6001     case BUILT_IN_SYNC_NAND_AND_FETCH_8:
6002     case BUILT_IN_SYNC_NAND_AND_FETCH_16:
6003       mode = get_builtin_sync_mode (fcode - BUILT_IN_SYNC_NAND_AND_FETCH_1);
6004       target = expand_builtin_sync_operation (mode, exp, NOT,
6005                                               true, target, ignore);
6006       if (target)
6007         return target;
6008       break;
6009
6010     case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_1:
6011     case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_2:
6012     case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_4:
6013     case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_8:
6014     case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_16:
6015       if (mode == VOIDmode)
6016         mode = TYPE_MODE (boolean_type_node);
6017       if (!target || !register_operand (target, mode))
6018         target = gen_reg_rtx (mode);
6019
6020       mode = get_builtin_sync_mode 
6021                                 (fcode - BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_1);
6022       target = expand_builtin_compare_and_swap (mode, exp, true, target);
6023       if (target)
6024         return target;
6025       break;
6026
6027     case BUILT_IN_SYNC_VAL_COMPARE_AND_SWAP_1:
6028     case BUILT_IN_SYNC_VAL_COMPARE_AND_SWAP_2:
6029     case BUILT_IN_SYNC_VAL_COMPARE_AND_SWAP_4:
6030     case BUILT_IN_SYNC_VAL_COMPARE_AND_SWAP_8:
6031     case BUILT_IN_SYNC_VAL_COMPARE_AND_SWAP_16:
6032       mode = get_builtin_sync_mode 
6033                                 (fcode - BUILT_IN_SYNC_VAL_COMPARE_AND_SWAP_1);
6034       target = expand_builtin_compare_and_swap (mode, exp, false, target);
6035       if (target)
6036         return target;
6037       break;
6038
6039     case BUILT_IN_SYNC_LOCK_TEST_AND_SET_1:
6040     case BUILT_IN_SYNC_LOCK_TEST_AND_SET_2:
6041     case BUILT_IN_SYNC_LOCK_TEST_AND_SET_4:
6042     case BUILT_IN_SYNC_LOCK_TEST_AND_SET_8:
6043     case BUILT_IN_SYNC_LOCK_TEST_AND_SET_16:
6044       mode = get_builtin_sync_mode (fcode - BUILT_IN_SYNC_LOCK_TEST_AND_SET_1);
6045       target = expand_builtin_sync_lock_test_and_set (mode, exp, target);
6046       if (target)
6047         return target;
6048       break;
6049
6050     case BUILT_IN_SYNC_LOCK_RELEASE_1:
6051     case BUILT_IN_SYNC_LOCK_RELEASE_2:
6052     case BUILT_IN_SYNC_LOCK_RELEASE_4:
6053     case BUILT_IN_SYNC_LOCK_RELEASE_8:
6054     case BUILT_IN_SYNC_LOCK_RELEASE_16:
6055       mode = get_builtin_sync_mode (fcode - BUILT_IN_SYNC_LOCK_RELEASE_1);
6056       expand_builtin_sync_lock_release (mode, exp);
6057       return const0_rtx;
6058
6059     case BUILT_IN_SYNC_SYNCHRONIZE:
6060       expand_builtin_sync_synchronize ();
6061       return const0_rtx;
6062
6063     case BUILT_IN_OBJECT_SIZE:
6064       return expand_builtin_object_size (exp);
6065
6066     case BUILT_IN_MEMCPY_CHK:
6067     case BUILT_IN_MEMPCPY_CHK:
6068     case BUILT_IN_MEMMOVE_CHK:
6069     case BUILT_IN_MEMSET_CHK:
6070       target = expand_builtin_memory_chk (exp, target, mode, fcode);
6071       if (target)
6072         return target;
6073       break;
6074
6075     case BUILT_IN_STRCPY_CHK:
6076     case BUILT_IN_STPCPY_CHK:
6077     case BUILT_IN_STRNCPY_CHK:
6078     case BUILT_IN_STRCAT_CHK:
6079     case BUILT_IN_STRNCAT_CHK:
6080     case BUILT_IN_SNPRINTF_CHK:
6081     case BUILT_IN_VSNPRINTF_CHK:
6082       maybe_emit_chk_warning (exp, fcode);
6083       break;
6084
6085     case BUILT_IN_SPRINTF_CHK:
6086     case BUILT_IN_VSPRINTF_CHK:
6087       maybe_emit_sprintf_chk_warning (exp, fcode);
6088       break;
6089
6090     case BUILT_IN_FREE:
6091       maybe_emit_free_warning (exp);
6092       break;
6093
6094     default:    /* just do library call, if unknown builtin */
6095       break;
6096     }
6097
6098   /* The switch statement above can drop through to cause the function
6099      to be called normally.  */
6100   return expand_call (exp, target, ignore);
6101 }
6102
6103 /* Determine whether a tree node represents a call to a built-in
6104    function.  If the tree T is a call to a built-in function with
6105    the right number of arguments of the appropriate types, return
6106    the DECL_FUNCTION_CODE of the call, e.g. BUILT_IN_SQRT.
6107    Otherwise the return value is END_BUILTINS.  */
6108
6109 enum built_in_function
6110 builtin_mathfn_code (const_tree t)
6111 {
6112   const_tree fndecl, arg, parmlist;
6113   const_tree argtype, parmtype;
6114   const_call_expr_arg_iterator iter;
6115
6116   if (TREE_CODE (t) != CALL_EXPR
6117       || TREE_CODE (CALL_EXPR_FN (t)) != ADDR_EXPR)
6118     return END_BUILTINS;
6119
6120   fndecl = get_callee_fndecl (t);
6121   if (fndecl == NULL_TREE
6122       || TREE_CODE (fndecl) != FUNCTION_DECL
6123       || ! DECL_BUILT_IN (fndecl)
6124       || DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_MD)
6125     return END_BUILTINS;
6126
6127   parmlist = TYPE_ARG_TYPES (TREE_TYPE (fndecl));
6128   init_const_call_expr_arg_iterator (t, &iter);
6129   for (; parmlist; parmlist = TREE_CHAIN (parmlist))
6130     {
6131       /* If a function doesn't take a variable number of arguments,
6132          the last element in the list will have type `void'.  */
6133       parmtype = TREE_VALUE (parmlist);
6134       if (VOID_TYPE_P (parmtype))
6135         {
6136           if (more_const_call_expr_args_p (&iter))
6137             return END_BUILTINS;
6138           return DECL_FUNCTION_CODE (fndecl);
6139         }
6140
6141       if (! more_const_call_expr_args_p (&iter))
6142         return END_BUILTINS;
6143
6144       arg = next_const_call_expr_arg (&iter);
6145       argtype = TREE_TYPE (arg);
6146
6147       if (SCALAR_FLOAT_TYPE_P (parmtype))
6148         {
6149           if (! SCALAR_FLOAT_TYPE_P (argtype))
6150             return END_BUILTINS;
6151         }
6152       else if (COMPLEX_FLOAT_TYPE_P (parmtype))
6153         {
6154           if (! COMPLEX_FLOAT_TYPE_P (argtype))
6155             return END_BUILTINS;
6156         }
6157       else if (POINTER_TYPE_P (parmtype))
6158         {
6159           if (! POINTER_TYPE_P (argtype))
6160             return END_BUILTINS;
6161         }
6162       else if (INTEGRAL_TYPE_P (parmtype))
6163         {
6164           if (! INTEGRAL_TYPE_P (argtype))
6165             return END_BUILTINS;
6166         }
6167       else
6168         return END_BUILTINS;
6169     }
6170
6171   /* Variable-length argument list.  */
6172   return DECL_FUNCTION_CODE (fndecl);
6173 }
6174
6175 /* Fold a call to __builtin_constant_p, if we know its argument ARG will
6176    evaluate to a constant.  */
6177
6178 static tree
6179 fold_builtin_constant_p (tree arg)
6180 {
6181   /* We return 1 for a numeric type that's known to be a constant
6182      value at compile-time or for an aggregate type that's a
6183      literal constant.  */
6184   STRIP_NOPS (arg);
6185
6186   /* If we know this is a constant, emit the constant of one.  */
6187   if (CONSTANT_CLASS_P (arg)
6188       || (TREE_CODE (arg) == CONSTRUCTOR
6189           && TREE_CONSTANT (arg)))
6190     return integer_one_node;
6191   if (TREE_CODE (arg) == ADDR_EXPR)
6192     {
6193        tree op = TREE_OPERAND (arg, 0);
6194        if (TREE_CODE (op) == STRING_CST
6195            || (TREE_CODE (op) == ARRAY_REF
6196                && integer_zerop (TREE_OPERAND (op, 1))
6197                && TREE_CODE (TREE_OPERAND (op, 0)) == STRING_CST))
6198          return integer_one_node;
6199     }
6200
6201   /* If this expression has side effects, show we don't know it to be a
6202      constant.  Likewise if it's a pointer or aggregate type since in
6203      those case we only want literals, since those are only optimized
6204      when generating RTL, not later.
6205      And finally, if we are compiling an initializer, not code, we
6206      need to return a definite result now; there's not going to be any
6207      more optimization done.  */
6208   if (TREE_SIDE_EFFECTS (arg)
6209       || AGGREGATE_TYPE_P (TREE_TYPE (arg))
6210       || POINTER_TYPE_P (TREE_TYPE (arg))
6211       || cfun == 0
6212       || folding_initializer)
6213     return integer_zero_node;
6214
6215   return NULL_TREE;
6216 }
6217
6218 /* Create builtin_expect with PRED and EXPECTED as its arguments and
6219    return it as a truthvalue.  */
6220
6221 static tree
6222 build_builtin_expect_predicate (location_t loc, tree pred, tree expected)
6223 {
6224   tree fn, arg_types, pred_type, expected_type, call_expr, ret_type;
6225
6226   fn = built_in_decls[BUILT_IN_EXPECT];
6227   arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
6228   ret_type = TREE_TYPE (TREE_TYPE (fn));
6229   pred_type = TREE_VALUE (arg_types);
6230   expected_type = TREE_VALUE (TREE_CHAIN (arg_types));
6231
6232   pred = fold_convert_loc (loc, pred_type, pred);
6233   expected = fold_convert_loc (loc, expected_type, expected);
6234   call_expr = build_call_expr_loc (loc, fn, 2, pred, expected);
6235
6236   return build2 (NE_EXPR, TREE_TYPE (pred), call_expr,
6237                  build_int_cst (ret_type, 0));
6238 }
6239
6240 /* Fold a call to builtin_expect with arguments ARG0 and ARG1.  Return
6241    NULL_TREE if no simplification is possible.  */
6242
6243 static tree
6244 fold_builtin_expect (location_t loc, tree arg0, tree arg1)
6245 {
6246   tree inner, fndecl;
6247   enum tree_code code;
6248
6249   /* If this is a builtin_expect within a builtin_expect keep the
6250      inner one.  See through a comparison against a constant.  It
6251      might have been added to create a thruthvalue.  */
6252   inner = arg0;
6253   if (COMPARISON_CLASS_P (inner)
6254       && TREE_CODE (TREE_OPERAND (inner, 1)) == INTEGER_CST)
6255     inner = TREE_OPERAND (inner, 0);
6256
6257   if (TREE_CODE (inner) == CALL_EXPR
6258       && (fndecl = get_callee_fndecl (inner))
6259       && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL
6260       && DECL_FUNCTION_CODE (fndecl) == BUILT_IN_EXPECT)
6261     return arg0;
6262
6263   /* Distribute the expected value over short-circuiting operators.
6264      See through the cast from truthvalue_type_node to long.  */
6265   inner = arg0;
6266   while (TREE_CODE (inner) == NOP_EXPR
6267          && INTEGRAL_TYPE_P (TREE_TYPE (inner))
6268          && INTEGRAL_TYPE_P (TREE_TYPE (TREE_OPERAND (inner, 0))))
6269     inner = TREE_OPERAND (inner, 0);
6270
6271   code = TREE_CODE (inner);
6272   if (code == TRUTH_ANDIF_EXPR || code == TRUTH_ORIF_EXPR)
6273     {
6274       tree op0 = TREE_OPERAND (inner, 0);
6275       tree op1 = TREE_OPERAND (inner, 1);
6276
6277       op0 = build_builtin_expect_predicate (loc, op0, arg1);
6278       op1 = build_builtin_expect_predicate (loc, op1, arg1);
6279       inner = build2 (code, TREE_TYPE (inner), op0, op1);
6280
6281       return fold_convert_loc (loc, TREE_TYPE (arg0), inner);
6282     }
6283
6284   /* If the argument isn't invariant then there's nothing else we can do.  */
6285   if (!TREE_CONSTANT (arg0))
6286     return NULL_TREE;
6287
6288   /* If we expect that a comparison against the argument will fold to
6289      a constant return the constant.  In practice, this means a true
6290      constant or the address of a non-weak symbol.  */
6291   inner = arg0;
6292   STRIP_NOPS (inner);
6293   if (TREE_CODE (inner) == ADDR_EXPR)
6294     {
6295       do
6296         {
6297           inner = TREE_OPERAND (inner, 0);
6298         }
6299       while (TREE_CODE (inner) == COMPONENT_REF
6300              || TREE_CODE (inner) == ARRAY_REF);
6301       if ((TREE_CODE (inner) == VAR_DECL
6302            || TREE_CODE (inner) == FUNCTION_DECL)
6303           && DECL_WEAK (inner))
6304         return NULL_TREE;
6305     }
6306
6307   /* Otherwise, ARG0 already has the proper type for the return value.  */
6308   return arg0;
6309 }
6310
6311 /* Fold a call to __builtin_classify_type with argument ARG.  */
6312
6313 static tree
6314 fold_builtin_classify_type (tree arg)
6315 {
6316   if (arg == 0)
6317     return build_int_cst (integer_type_node, no_type_class);
6318
6319   return build_int_cst (integer_type_node, type_to_class (TREE_TYPE (arg)));
6320 }
6321
6322 /* Fold a call to __builtin_strlen with argument ARG.  */
6323
6324 static tree
6325 fold_builtin_strlen (location_t loc, tree type, tree arg)
6326 {
6327   if (!validate_arg (arg, POINTER_TYPE))
6328     return NULL_TREE;
6329   else
6330     {
6331       tree len = c_strlen (arg, 0);
6332
6333       if (len)
6334         return fold_convert_loc (loc, type, len);
6335
6336       return NULL_TREE;
6337     }
6338 }
6339
6340 /* Fold a call to __builtin_inf or __builtin_huge_val.  */
6341
6342 static tree
6343 fold_builtin_inf (location_t loc, tree type, int warn)
6344 {
6345   REAL_VALUE_TYPE real;
6346
6347   /* __builtin_inff is intended to be usable to define INFINITY on all
6348      targets.  If an infinity is not available, INFINITY expands "to a
6349      positive constant of type float that overflows at translation
6350      time", footnote "In this case, using INFINITY will violate the
6351      constraint in 6.4.4 and thus require a diagnostic." (C99 7.12#4).
6352      Thus we pedwarn to ensure this constraint violation is
6353      diagnosed.  */
6354   if (!MODE_HAS_INFINITIES (TYPE_MODE (type)) && warn)
6355     pedwarn (loc, 0, "target format does not support infinity");
6356
6357   real_inf (&real);
6358   return build_real (type, real);
6359 }
6360
6361 /* Fold a call to __builtin_nan or __builtin_nans with argument ARG.  */
6362
6363 static tree
6364 fold_builtin_nan (tree arg, tree type, int quiet)
6365 {
6366   REAL_VALUE_TYPE real;
6367   const char *str;
6368
6369   if (!validate_arg (arg, POINTER_TYPE))
6370     return NULL_TREE;
6371   str = c_getstr (arg);
6372   if (!str)
6373     return NULL_TREE;
6374
6375   if (!real_nan (&real, str, quiet, TYPE_MODE (type)))
6376     return NULL_TREE;
6377
6378   return build_real (type, real);
6379 }
6380
6381 /* Return true if the floating point expression T has an integer value.
6382    We also allow +Inf, -Inf and NaN to be considered integer values.  */
6383
6384 static bool
6385 integer_valued_real_p (tree t)
6386 {
6387   switch (TREE_CODE (t))
6388     {
6389     case FLOAT_EXPR:
6390       return true;
6391
6392     case ABS_EXPR:
6393     case SAVE_EXPR:
6394       return integer_valued_real_p (TREE_OPERAND (t, 0));
6395
6396     case COMPOUND_EXPR:
6397     case MODIFY_EXPR:
6398     case BIND_EXPR:
6399       return integer_valued_real_p (TREE_OPERAND (t, 1));
6400
6401     case PLUS_EXPR:
6402     case MINUS_EXPR:
6403     case MULT_EXPR:
6404     case MIN_EXPR:
6405     case MAX_EXPR:
6406       return integer_valued_real_p (TREE_OPERAND (t, 0))
6407              && integer_valued_real_p (TREE_OPERAND (t, 1));
6408
6409     case COND_EXPR:
6410       return integer_valued_real_p (TREE_OPERAND (t, 1))
6411              && integer_valued_real_p (TREE_OPERAND (t, 2));
6412
6413     case REAL_CST:
6414       return real_isinteger (TREE_REAL_CST_PTR (t), TYPE_MODE (TREE_TYPE (t)));
6415
6416     case NOP_EXPR:
6417       {
6418         tree type = TREE_TYPE (TREE_OPERAND (t, 0));
6419         if (TREE_CODE (type) == INTEGER_TYPE)
6420           return true;
6421         if (TREE_CODE (type) == REAL_TYPE)
6422           return integer_valued_real_p (TREE_OPERAND (t, 0));
6423         break;
6424       }
6425
6426     case CALL_EXPR:
6427       switch (builtin_mathfn_code (t))
6428         {
6429         CASE_FLT_FN (BUILT_IN_CEIL):
6430         CASE_FLT_FN (BUILT_IN_FLOOR):
6431         CASE_FLT_FN (BUILT_IN_NEARBYINT):
6432         CASE_FLT_FN (BUILT_IN_RINT):
6433         CASE_FLT_FN (BUILT_IN_ROUND):
6434         CASE_FLT_FN (BUILT_IN_TRUNC):
6435           return true;
6436
6437         CASE_FLT_FN (BUILT_IN_FMIN):
6438         CASE_FLT_FN (BUILT_IN_FMAX):
6439           return integer_valued_real_p (CALL_EXPR_ARG (t, 0))
6440             && integer_valued_real_p (CALL_EXPR_ARG (t, 1));
6441
6442         default:
6443           break;
6444         }
6445       break;
6446
6447     default:
6448       break;
6449     }
6450   return false;
6451 }
6452
6453 /* FNDECL is assumed to be a builtin where truncation can be propagated
6454    across (for instance floor((double)f) == (double)floorf (f).
6455    Do the transformation for a call with argument ARG.  */
6456
6457 static tree
6458 fold_trunc_transparent_mathfn (location_t loc, tree fndecl, tree arg)
6459 {
6460   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
6461
6462   if (!validate_arg (arg, REAL_TYPE))
6463     return NULL_TREE;
6464
6465   /* Integer rounding functions are idempotent.  */
6466   if (fcode == builtin_mathfn_code (arg))
6467     return arg;
6468
6469   /* If argument is already integer valued, and we don't need to worry
6470      about setting errno, there's no need to perform rounding.  */
6471   if (! flag_errno_math && integer_valued_real_p (arg))
6472     return arg;
6473
6474   if (optimize)
6475     {
6476       tree arg0 = strip_float_extensions (arg);
6477       tree ftype = TREE_TYPE (TREE_TYPE (fndecl));
6478       tree newtype = TREE_TYPE (arg0);
6479       tree decl;
6480
6481       if (TYPE_PRECISION (newtype) < TYPE_PRECISION (ftype)
6482           && (decl = mathfn_built_in (newtype, fcode)))
6483         return fold_convert_loc (loc, ftype,
6484                                  build_call_expr_loc (loc, decl, 1,
6485                                                   fold_convert_loc (loc,
6486                                                                     newtype,
6487                                                                     arg0)));
6488     }
6489   return NULL_TREE;
6490 }
6491
6492 /* FNDECL is assumed to be builtin which can narrow the FP type of
6493    the argument, for instance lround((double)f) -> lroundf (f).
6494    Do the transformation for a call with argument ARG.  */
6495
6496 static tree
6497 fold_fixed_mathfn (location_t loc, tree fndecl, tree arg)
6498 {
6499   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
6500
6501   if (!validate_arg (arg, REAL_TYPE))
6502     return NULL_TREE;
6503
6504   /* If argument is already integer valued, and we don't need to worry
6505      about setting errno, there's no need to perform rounding.  */
6506   if (! flag_errno_math && integer_valued_real_p (arg))
6507     return fold_build1_loc (loc, FIX_TRUNC_EXPR,
6508                         TREE_TYPE (TREE_TYPE (fndecl)), arg);
6509
6510   if (optimize)
6511     {
6512       tree ftype = TREE_TYPE (arg);
6513       tree arg0 = strip_float_extensions (arg);
6514       tree newtype = TREE_TYPE (arg0);
6515       tree decl;
6516
6517       if (TYPE_PRECISION (newtype) < TYPE_PRECISION (ftype)
6518           && (decl = mathfn_built_in (newtype, fcode)))
6519         return build_call_expr_loc (loc, decl, 1,
6520                                 fold_convert_loc (loc, newtype, arg0));
6521     }
6522
6523   /* Canonicalize llround (x) to lround (x) on LP64 targets where
6524      sizeof (long long) == sizeof (long).  */
6525   if (TYPE_PRECISION (long_long_integer_type_node)
6526       == TYPE_PRECISION (long_integer_type_node))
6527     {
6528       tree newfn = NULL_TREE;
6529       switch (fcode)
6530         {
6531         CASE_FLT_FN (BUILT_IN_LLCEIL):
6532           newfn = mathfn_built_in (TREE_TYPE (arg), BUILT_IN_LCEIL);
6533           break;
6534
6535         CASE_FLT_FN (BUILT_IN_LLFLOOR):
6536           newfn = mathfn_built_in (TREE_TYPE (arg), BUILT_IN_LFLOOR);
6537           break;
6538
6539         CASE_FLT_FN (BUILT_IN_LLROUND):
6540           newfn = mathfn_built_in (TREE_TYPE (arg), BUILT_IN_LROUND);
6541           break;
6542
6543         CASE_FLT_FN (BUILT_IN_LLRINT):
6544           newfn = mathfn_built_in (TREE_TYPE (arg), BUILT_IN_LRINT);
6545           break;
6546
6547         default:
6548           break;
6549         }
6550
6551       if (newfn)
6552         {
6553           tree newcall = build_call_expr_loc (loc, newfn, 1, arg);
6554           return fold_convert_loc (loc,
6555                                    TREE_TYPE (TREE_TYPE (fndecl)), newcall);
6556         }
6557     }
6558
6559   return NULL_TREE;
6560 }
6561
6562 /* Fold call to builtin cabs, cabsf or cabsl with argument ARG.  TYPE is the
6563    return type.  Return NULL_TREE if no simplification can be made.  */
6564
6565 static tree
6566 fold_builtin_cabs (location_t loc, tree arg, tree type, tree fndecl)
6567 {
6568   tree res;
6569
6570   if (!validate_arg (arg, COMPLEX_TYPE)
6571       || TREE_CODE (TREE_TYPE (TREE_TYPE (arg))) != REAL_TYPE)
6572     return NULL_TREE;
6573
6574   /* Calculate the result when the argument is a constant.  */
6575   if (TREE_CODE (arg) == COMPLEX_CST
6576       && (res = do_mpfr_arg2 (TREE_REALPART (arg), TREE_IMAGPART (arg),
6577                               type, mpfr_hypot)))
6578     return res;
6579
6580   if (TREE_CODE (arg) == COMPLEX_EXPR)
6581     {
6582       tree real = TREE_OPERAND (arg, 0);
6583       tree imag = TREE_OPERAND (arg, 1);
6584
6585       /* If either part is zero, cabs is fabs of the other.  */
6586       if (real_zerop (real))
6587         return fold_build1_loc (loc, ABS_EXPR, type, imag);
6588       if (real_zerop (imag))
6589         return fold_build1_loc (loc, ABS_EXPR, type, real);
6590
6591       /* cabs(x+xi) -> fabs(x)*sqrt(2).  */
6592       if (flag_unsafe_math_optimizations
6593           && operand_equal_p (real, imag, OEP_PURE_SAME))
6594         {
6595           const REAL_VALUE_TYPE sqrt2_trunc
6596             = real_value_truncate (TYPE_MODE (type), dconst_sqrt2 ());
6597           STRIP_NOPS (real);
6598           return fold_build2_loc (loc, MULT_EXPR, type,
6599                               fold_build1_loc (loc, ABS_EXPR, type, real),
6600                               build_real (type, sqrt2_trunc));
6601         }
6602     }
6603
6604   /* Optimize cabs(-z) and cabs(conj(z)) as cabs(z).  */
6605   if (TREE_CODE (arg) == NEGATE_EXPR
6606       || TREE_CODE (arg) == CONJ_EXPR)
6607     return build_call_expr_loc (loc, fndecl, 1, TREE_OPERAND (arg, 0));
6608
6609   /* Don't do this when optimizing for size.  */
6610   if (flag_unsafe_math_optimizations
6611       && optimize && optimize_function_for_speed_p (cfun))
6612     {
6613       tree sqrtfn = mathfn_built_in (type, BUILT_IN_SQRT);
6614
6615       if (sqrtfn != NULL_TREE)
6616         {
6617           tree rpart, ipart, result;
6618
6619           arg = builtin_save_expr (arg);
6620
6621           rpart = fold_build1_loc (loc, REALPART_EXPR, type, arg);
6622           ipart = fold_build1_loc (loc, IMAGPART_EXPR, type, arg);
6623
6624           rpart = builtin_save_expr (rpart);
6625           ipart = builtin_save_expr (ipart);
6626
6627           result = fold_build2_loc (loc, PLUS_EXPR, type,
6628                                 fold_build2_loc (loc, MULT_EXPR, type,
6629                                              rpart, rpart),
6630                                 fold_build2_loc (loc, MULT_EXPR, type,
6631                                              ipart, ipart));
6632
6633           return build_call_expr_loc (loc, sqrtfn, 1, result);
6634         }
6635     }
6636
6637   return NULL_TREE;
6638 }
6639
6640 /* Build a complex (inf +- 0i) for the result of cproj.  TYPE is the
6641    complex tree type of the result.  If NEG is true, the imaginary
6642    zero is negative.  */
6643
6644 static tree
6645 build_complex_cproj (tree type, bool neg)
6646 {
6647   REAL_VALUE_TYPE rinf, rzero = dconst0;
6648   
6649   real_inf (&rinf);
6650   rzero.sign = neg;
6651   return build_complex (type, build_real (TREE_TYPE (type), rinf),
6652                         build_real (TREE_TYPE (type), rzero));
6653 }
6654
6655 /* Fold call to builtin cproj, cprojf or cprojl with argument ARG.  TYPE is the
6656    return type.  Return NULL_TREE if no simplification can be made.  */
6657
6658 static tree
6659 fold_builtin_cproj (location_t loc, tree arg, tree type)
6660 {
6661   if (!validate_arg (arg, COMPLEX_TYPE)
6662       || TREE_CODE (TREE_TYPE (TREE_TYPE (arg))) != REAL_TYPE)
6663     return NULL_TREE;
6664
6665   /* If there are no infinities, return arg.  */
6666   if (! HONOR_INFINITIES (TYPE_MODE (TREE_TYPE (type))))
6667     return non_lvalue_loc (loc, arg);
6668
6669   /* Calculate the result when the argument is a constant.  */
6670   if (TREE_CODE (arg) == COMPLEX_CST)
6671     {
6672       const REAL_VALUE_TYPE *real = TREE_REAL_CST_PTR (TREE_REALPART (arg));
6673       const REAL_VALUE_TYPE *imag = TREE_REAL_CST_PTR (TREE_IMAGPART (arg));
6674       
6675       if (real_isinf (real) || real_isinf (imag))
6676         return build_complex_cproj (type, imag->sign);
6677       else
6678         return arg;
6679     }
6680   else if (TREE_CODE (arg) == COMPLEX_EXPR)
6681     {
6682       tree real = TREE_OPERAND (arg, 0);
6683       tree imag = TREE_OPERAND (arg, 1);
6684
6685       STRIP_NOPS (real);
6686       STRIP_NOPS (imag);
6687       
6688       /* If the real part is inf and the imag part is known to be
6689          nonnegative, return (inf + 0i).  Remember side-effects are
6690          possible in the imag part.  */
6691       if (TREE_CODE (real) == REAL_CST
6692           && real_isinf (TREE_REAL_CST_PTR (real))
6693           && tree_expr_nonnegative_p (imag))
6694         return omit_one_operand_loc (loc, type,
6695                                      build_complex_cproj (type, false),
6696                                      arg);
6697       
6698       /* If the imag part is inf, return (inf+I*copysign(0,imag)).
6699          Remember side-effects are possible in the real part.  */
6700       if (TREE_CODE (imag) == REAL_CST
6701           && real_isinf (TREE_REAL_CST_PTR (imag)))
6702         return
6703           omit_one_operand_loc (loc, type,
6704                                 build_complex_cproj (type, TREE_REAL_CST_PTR
6705                                                      (imag)->sign), arg);
6706     }
6707
6708   return NULL_TREE;
6709 }
6710
6711 /* Fold a builtin function call to sqrt, sqrtf, or sqrtl with argument ARG.
6712    Return NULL_TREE if no simplification can be made.  */
6713
6714 static tree
6715 fold_builtin_sqrt (location_t loc, tree arg, tree type)
6716 {
6717
6718   enum built_in_function fcode;
6719   tree res;
6720
6721   if (!validate_arg (arg, REAL_TYPE))
6722     return NULL_TREE;
6723
6724   /* Calculate the result when the argument is a constant.  */
6725   if ((res = do_mpfr_arg1 (arg, type, mpfr_sqrt, &dconst0, NULL, true)))
6726     return res;
6727
6728   /* Optimize sqrt(expN(x)) = expN(x*0.5).  */
6729   fcode = builtin_mathfn_code (arg);
6730   if (flag_unsafe_math_optimizations && BUILTIN_EXPONENT_P (fcode))
6731     {
6732       tree expfn = TREE_OPERAND (CALL_EXPR_FN (arg), 0);
6733       arg = fold_build2_loc (loc, MULT_EXPR, type,
6734                          CALL_EXPR_ARG (arg, 0),
6735                          build_real (type, dconsthalf));
6736       return build_call_expr_loc (loc, expfn, 1, arg);
6737     }
6738
6739   /* Optimize sqrt(Nroot(x)) -> pow(x,1/(2*N)).  */
6740   if (flag_unsafe_math_optimizations && BUILTIN_ROOT_P (fcode))
6741     {
6742       tree powfn = mathfn_built_in (type, BUILT_IN_POW);
6743
6744       if (powfn)
6745         {
6746           tree arg0 = CALL_EXPR_ARG (arg, 0);
6747           tree tree_root;
6748           /* The inner root was either sqrt or cbrt.  */
6749           /* This was a conditional expression but it triggered a bug
6750              in Sun C 5.5.  */
6751           REAL_VALUE_TYPE dconstroot;
6752           if (BUILTIN_SQRT_P (fcode))
6753             dconstroot = dconsthalf;
6754           else
6755             dconstroot = dconst_third ();
6756
6757           /* Adjust for the outer root.  */
6758           SET_REAL_EXP (&dconstroot, REAL_EXP (&dconstroot) - 1);
6759           dconstroot = real_value_truncate (TYPE_MODE (type), dconstroot);
6760           tree_root = build_real (type, dconstroot);
6761           return build_call_expr_loc (loc, powfn, 2, arg0, tree_root);
6762         }
6763     }
6764
6765   /* Optimize sqrt(pow(x,y)) = pow(|x|,y*0.5).  */
6766   if (flag_unsafe_math_optimizations
6767       && (fcode == BUILT_IN_POW
6768           || fcode == BUILT_IN_POWF
6769           || fcode == BUILT_IN_POWL))
6770     {
6771       tree powfn = TREE_OPERAND (CALL_EXPR_FN (arg), 0);
6772       tree arg0 = CALL_EXPR_ARG (arg, 0);
6773       tree arg1 = CALL_EXPR_ARG (arg, 1);
6774       tree narg1;
6775       if (!tree_expr_nonnegative_p (arg0))
6776         arg0 = build1 (ABS_EXPR, type, arg0);
6777       narg1 = fold_build2_loc (loc, MULT_EXPR, type, arg1,
6778                            build_real (type, dconsthalf));
6779       return build_call_expr_loc (loc, powfn, 2, arg0, narg1);
6780     }
6781
6782   return NULL_TREE;
6783 }
6784
6785 /* Fold a builtin function call to cbrt, cbrtf, or cbrtl with argument ARG.
6786    Return NULL_TREE if no simplification can be made.  */
6787
6788 static tree
6789 fold_builtin_cbrt (location_t loc, tree arg, tree type)
6790 {
6791   const enum built_in_function fcode = builtin_mathfn_code (arg);
6792   tree res;
6793
6794   if (!validate_arg (arg, REAL_TYPE))
6795     return NULL_TREE;
6796
6797   /* Calculate the result when the argument is a constant.  */
6798   if ((res = do_mpfr_arg1 (arg, type, mpfr_cbrt, NULL, NULL, 0)))
6799     return res;
6800
6801   if (flag_unsafe_math_optimizations)
6802     {
6803       /* Optimize cbrt(expN(x)) -> expN(x/3).  */
6804       if (BUILTIN_EXPONENT_P (fcode))
6805         {
6806           tree expfn = TREE_OPERAND (CALL_EXPR_FN (arg), 0);
6807           const REAL_VALUE_TYPE third_trunc =
6808             real_value_truncate (TYPE_MODE (type), dconst_third ());
6809           arg = fold_build2_loc (loc, MULT_EXPR, type,
6810                              CALL_EXPR_ARG (arg, 0),
6811                              build_real (type, third_trunc));
6812           return build_call_expr_loc (loc, expfn, 1, arg);
6813         }
6814
6815       /* Optimize cbrt(sqrt(x)) -> pow(x,1/6).  */
6816       if (BUILTIN_SQRT_P (fcode))
6817         {
6818           tree powfn = mathfn_built_in (type, BUILT_IN_POW);
6819
6820           if (powfn)
6821             {
6822               tree arg0 = CALL_EXPR_ARG (arg, 0);
6823               tree tree_root;
6824               REAL_VALUE_TYPE dconstroot = dconst_third ();
6825
6826               SET_REAL_EXP (&dconstroot, REAL_EXP (&dconstroot) - 1);
6827               dconstroot = real_value_truncate (TYPE_MODE (type), dconstroot);
6828               tree_root = build_real (type, dconstroot);
6829               return build_call_expr_loc (loc, powfn, 2, arg0, tree_root);
6830             }
6831         }
6832
6833       /* Optimize cbrt(cbrt(x)) -> pow(x,1/9) iff x is nonnegative.  */
6834       if (BUILTIN_CBRT_P (fcode))
6835         {
6836           tree arg0 = CALL_EXPR_ARG (arg, 0);
6837           if (tree_expr_nonnegative_p (arg0))
6838             {
6839               tree powfn = mathfn_built_in (type, BUILT_IN_POW);
6840
6841               if (powfn)
6842                 {
6843                   tree tree_root;
6844                   REAL_VALUE_TYPE dconstroot;
6845
6846                   real_arithmetic (&dconstroot, MULT_EXPR,
6847                                    dconst_third_ptr (), dconst_third_ptr ());
6848                   dconstroot = real_value_truncate (TYPE_MODE (type), dconstroot);
6849                   tree_root = build_real (type, dconstroot);
6850                   return build_call_expr_loc (loc, powfn, 2, arg0, tree_root);
6851                 }
6852             }
6853         }
6854
6855       /* Optimize cbrt(pow(x,y)) -> pow(x,y/3) iff x is nonnegative.  */
6856       if (fcode == BUILT_IN_POW
6857           || fcode == BUILT_IN_POWF
6858           || fcode == BUILT_IN_POWL)
6859         {
6860           tree arg00 = CALL_EXPR_ARG (arg, 0);
6861           tree arg01 = CALL_EXPR_ARG (arg, 1);
6862           if (tree_expr_nonnegative_p (arg00))
6863             {
6864               tree powfn = TREE_OPERAND (CALL_EXPR_FN (arg), 0);
6865               const REAL_VALUE_TYPE dconstroot
6866                 = real_value_truncate (TYPE_MODE (type), dconst_third ());
6867               tree narg01 = fold_build2_loc (loc, MULT_EXPR, type, arg01,
6868                                          build_real (type, dconstroot));
6869               return build_call_expr_loc (loc, powfn, 2, arg00, narg01);
6870             }
6871         }
6872     }
6873   return NULL_TREE;
6874 }
6875
6876 /* Fold function call to builtin cos, cosf, or cosl with argument ARG.
6877    TYPE is the type of the return value.  Return NULL_TREE if no
6878    simplification can be made.  */
6879
6880 static tree
6881 fold_builtin_cos (location_t loc,
6882                   tree arg, tree type, tree fndecl)
6883 {
6884   tree res, narg;
6885
6886   if (!validate_arg (arg, REAL_TYPE))
6887     return NULL_TREE;
6888
6889   /* Calculate the result when the argument is a constant.  */
6890   if ((res = do_mpfr_arg1 (arg, type, mpfr_cos, NULL, NULL, 0)))
6891     return res;
6892
6893   /* Optimize cos(-x) into cos (x).  */
6894   if ((narg = fold_strip_sign_ops (arg)))
6895     return build_call_expr_loc (loc, fndecl, 1, narg);
6896
6897   return NULL_TREE;
6898 }
6899
6900 /* Fold function call to builtin cosh, coshf, or coshl with argument ARG.
6901    Return NULL_TREE if no simplification can be made.  */
6902
6903 static tree
6904 fold_builtin_cosh (location_t loc, tree arg, tree type, tree fndecl)
6905 {
6906   if (validate_arg (arg, REAL_TYPE))
6907     {
6908       tree res, narg;
6909
6910       /* Calculate the result when the argument is a constant.  */
6911       if ((res = do_mpfr_arg1 (arg, type, mpfr_cosh, NULL, NULL, 0)))
6912         return res;
6913
6914       /* Optimize cosh(-x) into cosh (x).  */
6915       if ((narg = fold_strip_sign_ops (arg)))
6916         return build_call_expr_loc (loc, fndecl, 1, narg);
6917     }
6918
6919   return NULL_TREE;
6920 }
6921
6922 /* Fold function call to builtin ccos (or ccosh if HYPER is TRUE) with
6923    argument ARG.  TYPE is the type of the return value.  Return
6924    NULL_TREE if no simplification can be made.  */
6925
6926 static tree
6927 fold_builtin_ccos (location_t loc, tree arg, tree type, tree fndecl,
6928                    bool hyper)
6929 {
6930   if (validate_arg (arg, COMPLEX_TYPE)
6931       && TREE_CODE (TREE_TYPE (TREE_TYPE (arg))) == REAL_TYPE)
6932     {
6933       tree tmp;
6934
6935       /* Calculate the result when the argument is a constant.  */
6936       if ((tmp = do_mpc_arg1 (arg, type, (hyper ? mpc_cosh : mpc_cos))))
6937         return tmp;
6938
6939       /* Optimize fn(-x) into fn(x).  */
6940       if ((tmp = fold_strip_sign_ops (arg)))
6941         return build_call_expr_loc (loc, fndecl, 1, tmp);
6942     }
6943
6944   return NULL_TREE;
6945 }
6946
6947 /* Fold function call to builtin tan, tanf, or tanl with argument ARG.
6948    Return NULL_TREE if no simplification can be made.  */
6949
6950 static tree
6951 fold_builtin_tan (tree arg, tree type)
6952 {
6953   enum built_in_function fcode;
6954   tree res;
6955
6956   if (!validate_arg (arg, REAL_TYPE))
6957     return NULL_TREE;
6958
6959   /* Calculate the result when the argument is a constant.  */
6960   if ((res = do_mpfr_arg1 (arg, type, mpfr_tan, NULL, NULL, 0)))
6961     return res;
6962
6963   /* Optimize tan(atan(x)) = x.  */
6964   fcode = builtin_mathfn_code (arg);
6965   if (flag_unsafe_math_optimizations
6966       && (fcode == BUILT_IN_ATAN
6967           || fcode == BUILT_IN_ATANF
6968           || fcode == BUILT_IN_ATANL))
6969     return CALL_EXPR_ARG (arg, 0);
6970
6971   return NULL_TREE;
6972 }
6973
6974 /* Fold function call to builtin sincos, sincosf, or sincosl.  Return
6975    NULL_TREE if no simplification can be made.  */
6976
6977 static tree
6978 fold_builtin_sincos (location_t loc,
6979                      tree arg0, tree arg1, tree arg2)
6980 {
6981   tree type;
6982   tree res, fn, call;
6983
6984   if (!validate_arg (arg0, REAL_TYPE)
6985       || !validate_arg (arg1, POINTER_TYPE)
6986       || !validate_arg (arg2, POINTER_TYPE))
6987     return NULL_TREE;
6988
6989   type = TREE_TYPE (arg0);
6990
6991   /* Calculate the result when the argument is a constant.  */
6992   if ((res = do_mpfr_sincos (arg0, arg1, arg2)))
6993     return res;
6994
6995   /* Canonicalize sincos to cexpi.  */
6996   if (!TARGET_C99_FUNCTIONS)
6997     return NULL_TREE;
6998   fn = mathfn_built_in (type, BUILT_IN_CEXPI);
6999   if (!fn)
7000     return NULL_TREE;
7001
7002   call = build_call_expr_loc (loc, fn, 1, arg0);
7003   call = builtin_save_expr (call);
7004
7005   return build2 (COMPOUND_EXPR, void_type_node,
7006                  build2 (MODIFY_EXPR, void_type_node,
7007                          build_fold_indirect_ref_loc (loc, arg1),
7008                          build1 (IMAGPART_EXPR, type, call)),
7009                  build2 (MODIFY_EXPR, void_type_node,
7010                          build_fold_indirect_ref_loc (loc, arg2),
7011                          build1 (REALPART_EXPR, type, call)));
7012 }
7013
7014 /* Fold function call to builtin cexp, cexpf, or cexpl.  Return
7015    NULL_TREE if no simplification can be made.  */
7016
7017 static tree
7018 fold_builtin_cexp (location_t loc, tree arg0, tree type)
7019 {
7020   tree rtype;
7021   tree realp, imagp, ifn;
7022   tree res;
7023
7024   if (!validate_arg (arg0, COMPLEX_TYPE)
7025       || TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) != REAL_TYPE)
7026     return NULL_TREE;
7027
7028   /* Calculate the result when the argument is a constant.  */
7029   if ((res = do_mpc_arg1 (arg0, type, mpc_exp)))
7030     return res;
7031
7032   rtype = TREE_TYPE (TREE_TYPE (arg0));
7033
7034   /* In case we can figure out the real part of arg0 and it is constant zero
7035      fold to cexpi.  */
7036   if (!TARGET_C99_FUNCTIONS)
7037     return NULL_TREE;
7038   ifn = mathfn_built_in (rtype, BUILT_IN_CEXPI);
7039   if (!ifn)
7040     return NULL_TREE;
7041
7042   if ((realp = fold_unary_loc (loc, REALPART_EXPR, rtype, arg0))
7043       && real_zerop (realp))
7044     {
7045       tree narg = fold_build1_loc (loc, IMAGPART_EXPR, rtype, arg0);
7046       return build_call_expr_loc (loc, ifn, 1, narg);
7047     }
7048
7049   /* In case we can easily decompose real and imaginary parts split cexp
7050      to exp (r) * cexpi (i).  */
7051   if (flag_unsafe_math_optimizations
7052       && realp)
7053     {
7054       tree rfn, rcall, icall;
7055
7056       rfn = mathfn_built_in (rtype, BUILT_IN_EXP);
7057       if (!rfn)
7058         return NULL_TREE;
7059
7060       imagp = fold_unary_loc (loc, IMAGPART_EXPR, rtype, arg0);
7061       if (!imagp)
7062         return NULL_TREE;
7063
7064       icall = build_call_expr_loc (loc, ifn, 1, imagp);
7065       icall = builtin_save_expr (icall);
7066       rcall = build_call_expr_loc (loc, rfn, 1, realp);
7067       rcall = builtin_save_expr (rcall);
7068       return fold_build2_loc (loc, COMPLEX_EXPR, type,
7069                           fold_build2_loc (loc, MULT_EXPR, rtype,
7070                                        rcall,
7071                                        fold_build1_loc (loc, REALPART_EXPR,
7072                                                     rtype, icall)),
7073                           fold_build2_loc (loc, MULT_EXPR, rtype,
7074                                        rcall,
7075                                        fold_build1_loc (loc, IMAGPART_EXPR,
7076                                                     rtype, icall)));
7077     }
7078
7079   return NULL_TREE;
7080 }
7081
7082 /* Fold function call to builtin trunc, truncf or truncl with argument ARG.
7083    Return NULL_TREE if no simplification can be made.  */
7084
7085 static tree
7086 fold_builtin_trunc (location_t loc, tree fndecl, tree arg)
7087 {
7088   if (!validate_arg (arg, REAL_TYPE))
7089     return NULL_TREE;
7090
7091   /* Optimize trunc of constant value.  */
7092   if (TREE_CODE (arg) == REAL_CST && !TREE_OVERFLOW (arg))
7093     {
7094       REAL_VALUE_TYPE r, x;
7095       tree type = TREE_TYPE (TREE_TYPE (fndecl));
7096
7097       x = TREE_REAL_CST (arg);
7098       real_trunc (&r, TYPE_MODE (type), &x);
7099       return build_real (type, r);
7100     }
7101
7102   return fold_trunc_transparent_mathfn (loc, fndecl, arg);
7103 }
7104
7105 /* Fold function call to builtin floor, floorf or floorl with argument ARG.
7106    Return NULL_TREE if no simplification can be made.  */
7107
7108 static tree
7109 fold_builtin_floor (location_t loc, tree fndecl, tree arg)
7110 {
7111   if (!validate_arg (arg, REAL_TYPE))
7112     return NULL_TREE;
7113
7114   /* Optimize floor of constant value.  */
7115   if (TREE_CODE (arg) == REAL_CST && !TREE_OVERFLOW (arg))
7116     {
7117       REAL_VALUE_TYPE x;
7118
7119       x = TREE_REAL_CST (arg);
7120       if (! REAL_VALUE_ISNAN (x) || ! flag_errno_math)
7121         {
7122           tree type = TREE_TYPE (TREE_TYPE (fndecl));
7123           REAL_VALUE_TYPE r;
7124
7125           real_floor (&r, TYPE_MODE (type), &x);
7126           return build_real (type, r);
7127         }
7128     }
7129
7130   /* Fold floor (x) where x is nonnegative to trunc (x).  */
7131   if (tree_expr_nonnegative_p (arg))
7132     {
7133       tree truncfn = mathfn_built_in (TREE_TYPE (arg), BUILT_IN_TRUNC);
7134       if (truncfn)
7135         return build_call_expr_loc (loc, truncfn, 1, arg);
7136     }
7137
7138   return fold_trunc_transparent_mathfn (loc, fndecl, arg);
7139 }
7140
7141 /* Fold function call to builtin ceil, ceilf or ceill with argument ARG.
7142    Return NULL_TREE if no simplification can be made.  */
7143
7144 static tree
7145 fold_builtin_ceil (location_t loc, tree fndecl, tree arg)
7146 {
7147   if (!validate_arg (arg, REAL_TYPE))
7148     return NULL_TREE;
7149
7150   /* Optimize ceil of constant value.  */
7151   if (TREE_CODE (arg) == REAL_CST && !TREE_OVERFLOW (arg))
7152     {
7153       REAL_VALUE_TYPE x;
7154
7155       x = TREE_REAL_CST (arg);
7156       if (! REAL_VALUE_ISNAN (x) || ! flag_errno_math)
7157         {
7158           tree type = TREE_TYPE (TREE_TYPE (fndecl));
7159           REAL_VALUE_TYPE r;
7160
7161           real_ceil (&r, TYPE_MODE (type), &x);
7162           return build_real (type, r);
7163         }
7164     }
7165
7166   return fold_trunc_transparent_mathfn (loc, fndecl, arg);
7167 }
7168
7169 /* Fold function call to builtin round, roundf or roundl with argument ARG.
7170    Return NULL_TREE if no simplification can be made.  */
7171
7172 static tree
7173 fold_builtin_round (location_t loc, tree fndecl, tree arg)
7174 {
7175   if (!validate_arg (arg, REAL_TYPE))
7176     return NULL_TREE;
7177
7178   /* Optimize round of constant value.  */
7179   if (TREE_CODE (arg) == REAL_CST && !TREE_OVERFLOW (arg))
7180     {
7181       REAL_VALUE_TYPE x;
7182
7183       x = TREE_REAL_CST (arg);
7184       if (! REAL_VALUE_ISNAN (x) || ! flag_errno_math)
7185         {
7186           tree type = TREE_TYPE (TREE_TYPE (fndecl));
7187           REAL_VALUE_TYPE r;
7188
7189           real_round (&r, TYPE_MODE (type), &x);
7190           return build_real (type, r);
7191         }
7192     }
7193
7194   return fold_trunc_transparent_mathfn (loc, fndecl, arg);
7195 }
7196
7197 /* Fold function call to builtin lround, lroundf or lroundl (or the
7198    corresponding long long versions) and other rounding functions.  ARG
7199    is the argument to the call.  Return NULL_TREE if no simplification
7200    can be made.  */
7201
7202 static tree
7203 fold_builtin_int_roundingfn (location_t loc, tree fndecl, tree arg)
7204 {
7205   if (!validate_arg (arg, REAL_TYPE))
7206     return NULL_TREE;
7207
7208   /* Optimize lround of constant value.  */
7209   if (TREE_CODE (arg) == REAL_CST && !TREE_OVERFLOW (arg))
7210     {
7211       const REAL_VALUE_TYPE x = TREE_REAL_CST (arg);
7212
7213       if (real_isfinite (&x))
7214         {
7215           tree itype = TREE_TYPE (TREE_TYPE (fndecl));
7216           tree ftype = TREE_TYPE (arg);
7217           double_int val;
7218           REAL_VALUE_TYPE r;
7219
7220           switch (DECL_FUNCTION_CODE (fndecl))
7221             {
7222             CASE_FLT_FN (BUILT_IN_LFLOOR):
7223             CASE_FLT_FN (BUILT_IN_LLFLOOR):
7224               real_floor (&r, TYPE_MODE (ftype), &x);
7225               break;
7226
7227             CASE_FLT_FN (BUILT_IN_LCEIL):
7228             CASE_FLT_FN (BUILT_IN_LLCEIL):
7229               real_ceil (&r, TYPE_MODE (ftype), &x);
7230               break;
7231
7232             CASE_FLT_FN (BUILT_IN_LROUND):
7233             CASE_FLT_FN (BUILT_IN_LLROUND):
7234               real_round (&r, TYPE_MODE (ftype), &x);
7235               break;
7236
7237             default:
7238               gcc_unreachable ();
7239             }
7240
7241           real_to_integer2 ((HOST_WIDE_INT *)&val.low, &val.high, &r);
7242           if (double_int_fits_to_tree_p (itype, val))
7243             return double_int_to_tree (itype, val);
7244         }
7245     }
7246
7247   switch (DECL_FUNCTION_CODE (fndecl))
7248     {
7249     CASE_FLT_FN (BUILT_IN_LFLOOR):
7250     CASE_FLT_FN (BUILT_IN_LLFLOOR):
7251       /* Fold lfloor (x) where x is nonnegative to FIX_TRUNC (x).  */
7252       if (tree_expr_nonnegative_p (arg))
7253         return fold_build1_loc (loc, FIX_TRUNC_EXPR,
7254                             TREE_TYPE (TREE_TYPE (fndecl)), arg);
7255       break;
7256     default:;
7257     }
7258
7259   return fold_fixed_mathfn (loc, fndecl, arg);
7260 }
7261
7262 /* Fold function call to builtin ffs, clz, ctz, popcount and parity
7263    and their long and long long variants (i.e. ffsl and ffsll).  ARG is
7264    the argument to the call.  Return NULL_TREE if no simplification can
7265    be made.  */
7266
7267 static tree
7268 fold_builtin_bitop (tree fndecl, tree arg)
7269 {
7270   if (!validate_arg (arg, INTEGER_TYPE))
7271     return NULL_TREE;
7272
7273   /* Optimize for constant argument.  */
7274   if (TREE_CODE (arg) == INTEGER_CST && !TREE_OVERFLOW (arg))
7275     {
7276       HOST_WIDE_INT hi, width, result;
7277       unsigned HOST_WIDE_INT lo;
7278       tree type;
7279
7280       type = TREE_TYPE (arg);
7281       width = TYPE_PRECISION (type);
7282       lo = TREE_INT_CST_LOW (arg);
7283
7284       /* Clear all the bits that are beyond the type's precision.  */
7285       if (width > HOST_BITS_PER_WIDE_INT)
7286         {
7287           hi = TREE_INT_CST_HIGH (arg);
7288           if (width < 2 * HOST_BITS_PER_WIDE_INT)
7289             hi &= ~((unsigned HOST_WIDE_INT) (-1)
7290                     << (width - HOST_BITS_PER_WIDE_INT));
7291         }
7292       else
7293         {
7294           hi = 0;
7295           if (width < HOST_BITS_PER_WIDE_INT)
7296             lo &= ~((unsigned HOST_WIDE_INT) (-1) << width);
7297         }
7298
7299       switch (DECL_FUNCTION_CODE (fndecl))
7300         {
7301         CASE_INT_FN (BUILT_IN_FFS):
7302           if (lo != 0)
7303             result = ffs_hwi (lo);
7304           else if (hi != 0)
7305             result = HOST_BITS_PER_WIDE_INT + ffs_hwi (hi);
7306           else
7307             result = 0;
7308           break;
7309
7310         CASE_INT_FN (BUILT_IN_CLZ):
7311           if (hi != 0)
7312             result = width - floor_log2 (hi) - 1 - HOST_BITS_PER_WIDE_INT;
7313           else if (lo != 0)
7314             result = width - floor_log2 (lo) - 1;
7315           else if (! CLZ_DEFINED_VALUE_AT_ZERO (TYPE_MODE (type), result))
7316             result = width;
7317           break;
7318
7319         CASE_INT_FN (BUILT_IN_CTZ):
7320           if (lo != 0)
7321             result = ctz_hwi (lo);
7322           else if (hi != 0)
7323             result = HOST_BITS_PER_WIDE_INT + ctz_hwi (hi);
7324           else if (! CTZ_DEFINED_VALUE_AT_ZERO (TYPE_MODE (type), result))
7325             result = width;
7326           break;
7327
7328         CASE_INT_FN (BUILT_IN_CLRSB):
7329           if (width > HOST_BITS_PER_WIDE_INT
7330               && (hi & ((unsigned HOST_WIDE_INT) 1
7331                         << (width - HOST_BITS_PER_WIDE_INT - 1))) != 0)
7332             {
7333               hi = ~hi & ~((unsigned HOST_WIDE_INT) (-1)
7334                            << (width - HOST_BITS_PER_WIDE_INT - 1));
7335               lo = ~lo;
7336             }
7337           else if (width <= HOST_BITS_PER_WIDE_INT
7338                    && (lo & ((unsigned HOST_WIDE_INT) 1 << (width - 1))) != 0)
7339             lo = ~lo & ~((unsigned HOST_WIDE_INT) (-1) << (width - 1));
7340           if (hi != 0)
7341             result = width - floor_log2 (hi) - 2 - HOST_BITS_PER_WIDE_INT;
7342           else if (lo != 0)
7343             result = width - floor_log2 (lo) - 2;
7344           else
7345             result = width - 1;
7346           break;
7347
7348         CASE_INT_FN (BUILT_IN_POPCOUNT):
7349           result = 0;
7350           while (lo)
7351             result++, lo &= lo - 1;
7352           while (hi)
7353             result++, hi &= (unsigned HOST_WIDE_INT) hi - 1;
7354           break;
7355
7356         CASE_INT_FN (BUILT_IN_PARITY):
7357           result = 0;
7358           while (lo)
7359             result++, lo &= lo - 1;
7360           while (hi)
7361             result++, hi &= (unsigned HOST_WIDE_INT) hi - 1;
7362           result &= 1;
7363           break;
7364
7365         default:
7366           gcc_unreachable ();
7367         }
7368
7369       return build_int_cst (TREE_TYPE (TREE_TYPE (fndecl)), result);
7370     }
7371
7372   return NULL_TREE;
7373 }
7374
7375 /* Fold function call to builtin_bswap and the long and long long
7376    variants.  Return NULL_TREE if no simplification can be made.  */
7377 static tree
7378 fold_builtin_bswap (tree fndecl, tree arg)
7379 {
7380   if (! validate_arg (arg, INTEGER_TYPE))
7381     return NULL_TREE;
7382
7383   /* Optimize constant value.  */
7384   if (TREE_CODE (arg) == INTEGER_CST && !TREE_OVERFLOW (arg))
7385     {
7386       HOST_WIDE_INT hi, width, r_hi = 0;
7387       unsigned HOST_WIDE_INT lo, r_lo = 0;
7388       tree type;
7389
7390       type = TREE_TYPE (arg);
7391       width = TYPE_PRECISION (type);
7392       lo = TREE_INT_CST_LOW (arg);
7393       hi = TREE_INT_CST_HIGH (arg);
7394
7395       switch (DECL_FUNCTION_CODE (fndecl))
7396         {
7397           case BUILT_IN_BSWAP32:
7398           case BUILT_IN_BSWAP64:
7399             {
7400               int s;
7401
7402               for (s = 0; s < width; s += 8)
7403                 {
7404                   int d = width - s - 8;
7405                   unsigned HOST_WIDE_INT byte;
7406
7407                   if (s < HOST_BITS_PER_WIDE_INT)
7408                     byte = (lo >> s) & 0xff;
7409                   else
7410                     byte = (hi >> (s - HOST_BITS_PER_WIDE_INT)) & 0xff;
7411
7412                   if (d < HOST_BITS_PER_WIDE_INT)
7413                     r_lo |= byte << d;
7414                   else
7415                     r_hi |= byte << (d - HOST_BITS_PER_WIDE_INT);
7416                 }
7417             }
7418
7419             break;
7420
7421         default:
7422           gcc_unreachable ();
7423         }
7424
7425       if (width < HOST_BITS_PER_WIDE_INT)
7426         return build_int_cst (TREE_TYPE (TREE_TYPE (fndecl)), r_lo);
7427       else
7428         return build_int_cst_wide (TREE_TYPE (TREE_TYPE (fndecl)), r_lo, r_hi);
7429     }
7430
7431   return NULL_TREE;
7432 }
7433
7434 /* A subroutine of fold_builtin to fold the various logarithmic
7435    functions.  Return NULL_TREE if no simplification can me made.
7436    FUNC is the corresponding MPFR logarithm function.  */
7437
7438 static tree
7439 fold_builtin_logarithm (location_t loc, tree fndecl, tree arg,
7440                         int (*func)(mpfr_ptr, mpfr_srcptr, mp_rnd_t))
7441 {
7442   if (validate_arg (arg, REAL_TYPE))
7443     {
7444       tree type = TREE_TYPE (TREE_TYPE (fndecl));
7445       tree res;
7446       const enum built_in_function fcode = builtin_mathfn_code (arg);
7447
7448       /* Calculate the result when the argument is a constant.  */
7449       if ((res = do_mpfr_arg1 (arg, type, func, &dconst0, NULL, false)))
7450         return res;
7451
7452       /* Special case, optimize logN(expN(x)) = x.  */
7453       if (flag_unsafe_math_optimizations
7454           && ((func == mpfr_log
7455                && (fcode == BUILT_IN_EXP
7456                    || fcode == BUILT_IN_EXPF
7457                    || fcode == BUILT_IN_EXPL))
7458               || (func == mpfr_log2
7459                   && (fcode == BUILT_IN_EXP2
7460                       || fcode == BUILT_IN_EXP2F
7461                       || fcode == BUILT_IN_EXP2L))
7462               || (func == mpfr_log10 && (BUILTIN_EXP10_P (fcode)))))
7463         return fold_convert_loc (loc, type, CALL_EXPR_ARG (arg, 0));
7464
7465       /* Optimize logN(func()) for various exponential functions.  We
7466          want to determine the value "x" and the power "exponent" in
7467          order to transform logN(x**exponent) into exponent*logN(x).  */
7468       if (flag_unsafe_math_optimizations)
7469         {
7470           tree exponent = 0, x = 0;
7471
7472           switch (fcode)
7473           {
7474           CASE_FLT_FN (BUILT_IN_EXP):
7475             /* Prepare to do logN(exp(exponent) -> exponent*logN(e).  */
7476             x = build_real (type, real_value_truncate (TYPE_MODE (type),
7477                                                        dconst_e ()));
7478             exponent = CALL_EXPR_ARG (arg, 0);
7479             break;
7480           CASE_FLT_FN (BUILT_IN_EXP2):
7481             /* Prepare to do logN(exp2(exponent) -> exponent*logN(2).  */
7482             x = build_real (type, dconst2);
7483             exponent = CALL_EXPR_ARG (arg, 0);
7484             break;
7485           CASE_FLT_FN (BUILT_IN_EXP10):
7486           CASE_FLT_FN (BUILT_IN_POW10):
7487             /* Prepare to do logN(exp10(exponent) -> exponent*logN(10).  */
7488             {
7489               REAL_VALUE_TYPE dconst10;
7490               real_from_integer (&dconst10, VOIDmode, 10, 0, 0);
7491               x = build_real (type, dconst10);
7492             }
7493             exponent = CALL_EXPR_ARG (arg, 0);
7494             break;
7495           CASE_FLT_FN (BUILT_IN_SQRT):
7496             /* Prepare to do logN(sqrt(x) -> 0.5*logN(x).  */
7497             x = CALL_EXPR_ARG (arg, 0);
7498             exponent = build_real (type, dconsthalf);
7499             break;
7500           CASE_FLT_FN (BUILT_IN_CBRT):
7501             /* Prepare to do logN(cbrt(x) -> (1/3)*logN(x).  */
7502             x = CALL_EXPR_ARG (arg, 0);
7503             exponent = build_real (type, real_value_truncate (TYPE_MODE (type),
7504                                                               dconst_third ()));
7505             break;
7506           CASE_FLT_FN (BUILT_IN_POW):
7507             /* Prepare to do logN(pow(x,exponent) -> exponent*logN(x).  */
7508             x = CALL_EXPR_ARG (arg, 0);
7509             exponent = CALL_EXPR_ARG (arg, 1);
7510             break;
7511           default:
7512             break;
7513           }
7514
7515           /* Now perform the optimization.  */
7516           if (x && exponent)
7517             {
7518               tree logfn = build_call_expr_loc (loc, fndecl, 1, x);
7519               return fold_build2_loc (loc, MULT_EXPR, type, exponent, logfn);
7520             }
7521         }
7522     }
7523
7524   return NULL_TREE;
7525 }
7526
7527 /* Fold a builtin function call to hypot, hypotf, or hypotl.  Return
7528    NULL_TREE if no simplification can be made.  */
7529
7530 static tree
7531 fold_builtin_hypot (location_t loc, tree fndecl,
7532                     tree arg0, tree arg1, tree type)
7533 {
7534   tree res, narg0, narg1;
7535
7536   if (!validate_arg (arg0, REAL_TYPE)
7537       || !validate_arg (arg1, REAL_TYPE))
7538     return NULL_TREE;
7539
7540   /* Calculate the result when the argument is a constant.  */
7541   if ((res = do_mpfr_arg2 (arg0, arg1, type, mpfr_hypot)))
7542     return res;
7543
7544   /* If either argument to hypot has a negate or abs, strip that off.
7545      E.g. hypot(-x,fabs(y)) -> hypot(x,y).  */
7546   narg0 = fold_strip_sign_ops (arg0);
7547   narg1 = fold_strip_sign_ops (arg1);
7548   if (narg0 || narg1)
7549     {
7550       return build_call_expr_loc (loc, fndecl, 2, narg0 ? narg0 : arg0,
7551                               narg1 ? narg1 : arg1);
7552     }
7553
7554   /* If either argument is zero, hypot is fabs of the other.  */
7555   if (real_zerop (arg0))
7556     return fold_build1_loc (loc, ABS_EXPR, type, arg1);
7557   else if (real_zerop (arg1))
7558     return fold_build1_loc (loc, ABS_EXPR, type, arg0);
7559
7560   /* hypot(x,x) -> fabs(x)*sqrt(2).  */
7561   if (flag_unsafe_math_optimizations
7562       && operand_equal_p (arg0, arg1, OEP_PURE_SAME))
7563     {
7564       const REAL_VALUE_TYPE sqrt2_trunc
7565         = real_value_truncate (TYPE_MODE (type), dconst_sqrt2 ());
7566       return fold_build2_loc (loc, MULT_EXPR, type,
7567                           fold_build1_loc (loc, ABS_EXPR, type, arg0),
7568                           build_real (type, sqrt2_trunc));
7569     }
7570
7571   return NULL_TREE;
7572 }
7573
7574
7575 /* Fold a builtin function call to pow, powf, or powl.  Return
7576    NULL_TREE if no simplification can be made.  */
7577 static tree
7578 fold_builtin_pow (location_t loc, tree fndecl, tree arg0, tree arg1, tree type)
7579 {
7580   tree res;
7581
7582   if (!validate_arg (arg0, REAL_TYPE)
7583        || !validate_arg (arg1, REAL_TYPE))
7584     return NULL_TREE;
7585
7586   /* Calculate the result when the argument is a constant.  */
7587   if ((res = do_mpfr_arg2 (arg0, arg1, type, mpfr_pow)))
7588     return res;
7589
7590   /* Optimize pow(1.0,y) = 1.0.  */
7591   if (real_onep (arg0))
7592     return omit_one_operand_loc (loc, type, build_real (type, dconst1), arg1);
7593
7594   if (TREE_CODE (arg1) == REAL_CST
7595       && !TREE_OVERFLOW (arg1))
7596     {
7597       REAL_VALUE_TYPE cint;
7598       REAL_VALUE_TYPE c;
7599       HOST_WIDE_INT n;
7600
7601       c = TREE_REAL_CST (arg1);
7602
7603       /* Optimize pow(x,0.0) = 1.0.  */
7604       if (REAL_VALUES_EQUAL (c, dconst0))
7605         return omit_one_operand_loc (loc, type, build_real (type, dconst1),
7606                                  arg0);
7607
7608       /* Optimize pow(x,1.0) = x.  */
7609       if (REAL_VALUES_EQUAL (c, dconst1))
7610         return arg0;
7611
7612       /* Optimize pow(x,-1.0) = 1.0/x.  */
7613       if (REAL_VALUES_EQUAL (c, dconstm1))
7614         return fold_build2_loc (loc, RDIV_EXPR, type,
7615                             build_real (type, dconst1), arg0);
7616
7617       /* Optimize pow(x,0.5) = sqrt(x).  */
7618       if (flag_unsafe_math_optimizations
7619           && REAL_VALUES_EQUAL (c, dconsthalf))
7620         {
7621           tree sqrtfn = mathfn_built_in (type, BUILT_IN_SQRT);
7622
7623           if (sqrtfn != NULL_TREE)
7624             return build_call_expr_loc (loc, sqrtfn, 1, arg0);
7625         }
7626
7627       /* Optimize pow(x,1.0/3.0) = cbrt(x).  */
7628       if (flag_unsafe_math_optimizations)
7629         {
7630           const REAL_VALUE_TYPE dconstroot
7631             = real_value_truncate (TYPE_MODE (type), dconst_third ());
7632
7633           if (REAL_VALUES_EQUAL (c, dconstroot))
7634             {
7635               tree cbrtfn = mathfn_built_in (type, BUILT_IN_CBRT);
7636               if (cbrtfn != NULL_TREE)
7637                 return build_call_expr_loc (loc, cbrtfn, 1, arg0);
7638             }
7639         }
7640
7641       /* Check for an integer exponent.  */
7642       n = real_to_integer (&c);
7643       real_from_integer (&cint, VOIDmode, n, n < 0 ? -1 : 0, 0);
7644       if (real_identical (&c, &cint))
7645         {
7646           /* Attempt to evaluate pow at compile-time, unless this should
7647              raise an exception.  */
7648           if (TREE_CODE (arg0) == REAL_CST
7649               && !TREE_OVERFLOW (arg0)
7650               && (n > 0
7651                   || (!flag_trapping_math && !flag_errno_math)
7652                   || !REAL_VALUES_EQUAL (TREE_REAL_CST (arg0), dconst0)))
7653             {
7654               REAL_VALUE_TYPE x;
7655               bool inexact;
7656
7657               x = TREE_REAL_CST (arg0);
7658               inexact = real_powi (&x, TYPE_MODE (type), &x, n);
7659               if (flag_unsafe_math_optimizations || !inexact)
7660                 return build_real (type, x);
7661             }
7662
7663           /* Strip sign ops from even integer powers.  */
7664           if ((n & 1) == 0 && flag_unsafe_math_optimizations)
7665             {
7666               tree narg0 = fold_strip_sign_ops (arg0);
7667               if (narg0)
7668                 return build_call_expr_loc (loc, fndecl, 2, narg0, arg1);
7669             }
7670         }
7671     }
7672
7673   if (flag_unsafe_math_optimizations)
7674     {
7675       const enum built_in_function fcode = builtin_mathfn_code (arg0);
7676
7677       /* Optimize pow(expN(x),y) = expN(x*y).  */
7678       if (BUILTIN_EXPONENT_P (fcode))
7679         {
7680           tree expfn = TREE_OPERAND (CALL_EXPR_FN (arg0), 0);
7681           tree arg = CALL_EXPR_ARG (arg0, 0);
7682           arg = fold_build2_loc (loc, MULT_EXPR, type, arg, arg1);
7683           return build_call_expr_loc (loc, expfn, 1, arg);
7684         }
7685
7686       /* Optimize pow(sqrt(x),y) = pow(x,y*0.5).  */
7687       if (BUILTIN_SQRT_P (fcode))
7688         {
7689           tree narg0 = CALL_EXPR_ARG (arg0, 0);
7690           tree narg1 = fold_build2_loc (loc, MULT_EXPR, type, arg1,
7691                                     build_real (type, dconsthalf));
7692           return build_call_expr_loc (loc, fndecl, 2, narg0, narg1);
7693         }
7694
7695       /* Optimize pow(cbrt(x),y) = pow(x,y/3) iff x is nonnegative.  */
7696       if (BUILTIN_CBRT_P (fcode))
7697         {
7698           tree arg = CALL_EXPR_ARG (arg0, 0);
7699           if (tree_expr_nonnegative_p (arg))
7700             {
7701               const REAL_VALUE_TYPE dconstroot
7702                 = real_value_truncate (TYPE_MODE (type), dconst_third ());
7703               tree narg1 = fold_build2_loc (loc, MULT_EXPR, type, arg1,
7704                                         build_real (type, dconstroot));
7705               return build_call_expr_loc (loc, fndecl, 2, arg, narg1);
7706             }
7707         }
7708
7709       /* Optimize pow(pow(x,y),z) = pow(x,y*z) iff x is nonnegative.  */
7710       if (fcode == BUILT_IN_POW
7711           || fcode == BUILT_IN_POWF
7712           || fcode == BUILT_IN_POWL)
7713         {
7714           tree arg00 = CALL_EXPR_ARG (arg0, 0);
7715           if (tree_expr_nonnegative_p (arg00))
7716             {
7717               tree arg01 = CALL_EXPR_ARG (arg0, 1);
7718               tree narg1 = fold_build2_loc (loc, MULT_EXPR, type, arg01, arg1);
7719               return build_call_expr_loc (loc, fndecl, 2, arg00, narg1);
7720             }
7721         }
7722     }
7723
7724   return NULL_TREE;
7725 }
7726
7727 /* Fold a builtin function call to powi, powif, or powil with argument ARG.
7728    Return NULL_TREE if no simplification can be made.  */
7729 static tree
7730 fold_builtin_powi (location_t loc, tree fndecl ATTRIBUTE_UNUSED,
7731                    tree arg0, tree arg1, tree type)
7732 {
7733   if (!validate_arg (arg0, REAL_TYPE)
7734       || !validate_arg (arg1, INTEGER_TYPE))
7735     return NULL_TREE;
7736
7737   /* Optimize pow(1.0,y) = 1.0.  */
7738   if (real_onep (arg0))
7739     return omit_one_operand_loc (loc, type, build_real (type, dconst1), arg1);
7740
7741   if (host_integerp (arg1, 0))
7742     {
7743       HOST_WIDE_INT c = TREE_INT_CST_LOW (arg1);
7744
7745       /* Evaluate powi at compile-time.  */
7746       if (TREE_CODE (arg0) == REAL_CST
7747           && !TREE_OVERFLOW (arg0))
7748         {
7749           REAL_VALUE_TYPE x;
7750           x = TREE_REAL_CST (arg0);
7751           real_powi (&x, TYPE_MODE (type), &x, c);
7752           return build_real (type, x);
7753         }
7754
7755       /* Optimize pow(x,0) = 1.0.  */
7756       if (c == 0)
7757         return omit_one_operand_loc (loc, type, build_real (type, dconst1),
7758                                  arg0);
7759
7760       /* Optimize pow(x,1) = x.  */
7761       if (c == 1)
7762         return arg0;
7763
7764       /* Optimize pow(x,-1) = 1.0/x.  */
7765       if (c == -1)
7766         return fold_build2_loc (loc, RDIV_EXPR, type,
7767                            build_real (type, dconst1), arg0);
7768     }
7769
7770   return NULL_TREE;
7771 }
7772
7773 /* A subroutine of fold_builtin to fold the various exponent
7774    functions.  Return NULL_TREE if no simplification can be made.
7775    FUNC is the corresponding MPFR exponent function.  */
7776
7777 static tree
7778 fold_builtin_exponent (location_t loc, tree fndecl, tree arg,
7779                        int (*func)(mpfr_ptr, mpfr_srcptr, mp_rnd_t))
7780 {
7781   if (validate_arg (arg, REAL_TYPE))
7782     {
7783       tree type = TREE_TYPE (TREE_TYPE (fndecl));
7784       tree res;
7785
7786       /* Calculate the result when the argument is a constant.  */
7787       if ((res = do_mpfr_arg1 (arg, type, func, NULL, NULL, 0)))
7788         return res;
7789
7790       /* Optimize expN(logN(x)) = x.  */
7791       if (flag_unsafe_math_optimizations)
7792         {
7793           const enum built_in_function fcode = builtin_mathfn_code (arg);
7794
7795           if ((func == mpfr_exp
7796                && (fcode == BUILT_IN_LOG
7797                    || fcode == BUILT_IN_LOGF
7798                    || fcode == BUILT_IN_LOGL))
7799               || (func == mpfr_exp2
7800                   && (fcode == BUILT_IN_LOG2
7801                       || fcode == BUILT_IN_LOG2F
7802                       || fcode == BUILT_IN_LOG2L))
7803               || (func == mpfr_exp10
7804                   && (fcode == BUILT_IN_LOG10
7805                       || fcode == BUILT_IN_LOG10F
7806                       || fcode == BUILT_IN_LOG10L)))
7807             return fold_convert_loc (loc, type, CALL_EXPR_ARG (arg, 0));
7808         }
7809     }
7810
7811   return NULL_TREE;
7812 }
7813
7814 /* Return true if VAR is a VAR_DECL or a component thereof.  */
7815
7816 static bool
7817 var_decl_component_p (tree var)
7818 {
7819   tree inner = var;
7820   while (handled_component_p (inner))
7821     inner = TREE_OPERAND (inner, 0);
7822   return SSA_VAR_P (inner);
7823 }
7824
7825 /* Fold function call to builtin memset.  Return
7826    NULL_TREE if no simplification can be made.  */
7827
7828 static tree
7829 fold_builtin_memset (location_t loc, tree dest, tree c, tree len,
7830                      tree type, bool ignore)
7831 {
7832   tree var, ret, etype;
7833   unsigned HOST_WIDE_INT length, cval;
7834
7835   if (! validate_arg (dest, POINTER_TYPE)
7836       || ! validate_arg (c, INTEGER_TYPE)
7837       || ! validate_arg (len, INTEGER_TYPE))
7838     return NULL_TREE;
7839
7840   if (! host_integerp (len, 1))
7841     return NULL_TREE;
7842
7843   /* If the LEN parameter is zero, return DEST.  */
7844   if (integer_zerop (len))
7845     return omit_one_operand_loc (loc, type, dest, c);
7846
7847   if (TREE_CODE (c) != INTEGER_CST || TREE_SIDE_EFFECTS (dest))
7848     return NULL_TREE;
7849
7850   var = dest;
7851   STRIP_NOPS (var);
7852   if (TREE_CODE (var) != ADDR_EXPR)
7853     return NULL_TREE;
7854
7855   var = TREE_OPERAND (var, 0);
7856   if (TREE_THIS_VOLATILE (var))
7857     return NULL_TREE;
7858
7859   etype = TREE_TYPE (var);
7860   if (TREE_CODE (etype) == ARRAY_TYPE)
7861     etype = TREE_TYPE (etype);
7862
7863   if (!INTEGRAL_TYPE_P (etype)
7864       && !POINTER_TYPE_P (etype))
7865     return NULL_TREE;
7866
7867   if (! var_decl_component_p (var))
7868     return NULL_TREE;
7869
7870   length = tree_low_cst (len, 1);
7871   if (GET_MODE_SIZE (TYPE_MODE (etype)) != length
7872       || get_pointer_alignment (dest, BIGGEST_ALIGNMENT) / BITS_PER_UNIT
7873          < length)
7874     return NULL_TREE;
7875
7876   if (length > HOST_BITS_PER_WIDE_INT / BITS_PER_UNIT)
7877     return NULL_TREE;
7878
7879   if (integer_zerop (c))
7880     cval = 0;
7881   else
7882     {
7883       if (CHAR_BIT != 8 || BITS_PER_UNIT != 8 || HOST_BITS_PER_WIDE_INT > 64)
7884         return NULL_TREE;
7885
7886       cval = TREE_INT_CST_LOW (c);
7887       cval &= 0xff;
7888       cval |= cval << 8;
7889       cval |= cval << 16;
7890       cval |= (cval << 31) << 1;
7891     }
7892
7893   ret = build_int_cst_type (etype, cval);
7894   var = build_fold_indirect_ref_loc (loc,
7895                                  fold_convert_loc (loc,
7896                                                    build_pointer_type (etype),
7897                                                    dest));
7898   ret = build2 (MODIFY_EXPR, etype, var, ret);
7899   if (ignore)
7900     return ret;
7901
7902   return omit_one_operand_loc (loc, type, dest, ret);
7903 }
7904
7905 /* Fold function call to builtin memset.  Return
7906    NULL_TREE if no simplification can be made.  */
7907
7908 static tree
7909 fold_builtin_bzero (location_t loc, tree dest, tree size, bool ignore)
7910 {
7911   if (! validate_arg (dest, POINTER_TYPE)
7912       || ! validate_arg (size, INTEGER_TYPE))
7913     return NULL_TREE;
7914
7915   if (!ignore)
7916     return NULL_TREE;
7917
7918   /* New argument list transforming bzero(ptr x, int y) to
7919      memset(ptr x, int 0, size_t y).   This is done this way
7920      so that if it isn't expanded inline, we fallback to
7921      calling bzero instead of memset.  */
7922
7923   return fold_builtin_memset (loc, dest, integer_zero_node,
7924                               fold_convert_loc (loc, sizetype, size),
7925                               void_type_node, ignore);
7926 }
7927
7928 /* Fold function call to builtin mem{{,p}cpy,move}.  Return
7929    NULL_TREE if no simplification can be made.
7930    If ENDP is 0, return DEST (like memcpy).
7931    If ENDP is 1, return DEST+LEN (like mempcpy).
7932    If ENDP is 2, return DEST+LEN-1 (like stpcpy).
7933    If ENDP is 3, return DEST, additionally *SRC and *DEST may overlap
7934    (memmove).   */
7935
7936 static tree
7937 fold_builtin_memory_op (location_t loc, tree dest, tree src,
7938                         tree len, tree type, bool ignore, int endp)
7939 {
7940   tree destvar, srcvar, expr;
7941
7942   if (! validate_arg (dest, POINTER_TYPE)
7943       || ! validate_arg (src, POINTER_TYPE)
7944       || ! validate_arg (len, INTEGER_TYPE))
7945     return NULL_TREE;
7946
7947   /* If the LEN parameter is zero, return DEST.  */
7948   if (integer_zerop (len))
7949     return omit_one_operand_loc (loc, type, dest, src);
7950
7951   /* If SRC and DEST are the same (and not volatile), return
7952      DEST{,+LEN,+LEN-1}.  */
7953   if (operand_equal_p (src, dest, 0))
7954     expr = len;
7955   else
7956     {
7957       tree srctype, desttype;
7958       unsigned int src_align, dest_align;
7959       tree off0;
7960
7961       if (endp == 3)
7962         {
7963           src_align = get_pointer_alignment (src, BIGGEST_ALIGNMENT);
7964           dest_align = get_pointer_alignment (dest, BIGGEST_ALIGNMENT);
7965
7966           /* Both DEST and SRC must be pointer types.
7967              ??? This is what old code did.  Is the testing for pointer types
7968              really mandatory?
7969
7970              If either SRC is readonly or length is 1, we can use memcpy.  */
7971           if (!dest_align || !src_align)
7972             return NULL_TREE;
7973           if (readonly_data_expr (src)
7974               || (host_integerp (len, 1)
7975                   && (MIN (src_align, dest_align) / BITS_PER_UNIT
7976                       >= (unsigned HOST_WIDE_INT) tree_low_cst (len, 1))))
7977             {
7978               tree fn = implicit_built_in_decls[BUILT_IN_MEMCPY];
7979               if (!fn)
7980                 return NULL_TREE;
7981               return build_call_expr_loc (loc, fn, 3, dest, src, len);
7982             }
7983
7984           /* If *src and *dest can't overlap, optimize into memcpy as well.  */
7985           if (TREE_CODE (src) == ADDR_EXPR
7986               && TREE_CODE (dest) == ADDR_EXPR)
7987             {
7988               tree src_base, dest_base, fn;
7989               HOST_WIDE_INT src_offset = 0, dest_offset = 0;
7990               HOST_WIDE_INT size = -1;
7991               HOST_WIDE_INT maxsize = -1;
7992
7993               srcvar = TREE_OPERAND (src, 0);
7994               src_base = get_ref_base_and_extent (srcvar, &src_offset,
7995                                                   &size, &maxsize);
7996               destvar = TREE_OPERAND (dest, 0);
7997               dest_base = get_ref_base_and_extent (destvar, &dest_offset,
7998                                                    &size, &maxsize);
7999               if (host_integerp (len, 1))
8000                 maxsize = tree_low_cst (len, 1);
8001               else
8002                 maxsize = -1;
8003               src_offset /= BITS_PER_UNIT;
8004               dest_offset /= BITS_PER_UNIT;
8005               if (SSA_VAR_P (src_base)
8006                   && SSA_VAR_P (dest_base))
8007                 {
8008                   if (operand_equal_p (src_base, dest_base, 0)
8009                       && ranges_overlap_p (src_offset, maxsize,
8010                                            dest_offset, maxsize))
8011                     return NULL_TREE;
8012                 }
8013               else if (TREE_CODE (src_base) == MEM_REF
8014                        && TREE_CODE (dest_base) == MEM_REF)
8015                 {
8016                   double_int off;
8017                   if (! operand_equal_p (TREE_OPERAND (src_base, 0),
8018                                          TREE_OPERAND (dest_base, 0), 0))
8019                     return NULL_TREE;
8020                   off = double_int_add (mem_ref_offset (src_base),
8021                                         shwi_to_double_int (src_offset));
8022                   if (!double_int_fits_in_shwi_p (off))
8023                     return NULL_TREE;
8024                   src_offset = off.low;
8025                   off = double_int_add (mem_ref_offset (dest_base),
8026                                         shwi_to_double_int (dest_offset));
8027                   if (!double_int_fits_in_shwi_p (off))
8028                     return NULL_TREE;
8029                   dest_offset = off.low;
8030                   if (ranges_overlap_p (src_offset, maxsize,
8031                                         dest_offset, maxsize))
8032                     return NULL_TREE;
8033                 }
8034               else
8035                 return NULL_TREE;
8036
8037               fn = implicit_built_in_decls[BUILT_IN_MEMCPY];
8038               if (!fn)
8039                 return NULL_TREE;
8040               return build_call_expr_loc (loc, fn, 3, dest, src, len);
8041             }
8042
8043           /* If the destination and source do not alias optimize into
8044              memcpy as well.  */
8045           if ((is_gimple_min_invariant (dest)
8046                || TREE_CODE (dest) == SSA_NAME)
8047               && (is_gimple_min_invariant (src)
8048                   || TREE_CODE (src) == SSA_NAME))
8049             {
8050               ao_ref destr, srcr;
8051               ao_ref_init_from_ptr_and_size (&destr, dest, len);
8052               ao_ref_init_from_ptr_and_size (&srcr, src, len);
8053               if (!refs_may_alias_p_1 (&destr, &srcr, false))
8054                 {
8055                   tree fn;
8056                   fn = implicit_built_in_decls[BUILT_IN_MEMCPY];
8057                   if (!fn)
8058                     return NULL_TREE;
8059                   return build_call_expr_loc (loc, fn, 3, dest, src, len);
8060                 }
8061             }
8062
8063           return NULL_TREE;
8064         }
8065
8066       if (!host_integerp (len, 0))
8067         return NULL_TREE;
8068       /* FIXME:
8069          This logic lose for arguments like (type *)malloc (sizeof (type)),
8070          since we strip the casts of up to VOID return value from malloc.
8071          Perhaps we ought to inherit type from non-VOID argument here?  */
8072       STRIP_NOPS (src);
8073       STRIP_NOPS (dest);
8074       if (!POINTER_TYPE_P (TREE_TYPE (src))
8075           || !POINTER_TYPE_P (TREE_TYPE (dest)))
8076         return NULL_TREE;
8077       /* As we fold (void *)(p + CST) to (void *)p + CST undo this here.  */
8078       if (TREE_CODE (src) == POINTER_PLUS_EXPR)
8079         {
8080           tree tem = TREE_OPERAND (src, 0);
8081           STRIP_NOPS (tem);
8082           if (tem != TREE_OPERAND (src, 0))
8083             src = build1 (NOP_EXPR, TREE_TYPE (tem), src);
8084         }
8085       if (TREE_CODE (dest) == POINTER_PLUS_EXPR)
8086         {
8087           tree tem = TREE_OPERAND (dest, 0);
8088           STRIP_NOPS (tem);
8089           if (tem != TREE_OPERAND (dest, 0))
8090             dest = build1 (NOP_EXPR, TREE_TYPE (tem), dest);
8091         }
8092       srctype = TREE_TYPE (TREE_TYPE (src));
8093       if (TREE_CODE (srctype) == ARRAY_TYPE
8094           && !tree_int_cst_equal (TYPE_SIZE_UNIT (srctype), len))
8095         {
8096           srctype = TREE_TYPE (srctype);
8097           STRIP_NOPS (src);
8098           src = build1 (NOP_EXPR, build_pointer_type (srctype), src);
8099         }
8100       desttype = TREE_TYPE (TREE_TYPE (dest));
8101       if (TREE_CODE (desttype) == ARRAY_TYPE
8102           && !tree_int_cst_equal (TYPE_SIZE_UNIT (desttype), len))
8103         {
8104           desttype = TREE_TYPE (desttype);
8105           STRIP_NOPS (dest);
8106           dest = build1 (NOP_EXPR, build_pointer_type (desttype), dest);
8107         }
8108       if (TREE_ADDRESSABLE (srctype)
8109           || TREE_ADDRESSABLE (desttype))
8110         return NULL_TREE;
8111
8112       src_align = get_pointer_alignment (src, BIGGEST_ALIGNMENT);
8113       dest_align = get_pointer_alignment (dest, BIGGEST_ALIGNMENT);
8114       if (dest_align < TYPE_ALIGN (desttype)
8115           || src_align < TYPE_ALIGN (srctype))
8116         return NULL_TREE;
8117
8118       if (!ignore)
8119         dest = builtin_save_expr (dest);
8120
8121       /* Build accesses at offset zero with a ref-all character type.  */
8122       off0 = build_int_cst (build_pointer_type_for_mode (char_type_node,
8123                                                          ptr_mode, true), 0);
8124
8125       destvar = dest;
8126       STRIP_NOPS (destvar);
8127       if (TREE_CODE (destvar) == ADDR_EXPR
8128           && var_decl_component_p (TREE_OPERAND (destvar, 0))
8129           && tree_int_cst_equal (TYPE_SIZE_UNIT (desttype), len))
8130         destvar = fold_build2 (MEM_REF, desttype, destvar, off0);
8131       else
8132         destvar = NULL_TREE;
8133
8134       srcvar = src;
8135       STRIP_NOPS (srcvar);
8136       if (TREE_CODE (srcvar) == ADDR_EXPR
8137           && var_decl_component_p (TREE_OPERAND (srcvar, 0))
8138           && tree_int_cst_equal (TYPE_SIZE_UNIT (srctype), len))
8139         {
8140           if (!destvar
8141               || src_align >= TYPE_ALIGN (desttype))
8142             srcvar = fold_build2 (MEM_REF, destvar ? desttype : srctype,
8143                                   srcvar, off0);
8144           else if (!STRICT_ALIGNMENT)
8145             {
8146               srctype = build_aligned_type (TYPE_MAIN_VARIANT (desttype),
8147                                             src_align);
8148               srcvar = fold_build2 (MEM_REF, srctype, srcvar, off0);
8149             }
8150           else
8151             srcvar = NULL_TREE;
8152         }
8153       else
8154         srcvar = NULL_TREE;
8155
8156       if (srcvar == NULL_TREE && destvar == NULL_TREE)
8157         return NULL_TREE;
8158
8159       if (srcvar == NULL_TREE)
8160         {
8161           STRIP_NOPS (src);
8162           if (src_align >= TYPE_ALIGN (desttype))
8163             srcvar = fold_build2 (MEM_REF, desttype, src, off0);
8164           else
8165             {
8166               if (STRICT_ALIGNMENT)
8167                 return NULL_TREE;
8168               srctype = build_aligned_type (TYPE_MAIN_VARIANT (desttype),
8169                                             src_align);
8170               srcvar = fold_build2 (MEM_REF, srctype, src, off0);
8171             }
8172         }
8173       else if (destvar == NULL_TREE)
8174         {
8175           STRIP_NOPS (dest);
8176           if (dest_align >= TYPE_ALIGN (srctype))
8177             destvar = fold_build2 (MEM_REF, srctype, dest, off0);
8178           else
8179             {
8180               if (STRICT_ALIGNMENT)
8181                 return NULL_TREE;
8182               desttype = build_aligned_type (TYPE_MAIN_VARIANT (srctype),
8183                                              dest_align);
8184               destvar = fold_build2 (MEM_REF, desttype, dest, off0);
8185             }
8186         }
8187
8188       expr = build2 (MODIFY_EXPR, TREE_TYPE (destvar), destvar, srcvar);
8189     }
8190
8191   if (ignore)
8192     return expr;
8193
8194   if (endp == 0 || endp == 3)
8195     return omit_one_operand_loc (loc, type, dest, expr);
8196
8197   if (expr == len)
8198     expr = NULL_TREE;
8199
8200   if (endp == 2)
8201     len = fold_build2_loc (loc, MINUS_EXPR, TREE_TYPE (len), len,
8202                        ssize_int (1));
8203
8204   len = fold_convert_loc (loc, sizetype, len);
8205   dest = fold_build2_loc (loc, POINTER_PLUS_EXPR, TREE_TYPE (dest), dest, len);
8206   dest = fold_convert_loc (loc, type, dest);
8207   if (expr)
8208     dest = omit_one_operand_loc (loc, type, dest, expr);
8209   return dest;
8210 }
8211
8212 /* Fold function call to builtin strcpy with arguments DEST and SRC.
8213    If LEN is not NULL, it represents the length of the string to be
8214    copied.  Return NULL_TREE if no simplification can be made.  */
8215
8216 tree
8217 fold_builtin_strcpy (location_t loc, tree fndecl, tree dest, tree src, tree len)
8218 {
8219   tree fn;
8220
8221   if (!validate_arg (dest, POINTER_TYPE)
8222       || !validate_arg (src, POINTER_TYPE))
8223     return NULL_TREE;
8224
8225   /* If SRC and DEST are the same (and not volatile), return DEST.  */
8226   if (operand_equal_p (src, dest, 0))
8227     return fold_convert_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)), dest);
8228
8229   if (optimize_function_for_size_p (cfun))
8230     return NULL_TREE;
8231
8232   fn = implicit_built_in_decls[BUILT_IN_MEMCPY];
8233   if (!fn)
8234     return NULL_TREE;
8235
8236   if (!len)
8237     {
8238       len = c_strlen (src, 1);
8239       if (! len || TREE_SIDE_EFFECTS (len))
8240         return NULL_TREE;
8241     }
8242
8243   len = size_binop_loc (loc, PLUS_EXPR, len, ssize_int (1));
8244   return fold_convert_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)),
8245                            build_call_expr_loc (loc, fn, 3, dest, src, len));
8246 }
8247
8248 /* Fold function call to builtin stpcpy with arguments DEST and SRC.
8249    Return NULL_TREE if no simplification can be made.  */
8250
8251 static tree
8252 fold_builtin_stpcpy (location_t loc, tree fndecl, tree dest, tree src)
8253 {
8254   tree fn, len, lenp1, call, type;
8255
8256   if (!validate_arg (dest, POINTER_TYPE)
8257       || !validate_arg (src, POINTER_TYPE))
8258     return NULL_TREE;
8259
8260   len = c_strlen (src, 1);
8261   if (!len
8262       || TREE_CODE (len) != INTEGER_CST)
8263     return NULL_TREE;
8264
8265   if (optimize_function_for_size_p (cfun)
8266       /* If length is zero it's small enough.  */
8267       && !integer_zerop (len))
8268     return NULL_TREE;
8269
8270   fn = implicit_built_in_decls[BUILT_IN_MEMCPY];
8271   if (!fn)
8272     return NULL_TREE;
8273
8274   lenp1 = size_binop_loc (loc, PLUS_EXPR, len, ssize_int (1));
8275   /* We use dest twice in building our expression.  Save it from
8276      multiple expansions.  */
8277   dest = builtin_save_expr (dest);
8278   call = build_call_expr_loc (loc, fn, 3, dest, src, lenp1);
8279
8280   type = TREE_TYPE (TREE_TYPE (fndecl));
8281   len = fold_convert_loc (loc, sizetype, len);
8282   dest = fold_build2_loc (loc, POINTER_PLUS_EXPR, TREE_TYPE (dest), dest, len);
8283   dest = fold_convert_loc (loc, type, dest);
8284   dest = omit_one_operand_loc (loc, type, dest, call);
8285   return dest;
8286 }
8287
8288 /* Fold function call to builtin strncpy with arguments DEST, SRC, and LEN.
8289    If SLEN is not NULL, it represents the length of the source string.
8290    Return NULL_TREE if no simplification can be made.  */
8291
8292 tree
8293 fold_builtin_strncpy (location_t loc, tree fndecl, tree dest,
8294                       tree src, tree len, tree slen)
8295 {
8296   tree fn;
8297
8298   if (!validate_arg (dest, POINTER_TYPE)
8299       || !validate_arg (src, POINTER_TYPE)
8300       || !validate_arg (len, INTEGER_TYPE))
8301     return NULL_TREE;
8302
8303   /* If the LEN parameter is zero, return DEST.  */
8304   if (integer_zerop (len))
8305     return omit_one_operand_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)), dest, src);
8306
8307   /* We can't compare slen with len as constants below if len is not a
8308      constant.  */
8309   if (len == 0 || TREE_CODE (len) != INTEGER_CST)
8310     return NULL_TREE;
8311
8312   if (!slen)
8313     slen = c_strlen (src, 1);
8314
8315   /* Now, we must be passed a constant src ptr parameter.  */
8316   if (slen == 0 || TREE_CODE (slen) != INTEGER_CST)
8317     return NULL_TREE;
8318
8319   slen = size_binop_loc (loc, PLUS_EXPR, slen, ssize_int (1));
8320
8321   /* We do not support simplification of this case, though we do
8322      support it when expanding trees into RTL.  */
8323   /* FIXME: generate a call to __builtin_memset.  */
8324   if (tree_int_cst_lt (slen, len))
8325     return NULL_TREE;
8326
8327   /* OK transform into builtin memcpy.  */
8328   fn = implicit_built_in_decls[BUILT_IN_MEMCPY];
8329   if (!fn)
8330     return NULL_TREE;
8331   return fold_convert_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)),
8332                            build_call_expr_loc (loc, fn, 3, dest, src, len));
8333 }
8334
8335 /* Fold function call to builtin memchr.  ARG1, ARG2 and LEN are the
8336    arguments to the call, and TYPE is its return type.
8337    Return NULL_TREE if no simplification can be made.  */
8338
8339 static tree
8340 fold_builtin_memchr (location_t loc, tree arg1, tree arg2, tree len, tree type)
8341 {
8342   if (!validate_arg (arg1, POINTER_TYPE)
8343       || !validate_arg (arg2, INTEGER_TYPE)
8344       || !validate_arg (len, INTEGER_TYPE))
8345     return NULL_TREE;
8346   else
8347     {
8348       const char *p1;
8349
8350       if (TREE_CODE (arg2) != INTEGER_CST
8351           || !host_integerp (len, 1))
8352         return NULL_TREE;
8353
8354       p1 = c_getstr (arg1);
8355       if (p1 && compare_tree_int (len, strlen (p1) + 1) <= 0)
8356         {
8357           char c;
8358           const char *r;
8359           tree tem;
8360
8361           if (target_char_cast (arg2, &c))
8362             return NULL_TREE;
8363
8364           r = (char *) memchr (p1, c, tree_low_cst (len, 1));
8365
8366           if (r == NULL)
8367             return build_int_cst (TREE_TYPE (arg1), 0);
8368
8369           tem = fold_build2_loc (loc, POINTER_PLUS_EXPR, TREE_TYPE (arg1), arg1,
8370                              size_int (r - p1));
8371           return fold_convert_loc (loc, type, tem);
8372         }
8373       return NULL_TREE;
8374     }
8375 }
8376
8377 /* Fold function call to builtin memcmp with arguments ARG1 and ARG2.
8378    Return NULL_TREE if no simplification can be made.  */
8379
8380 static tree
8381 fold_builtin_memcmp (location_t loc, tree arg1, tree arg2, tree len)
8382 {
8383   const char *p1, *p2;
8384
8385   if (!validate_arg (arg1, POINTER_TYPE)
8386       || !validate_arg (arg2, POINTER_TYPE)
8387       || !validate_arg (len, INTEGER_TYPE))
8388     return NULL_TREE;
8389
8390   /* If the LEN parameter is zero, return zero.  */
8391   if (integer_zerop (len))
8392     return omit_two_operands_loc (loc, integer_type_node, integer_zero_node,
8393                               arg1, arg2);
8394
8395   /* If ARG1 and ARG2 are the same (and not volatile), return zero.  */
8396   if (operand_equal_p (arg1, arg2, 0))
8397     return omit_one_operand_loc (loc, integer_type_node, integer_zero_node, len);
8398
8399   p1 = c_getstr (arg1);
8400   p2 = c_getstr (arg2);
8401
8402   /* If all arguments are constant, and the value of len is not greater
8403      than the lengths of arg1 and arg2, evaluate at compile-time.  */
8404   if (host_integerp (len, 1) && p1 && p2
8405       && compare_tree_int (len, strlen (p1) + 1) <= 0
8406       && compare_tree_int (len, strlen (p2) + 1) <= 0)
8407     {
8408       const int r = memcmp (p1, p2, tree_low_cst (len, 1));
8409
8410       if (r > 0)
8411         return integer_one_node;
8412       else if (r < 0)
8413         return integer_minus_one_node;
8414       else
8415         return integer_zero_node;
8416     }
8417
8418   /* If len parameter is one, return an expression corresponding to
8419      (*(const unsigned char*)arg1 - (const unsigned char*)arg2).  */
8420   if (host_integerp (len, 1) && tree_low_cst (len, 1) == 1)
8421     {
8422       tree cst_uchar_node = build_type_variant (unsigned_char_type_node, 1, 0);
8423       tree cst_uchar_ptr_node
8424         = build_pointer_type_for_mode (cst_uchar_node, ptr_mode, true);
8425
8426       tree ind1
8427         = fold_convert_loc (loc, integer_type_node,
8428                             build1 (INDIRECT_REF, cst_uchar_node,
8429                                     fold_convert_loc (loc,
8430                                                       cst_uchar_ptr_node,
8431                                                       arg1)));
8432       tree ind2
8433         = fold_convert_loc (loc, integer_type_node,
8434                             build1 (INDIRECT_REF, cst_uchar_node,
8435                                     fold_convert_loc (loc,
8436                                                       cst_uchar_ptr_node,
8437                                                       arg2)));
8438       return fold_build2_loc (loc, MINUS_EXPR, integer_type_node, ind1, ind2);
8439     }
8440
8441   return NULL_TREE;
8442 }
8443
8444 /* Fold function call to builtin strcmp with arguments ARG1 and ARG2.
8445    Return NULL_TREE if no simplification can be made.  */
8446
8447 static tree
8448 fold_builtin_strcmp (location_t loc, tree arg1, tree arg2)
8449 {
8450   const char *p1, *p2;
8451
8452   if (!validate_arg (arg1, POINTER_TYPE)
8453       || !validate_arg (arg2, POINTER_TYPE))
8454     return NULL_TREE;
8455
8456   /* If ARG1 and ARG2 are the same (and not volatile), return zero.  */
8457   if (operand_equal_p (arg1, arg2, 0))
8458     return integer_zero_node;
8459
8460   p1 = c_getstr (arg1);
8461   p2 = c_getstr (arg2);
8462
8463   if (p1 && p2)
8464     {
8465       const int i = strcmp (p1, p2);
8466       if (i < 0)
8467         return integer_minus_one_node;
8468       else if (i > 0)
8469         return integer_one_node;
8470       else
8471         return integer_zero_node;
8472     }
8473
8474   /* If the second arg is "", return *(const unsigned char*)arg1.  */
8475   if (p2 && *p2 == '\0')
8476     {
8477       tree cst_uchar_node = build_type_variant (unsigned_char_type_node, 1, 0);
8478       tree cst_uchar_ptr_node
8479         = build_pointer_type_for_mode (cst_uchar_node, ptr_mode, true);
8480
8481       return fold_convert_loc (loc, integer_type_node,
8482                                build1 (INDIRECT_REF, cst_uchar_node,
8483                                        fold_convert_loc (loc,
8484                                                          cst_uchar_ptr_node,
8485                                                          arg1)));
8486     }
8487
8488   /* If the first arg is "", return -*(const unsigned char*)arg2.  */
8489   if (p1 && *p1 == '\0')
8490     {
8491       tree cst_uchar_node = build_type_variant (unsigned_char_type_node, 1, 0);
8492       tree cst_uchar_ptr_node
8493         = build_pointer_type_for_mode (cst_uchar_node, ptr_mode, true);
8494
8495       tree temp
8496         = fold_convert_loc (loc, integer_type_node,
8497                             build1 (INDIRECT_REF, cst_uchar_node,
8498                                     fold_convert_loc (loc,
8499                                                       cst_uchar_ptr_node,
8500                                                       arg2)));
8501       return fold_build1_loc (loc, NEGATE_EXPR, integer_type_node, temp);
8502     }
8503
8504   return NULL_TREE;
8505 }
8506
8507 /* Fold function call to builtin strncmp with arguments ARG1, ARG2, and LEN.
8508    Return NULL_TREE if no simplification can be made.  */
8509
8510 static tree
8511 fold_builtin_strncmp (location_t loc, tree arg1, tree arg2, tree len)
8512 {
8513   const char *p1, *p2;
8514
8515   if (!validate_arg (arg1, POINTER_TYPE)
8516       || !validate_arg (arg2, POINTER_TYPE)
8517       || !validate_arg (len, INTEGER_TYPE))
8518     return NULL_TREE;
8519
8520   /* If the LEN parameter is zero, return zero.  */
8521   if (integer_zerop (len))
8522     return omit_two_operands_loc (loc, integer_type_node, integer_zero_node,
8523                               arg1, arg2);
8524
8525   /* If ARG1 and ARG2 are the same (and not volatile), return zero.  */
8526   if (operand_equal_p (arg1, arg2, 0))
8527     return omit_one_operand_loc (loc, integer_type_node, integer_zero_node, len);
8528
8529   p1 = c_getstr (arg1);
8530   p2 = c_getstr (arg2);
8531
8532   if (host_integerp (len, 1) && p1 && p2)
8533     {
8534       const int i = strncmp (p1, p2, tree_low_cst (len, 1));
8535       if (i > 0)
8536         return integer_one_node;
8537       else if (i < 0)
8538         return integer_minus_one_node;
8539       else
8540         return integer_zero_node;
8541     }
8542
8543   /* If the second arg is "", and the length is greater than zero,
8544      return *(const unsigned char*)arg1.  */
8545   if (p2 && *p2 == '\0'
8546       && TREE_CODE (len) == INTEGER_CST
8547       && tree_int_cst_sgn (len) == 1)
8548     {
8549       tree cst_uchar_node = build_type_variant (unsigned_char_type_node, 1, 0);
8550       tree cst_uchar_ptr_node
8551         = build_pointer_type_for_mode (cst_uchar_node, ptr_mode, true);
8552
8553       return fold_convert_loc (loc, integer_type_node,
8554                                build1 (INDIRECT_REF, cst_uchar_node,
8555                                        fold_convert_loc (loc,
8556                                                          cst_uchar_ptr_node,
8557                                                          arg1)));
8558     }
8559
8560   /* If the first arg is "", and the length is greater than zero,
8561      return -*(const unsigned char*)arg2.  */
8562   if (p1 && *p1 == '\0'
8563       && TREE_CODE (len) == INTEGER_CST
8564       && tree_int_cst_sgn (len) == 1)
8565     {
8566       tree cst_uchar_node = build_type_variant (unsigned_char_type_node, 1, 0);
8567       tree cst_uchar_ptr_node
8568         = build_pointer_type_for_mode (cst_uchar_node, ptr_mode, true);
8569
8570       tree temp = fold_convert_loc (loc, integer_type_node,
8571                                     build1 (INDIRECT_REF, cst_uchar_node,
8572                                             fold_convert_loc (loc,
8573                                                               cst_uchar_ptr_node,
8574                                                               arg2)));
8575       return fold_build1_loc (loc, NEGATE_EXPR, integer_type_node, temp);
8576     }
8577
8578   /* If len parameter is one, return an expression corresponding to
8579      (*(const unsigned char*)arg1 - (const unsigned char*)arg2).  */
8580   if (host_integerp (len, 1) && tree_low_cst (len, 1) == 1)
8581     {
8582       tree cst_uchar_node = build_type_variant (unsigned_char_type_node, 1, 0);
8583       tree cst_uchar_ptr_node
8584         = build_pointer_type_for_mode (cst_uchar_node, ptr_mode, true);
8585
8586       tree ind1 = fold_convert_loc (loc, integer_type_node,
8587                                     build1 (INDIRECT_REF, cst_uchar_node,
8588                                             fold_convert_loc (loc,
8589                                                               cst_uchar_ptr_node,
8590                                                               arg1)));
8591       tree ind2 = fold_convert_loc (loc, integer_type_node,
8592                                     build1 (INDIRECT_REF, cst_uchar_node,
8593                                             fold_convert_loc (loc,
8594                                                               cst_uchar_ptr_node,
8595                                                               arg2)));
8596       return fold_build2_loc (loc, MINUS_EXPR, integer_type_node, ind1, ind2);
8597     }
8598
8599   return NULL_TREE;
8600 }
8601
8602 /* Fold function call to builtin signbit, signbitf or signbitl with argument
8603    ARG.  Return NULL_TREE if no simplification can be made.  */
8604
8605 static tree
8606 fold_builtin_signbit (location_t loc, tree arg, tree type)
8607 {
8608   if (!validate_arg (arg, REAL_TYPE))
8609     return NULL_TREE;
8610
8611   /* If ARG is a compile-time constant, determine the result.  */
8612   if (TREE_CODE (arg) == REAL_CST
8613       && !TREE_OVERFLOW (arg))
8614     {
8615       REAL_VALUE_TYPE c;
8616
8617       c = TREE_REAL_CST (arg);
8618       return (REAL_VALUE_NEGATIVE (c)
8619               ? build_one_cst (type)
8620               : build_zero_cst (type));
8621     }
8622
8623   /* If ARG is non-negative, the result is always zero.  */
8624   if (tree_expr_nonnegative_p (arg))
8625     return omit_one_operand_loc (loc, type, integer_zero_node, arg);
8626
8627   /* If ARG's format doesn't have signed zeros, return "arg < 0.0".  */
8628   if (!HONOR_SIGNED_ZEROS (TYPE_MODE (TREE_TYPE (arg))))
8629     return fold_build2_loc (loc, LT_EXPR, type, arg,
8630                         build_real (TREE_TYPE (arg), dconst0));
8631
8632   return NULL_TREE;
8633 }
8634
8635 /* Fold function call to builtin copysign, copysignf or copysignl with
8636    arguments ARG1 and ARG2.  Return NULL_TREE if no simplification can
8637    be made.  */
8638
8639 static tree
8640 fold_builtin_copysign (location_t loc, tree fndecl,
8641                        tree arg1, tree arg2, tree type)
8642 {
8643   tree tem;
8644
8645   if (!validate_arg (arg1, REAL_TYPE)
8646       || !validate_arg (arg2, REAL_TYPE))
8647     return NULL_TREE;
8648
8649   /* copysign(X,X) is X.  */
8650   if (operand_equal_p (arg1, arg2, 0))
8651     return fold_convert_loc (loc, type, arg1);
8652
8653   /* If ARG1 and ARG2 are compile-time constants, determine the result.  */
8654   if (TREE_CODE (arg1) == REAL_CST
8655       && TREE_CODE (arg2) == REAL_CST
8656       && !TREE_OVERFLOW (arg1)
8657       && !TREE_OVERFLOW (arg2))
8658     {
8659       REAL_VALUE_TYPE c1, c2;
8660
8661       c1 = TREE_REAL_CST (arg1);
8662       c2 = TREE_REAL_CST (arg2);
8663       /* c1.sign := c2.sign.  */
8664       real_copysign (&c1, &c2);
8665       return build_real (type, c1);
8666     }
8667
8668   /* copysign(X, Y) is fabs(X) when Y is always non-negative.
8669      Remember to evaluate Y for side-effects.  */
8670   if (tree_expr_nonnegative_p (arg2))
8671     return omit_one_operand_loc (loc, type,
8672                              fold_build1_loc (loc, ABS_EXPR, type, arg1),
8673                              arg2);
8674
8675   /* Strip sign changing operations for the first argument.  */
8676   tem = fold_strip_sign_ops (arg1);
8677   if (tem)
8678     return build_call_expr_loc (loc, fndecl, 2, tem, arg2);
8679
8680   return NULL_TREE;
8681 }
8682
8683 /* Fold a call to builtin isascii with argument ARG.  */
8684
8685 static tree
8686 fold_builtin_isascii (location_t loc, tree arg)
8687 {
8688   if (!validate_arg (arg, INTEGER_TYPE))
8689     return NULL_TREE;
8690   else
8691     {
8692       /* Transform isascii(c) -> ((c & ~0x7f) == 0).  */
8693       arg = fold_build2 (BIT_AND_EXPR, integer_type_node, arg,
8694                          build_int_cst (integer_type_node,
8695                                         ~ (unsigned HOST_WIDE_INT) 0x7f));
8696       return fold_build2_loc (loc, EQ_EXPR, integer_type_node,
8697                               arg, integer_zero_node);
8698     }
8699 }
8700
8701 /* Fold a call to builtin toascii with argument ARG.  */
8702
8703 static tree
8704 fold_builtin_toascii (location_t loc, tree arg)
8705 {
8706   if (!validate_arg (arg, INTEGER_TYPE))
8707     return NULL_TREE;
8708
8709   /* Transform toascii(c) -> (c & 0x7f).  */
8710   return fold_build2_loc (loc, BIT_AND_EXPR, integer_type_node, arg,
8711                           build_int_cst (integer_type_node, 0x7f));
8712 }
8713
8714 /* Fold a call to builtin isdigit with argument ARG.  */
8715
8716 static tree
8717 fold_builtin_isdigit (location_t loc, tree arg)
8718 {
8719   if (!validate_arg (arg, INTEGER_TYPE))
8720     return NULL_TREE;
8721   else
8722     {
8723       /* Transform isdigit(c) -> (unsigned)(c) - '0' <= 9.  */
8724       /* According to the C standard, isdigit is unaffected by locale.
8725          However, it definitely is affected by the target character set.  */
8726       unsigned HOST_WIDE_INT target_digit0
8727         = lang_hooks.to_target_charset ('0');
8728
8729       if (target_digit0 == 0)
8730         return NULL_TREE;
8731
8732       arg = fold_convert_loc (loc, unsigned_type_node, arg);
8733       arg = fold_build2 (MINUS_EXPR, unsigned_type_node, arg,
8734                          build_int_cst (unsigned_type_node, target_digit0));
8735       return fold_build2_loc (loc, LE_EXPR, integer_type_node, arg,
8736                           build_int_cst (unsigned_type_node, 9));
8737     }
8738 }
8739
8740 /* Fold a call to fabs, fabsf or fabsl with argument ARG.  */
8741
8742 static tree
8743 fold_builtin_fabs (location_t loc, tree arg, tree type)
8744 {
8745   if (!validate_arg (arg, REAL_TYPE))
8746     return NULL_TREE;
8747
8748   arg = fold_convert_loc (loc, type, arg);
8749   if (TREE_CODE (arg) == REAL_CST)
8750     return fold_abs_const (arg, type);
8751   return fold_build1_loc (loc, ABS_EXPR, type, arg);
8752 }
8753
8754 /* Fold a call to abs, labs, llabs or imaxabs with argument ARG.  */
8755
8756 static tree
8757 fold_builtin_abs (location_t loc, tree arg, tree type)
8758 {
8759   if (!validate_arg (arg, INTEGER_TYPE))
8760     return NULL_TREE;
8761
8762   arg = fold_convert_loc (loc, type, arg);
8763   if (TREE_CODE (arg) == INTEGER_CST)
8764     return fold_abs_const (arg, type);
8765   return fold_build1_loc (loc, ABS_EXPR, type, arg);
8766 }
8767
8768 /* Fold a fma operation with arguments ARG[012].  */
8769
8770 tree
8771 fold_fma (location_t loc ATTRIBUTE_UNUSED,
8772           tree type, tree arg0, tree arg1, tree arg2)
8773 {
8774   if (TREE_CODE (arg0) == REAL_CST
8775       && TREE_CODE (arg1) == REAL_CST
8776       && TREE_CODE (arg2) == REAL_CST)
8777     return do_mpfr_arg3 (arg0, arg1, arg2, type, mpfr_fma);
8778
8779   return NULL_TREE;
8780 }
8781
8782 /* Fold a call to fma, fmaf, or fmal with arguments ARG[012].  */
8783
8784 static tree
8785 fold_builtin_fma (location_t loc, tree arg0, tree arg1, tree arg2, tree type)
8786 {
8787   if (validate_arg (arg0, REAL_TYPE)
8788       && validate_arg(arg1, REAL_TYPE)
8789       && validate_arg(arg2, REAL_TYPE))
8790     {
8791       tree tem = fold_fma (loc, type, arg0, arg1, arg2);
8792       if (tem)
8793         return tem;
8794
8795       /* ??? Only expand to FMA_EXPR if it's directly supported.  */
8796       if (optab_handler (fma_optab, TYPE_MODE (type)) != CODE_FOR_nothing)
8797         return fold_build3_loc (loc, FMA_EXPR, type, arg0, arg1, arg2);
8798     }
8799   return NULL_TREE;
8800 }
8801
8802 /* Fold a call to builtin fmin or fmax.  */
8803
8804 static tree
8805 fold_builtin_fmin_fmax (location_t loc, tree arg0, tree arg1,
8806                         tree type, bool max)
8807 {
8808   if (validate_arg (arg0, REAL_TYPE) && validate_arg (arg1, REAL_TYPE))
8809     {
8810       /* Calculate the result when the argument is a constant.  */
8811       tree res = do_mpfr_arg2 (arg0, arg1, type, (max ? mpfr_max : mpfr_min));
8812
8813       if (res)
8814         return res;
8815
8816       /* If either argument is NaN, return the other one.  Avoid the
8817          transformation if we get (and honor) a signalling NaN.  Using
8818          omit_one_operand() ensures we create a non-lvalue.  */
8819       if (TREE_CODE (arg0) == REAL_CST
8820           && real_isnan (&TREE_REAL_CST (arg0))
8821           && (! HONOR_SNANS (TYPE_MODE (TREE_TYPE (arg0)))
8822               || ! TREE_REAL_CST (arg0).signalling))
8823         return omit_one_operand_loc (loc, type, arg1, arg0);
8824       if (TREE_CODE (arg1) == REAL_CST
8825           && real_isnan (&TREE_REAL_CST (arg1))
8826           && (! HONOR_SNANS (TYPE_MODE (TREE_TYPE (arg1)))
8827               || ! TREE_REAL_CST (arg1).signalling))
8828         return omit_one_operand_loc (loc, type, arg0, arg1);
8829
8830       /* Transform fmin/fmax(x,x) -> x.  */
8831       if (operand_equal_p (arg0, arg1, OEP_PURE_SAME))
8832         return omit_one_operand_loc (loc, type, arg0, arg1);
8833
8834       /* Convert fmin/fmax to MIN_EXPR/MAX_EXPR.  C99 requires these
8835          functions to return the numeric arg if the other one is NaN.
8836          These tree codes don't honor that, so only transform if
8837          -ffinite-math-only is set.  C99 doesn't require -0.0 to be
8838          handled, so we don't have to worry about it either.  */
8839       if (flag_finite_math_only)
8840         return fold_build2_loc (loc, (max ? MAX_EXPR : MIN_EXPR), type,
8841                             fold_convert_loc (loc, type, arg0),
8842                             fold_convert_loc (loc, type, arg1));
8843     }
8844   return NULL_TREE;
8845 }
8846
8847 /* Fold a call to builtin carg(a+bi) -> atan2(b,a).  */
8848
8849 static tree
8850 fold_builtin_carg (location_t loc, tree arg, tree type)
8851 {
8852   if (validate_arg (arg, COMPLEX_TYPE)
8853       && TREE_CODE (TREE_TYPE (TREE_TYPE (arg))) == REAL_TYPE)
8854     {
8855       tree atan2_fn = mathfn_built_in (type, BUILT_IN_ATAN2);
8856
8857       if (atan2_fn)
8858         {
8859           tree new_arg = builtin_save_expr (arg);
8860           tree r_arg = fold_build1_loc (loc, REALPART_EXPR, type, new_arg);
8861           tree i_arg = fold_build1_loc (loc, IMAGPART_EXPR, type, new_arg);
8862           return build_call_expr_loc (loc, atan2_fn, 2, i_arg, r_arg);
8863         }
8864     }
8865
8866   return NULL_TREE;
8867 }
8868
8869 /* Fold a call to builtin logb/ilogb.  */
8870
8871 static tree
8872 fold_builtin_logb (location_t loc, tree arg, tree rettype)
8873 {
8874   if (! validate_arg (arg, REAL_TYPE))
8875     return NULL_TREE;
8876
8877   STRIP_NOPS (arg);
8878
8879   if (TREE_CODE (arg) == REAL_CST && ! TREE_OVERFLOW (arg))
8880     {
8881       const REAL_VALUE_TYPE *const value = TREE_REAL_CST_PTR (arg);
8882
8883       switch (value->cl)
8884       {
8885       case rvc_nan:
8886       case rvc_inf:
8887         /* If arg is Inf or NaN and we're logb, return it.  */
8888         if (TREE_CODE (rettype) == REAL_TYPE)
8889           return fold_convert_loc (loc, rettype, arg);
8890         /* Fall through... */
8891       case rvc_zero:
8892         /* Zero may set errno and/or raise an exception for logb, also
8893            for ilogb we don't know FP_ILOGB0.  */
8894         return NULL_TREE;
8895       case rvc_normal:
8896         /* For normal numbers, proceed iff radix == 2.  In GCC,
8897            normalized significands are in the range [0.5, 1.0).  We
8898            want the exponent as if they were [1.0, 2.0) so get the
8899            exponent and subtract 1.  */
8900         if (REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (arg)))->b == 2)
8901           return fold_convert_loc (loc, rettype,
8902                                    build_int_cst (integer_type_node,
8903                                                   REAL_EXP (value)-1));
8904         break;
8905       }
8906     }
8907
8908   return NULL_TREE;
8909 }
8910
8911 /* Fold a call to builtin significand, if radix == 2.  */
8912
8913 static tree
8914 fold_builtin_significand (location_t loc, tree arg, tree rettype)
8915 {
8916   if (! validate_arg (arg, REAL_TYPE))
8917     return NULL_TREE;
8918
8919   STRIP_NOPS (arg);
8920
8921   if (TREE_CODE (arg) == REAL_CST && ! TREE_OVERFLOW (arg))
8922     {
8923       const REAL_VALUE_TYPE *const value = TREE_REAL_CST_PTR (arg);
8924
8925       switch (value->cl)
8926       {
8927       case rvc_zero:
8928       case rvc_nan:
8929       case rvc_inf:
8930         /* If arg is +-0, +-Inf or +-NaN, then return it.  */
8931         return fold_convert_loc (loc, rettype, arg);
8932       case rvc_normal:
8933         /* For normal numbers, proceed iff radix == 2.  */
8934         if (REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (arg)))->b == 2)
8935           {
8936             REAL_VALUE_TYPE result = *value;
8937             /* In GCC, normalized significands are in the range [0.5,
8938                1.0).  We want them to be [1.0, 2.0) so set the
8939                exponent to 1.  */
8940             SET_REAL_EXP (&result, 1);
8941             return build_real (rettype, result);
8942           }
8943         break;
8944       }
8945     }
8946
8947   return NULL_TREE;
8948 }
8949
8950 /* Fold a call to builtin frexp, we can assume the base is 2.  */
8951
8952 static tree
8953 fold_builtin_frexp (location_t loc, tree arg0, tree arg1, tree rettype)
8954 {
8955   if (! validate_arg (arg0, REAL_TYPE) || ! validate_arg (arg1, POINTER_TYPE))
8956     return NULL_TREE;
8957
8958   STRIP_NOPS (arg0);
8959
8960   if (!(TREE_CODE (arg0) == REAL_CST && ! TREE_OVERFLOW (arg0)))
8961     return NULL_TREE;
8962
8963   arg1 = build_fold_indirect_ref_loc (loc, arg1);
8964
8965   /* Proceed if a valid pointer type was passed in.  */
8966   if (TYPE_MAIN_VARIANT (TREE_TYPE (arg1)) == integer_type_node)
8967     {
8968       const REAL_VALUE_TYPE *const value = TREE_REAL_CST_PTR (arg0);
8969       tree frac, exp;
8970
8971       switch (value->cl)
8972       {
8973       case rvc_zero:
8974         /* For +-0, return (*exp = 0, +-0).  */
8975         exp = integer_zero_node;
8976         frac = arg0;
8977         break;
8978       case rvc_nan:
8979       case rvc_inf:
8980         /* For +-NaN or +-Inf, *exp is unspecified, return arg0.  */
8981         return omit_one_operand_loc (loc, rettype, arg0, arg1);
8982       case rvc_normal:
8983         {
8984           /* Since the frexp function always expects base 2, and in
8985              GCC normalized significands are already in the range
8986              [0.5, 1.0), we have exactly what frexp wants.  */
8987           REAL_VALUE_TYPE frac_rvt = *value;
8988           SET_REAL_EXP (&frac_rvt, 0);
8989           frac = build_real (rettype, frac_rvt);
8990           exp = build_int_cst (integer_type_node, REAL_EXP (value));
8991         }
8992         break;
8993       default:
8994         gcc_unreachable ();
8995       }
8996
8997       /* Create the COMPOUND_EXPR (*arg1 = trunc, frac). */
8998       arg1 = fold_build2_loc (loc, MODIFY_EXPR, rettype, arg1, exp);
8999       TREE_SIDE_EFFECTS (arg1) = 1;
9000       return fold_build2_loc (loc, COMPOUND_EXPR, rettype, arg1, frac);
9001     }
9002
9003   return NULL_TREE;
9004 }
9005
9006 /* Fold a call to builtin ldexp or scalbn/scalbln.  If LDEXP is true
9007    then we can assume the base is two.  If it's false, then we have to
9008    check the mode of the TYPE parameter in certain cases.  */
9009
9010 static tree
9011 fold_builtin_load_exponent (location_t loc, tree arg0, tree arg1,
9012                             tree type, bool ldexp)
9013 {
9014   if (validate_arg (arg0, REAL_TYPE) && validate_arg (arg1, INTEGER_TYPE))
9015     {
9016       STRIP_NOPS (arg0);
9017       STRIP_NOPS (arg1);
9018
9019       /* If arg0 is 0, Inf or NaN, or if arg1 is 0, then return arg0.  */
9020       if (real_zerop (arg0) || integer_zerop (arg1)
9021           || (TREE_CODE (arg0) == REAL_CST
9022               && !real_isfinite (&TREE_REAL_CST (arg0))))
9023         return omit_one_operand_loc (loc, type, arg0, arg1);
9024
9025       /* If both arguments are constant, then try to evaluate it.  */
9026       if ((ldexp || REAL_MODE_FORMAT (TYPE_MODE (type))->b == 2)
9027           && TREE_CODE (arg0) == REAL_CST && !TREE_OVERFLOW (arg0)
9028           && host_integerp (arg1, 0))
9029         {
9030           /* Bound the maximum adjustment to twice the range of the
9031              mode's valid exponents.  Use abs to ensure the range is
9032              positive as a sanity check.  */
9033           const long max_exp_adj = 2 *
9034             labs (REAL_MODE_FORMAT (TYPE_MODE (type))->emax
9035                  - REAL_MODE_FORMAT (TYPE_MODE (type))->emin);
9036
9037           /* Get the user-requested adjustment.  */
9038           const HOST_WIDE_INT req_exp_adj = tree_low_cst (arg1, 0);
9039
9040           /* The requested adjustment must be inside this range.  This
9041              is a preliminary cap to avoid things like overflow, we
9042              may still fail to compute the result for other reasons.  */
9043           if (-max_exp_adj < req_exp_adj && req_exp_adj < max_exp_adj)
9044             {
9045               REAL_VALUE_TYPE initial_result;
9046
9047               real_ldexp (&initial_result, &TREE_REAL_CST (arg0), req_exp_adj);
9048
9049               /* Ensure we didn't overflow.  */
9050               if (! real_isinf (&initial_result))
9051                 {
9052                   const REAL_VALUE_TYPE trunc_result
9053                     = real_value_truncate (TYPE_MODE (type), initial_result);
9054
9055                   /* Only proceed if the target mode can hold the
9056                      resulting value.  */
9057                   if (REAL_VALUES_EQUAL (initial_result, trunc_result))
9058                     return build_real (type, trunc_result);
9059                 }
9060             }
9061         }
9062     }
9063
9064   return NULL_TREE;
9065 }
9066
9067 /* Fold a call to builtin modf.  */
9068
9069 static tree
9070 fold_builtin_modf (location_t loc, tree arg0, tree arg1, tree rettype)
9071 {
9072   if (! validate_arg (arg0, REAL_TYPE) || ! validate_arg (arg1, POINTER_TYPE))
9073     return NULL_TREE;
9074
9075   STRIP_NOPS (arg0);
9076
9077   if (!(TREE_CODE (arg0) == REAL_CST && ! TREE_OVERFLOW (arg0)))
9078     return NULL_TREE;
9079
9080   arg1 = build_fold_indirect_ref_loc (loc, arg1);
9081
9082   /* Proceed if a valid pointer type was passed in.  */
9083   if (TYPE_MAIN_VARIANT (TREE_TYPE (arg1)) == TYPE_MAIN_VARIANT (rettype))
9084     {
9085       const REAL_VALUE_TYPE *const value = TREE_REAL_CST_PTR (arg0);
9086       REAL_VALUE_TYPE trunc, frac;
9087
9088       switch (value->cl)
9089       {
9090       case rvc_nan:
9091       case rvc_zero:
9092         /* For +-NaN or +-0, return (*arg1 = arg0, arg0).  */
9093         trunc = frac = *value;
9094         break;
9095       case rvc_inf:
9096         /* For +-Inf, return (*arg1 = arg0, +-0).  */
9097         frac = dconst0;
9098         frac.sign = value->sign;
9099         trunc = *value;
9100         break;
9101       case rvc_normal:
9102         /* Return (*arg1 = trunc(arg0), arg0-trunc(arg0)).  */
9103         real_trunc (&trunc, VOIDmode, value);
9104         real_arithmetic (&frac, MINUS_EXPR, value, &trunc);
9105         /* If the original number was negative and already
9106            integral, then the fractional part is -0.0.  */
9107         if (value->sign && frac.cl == rvc_zero)
9108           frac.sign = value->sign;
9109         break;
9110       }
9111
9112       /* Create the COMPOUND_EXPR (*arg1 = trunc, frac). */
9113       arg1 = fold_build2_loc (loc, MODIFY_EXPR, rettype, arg1,
9114                           build_real (rettype, trunc));
9115       TREE_SIDE_EFFECTS (arg1) = 1;
9116       return fold_build2_loc (loc, COMPOUND_EXPR, rettype, arg1,
9117                           build_real (rettype, frac));
9118     }
9119
9120   return NULL_TREE;
9121 }
9122
9123 /* Given a location LOC, an interclass builtin function decl FNDECL
9124    and its single argument ARG, return an folded expression computing
9125    the same, or NULL_TREE if we either couldn't or didn't want to fold
9126    (the latter happen if there's an RTL instruction available).  */
9127
9128 static tree
9129 fold_builtin_interclass_mathfn (location_t loc, tree fndecl, tree arg)
9130 {
9131   enum machine_mode mode;
9132
9133   if (!validate_arg (arg, REAL_TYPE))
9134     return NULL_TREE;
9135
9136   if (interclass_mathfn_icode (arg, fndecl) != CODE_FOR_nothing)
9137     return NULL_TREE;
9138
9139   mode = TYPE_MODE (TREE_TYPE (arg));
9140
9141   /* If there is no optab, try generic code.  */
9142   switch (DECL_FUNCTION_CODE (fndecl))
9143     {
9144       tree result;
9145
9146     CASE_FLT_FN (BUILT_IN_ISINF):
9147       {
9148         /* isinf(x) -> isgreater(fabs(x),DBL_MAX).  */
9149         tree const isgr_fn = built_in_decls[BUILT_IN_ISGREATER];
9150         tree const type = TREE_TYPE (arg);
9151         REAL_VALUE_TYPE r;
9152         char buf[128];
9153
9154         get_max_float (REAL_MODE_FORMAT (mode), buf, sizeof (buf));
9155         real_from_string (&r, buf);
9156         result = build_call_expr (isgr_fn, 2,
9157                                   fold_build1_loc (loc, ABS_EXPR, type, arg),
9158                                   build_real (type, r));
9159         return result;
9160       }
9161     CASE_FLT_FN (BUILT_IN_FINITE):
9162     case BUILT_IN_ISFINITE:
9163       {
9164         /* isfinite(x) -> islessequal(fabs(x),DBL_MAX).  */
9165         tree const isle_fn = built_in_decls[BUILT_IN_ISLESSEQUAL];
9166         tree const type = TREE_TYPE (arg);
9167         REAL_VALUE_TYPE r;
9168         char buf[128];
9169
9170         get_max_float (REAL_MODE_FORMAT (mode), buf, sizeof (buf));
9171         real_from_string (&r, buf);
9172         result = build_call_expr (isle_fn, 2,
9173                                   fold_build1_loc (loc, ABS_EXPR, type, arg),
9174                                   build_real (type, r));
9175         /*result = fold_build2_loc (loc, UNGT_EXPR,
9176                                   TREE_TYPE (TREE_TYPE (fndecl)),
9177                                   fold_build1_loc (loc, ABS_EXPR, type, arg),
9178                                   build_real (type, r));
9179         result = fold_build1_loc (loc, TRUTH_NOT_EXPR,
9180                                   TREE_TYPE (TREE_TYPE (fndecl)),
9181                                   result);*/
9182         return result;
9183       }
9184     case BUILT_IN_ISNORMAL:
9185       {
9186         /* isnormal(x) -> isgreaterequal(fabs(x),DBL_MIN) &
9187            islessequal(fabs(x),DBL_MAX).  */
9188         tree const isle_fn = built_in_decls[BUILT_IN_ISLESSEQUAL];
9189         tree const isge_fn = built_in_decls[BUILT_IN_ISGREATEREQUAL];
9190         tree const type = TREE_TYPE (arg);
9191         REAL_VALUE_TYPE rmax, rmin;
9192         char buf[128];
9193
9194         get_max_float (REAL_MODE_FORMAT (mode), buf, sizeof (buf));
9195         real_from_string (&rmax, buf);
9196         sprintf (buf, "0x1p%d", REAL_MODE_FORMAT (mode)->emin - 1);
9197         real_from_string (&rmin, buf);
9198         arg = builtin_save_expr (fold_build1_loc (loc, ABS_EXPR, type, arg));
9199         result = build_call_expr (isle_fn, 2, arg,
9200                                   build_real (type, rmax));
9201         result = fold_build2 (BIT_AND_EXPR, integer_type_node, result,
9202                               build_call_expr (isge_fn, 2, arg,
9203                                                build_real (type, rmin)));
9204         return result;
9205       }
9206     default:
9207       break;
9208     }
9209
9210   return NULL_TREE;
9211 }
9212
9213 /* Fold a call to __builtin_isnan(), __builtin_isinf, __builtin_finite.
9214    ARG is the argument for the call.  */
9215
9216 static tree
9217 fold_builtin_classify (location_t loc, tree fndecl, tree arg, int builtin_index)
9218 {
9219   tree type = TREE_TYPE (TREE_TYPE (fndecl));
9220   REAL_VALUE_TYPE r;
9221
9222   if (!validate_arg (arg, REAL_TYPE))
9223     return NULL_TREE;
9224
9225   switch (builtin_index)
9226     {
9227     case BUILT_IN_ISINF:
9228       if (!HONOR_INFINITIES (TYPE_MODE (TREE_TYPE (arg))))
9229         return omit_one_operand_loc (loc, type, integer_zero_node, arg);
9230
9231       if (TREE_CODE (arg) == REAL_CST)
9232         {
9233           r = TREE_REAL_CST (arg);
9234           if (real_isinf (&r))
9235             return real_compare (GT_EXPR, &r, &dconst0)
9236                    ? integer_one_node : integer_minus_one_node;
9237           else
9238             return integer_zero_node;
9239         }
9240
9241       return NULL_TREE;
9242
9243     case BUILT_IN_ISINF_SIGN:
9244       {
9245         /* isinf_sign(x) -> isinf(x) ? (signbit(x) ? -1 : 1) : 0 */
9246         /* In a boolean context, GCC will fold the inner COND_EXPR to
9247            1.  So e.g. "if (isinf_sign(x))" would be folded to just
9248            "if (isinf(x) ? 1 : 0)" which becomes "if (isinf(x))". */
9249         tree signbit_fn = mathfn_built_in_1 (TREE_TYPE (arg), BUILT_IN_SIGNBIT, 0);
9250         tree isinf_fn = built_in_decls[BUILT_IN_ISINF];
9251         tree tmp = NULL_TREE;
9252
9253         arg = builtin_save_expr (arg);
9254
9255         if (signbit_fn && isinf_fn)
9256           {
9257             tree signbit_call = build_call_expr_loc (loc, signbit_fn, 1, arg);
9258             tree isinf_call = build_call_expr_loc (loc, isinf_fn, 1, arg);
9259
9260             signbit_call = fold_build2_loc (loc, NE_EXPR, integer_type_node,
9261                                         signbit_call, integer_zero_node);
9262             isinf_call = fold_build2_loc (loc, NE_EXPR, integer_type_node,
9263                                       isinf_call, integer_zero_node);
9264
9265             tmp = fold_build3_loc (loc, COND_EXPR, integer_type_node, signbit_call,
9266                                integer_minus_one_node, integer_one_node);
9267             tmp = fold_build3_loc (loc, COND_EXPR, integer_type_node,
9268                                isinf_call, tmp,
9269                                integer_zero_node);
9270           }
9271
9272         return tmp;
9273       }
9274
9275     case BUILT_IN_ISFINITE:
9276       if (!HONOR_NANS (TYPE_MODE (TREE_TYPE (arg)))
9277           && !HONOR_INFINITIES (TYPE_MODE (TREE_TYPE (arg))))
9278         return omit_one_operand_loc (loc, type, integer_one_node, arg);
9279
9280       if (TREE_CODE (arg) == REAL_CST)
9281         {
9282           r = TREE_REAL_CST (arg);
9283           return real_isfinite (&r) ? integer_one_node : integer_zero_node;
9284         }
9285
9286       return NULL_TREE;
9287
9288     case BUILT_IN_ISNAN:
9289       if (!HONOR_NANS (TYPE_MODE (TREE_TYPE (arg))))
9290         return omit_one_operand_loc (loc, type, integer_zero_node, arg);
9291
9292       if (TREE_CODE (arg) == REAL_CST)
9293         {
9294           r = TREE_REAL_CST (arg);
9295           return real_isnan (&r) ? integer_one_node : integer_zero_node;
9296         }
9297
9298       arg = builtin_save_expr (arg);
9299       return fold_build2_loc (loc, UNORDERED_EXPR, type, arg, arg);
9300
9301     default:
9302       gcc_unreachable ();
9303     }
9304 }
9305
9306 /* Fold a call to __builtin_fpclassify(int, int, int, int, int, ...).
9307    This builtin will generate code to return the appropriate floating
9308    point classification depending on the value of the floating point
9309    number passed in.  The possible return values must be supplied as
9310    int arguments to the call in the following order: FP_NAN, FP_INFINITE,
9311    FP_NORMAL, FP_SUBNORMAL and FP_ZERO.  The ellipses is for exactly
9312    one floating point argument which is "type generic".  */
9313
9314 static tree
9315 fold_builtin_fpclassify (location_t loc, tree exp)
9316 {
9317   tree fp_nan, fp_infinite, fp_normal, fp_subnormal, fp_zero,
9318     arg, type, res, tmp;
9319   enum machine_mode mode;
9320   REAL_VALUE_TYPE r;
9321   char buf[128];
9322
9323   /* Verify the required arguments in the original call.  */
9324   if (!validate_arglist (exp, INTEGER_TYPE, INTEGER_TYPE,
9325                          INTEGER_TYPE, INTEGER_TYPE,
9326                          INTEGER_TYPE, REAL_TYPE, VOID_TYPE))
9327     return NULL_TREE;
9328
9329   fp_nan = CALL_EXPR_ARG (exp, 0);
9330   fp_infinite = CALL_EXPR_ARG (exp, 1);
9331   fp_normal = CALL_EXPR_ARG (exp, 2);
9332   fp_subnormal = CALL_EXPR_ARG (exp, 3);
9333   fp_zero = CALL_EXPR_ARG (exp, 4);
9334   arg = CALL_EXPR_ARG (exp, 5);
9335   type = TREE_TYPE (arg);
9336   mode = TYPE_MODE (type);
9337   arg = builtin_save_expr (fold_build1_loc (loc, ABS_EXPR, type, arg));
9338
9339   /* fpclassify(x) ->
9340        isnan(x) ? FP_NAN :
9341          (fabs(x) == Inf ? FP_INFINITE :
9342            (fabs(x) >= DBL_MIN ? FP_NORMAL :
9343              (x == 0 ? FP_ZERO : FP_SUBNORMAL))).  */
9344
9345   tmp = fold_build2_loc (loc, EQ_EXPR, integer_type_node, arg,
9346                      build_real (type, dconst0));
9347   res = fold_build3_loc (loc, COND_EXPR, integer_type_node,
9348                      tmp, fp_zero, fp_subnormal);
9349
9350   sprintf (buf, "0x1p%d", REAL_MODE_FORMAT (mode)->emin - 1);
9351   real_from_string (&r, buf);
9352   tmp = fold_build2_loc (loc, GE_EXPR, integer_type_node,
9353                      arg, build_real (type, r));
9354   res = fold_build3_loc (loc, COND_EXPR, integer_type_node, tmp, fp_normal, res);
9355
9356   if (HONOR_INFINITIES (mode))
9357     {
9358       real_inf (&r);
9359       tmp = fold_build2_loc (loc, EQ_EXPR, integer_type_node, arg,
9360                          build_real (type, r));
9361       res = fold_build3_loc (loc, COND_EXPR, integer_type_node, tmp,
9362                          fp_infinite, res);
9363     }
9364
9365   if (HONOR_NANS (mode))
9366     {
9367       tmp = fold_build2_loc (loc, ORDERED_EXPR, integer_type_node, arg, arg);
9368       res = fold_build3_loc (loc, COND_EXPR, integer_type_node, tmp, res, fp_nan);
9369     }
9370
9371   return res;
9372 }
9373
9374 /* Fold a call to an unordered comparison function such as
9375    __builtin_isgreater().  FNDECL is the FUNCTION_DECL for the function
9376    being called and ARG0 and ARG1 are the arguments for the call.
9377    UNORDERED_CODE and ORDERED_CODE are comparison codes that give
9378    the opposite of the desired result.  UNORDERED_CODE is used
9379    for modes that can hold NaNs and ORDERED_CODE is used for
9380    the rest.  */
9381
9382 static tree
9383 fold_builtin_unordered_cmp (location_t loc, tree fndecl, tree arg0, tree arg1,
9384                             enum tree_code unordered_code,
9385                             enum tree_code ordered_code)
9386 {
9387   tree type = TREE_TYPE (TREE_TYPE (fndecl));
9388   enum tree_code code;
9389   tree type0, type1;
9390   enum tree_code code0, code1;
9391   tree cmp_type = NULL_TREE;
9392
9393   type0 = TREE_TYPE (arg0);
9394   type1 = TREE_TYPE (arg1);
9395
9396   code0 = TREE_CODE (type0);
9397   code1 = TREE_CODE (type1);
9398
9399   if (code0 == REAL_TYPE && code1 == REAL_TYPE)
9400     /* Choose the wider of two real types.  */
9401     cmp_type = TYPE_PRECISION (type0) >= TYPE_PRECISION (type1)
9402       ? type0 : type1;
9403   else if (code0 == REAL_TYPE && code1 == INTEGER_TYPE)
9404     cmp_type = type0;
9405   else if (code0 == INTEGER_TYPE && code1 == REAL_TYPE)
9406     cmp_type = type1;
9407
9408   arg0 = fold_convert_loc (loc, cmp_type, arg0);
9409   arg1 = fold_convert_loc (loc, cmp_type, arg1);
9410
9411   if (unordered_code == UNORDERED_EXPR)
9412     {
9413       if (!HONOR_NANS (TYPE_MODE (TREE_TYPE (arg0))))
9414         return omit_two_operands_loc (loc, type, integer_zero_node, arg0, arg1);
9415       return fold_build2_loc (loc, UNORDERED_EXPR, type, arg0, arg1);
9416     }
9417
9418   code = HONOR_NANS (TYPE_MODE (TREE_TYPE (arg0))) ? unordered_code
9419                                                    : ordered_code;
9420   return fold_build1_loc (loc, TRUTH_NOT_EXPR, type,
9421                       fold_build2_loc (loc, code, type, arg0, arg1));
9422 }
9423
9424 /* Fold a call to built-in function FNDECL with 0 arguments.
9425    IGNORE is true if the result of the function call is ignored.  This
9426    function returns NULL_TREE if no simplification was possible.  */
9427
9428 static tree
9429 fold_builtin_0 (location_t loc, tree fndecl, bool ignore ATTRIBUTE_UNUSED)
9430 {
9431   tree type = TREE_TYPE (TREE_TYPE (fndecl));
9432   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
9433   switch (fcode)
9434     {
9435     CASE_FLT_FN (BUILT_IN_INF):
9436     case BUILT_IN_INFD32:
9437     case BUILT_IN_INFD64:
9438     case BUILT_IN_INFD128:
9439       return fold_builtin_inf (loc, type, true);
9440
9441     CASE_FLT_FN (BUILT_IN_HUGE_VAL):
9442       return fold_builtin_inf (loc, type, false);
9443
9444     case BUILT_IN_CLASSIFY_TYPE:
9445       return fold_builtin_classify_type (NULL_TREE);
9446
9447     default:
9448       break;
9449     }
9450   return NULL_TREE;
9451 }
9452
9453 /* Fold a call to built-in function FNDECL with 1 argument, ARG0.
9454    IGNORE is true if the result of the function call is ignored.  This
9455    function returns NULL_TREE if no simplification was possible.  */
9456
9457 static tree
9458 fold_builtin_1 (location_t loc, tree fndecl, tree arg0, bool ignore)
9459 {
9460   tree type = TREE_TYPE (TREE_TYPE (fndecl));
9461   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
9462   switch (fcode)
9463     {
9464     case BUILT_IN_CONSTANT_P:
9465       {
9466         tree val = fold_builtin_constant_p (arg0);
9467
9468         /* Gimplification will pull the CALL_EXPR for the builtin out of
9469            an if condition.  When not optimizing, we'll not CSE it back.
9470            To avoid link error types of regressions, return false now.  */
9471         if (!val && !optimize)
9472           val = integer_zero_node;
9473
9474         return val;
9475       }
9476
9477     case BUILT_IN_CLASSIFY_TYPE:
9478       return fold_builtin_classify_type (arg0);
9479
9480     case BUILT_IN_STRLEN:
9481       return fold_builtin_strlen (loc, type, arg0);
9482
9483     CASE_FLT_FN (BUILT_IN_FABS):
9484       return fold_builtin_fabs (loc, arg0, type);
9485
9486     case BUILT_IN_ABS:
9487     case BUILT_IN_LABS:
9488     case BUILT_IN_LLABS:
9489     case BUILT_IN_IMAXABS:
9490       return fold_builtin_abs (loc, arg0, type);
9491
9492     CASE_FLT_FN (BUILT_IN_CONJ):
9493       if (validate_arg (arg0, COMPLEX_TYPE)
9494         && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
9495         return fold_build1_loc (loc, CONJ_EXPR, type, arg0);
9496     break;
9497
9498     CASE_FLT_FN (BUILT_IN_CREAL):
9499       if (validate_arg (arg0, COMPLEX_TYPE)
9500         && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
9501         return non_lvalue_loc (loc, fold_build1_loc (loc, REALPART_EXPR, type, arg0));;
9502     break;
9503
9504     CASE_FLT_FN (BUILT_IN_CIMAG):
9505       if (validate_arg (arg0, COMPLEX_TYPE)
9506           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
9507         return non_lvalue_loc (loc, fold_build1_loc (loc, IMAGPART_EXPR, type, arg0));
9508     break;
9509
9510     CASE_FLT_FN (BUILT_IN_CCOS):
9511       return fold_builtin_ccos(loc, arg0, type, fndecl, /*hyper=*/ false);
9512
9513     CASE_FLT_FN (BUILT_IN_CCOSH):
9514       return fold_builtin_ccos(loc, arg0, type, fndecl, /*hyper=*/ true);
9515
9516     CASE_FLT_FN (BUILT_IN_CPROJ):
9517       return fold_builtin_cproj(loc, arg0, type);
9518
9519     CASE_FLT_FN (BUILT_IN_CSIN):
9520       if (validate_arg (arg0, COMPLEX_TYPE)
9521           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
9522         return do_mpc_arg1 (arg0, type, mpc_sin);
9523     break;
9524
9525     CASE_FLT_FN (BUILT_IN_CSINH):
9526       if (validate_arg (arg0, COMPLEX_TYPE)
9527           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
9528         return do_mpc_arg1 (arg0, type, mpc_sinh);
9529     break;
9530
9531     CASE_FLT_FN (BUILT_IN_CTAN):
9532       if (validate_arg (arg0, COMPLEX_TYPE)
9533           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
9534         return do_mpc_arg1 (arg0, type, mpc_tan);
9535     break;
9536
9537     CASE_FLT_FN (BUILT_IN_CTANH):
9538       if (validate_arg (arg0, COMPLEX_TYPE)
9539           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
9540         return do_mpc_arg1 (arg0, type, mpc_tanh);
9541     break;
9542
9543     CASE_FLT_FN (BUILT_IN_CLOG):
9544       if (validate_arg (arg0, COMPLEX_TYPE)
9545           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
9546         return do_mpc_arg1 (arg0, type, mpc_log);
9547     break;
9548
9549     CASE_FLT_FN (BUILT_IN_CSQRT):
9550       if (validate_arg (arg0, COMPLEX_TYPE)
9551           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
9552         return do_mpc_arg1 (arg0, type, mpc_sqrt);
9553     break;
9554
9555     CASE_FLT_FN (BUILT_IN_CASIN):
9556       if (validate_arg (arg0, COMPLEX_TYPE)
9557           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
9558         return do_mpc_arg1 (arg0, type, mpc_asin);
9559     break;
9560
9561     CASE_FLT_FN (BUILT_IN_CACOS):
9562       if (validate_arg (arg0, COMPLEX_TYPE)
9563           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
9564         return do_mpc_arg1 (arg0, type, mpc_acos);
9565     break;
9566
9567     CASE_FLT_FN (BUILT_IN_CATAN):
9568       if (validate_arg (arg0, COMPLEX_TYPE)
9569           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
9570         return do_mpc_arg1 (arg0, type, mpc_atan);
9571     break;
9572
9573     CASE_FLT_FN (BUILT_IN_CASINH):
9574       if (validate_arg (arg0, COMPLEX_TYPE)
9575           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
9576         return do_mpc_arg1 (arg0, type, mpc_asinh);
9577     break;
9578
9579     CASE_FLT_FN (BUILT_IN_CACOSH):
9580       if (validate_arg (arg0, COMPLEX_TYPE)
9581           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
9582         return do_mpc_arg1 (arg0, type, mpc_acosh);
9583     break;
9584
9585     CASE_FLT_FN (BUILT_IN_CATANH):
9586       if (validate_arg (arg0, COMPLEX_TYPE)
9587           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
9588         return do_mpc_arg1 (arg0, type, mpc_atanh);
9589     break;
9590
9591     CASE_FLT_FN (BUILT_IN_CABS):
9592       return fold_builtin_cabs (loc, arg0, type, fndecl);
9593
9594     CASE_FLT_FN (BUILT_IN_CARG):
9595       return fold_builtin_carg (loc, arg0, type);
9596
9597     CASE_FLT_FN (BUILT_IN_SQRT):
9598       return fold_builtin_sqrt (loc, arg0, type);
9599
9600     CASE_FLT_FN (BUILT_IN_CBRT):
9601       return fold_builtin_cbrt (loc, arg0, type);
9602
9603     CASE_FLT_FN (BUILT_IN_ASIN):
9604       if (validate_arg (arg0, REAL_TYPE))
9605         return do_mpfr_arg1 (arg0, type, mpfr_asin,
9606                              &dconstm1, &dconst1, true);
9607     break;
9608
9609     CASE_FLT_FN (BUILT_IN_ACOS):
9610       if (validate_arg (arg0, REAL_TYPE))
9611         return do_mpfr_arg1 (arg0, type, mpfr_acos,
9612                              &dconstm1, &dconst1, true);
9613     break;
9614
9615     CASE_FLT_FN (BUILT_IN_ATAN):
9616       if (validate_arg (arg0, REAL_TYPE))
9617         return do_mpfr_arg1 (arg0, type, mpfr_atan, NULL, NULL, 0);
9618     break;
9619
9620     CASE_FLT_FN (BUILT_IN_ASINH):
9621       if (validate_arg (arg0, REAL_TYPE))
9622         return do_mpfr_arg1 (arg0, type, mpfr_asinh, NULL, NULL, 0);
9623     break;
9624
9625     CASE_FLT_FN (BUILT_IN_ACOSH):
9626       if (validate_arg (arg0, REAL_TYPE))
9627         return do_mpfr_arg1 (arg0, type, mpfr_acosh,
9628                              &dconst1, NULL, true);
9629     break;
9630
9631     CASE_FLT_FN (BUILT_IN_ATANH):
9632       if (validate_arg (arg0, REAL_TYPE))
9633         return do_mpfr_arg1 (arg0, type, mpfr_atanh,
9634                              &dconstm1, &dconst1, false);
9635     break;
9636
9637     CASE_FLT_FN (BUILT_IN_SIN):
9638       if (validate_arg (arg0, REAL_TYPE))
9639         return do_mpfr_arg1 (arg0, type, mpfr_sin, NULL, NULL, 0);
9640     break;
9641
9642     CASE_FLT_FN (BUILT_IN_COS):
9643       return fold_builtin_cos (loc, arg0, type, fndecl);
9644
9645     CASE_FLT_FN (BUILT_IN_TAN):
9646       return fold_builtin_tan (arg0, type);
9647
9648     CASE_FLT_FN (BUILT_IN_CEXP):
9649       return fold_builtin_cexp (loc, arg0, type);
9650
9651     CASE_FLT_FN (BUILT_IN_CEXPI):
9652       if (validate_arg (arg0, REAL_TYPE))
9653         return do_mpfr_sincos (arg0, NULL_TREE, NULL_TREE);
9654     break;
9655
9656     CASE_FLT_FN (BUILT_IN_SINH):
9657       if (validate_arg (arg0, REAL_TYPE))
9658         return do_mpfr_arg1 (arg0, type, mpfr_sinh, NULL, NULL, 0);
9659     break;
9660
9661     CASE_FLT_FN (BUILT_IN_COSH):
9662       return fold_builtin_cosh (loc, arg0, type, fndecl);
9663
9664     CASE_FLT_FN (BUILT_IN_TANH):
9665       if (validate_arg (arg0, REAL_TYPE))
9666         return do_mpfr_arg1 (arg0, type, mpfr_tanh, NULL, NULL, 0);
9667     break;
9668
9669     CASE_FLT_FN (BUILT_IN_ERF):
9670       if (validate_arg (arg0, REAL_TYPE))
9671         return do_mpfr_arg1 (arg0, type, mpfr_erf, NULL, NULL, 0);
9672     break;
9673
9674     CASE_FLT_FN (BUILT_IN_ERFC):
9675       if (validate_arg (arg0, REAL_TYPE))
9676         return do_mpfr_arg1 (arg0, type, mpfr_erfc, NULL, NULL, 0);
9677     break;
9678
9679     CASE_FLT_FN (BUILT_IN_TGAMMA):
9680       if (validate_arg (arg0, REAL_TYPE))
9681         return do_mpfr_arg1 (arg0, type, mpfr_gamma, NULL, NULL, 0);
9682     break;
9683
9684     CASE_FLT_FN (BUILT_IN_EXP):
9685       return fold_builtin_exponent (loc, fndecl, arg0, mpfr_exp);
9686
9687     CASE_FLT_FN (BUILT_IN_EXP2):
9688       return fold_builtin_exponent (loc, fndecl, arg0, mpfr_exp2);
9689
9690     CASE_FLT_FN (BUILT_IN_EXP10):
9691     CASE_FLT_FN (BUILT_IN_POW10):
9692       return fold_builtin_exponent (loc, fndecl, arg0, mpfr_exp10);
9693
9694     CASE_FLT_FN (BUILT_IN_EXPM1):
9695       if (validate_arg (arg0, REAL_TYPE))
9696         return do_mpfr_arg1 (arg0, type, mpfr_expm1, NULL, NULL, 0);
9697     break;
9698
9699     CASE_FLT_FN (BUILT_IN_LOG):
9700     return fold_builtin_logarithm (loc, fndecl, arg0, mpfr_log);
9701
9702     CASE_FLT_FN (BUILT_IN_LOG2):
9703       return fold_builtin_logarithm (loc, fndecl, arg0, mpfr_log2);
9704
9705     CASE_FLT_FN (BUILT_IN_LOG10):
9706       return fold_builtin_logarithm (loc, fndecl, arg0, mpfr_log10);
9707
9708     CASE_FLT_FN (BUILT_IN_LOG1P):
9709       if (validate_arg (arg0, REAL_TYPE))
9710         return do_mpfr_arg1 (arg0, type, mpfr_log1p,
9711                              &dconstm1, NULL, false);
9712     break;
9713
9714     CASE_FLT_FN (BUILT_IN_J0):
9715       if (validate_arg (arg0, REAL_TYPE))
9716         return do_mpfr_arg1 (arg0, type, mpfr_j0,
9717                              NULL, NULL, 0);
9718     break;
9719
9720     CASE_FLT_FN (BUILT_IN_J1):
9721       if (validate_arg (arg0, REAL_TYPE))
9722         return do_mpfr_arg1 (arg0, type, mpfr_j1,
9723                              NULL, NULL, 0);
9724     break;
9725
9726     CASE_FLT_FN (BUILT_IN_Y0):
9727       if (validate_arg (arg0, REAL_TYPE))
9728         return do_mpfr_arg1 (arg0, type, mpfr_y0,
9729                              &dconst0, NULL, false);
9730     break;
9731
9732     CASE_FLT_FN (BUILT_IN_Y1):
9733       if (validate_arg (arg0, REAL_TYPE))
9734         return do_mpfr_arg1 (arg0, type, mpfr_y1,
9735                              &dconst0, NULL, false);
9736     break;
9737
9738     CASE_FLT_FN (BUILT_IN_NAN):
9739     case BUILT_IN_NAND32:
9740     case BUILT_IN_NAND64:
9741     case BUILT_IN_NAND128:
9742       return fold_builtin_nan (arg0, type, true);
9743
9744     CASE_FLT_FN (BUILT_IN_NANS):
9745       return fold_builtin_nan (arg0, type, false);
9746
9747     CASE_FLT_FN (BUILT_IN_FLOOR):
9748       return fold_builtin_floor (loc, fndecl, arg0);
9749
9750     CASE_FLT_FN (BUILT_IN_CEIL):
9751       return fold_builtin_ceil (loc, fndecl, arg0);
9752
9753     CASE_FLT_FN (BUILT_IN_TRUNC):
9754       return fold_builtin_trunc (loc, fndecl, arg0);
9755
9756     CASE_FLT_FN (BUILT_IN_ROUND):
9757       return fold_builtin_round (loc, fndecl, arg0);
9758
9759     CASE_FLT_FN (BUILT_IN_NEARBYINT):
9760     CASE_FLT_FN (BUILT_IN_RINT):
9761       return fold_trunc_transparent_mathfn (loc, fndecl, arg0);
9762
9763     CASE_FLT_FN (BUILT_IN_LCEIL):
9764     CASE_FLT_FN (BUILT_IN_LLCEIL):
9765     CASE_FLT_FN (BUILT_IN_LFLOOR):
9766     CASE_FLT_FN (BUILT_IN_LLFLOOR):
9767     CASE_FLT_FN (BUILT_IN_LROUND):
9768     CASE_FLT_FN (BUILT_IN_LLROUND):
9769       return fold_builtin_int_roundingfn (loc, fndecl, arg0);
9770
9771     CASE_FLT_FN (BUILT_IN_LRINT):
9772     CASE_FLT_FN (BUILT_IN_LLRINT):
9773       return fold_fixed_mathfn (loc, fndecl, arg0);
9774
9775     case BUILT_IN_BSWAP32:
9776     case BUILT_IN_BSWAP64:
9777       return fold_builtin_bswap (fndecl, arg0);
9778
9779     CASE_INT_FN (BUILT_IN_FFS):
9780     CASE_INT_FN (BUILT_IN_CLZ):
9781     CASE_INT_FN (BUILT_IN_CTZ):
9782     CASE_INT_FN (BUILT_IN_CLRSB):
9783     CASE_INT_FN (BUILT_IN_POPCOUNT):
9784     CASE_INT_FN (BUILT_IN_PARITY):
9785       return fold_builtin_bitop (fndecl, arg0);
9786
9787     CASE_FLT_FN (BUILT_IN_SIGNBIT):
9788       return fold_builtin_signbit (loc, arg0, type);
9789
9790     CASE_FLT_FN (BUILT_IN_SIGNIFICAND):
9791       return fold_builtin_significand (loc, arg0, type);
9792
9793     CASE_FLT_FN (BUILT_IN_ILOGB):
9794     CASE_FLT_FN (BUILT_IN_LOGB):
9795       return fold_builtin_logb (loc, arg0, type);
9796
9797     case BUILT_IN_ISASCII:
9798       return fold_builtin_isascii (loc, arg0);
9799
9800     case BUILT_IN_TOASCII:
9801       return fold_builtin_toascii (loc, arg0);
9802
9803     case BUILT_IN_ISDIGIT:
9804       return fold_builtin_isdigit (loc, arg0);
9805
9806     CASE_FLT_FN (BUILT_IN_FINITE):
9807     case BUILT_IN_FINITED32:
9808     case BUILT_IN_FINITED64:
9809     case BUILT_IN_FINITED128:
9810     case BUILT_IN_ISFINITE:
9811       {
9812         tree ret = fold_builtin_classify (loc, fndecl, arg0, BUILT_IN_ISFINITE);
9813         if (ret)
9814           return ret;
9815         return fold_builtin_interclass_mathfn (loc, fndecl, arg0);
9816       }
9817
9818     CASE_FLT_FN (BUILT_IN_ISINF):
9819     case BUILT_IN_ISINFD32:
9820     case BUILT_IN_ISINFD64:
9821     case BUILT_IN_ISINFD128:
9822       {
9823         tree ret = fold_builtin_classify (loc, fndecl, arg0, BUILT_IN_ISINF);
9824         if (ret)
9825           return ret;
9826         return fold_builtin_interclass_mathfn (loc, fndecl, arg0);
9827       }
9828
9829     case BUILT_IN_ISNORMAL:
9830       return fold_builtin_interclass_mathfn (loc, fndecl, arg0);
9831
9832     case BUILT_IN_ISINF_SIGN:
9833       return fold_builtin_classify (loc, fndecl, arg0, BUILT_IN_ISINF_SIGN);
9834
9835     CASE_FLT_FN (BUILT_IN_ISNAN):
9836     case BUILT_IN_ISNAND32:
9837     case BUILT_IN_ISNAND64:
9838     case BUILT_IN_ISNAND128:
9839       return fold_builtin_classify (loc, fndecl, arg0, BUILT_IN_ISNAN);
9840
9841     case BUILT_IN_PRINTF:
9842     case BUILT_IN_PRINTF_UNLOCKED:
9843     case BUILT_IN_VPRINTF:
9844       return fold_builtin_printf (loc, fndecl, arg0, NULL_TREE, ignore, fcode);
9845
9846     case BUILT_IN_FREE:
9847       if (integer_zerop (arg0))
9848         return build_empty_stmt (loc);
9849       break;
9850
9851     default:
9852       break;
9853     }
9854
9855   return NULL_TREE;
9856
9857 }
9858
9859 /* Fold a call to built-in function FNDECL with 2 arguments, ARG0 and ARG1.
9860    IGNORE is true if the result of the function call is ignored.  This
9861    function returns NULL_TREE if no simplification was possible.  */
9862
9863 static tree
9864 fold_builtin_2 (location_t loc, tree fndecl, tree arg0, tree arg1, bool ignore)
9865 {
9866   tree type = TREE_TYPE (TREE_TYPE (fndecl));
9867   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
9868
9869   switch (fcode)
9870     {
9871     CASE_FLT_FN (BUILT_IN_JN):
9872       if (validate_arg (arg0, INTEGER_TYPE)
9873           && validate_arg (arg1, REAL_TYPE))
9874         return do_mpfr_bessel_n (arg0, arg1, type, mpfr_jn, NULL, 0);
9875     break;
9876
9877     CASE_FLT_FN (BUILT_IN_YN):
9878       if (validate_arg (arg0, INTEGER_TYPE)
9879           && validate_arg (arg1, REAL_TYPE))
9880         return do_mpfr_bessel_n (arg0, arg1, type, mpfr_yn,
9881                                  &dconst0, false);
9882     break;
9883
9884     CASE_FLT_FN (BUILT_IN_DREM):
9885     CASE_FLT_FN (BUILT_IN_REMAINDER):
9886       if (validate_arg (arg0, REAL_TYPE)
9887           && validate_arg(arg1, REAL_TYPE))
9888         return do_mpfr_arg2 (arg0, arg1, type, mpfr_remainder);
9889     break;
9890
9891     CASE_FLT_FN_REENT (BUILT_IN_GAMMA): /* GAMMA_R */
9892     CASE_FLT_FN_REENT (BUILT_IN_LGAMMA): /* LGAMMA_R */
9893       if (validate_arg (arg0, REAL_TYPE)
9894           && validate_arg(arg1, POINTER_TYPE))
9895         return do_mpfr_lgamma_r (arg0, arg1, type);
9896     break;
9897
9898     CASE_FLT_FN (BUILT_IN_ATAN2):
9899       if (validate_arg (arg0, REAL_TYPE)
9900           && validate_arg(arg1, REAL_TYPE))
9901         return do_mpfr_arg2 (arg0, arg1, type, mpfr_atan2);
9902     break;
9903
9904     CASE_FLT_FN (BUILT_IN_FDIM):
9905       if (validate_arg (arg0, REAL_TYPE)
9906           && validate_arg(arg1, REAL_TYPE))
9907         return do_mpfr_arg2 (arg0, arg1, type, mpfr_dim);
9908     break;
9909
9910     CASE_FLT_FN (BUILT_IN_HYPOT):
9911       return fold_builtin_hypot (loc, fndecl, arg0, arg1, type);
9912
9913     CASE_FLT_FN (BUILT_IN_CPOW):
9914       if (validate_arg (arg0, COMPLEX_TYPE)
9915           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE
9916           && validate_arg (arg1, COMPLEX_TYPE)
9917           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg1))) == REAL_TYPE)
9918         return do_mpc_arg2 (arg0, arg1, type, /*do_nonfinite=*/ 0, mpc_pow);
9919     break;
9920
9921     CASE_FLT_FN (BUILT_IN_LDEXP):
9922       return fold_builtin_load_exponent (loc, arg0, arg1, type, /*ldexp=*/true);
9923     CASE_FLT_FN (BUILT_IN_SCALBN):
9924     CASE_FLT_FN (BUILT_IN_SCALBLN):
9925       return fold_builtin_load_exponent (loc, arg0, arg1,
9926                                          type, /*ldexp=*/false);
9927
9928     CASE_FLT_FN (BUILT_IN_FREXP):
9929       return fold_builtin_frexp (loc, arg0, arg1, type);
9930
9931     CASE_FLT_FN (BUILT_IN_MODF):
9932       return fold_builtin_modf (loc, arg0, arg1, type);
9933
9934     case BUILT_IN_BZERO:
9935       return fold_builtin_bzero (loc, arg0, arg1, ignore);
9936
9937     case BUILT_IN_FPUTS:
9938       return fold_builtin_fputs (loc, arg0, arg1, ignore, false, NULL_TREE);
9939
9940     case BUILT_IN_FPUTS_UNLOCKED:
9941       return fold_builtin_fputs (loc, arg0, arg1, ignore, true, NULL_TREE);
9942
9943     case BUILT_IN_STRSTR:
9944       return fold_builtin_strstr (loc, arg0, arg1, type);
9945
9946     case BUILT_IN_STRCAT:
9947       return fold_builtin_strcat (loc, arg0, arg1);
9948
9949     case BUILT_IN_STRSPN:
9950       return fold_builtin_strspn (loc, arg0, arg1);
9951
9952     case BUILT_IN_STRCSPN:
9953       return fold_builtin_strcspn (loc, arg0, arg1);
9954
9955     case BUILT_IN_STRCHR:
9956     case BUILT_IN_INDEX:
9957       return fold_builtin_strchr (loc, arg0, arg1, type);
9958
9959     case BUILT_IN_STRRCHR:
9960     case BUILT_IN_RINDEX:
9961       return fold_builtin_strrchr (loc, arg0, arg1, type);
9962
9963     case BUILT_IN_STRCPY:
9964       return fold_builtin_strcpy (loc, fndecl, arg0, arg1, NULL_TREE);
9965
9966     case BUILT_IN_STPCPY:
9967       if (ignore)
9968         {
9969           tree fn = implicit_built_in_decls[BUILT_IN_STRCPY];
9970           if (!fn)
9971             break;
9972
9973           return build_call_expr_loc (loc, fn, 2, arg0, arg1);
9974         }
9975       else
9976         return fold_builtin_stpcpy (loc, fndecl, arg0, arg1);
9977       break;
9978
9979     case BUILT_IN_STRCMP:
9980       return fold_builtin_strcmp (loc, arg0, arg1);
9981
9982     case BUILT_IN_STRPBRK:
9983       return fold_builtin_strpbrk (loc, arg0, arg1, type);
9984
9985     case BUILT_IN_EXPECT:
9986       return fold_builtin_expect (loc, arg0, arg1);
9987
9988     CASE_FLT_FN (BUILT_IN_POW):
9989       return fold_builtin_pow (loc, fndecl, arg0, arg1, type);
9990
9991     CASE_FLT_FN (BUILT_IN_POWI):
9992       return fold_builtin_powi (loc, fndecl, arg0, arg1, type);
9993
9994     CASE_FLT_FN (BUILT_IN_COPYSIGN):
9995       return fold_builtin_copysign (loc, fndecl, arg0, arg1, type);
9996
9997     CASE_FLT_FN (BUILT_IN_FMIN):
9998       return fold_builtin_fmin_fmax (loc, arg0, arg1, type, /*max=*/false);
9999
10000     CASE_FLT_FN (BUILT_IN_FMAX):
10001       return fold_builtin_fmin_fmax (loc, arg0, arg1, type, /*max=*/true);
10002
10003     case BUILT_IN_ISGREATER:
10004       return fold_builtin_unordered_cmp (loc, fndecl,
10005                                          arg0, arg1, UNLE_EXPR, LE_EXPR);
10006     case BUILT_IN_ISGREATEREQUAL:
10007       return fold_builtin_unordered_cmp (loc, fndecl,
10008                                          arg0, arg1, UNLT_EXPR, LT_EXPR);
10009     case BUILT_IN_ISLESS:
10010       return fold_builtin_unordered_cmp (loc, fndecl,
10011                                          arg0, arg1, UNGE_EXPR, GE_EXPR);
10012     case BUILT_IN_ISLESSEQUAL:
10013       return fold_builtin_unordered_cmp (loc, fndecl,
10014                                          arg0, arg1, UNGT_EXPR, GT_EXPR);
10015     case BUILT_IN_ISLESSGREATER:
10016       return fold_builtin_unordered_cmp (loc, fndecl,
10017                                          arg0, arg1, UNEQ_EXPR, EQ_EXPR);
10018     case BUILT_IN_ISUNORDERED:
10019       return fold_builtin_unordered_cmp (loc, fndecl,
10020                                          arg0, arg1, UNORDERED_EXPR,
10021                                          NOP_EXPR);
10022
10023       /* We do the folding for va_start in the expander.  */
10024     case BUILT_IN_VA_START:
10025       break;
10026
10027     case BUILT_IN_SPRINTF:
10028       return fold_builtin_sprintf (loc, arg0, arg1, NULL_TREE, ignore);
10029
10030     case BUILT_IN_OBJECT_SIZE:
10031       return fold_builtin_object_size (arg0, arg1);
10032
10033     case BUILT_IN_PRINTF:
10034     case BUILT_IN_PRINTF_UNLOCKED:
10035     case BUILT_IN_VPRINTF:
10036       return fold_builtin_printf (loc, fndecl, arg0, arg1, ignore, fcode);
10037
10038     case BUILT_IN_PRINTF_CHK:
10039     case BUILT_IN_VPRINTF_CHK:
10040       if (!validate_arg (arg0, INTEGER_TYPE)
10041           || TREE_SIDE_EFFECTS (arg0))
10042         return NULL_TREE;
10043       else
10044         return fold_builtin_printf (loc, fndecl,
10045                                     arg1, NULL_TREE, ignore, fcode);
10046     break;
10047
10048     case BUILT_IN_FPRINTF:
10049     case BUILT_IN_FPRINTF_UNLOCKED:
10050     case BUILT_IN_VFPRINTF:
10051       return fold_builtin_fprintf (loc, fndecl, arg0, arg1, NULL_TREE,
10052                                    ignore, fcode);
10053
10054     default:
10055       break;
10056     }
10057   return NULL_TREE;
10058 }
10059
10060 /* Fold a call to built-in function FNDECL with 3 arguments, ARG0, ARG1,
10061    and ARG2.  IGNORE is true if the result of the function call is ignored.
10062    This function returns NULL_TREE if no simplification was possible.  */
10063
10064 static tree
10065 fold_builtin_3 (location_t loc, tree fndecl,
10066                 tree arg0, tree arg1, tree arg2, bool ignore)
10067 {
10068   tree type = TREE_TYPE (TREE_TYPE (fndecl));
10069   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
10070   switch (fcode)
10071     {
10072
10073     CASE_FLT_FN (BUILT_IN_SINCOS):
10074       return fold_builtin_sincos (loc, arg0, arg1, arg2);
10075
10076     CASE_FLT_FN (BUILT_IN_FMA):
10077       return fold_builtin_fma (loc, arg0, arg1, arg2, type);
10078     break;
10079
10080     CASE_FLT_FN (BUILT_IN_REMQUO):
10081       if (validate_arg (arg0, REAL_TYPE)
10082           && validate_arg(arg1, REAL_TYPE)
10083           && validate_arg(arg2, POINTER_TYPE))
10084         return do_mpfr_remquo (arg0, arg1, arg2);
10085     break;
10086
10087     case BUILT_IN_MEMSET:
10088       return fold_builtin_memset (loc, arg0, arg1, arg2, type, ignore);
10089
10090     case BUILT_IN_BCOPY:
10091       return fold_builtin_memory_op (loc, arg1, arg0, arg2,
10092                                      void_type_node, true, /*endp=*/3);
10093
10094     case BUILT_IN_MEMCPY:
10095       return fold_builtin_memory_op (loc, arg0, arg1, arg2,
10096                                      type, ignore, /*endp=*/0);
10097
10098     case BUILT_IN_MEMPCPY:
10099       return fold_builtin_memory_op (loc, arg0, arg1, arg2,
10100                                      type, ignore, /*endp=*/1);
10101
10102     case BUILT_IN_MEMMOVE:
10103       return fold_builtin_memory_op (loc, arg0, arg1, arg2,
10104                                      type, ignore, /*endp=*/3);
10105
10106     case BUILT_IN_STRNCAT:
10107       return fold_builtin_strncat (loc, arg0, arg1, arg2);
10108
10109     case BUILT_IN_STRNCPY:
10110       return fold_builtin_strncpy (loc, fndecl, arg0, arg1, arg2, NULL_TREE);
10111
10112     case BUILT_IN_STRNCMP:
10113       return fold_builtin_strncmp (loc, arg0, arg1, arg2);
10114
10115     case BUILT_IN_MEMCHR:
10116       return fold_builtin_memchr (loc, arg0, arg1, arg2, type);
10117
10118     case BUILT_IN_BCMP:
10119     case BUILT_IN_MEMCMP:
10120       return fold_builtin_memcmp (loc, arg0, arg1, arg2);;
10121
10122     case BUILT_IN_SPRINTF:
10123       return fold_builtin_sprintf (loc, arg0, arg1, arg2, ignore);
10124
10125     case BUILT_IN_SNPRINTF:
10126       return fold_builtin_snprintf (loc, arg0, arg1, arg2, NULL_TREE, ignore);
10127
10128     case BUILT_IN_STRCPY_CHK:
10129     case BUILT_IN_STPCPY_CHK:
10130       return fold_builtin_stxcpy_chk (loc, fndecl, arg0, arg1, arg2, NULL_TREE,
10131                                       ignore, fcode);
10132
10133     case BUILT_IN_STRCAT_CHK:
10134       return fold_builtin_strcat_chk (loc, fndecl, arg0, arg1, arg2);
10135
10136     case BUILT_IN_PRINTF_CHK:
10137     case BUILT_IN_VPRINTF_CHK:
10138       if (!validate_arg (arg0, INTEGER_TYPE)
10139           || TREE_SIDE_EFFECTS (arg0))
10140         return NULL_TREE;
10141       else
10142         return fold_builtin_printf (loc, fndecl, arg1, arg2, ignore, fcode);
10143     break;
10144
10145     case BUILT_IN_FPRINTF:
10146     case BUILT_IN_FPRINTF_UNLOCKED:
10147     case BUILT_IN_VFPRINTF:
10148       return fold_builtin_fprintf (loc, fndecl, arg0, arg1, arg2,
10149                                    ignore, fcode);
10150
10151     case BUILT_IN_FPRINTF_CHK:
10152     case BUILT_IN_VFPRINTF_CHK:
10153       if (!validate_arg (arg1, INTEGER_TYPE)
10154           || TREE_SIDE_EFFECTS (arg1))
10155         return NULL_TREE;
10156       else
10157         return fold_builtin_fprintf (loc, fndecl, arg0, arg2, NULL_TREE,
10158                                      ignore, fcode);
10159
10160     default:
10161       break;
10162     }
10163   return NULL_TREE;
10164 }
10165
10166 /* Fold a call to built-in function FNDECL with 4 arguments, ARG0, ARG1,
10167    ARG2, and ARG3.  IGNORE is true if the result of the function call is
10168    ignored.  This function returns NULL_TREE if no simplification was
10169    possible.  */
10170
10171 static tree
10172 fold_builtin_4 (location_t loc, tree fndecl,
10173                 tree arg0, tree arg1, tree arg2, tree arg3, bool ignore)
10174 {
10175   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
10176
10177   switch (fcode)
10178     {
10179     case BUILT_IN_MEMCPY_CHK:
10180     case BUILT_IN_MEMPCPY_CHK:
10181     case BUILT_IN_MEMMOVE_CHK:
10182     case BUILT_IN_MEMSET_CHK:
10183       return fold_builtin_memory_chk (loc, fndecl, arg0, arg1, arg2, arg3,
10184                                       NULL_TREE, ignore,
10185                                       DECL_FUNCTION_CODE (fndecl));
10186
10187     case BUILT_IN_STRNCPY_CHK:
10188       return fold_builtin_strncpy_chk (loc, arg0, arg1, arg2, arg3, NULL_TREE);
10189
10190     case BUILT_IN_STRNCAT_CHK:
10191       return fold_builtin_strncat_chk (loc, fndecl, arg0, arg1, arg2, arg3);
10192
10193     case BUILT_IN_SNPRINTF:
10194       return fold_builtin_snprintf (loc, arg0, arg1, arg2, arg3, ignore);
10195
10196     case BUILT_IN_FPRINTF_CHK:
10197     case BUILT_IN_VFPRINTF_CHK:
10198       if (!validate_arg (arg1, INTEGER_TYPE)
10199           || TREE_SIDE_EFFECTS (arg1))
10200         return NULL_TREE;
10201       else
10202         return fold_builtin_fprintf (loc, fndecl, arg0, arg2, arg3,
10203                                      ignore, fcode);
10204     break;
10205
10206     default:
10207       break;
10208     }
10209   return NULL_TREE;
10210 }
10211
10212 /* Fold a call to built-in function FNDECL.  ARGS is an array of NARGS
10213     arguments, where NARGS <= 4.  IGNORE is true if the result of the
10214     function call is ignored.  This function returns NULL_TREE if no
10215     simplification was possible.  Note that this only folds builtins with
10216     fixed argument patterns.  Foldings that do varargs-to-varargs
10217     transformations, or that match calls with more than 4 arguments,
10218     need to be handled with fold_builtin_varargs instead.  */
10219
10220 #define MAX_ARGS_TO_FOLD_BUILTIN 4
10221
10222 static tree
10223 fold_builtin_n (location_t loc, tree fndecl, tree *args, int nargs, bool ignore)
10224 {
10225   tree ret = NULL_TREE;
10226
10227   switch (nargs)
10228     {
10229     case 0:
10230       ret = fold_builtin_0 (loc, fndecl, ignore);
10231       break;
10232     case 1:
10233       ret = fold_builtin_1 (loc, fndecl, args[0], ignore);
10234       break;
10235     case 2:
10236       ret = fold_builtin_2 (loc, fndecl, args[0], args[1], ignore);
10237       break;
10238     case 3:
10239       ret = fold_builtin_3 (loc, fndecl, args[0], args[1], args[2], ignore);
10240       break;
10241     case 4:
10242       ret = fold_builtin_4 (loc, fndecl, args[0], args[1], args[2], args[3],
10243                             ignore);
10244       break;
10245     default:
10246       break;
10247     }
10248   if (ret)
10249     {
10250       ret = build1 (NOP_EXPR, TREE_TYPE (ret), ret);
10251       SET_EXPR_LOCATION (ret, loc);
10252       TREE_NO_WARNING (ret) = 1;
10253       return ret;
10254     }
10255   return NULL_TREE;
10256 }
10257
10258 /* Builtins with folding operations that operate on "..." arguments
10259    need special handling; we need to store the arguments in a convenient
10260    data structure before attempting any folding.  Fortunately there are
10261    only a few builtins that fall into this category.  FNDECL is the
10262    function, EXP is the CALL_EXPR for the call, and IGNORE is true if the
10263    result of the function call is ignored.  */
10264
10265 static tree
10266 fold_builtin_varargs (location_t loc, tree fndecl, tree exp,
10267                       bool ignore ATTRIBUTE_UNUSED)
10268 {
10269   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
10270   tree ret = NULL_TREE;
10271
10272   switch (fcode)
10273     {
10274     case BUILT_IN_SPRINTF_CHK:
10275     case BUILT_IN_VSPRINTF_CHK:
10276       ret = fold_builtin_sprintf_chk (loc, exp, fcode);
10277       break;
10278
10279     case BUILT_IN_SNPRINTF_CHK:
10280     case BUILT_IN_VSNPRINTF_CHK:
10281       ret = fold_builtin_snprintf_chk (loc, exp, NULL_TREE, fcode);
10282       break;
10283
10284     case BUILT_IN_FPCLASSIFY:
10285       ret = fold_builtin_fpclassify (loc, exp);
10286       break;
10287
10288     default:
10289       break;
10290     }
10291   if (ret)
10292     {
10293       ret = build1 (NOP_EXPR, TREE_TYPE (ret), ret);
10294       SET_EXPR_LOCATION (ret, loc);
10295       TREE_NO_WARNING (ret) = 1;
10296       return ret;
10297     }
10298   return NULL_TREE;
10299 }
10300
10301 /* Return true if FNDECL shouldn't be folded right now.
10302    If a built-in function has an inline attribute always_inline
10303    wrapper, defer folding it after always_inline functions have
10304    been inlined, otherwise e.g. -D_FORTIFY_SOURCE checking
10305    might not be performed.  */
10306
10307 static bool
10308 avoid_folding_inline_builtin (tree fndecl)
10309 {
10310   return (DECL_DECLARED_INLINE_P (fndecl)
10311           && DECL_DISREGARD_INLINE_LIMITS (fndecl)
10312           && cfun
10313           && !cfun->always_inline_functions_inlined
10314           && lookup_attribute ("always_inline", DECL_ATTRIBUTES (fndecl)));
10315 }
10316
10317 /* A wrapper function for builtin folding that prevents warnings for
10318    "statement without effect" and the like, caused by removing the
10319    call node earlier than the warning is generated.  */
10320
10321 tree
10322 fold_call_expr (location_t loc, tree exp, bool ignore)
10323 {
10324   tree ret = NULL_TREE;
10325   tree fndecl = get_callee_fndecl (exp);
10326   if (fndecl
10327       && TREE_CODE (fndecl) == FUNCTION_DECL
10328       && DECL_BUILT_IN (fndecl)
10329       /* If CALL_EXPR_VA_ARG_PACK is set, the arguments aren't finalized
10330          yet.  Defer folding until we see all the arguments
10331          (after inlining).  */
10332       && !CALL_EXPR_VA_ARG_PACK (exp))
10333     {
10334       int nargs = call_expr_nargs (exp);
10335
10336       /* Before gimplification CALL_EXPR_VA_ARG_PACK is not set, but
10337          instead last argument is __builtin_va_arg_pack ().  Defer folding
10338          even in that case, until arguments are finalized.  */
10339       if (nargs && TREE_CODE (CALL_EXPR_ARG (exp, nargs - 1)) == CALL_EXPR)
10340         {
10341           tree fndecl2 = get_callee_fndecl (CALL_EXPR_ARG (exp, nargs - 1));
10342           if (fndecl2
10343               && TREE_CODE (fndecl2) == FUNCTION_DECL
10344               && DECL_BUILT_IN_CLASS (fndecl2) == BUILT_IN_NORMAL
10345               && DECL_FUNCTION_CODE (fndecl2) == BUILT_IN_VA_ARG_PACK)
10346             return NULL_TREE;
10347         }
10348
10349       if (avoid_folding_inline_builtin (fndecl))
10350         return NULL_TREE;
10351
10352       if (DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_MD)
10353         return targetm.fold_builtin (fndecl, call_expr_nargs (exp),
10354                                      CALL_EXPR_ARGP (exp), ignore);
10355       else
10356         {
10357           if (nargs <= MAX_ARGS_TO_FOLD_BUILTIN)
10358             {
10359               tree *args = CALL_EXPR_ARGP (exp);
10360               ret = fold_builtin_n (loc, fndecl, args, nargs, ignore);
10361             }
10362           if (!ret)
10363             ret = fold_builtin_varargs (loc, fndecl, exp, ignore);
10364           if (ret)
10365             return ret;
10366         }
10367     }
10368   return NULL_TREE;
10369 }
10370
10371 /* Conveniently construct a function call expression.  FNDECL names the
10372    function to be called and N arguments are passed in the array
10373    ARGARRAY.  */
10374
10375 tree
10376 build_call_expr_loc_array (location_t loc, tree fndecl, int n, tree *argarray)
10377 {
10378   tree fntype = TREE_TYPE (fndecl);
10379   tree fn = build1 (ADDR_EXPR, build_pointer_type (fntype), fndecl);
10380  
10381   return fold_builtin_call_array (loc, TREE_TYPE (fntype), fn, n, argarray);
10382 }
10383
10384 /* Conveniently construct a function call expression.  FNDECL names the
10385    function to be called and the arguments are passed in the vector
10386    VEC.  */
10387
10388 tree
10389 build_call_expr_loc_vec (location_t loc, tree fndecl, VEC(tree,gc) *vec)
10390 {
10391   return build_call_expr_loc_array (loc, fndecl, VEC_length (tree, vec),
10392                                     VEC_address (tree, vec));
10393 }
10394
10395
10396 /* Conveniently construct a function call expression.  FNDECL names the
10397    function to be called, N is the number of arguments, and the "..."
10398    parameters are the argument expressions.  */
10399
10400 tree
10401 build_call_expr_loc (location_t loc, tree fndecl, int n, ...)
10402 {
10403   va_list ap;
10404   tree *argarray = XALLOCAVEC (tree, n);
10405   int i;
10406
10407   va_start (ap, n);
10408   for (i = 0; i < n; i++)
10409     argarray[i] = va_arg (ap, tree);
10410   va_end (ap);
10411   return build_call_expr_loc_array (loc, fndecl, n, argarray);
10412 }
10413
10414 /* Like build_call_expr_loc (UNKNOWN_LOCATION, ...).  Duplicated because
10415    varargs macros aren't supported by all bootstrap compilers.  */
10416
10417 tree
10418 build_call_expr (tree fndecl, int n, ...)
10419 {
10420   va_list ap;
10421   tree *argarray = XALLOCAVEC (tree, n);
10422   int i;
10423
10424   va_start (ap, n);
10425   for (i = 0; i < n; i++)
10426     argarray[i] = va_arg (ap, tree);
10427   va_end (ap);
10428   return build_call_expr_loc_array (UNKNOWN_LOCATION, fndecl, n, argarray);
10429 }
10430
10431 /* Construct a CALL_EXPR with type TYPE with FN as the function expression.
10432    N arguments are passed in the array ARGARRAY.  */
10433
10434 tree
10435 fold_builtin_call_array (location_t loc, tree type,
10436                          tree fn,
10437                          int n,
10438                          tree *argarray)
10439 {
10440   tree ret = NULL_TREE;
10441    tree exp;
10442
10443   if (TREE_CODE (fn) == ADDR_EXPR)
10444   {
10445     tree fndecl = TREE_OPERAND (fn, 0);
10446     if (TREE_CODE (fndecl) == FUNCTION_DECL
10447         && DECL_BUILT_IN (fndecl))
10448       {
10449         /* If last argument is __builtin_va_arg_pack (), arguments to this
10450            function are not finalized yet.  Defer folding until they are.  */
10451         if (n && TREE_CODE (argarray[n - 1]) == CALL_EXPR)
10452           {
10453             tree fndecl2 = get_callee_fndecl (argarray[n - 1]);
10454             if (fndecl2
10455                 && TREE_CODE (fndecl2) == FUNCTION_DECL
10456                 && DECL_BUILT_IN_CLASS (fndecl2) == BUILT_IN_NORMAL
10457                 && DECL_FUNCTION_CODE (fndecl2) == BUILT_IN_VA_ARG_PACK)
10458               return build_call_array_loc (loc, type, fn, n, argarray);
10459           }
10460         if (avoid_folding_inline_builtin (fndecl))
10461           return build_call_array_loc (loc, type, fn, n, argarray);
10462         if (DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_MD)
10463           {
10464             ret = targetm.fold_builtin (fndecl, n, argarray, false);
10465             if (ret)
10466               return ret;
10467
10468             return build_call_array_loc (loc, type, fn, n, argarray);
10469           }
10470         else if (n <= MAX_ARGS_TO_FOLD_BUILTIN)
10471           {
10472             /* First try the transformations that don't require consing up
10473                an exp.  */
10474             ret = fold_builtin_n (loc, fndecl, argarray, n, false);
10475             if (ret)
10476               return ret;
10477           }
10478
10479         /* If we got this far, we need to build an exp.  */
10480         exp = build_call_array_loc (loc, type, fn, n, argarray);
10481         ret = fold_builtin_varargs (loc, fndecl, exp, false);
10482         return ret ? ret : exp;
10483       }
10484   }
10485
10486   return build_call_array_loc (loc, type, fn, n, argarray);
10487 }
10488
10489 /* Construct a new CALL_EXPR to FNDECL using the tail of the argument
10490    list ARGS along with N new arguments in NEWARGS.  SKIP is the number
10491    of arguments in ARGS to be omitted.  OLDNARGS is the number of
10492    elements in ARGS.  */
10493
10494 static tree
10495 rewrite_call_expr_valist (location_t loc, int oldnargs, tree *args,
10496                           int skip, tree fndecl, int n, va_list newargs)
10497 {
10498   int nargs = oldnargs - skip + n;
10499   tree *buffer;
10500
10501   if (n > 0)
10502     {
10503       int i, j;
10504
10505       buffer = XALLOCAVEC (tree, nargs);
10506       for (i = 0; i < n; i++)
10507         buffer[i] = va_arg (newargs, tree);
10508       for (j = skip; j < oldnargs; j++, i++)
10509         buffer[i] = args[j];
10510     }
10511   else
10512     buffer = args + skip;
10513
10514   return build_call_expr_loc_array (loc, fndecl, nargs, buffer);
10515 }
10516
10517 /* Construct a new CALL_EXPR to FNDECL using the tail of the argument
10518    list ARGS along with N new arguments specified as the "..."
10519    parameters.  SKIP is the number of arguments in ARGS to be omitted.
10520    OLDNARGS is the number of elements in ARGS.  */
10521
10522 static tree
10523 rewrite_call_expr_array (location_t loc, int oldnargs, tree *args,
10524                          int skip, tree fndecl, int n, ...)
10525 {
10526   va_list ap;
10527   tree t;
10528
10529   va_start (ap, n);
10530   t = rewrite_call_expr_valist (loc, oldnargs, args, skip, fndecl, n, ap);
10531   va_end (ap);
10532
10533   return t;
10534 }
10535
10536 /* Construct a new CALL_EXPR using the tail of the argument list of EXP
10537    along with N new arguments specified as the "..." parameters.  SKIP
10538    is the number of arguments in EXP to be omitted.  This function is used
10539    to do varargs-to-varargs transformations.  */
10540
10541 static tree
10542 rewrite_call_expr (location_t loc, tree exp, int skip, tree fndecl, int n, ...)
10543 {
10544   va_list ap;
10545   tree t;
10546
10547   va_start (ap, n);
10548   t = rewrite_call_expr_valist (loc, call_expr_nargs (exp),
10549                                 CALL_EXPR_ARGP (exp), skip, fndecl, n, ap);
10550   va_end (ap);
10551
10552   return t;
10553 }
10554
10555 /* Validate a single argument ARG against a tree code CODE representing
10556    a type.  */
10557
10558 static bool
10559 validate_arg (const_tree arg, enum tree_code code)
10560 {
10561   if (!arg)
10562     return false;
10563   else if (code == POINTER_TYPE)
10564     return POINTER_TYPE_P (TREE_TYPE (arg));
10565   else if (code == INTEGER_TYPE)
10566     return INTEGRAL_TYPE_P (TREE_TYPE (arg));
10567   return code == TREE_CODE (TREE_TYPE (arg));
10568 }
10569
10570 /* This function validates the types of a function call argument list
10571    against a specified list of tree_codes.  If the last specifier is a 0,
10572    that represents an ellipses, otherwise the last specifier must be a
10573    VOID_TYPE.
10574
10575    This is the GIMPLE version of validate_arglist.  Eventually we want to
10576    completely convert builtins.c to work from GIMPLEs and the tree based
10577    validate_arglist will then be removed.  */
10578
10579 bool
10580 validate_gimple_arglist (const_gimple call, ...)
10581 {
10582   enum tree_code code;
10583   bool res = 0;
10584   va_list ap;
10585   const_tree arg;
10586   size_t i;
10587
10588   va_start (ap, call);
10589   i = 0;
10590
10591   do
10592     {
10593       code = (enum tree_code) va_arg (ap, int);
10594       switch (code)
10595         {
10596         case 0:
10597           /* This signifies an ellipses, any further arguments are all ok.  */
10598           res = true;
10599           goto end;
10600         case VOID_TYPE:
10601           /* This signifies an endlink, if no arguments remain, return
10602              true, otherwise return false.  */
10603           res = (i == gimple_call_num_args (call));
10604           goto end;
10605         default:
10606           /* If no parameters remain or the parameter's code does not
10607              match the specified code, return false.  Otherwise continue
10608              checking any remaining arguments.  */
10609           arg = gimple_call_arg (call, i++);
10610           if (!validate_arg (arg, code))
10611             goto end;
10612           break;
10613         }
10614     }
10615   while (1);
10616
10617   /* We need gotos here since we can only have one VA_CLOSE in a
10618      function.  */
10619  end: ;
10620   va_end (ap);
10621
10622   return res;
10623 }
10624
10625 /* This function validates the types of a function call argument list
10626    against a specified list of tree_codes.  If the last specifier is a 0,
10627    that represents an ellipses, otherwise the last specifier must be a
10628    VOID_TYPE.  */
10629
10630 bool
10631 validate_arglist (const_tree callexpr, ...)
10632 {
10633   enum tree_code code;
10634   bool res = 0;
10635   va_list ap;
10636   const_call_expr_arg_iterator iter;
10637   const_tree arg;
10638
10639   va_start (ap, callexpr);
10640   init_const_call_expr_arg_iterator (callexpr, &iter);
10641
10642   do
10643     {
10644       code = (enum tree_code) va_arg (ap, int);
10645       switch (code)
10646         {
10647         case 0:
10648           /* This signifies an ellipses, any further arguments are all ok.  */
10649           res = true;
10650           goto end;
10651         case VOID_TYPE:
10652           /* This signifies an endlink, if no arguments remain, return
10653              true, otherwise return false.  */
10654           res = !more_const_call_expr_args_p (&iter);
10655           goto end;
10656         default:
10657           /* If no parameters remain or the parameter's code does not
10658              match the specified code, return false.  Otherwise continue
10659              checking any remaining arguments.  */
10660           arg = next_const_call_expr_arg (&iter);
10661           if (!validate_arg (arg, code))
10662             goto end;
10663           break;
10664         }
10665     }
10666   while (1);
10667
10668   /* We need gotos here since we can only have one VA_CLOSE in a
10669      function.  */
10670  end: ;
10671   va_end (ap);
10672
10673   return res;
10674 }
10675
10676 /* Default target-specific builtin expander that does nothing.  */
10677
10678 rtx
10679 default_expand_builtin (tree exp ATTRIBUTE_UNUSED,
10680                         rtx target ATTRIBUTE_UNUSED,
10681                         rtx subtarget ATTRIBUTE_UNUSED,
10682                         enum machine_mode mode ATTRIBUTE_UNUSED,
10683                         int ignore ATTRIBUTE_UNUSED)
10684 {
10685   return NULL_RTX;
10686 }
10687
10688 /* Returns true is EXP represents data that would potentially reside
10689    in a readonly section.  */
10690
10691 static bool
10692 readonly_data_expr (tree exp)
10693 {
10694   STRIP_NOPS (exp);
10695
10696   if (TREE_CODE (exp) != ADDR_EXPR)
10697     return false;
10698
10699   exp = get_base_address (TREE_OPERAND (exp, 0));
10700   if (!exp)
10701     return false;
10702
10703   /* Make sure we call decl_readonly_section only for trees it
10704      can handle (since it returns true for everything it doesn't
10705      understand).  */
10706   if (TREE_CODE (exp) == STRING_CST
10707       || TREE_CODE (exp) == CONSTRUCTOR
10708       || (TREE_CODE (exp) == VAR_DECL && TREE_STATIC (exp)))
10709     return decl_readonly_section (exp, 0);
10710   else
10711     return false;
10712 }
10713
10714 /* Simplify a call to the strstr builtin.  S1 and S2 are the arguments
10715    to the call, and TYPE is its return type.
10716
10717    Return NULL_TREE if no simplification was possible, otherwise return the
10718    simplified form of the call as a tree.
10719
10720    The simplified form may be a constant or other expression which
10721    computes the same value, but in a more efficient manner (including
10722    calls to other builtin functions).
10723
10724    The call may contain arguments which need to be evaluated, but
10725    which are not useful to determine the result of the call.  In
10726    this case we return a chain of COMPOUND_EXPRs.  The LHS of each
10727    COMPOUND_EXPR will be an argument which must be evaluated.
10728    COMPOUND_EXPRs are chained through their RHS.  The RHS of the last
10729    COMPOUND_EXPR in the chain will contain the tree for the simplified
10730    form of the builtin function call.  */
10731
10732 static tree
10733 fold_builtin_strstr (location_t loc, tree s1, tree s2, tree type)
10734 {
10735   if (!validate_arg (s1, POINTER_TYPE)
10736       || !validate_arg (s2, POINTER_TYPE))
10737     return NULL_TREE;
10738   else
10739     {
10740       tree fn;
10741       const char *p1, *p2;
10742
10743       p2 = c_getstr (s2);
10744       if (p2 == NULL)
10745         return NULL_TREE;
10746
10747       p1 = c_getstr (s1);
10748       if (p1 != NULL)
10749         {
10750           const char *r = strstr (p1, p2);
10751           tree tem;
10752
10753           if (r == NULL)
10754             return build_int_cst (TREE_TYPE (s1), 0);
10755
10756           /* Return an offset into the constant string argument.  */
10757           tem = fold_build2_loc (loc, POINTER_PLUS_EXPR, TREE_TYPE (s1),
10758                              s1, size_int (r - p1));
10759           return fold_convert_loc (loc, type, tem);
10760         }
10761
10762       /* The argument is const char *, and the result is char *, so we need
10763          a type conversion here to avoid a warning.  */
10764       if (p2[0] == '\0')
10765         return fold_convert_loc (loc, type, s1);
10766
10767       if (p2[1] != '\0')
10768         return NULL_TREE;
10769
10770       fn = implicit_built_in_decls[BUILT_IN_STRCHR];
10771       if (!fn)
10772         return NULL_TREE;
10773
10774       /* New argument list transforming strstr(s1, s2) to
10775          strchr(s1, s2[0]).  */
10776       return build_call_expr_loc (loc, fn, 2, s1,
10777                                   build_int_cst (integer_type_node, p2[0]));
10778     }
10779 }
10780
10781 /* Simplify a call to the strchr builtin.  S1 and S2 are the arguments to
10782    the call, and TYPE is its return type.
10783
10784    Return NULL_TREE if no simplification was possible, otherwise return the
10785    simplified form of the call as a tree.
10786
10787    The simplified form may be a constant or other expression which
10788    computes the same value, but in a more efficient manner (including
10789    calls to other builtin functions).
10790
10791    The call may contain arguments which need to be evaluated, but
10792    which are not useful to determine the result of the call.  In
10793    this case we return a chain of COMPOUND_EXPRs.  The LHS of each
10794    COMPOUND_EXPR will be an argument which must be evaluated.
10795    COMPOUND_EXPRs are chained through their RHS.  The RHS of the last
10796    COMPOUND_EXPR in the chain will contain the tree for the simplified
10797    form of the builtin function call.  */
10798
10799 static tree
10800 fold_builtin_strchr (location_t loc, tree s1, tree s2, tree type)
10801 {
10802   if (!validate_arg (s1, POINTER_TYPE)
10803       || !validate_arg (s2, INTEGER_TYPE))
10804     return NULL_TREE;
10805   else
10806     {
10807       const char *p1;
10808
10809       if (TREE_CODE (s2) != INTEGER_CST)
10810         return NULL_TREE;
10811
10812       p1 = c_getstr (s1);
10813       if (p1 != NULL)
10814         {
10815           char c;
10816           const char *r;
10817           tree tem;
10818
10819           if (target_char_cast (s2, &c))
10820             return NULL_TREE;
10821
10822           r = strchr (p1, c);
10823
10824           if (r == NULL)
10825             return build_int_cst (TREE_TYPE (s1), 0);
10826
10827           /* Return an offset into the constant string argument.  */
10828           tem = fold_build2_loc (loc, POINTER_PLUS_EXPR, TREE_TYPE (s1),
10829                              s1, size_int (r - p1));
10830           return fold_convert_loc (loc, type, tem);
10831         }
10832       return NULL_TREE;
10833     }
10834 }
10835
10836 /* Simplify a call to the strrchr builtin.  S1 and S2 are the arguments to
10837    the call, and TYPE is its return type.
10838
10839    Return NULL_TREE if no simplification was possible, otherwise return the
10840    simplified form of the call as a tree.
10841
10842    The simplified form may be a constant or other expression which
10843    computes the same value, but in a more efficient manner (including
10844    calls to other builtin functions).
10845
10846    The call may contain arguments which need to be evaluated, but
10847    which are not useful to determine the result of the call.  In
10848    this case we return a chain of COMPOUND_EXPRs.  The LHS of each
10849    COMPOUND_EXPR will be an argument which must be evaluated.
10850    COMPOUND_EXPRs are chained through their RHS.  The RHS of the last
10851    COMPOUND_EXPR in the chain will contain the tree for the simplified
10852    form of the builtin function call.  */
10853
10854 static tree
10855 fold_builtin_strrchr (location_t loc, tree s1, tree s2, tree type)
10856 {
10857   if (!validate_arg (s1, POINTER_TYPE)
10858       || !validate_arg (s2, INTEGER_TYPE))
10859     return NULL_TREE;
10860   else
10861     {
10862       tree fn;
10863       const char *p1;
10864
10865       if (TREE_CODE (s2) != INTEGER_CST)
10866         return NULL_TREE;
10867
10868       p1 = c_getstr (s1);
10869       if (p1 != NULL)
10870         {
10871           char c;
10872           const char *r;
10873           tree tem;
10874
10875           if (target_char_cast (s2, &c))
10876             return NULL_TREE;
10877
10878           r = strrchr (p1, c);
10879
10880           if (r == NULL)
10881             return build_int_cst (TREE_TYPE (s1), 0);
10882
10883           /* Return an offset into the constant string argument.  */
10884           tem = fold_build2_loc (loc, POINTER_PLUS_EXPR, TREE_TYPE (s1),
10885                              s1, size_int (r - p1));
10886           return fold_convert_loc (loc, type, tem);
10887         }
10888
10889       if (! integer_zerop (s2))
10890         return NULL_TREE;
10891
10892       fn = implicit_built_in_decls[BUILT_IN_STRCHR];
10893       if (!fn)
10894         return NULL_TREE;
10895
10896       /* Transform strrchr(s1, '\0') to strchr(s1, '\0').  */
10897       return build_call_expr_loc (loc, fn, 2, s1, s2);
10898     }
10899 }
10900
10901 /* Simplify a call to the strpbrk builtin.  S1 and S2 are the arguments
10902    to the call, and TYPE is its return type.
10903
10904    Return NULL_TREE if no simplification was possible, otherwise return the
10905    simplified form of the call as a tree.
10906
10907    The simplified form may be a constant or other expression which
10908    computes the same value, but in a more efficient manner (including
10909    calls to other builtin functions).
10910
10911    The call may contain arguments which need to be evaluated, but
10912    which are not useful to determine the result of the call.  In
10913    this case we return a chain of COMPOUND_EXPRs.  The LHS of each
10914    COMPOUND_EXPR will be an argument which must be evaluated.
10915    COMPOUND_EXPRs are chained through their RHS.  The RHS of the last
10916    COMPOUND_EXPR in the chain will contain the tree for the simplified
10917    form of the builtin function call.  */
10918
10919 static tree
10920 fold_builtin_strpbrk (location_t loc, tree s1, tree s2, tree type)
10921 {
10922   if (!validate_arg (s1, POINTER_TYPE)
10923       || !validate_arg (s2, POINTER_TYPE))
10924     return NULL_TREE;
10925   else
10926     {
10927       tree fn;
10928       const char *p1, *p2;
10929
10930       p2 = c_getstr (s2);
10931       if (p2 == NULL)
10932         return NULL_TREE;
10933
10934       p1 = c_getstr (s1);
10935       if (p1 != NULL)
10936         {
10937           const char *r = strpbrk (p1, p2);
10938           tree tem;
10939
10940           if (r == NULL)
10941             return build_int_cst (TREE_TYPE (s1), 0);
10942
10943           /* Return an offset into the constant string argument.  */
10944           tem = fold_build2_loc (loc, POINTER_PLUS_EXPR, TREE_TYPE (s1),
10945                              s1, size_int (r - p1));
10946           return fold_convert_loc (loc, type, tem);
10947         }
10948
10949       if (p2[0] == '\0')
10950         /* strpbrk(x, "") == NULL.
10951            Evaluate and ignore s1 in case it had side-effects.  */
10952         return omit_one_operand_loc (loc, TREE_TYPE (s1), integer_zero_node, s1);
10953
10954       if (p2[1] != '\0')
10955         return NULL_TREE;  /* Really call strpbrk.  */
10956
10957       fn = implicit_built_in_decls[BUILT_IN_STRCHR];
10958       if (!fn)
10959         return NULL_TREE;
10960
10961       /* New argument list transforming strpbrk(s1, s2) to
10962          strchr(s1, s2[0]).  */
10963       return build_call_expr_loc (loc, fn, 2, s1,
10964                                   build_int_cst (integer_type_node, p2[0]));
10965     }
10966 }
10967
10968 /* Simplify a call to the strcat builtin.  DST and SRC are the arguments
10969    to the call.
10970
10971    Return NULL_TREE if no simplification was possible, otherwise return the
10972    simplified form of the call as a tree.
10973
10974    The simplified form may be a constant or other expression which
10975    computes the same value, but in a more efficient manner (including
10976    calls to other builtin functions).
10977
10978    The call may contain arguments which need to be evaluated, but
10979    which are not useful to determine the result of the call.  In
10980    this case we return a chain of COMPOUND_EXPRs.  The LHS of each
10981    COMPOUND_EXPR will be an argument which must be evaluated.
10982    COMPOUND_EXPRs are chained through their RHS.  The RHS of the last
10983    COMPOUND_EXPR in the chain will contain the tree for the simplified
10984    form of the builtin function call.  */
10985
10986 static tree
10987 fold_builtin_strcat (location_t loc ATTRIBUTE_UNUSED, tree dst, tree src)
10988 {
10989   if (!validate_arg (dst, POINTER_TYPE)
10990       || !validate_arg (src, POINTER_TYPE))
10991     return NULL_TREE;
10992   else
10993     {
10994       const char *p = c_getstr (src);
10995
10996       /* If the string length is zero, return the dst parameter.  */
10997       if (p && *p == '\0')
10998         return dst;
10999
11000       if (optimize_insn_for_speed_p ())
11001         {
11002           /* See if we can store by pieces into (dst + strlen(dst)).  */
11003           tree newdst, call;
11004           tree strlen_fn = implicit_built_in_decls[BUILT_IN_STRLEN];
11005           tree strcpy_fn = implicit_built_in_decls[BUILT_IN_STRCPY];
11006
11007           if (!strlen_fn || !strcpy_fn)
11008             return NULL_TREE;
11009
11010           /* If we don't have a movstr we don't want to emit an strcpy
11011              call.  We have to do that if the length of the source string
11012              isn't computable (in that case we can use memcpy probably
11013              later expanding to a sequence of mov instructions).  If we
11014              have movstr instructions we can emit strcpy calls.  */
11015           if (!HAVE_movstr)
11016             {
11017               tree len = c_strlen (src, 1);
11018               if (! len || TREE_SIDE_EFFECTS (len))
11019                 return NULL_TREE;
11020             }
11021
11022           /* Stabilize the argument list.  */
11023           dst = builtin_save_expr (dst);
11024
11025           /* Create strlen (dst).  */
11026           newdst = build_call_expr_loc (loc, strlen_fn, 1, dst);
11027           /* Create (dst p+ strlen (dst)).  */
11028
11029           newdst = fold_build2_loc (loc, POINTER_PLUS_EXPR,
11030                                 TREE_TYPE (dst), dst, newdst);
11031           newdst = builtin_save_expr (newdst);
11032
11033           call = build_call_expr_loc (loc, strcpy_fn, 2, newdst, src);
11034           return build2 (COMPOUND_EXPR, TREE_TYPE (dst), call, dst);
11035         }
11036       return NULL_TREE;
11037     }
11038 }
11039
11040 /* Simplify a call to the strncat builtin.  DST, SRC, and LEN are the
11041    arguments to the call.
11042
11043    Return NULL_TREE if no simplification was possible, otherwise return the
11044    simplified form of the call as a tree.
11045
11046    The simplified form may be a constant or other expression which
11047    computes the same value, but in a more efficient manner (including
11048    calls to other builtin functions).
11049
11050    The call may contain arguments which need to be evaluated, but
11051    which are not useful to determine the result of the call.  In
11052    this case we return a chain of COMPOUND_EXPRs.  The LHS of each
11053    COMPOUND_EXPR will be an argument which must be evaluated.
11054    COMPOUND_EXPRs are chained through their RHS.  The RHS of the last
11055    COMPOUND_EXPR in the chain will contain the tree for the simplified
11056    form of the builtin function call.  */
11057
11058 static tree
11059 fold_builtin_strncat (location_t loc, tree dst, tree src, tree len)
11060 {
11061   if (!validate_arg (dst, POINTER_TYPE)
11062       || !validate_arg (src, POINTER_TYPE)
11063       || !validate_arg (len, INTEGER_TYPE))
11064     return NULL_TREE;
11065   else
11066     {
11067       const char *p = c_getstr (src);
11068
11069       /* If the requested length is zero, or the src parameter string
11070          length is zero, return the dst parameter.  */
11071       if (integer_zerop (len) || (p && *p == '\0'))
11072         return omit_two_operands_loc (loc, TREE_TYPE (dst), dst, src, len);
11073
11074       /* If the requested len is greater than or equal to the string
11075          length, call strcat.  */
11076       if (TREE_CODE (len) == INTEGER_CST && p
11077           && compare_tree_int (len, strlen (p)) >= 0)
11078         {
11079           tree fn = implicit_built_in_decls[BUILT_IN_STRCAT];
11080
11081           /* If the replacement _DECL isn't initialized, don't do the
11082              transformation.  */
11083           if (!fn)
11084             return NULL_TREE;
11085
11086           return build_call_expr_loc (loc, fn, 2, dst, src);
11087         }
11088       return NULL_TREE;
11089     }
11090 }
11091
11092 /* Simplify a call to the strspn builtin.  S1 and S2 are the arguments
11093    to the call.
11094
11095    Return NULL_TREE if no simplification was possible, otherwise return the
11096    simplified form of the call as a tree.
11097
11098    The simplified form may be a constant or other expression which
11099    computes the same value, but in a more efficient manner (including
11100    calls to other builtin functions).
11101
11102    The call may contain arguments which need to be evaluated, but
11103    which are not useful to determine the result of the call.  In
11104    this case we return a chain of COMPOUND_EXPRs.  The LHS of each
11105    COMPOUND_EXPR will be an argument which must be evaluated.
11106    COMPOUND_EXPRs are chained through their RHS.  The RHS of the last
11107    COMPOUND_EXPR in the chain will contain the tree for the simplified
11108    form of the builtin function call.  */
11109
11110 static tree
11111 fold_builtin_strspn (location_t loc, tree s1, tree s2)
11112 {
11113   if (!validate_arg (s1, POINTER_TYPE)
11114       || !validate_arg (s2, POINTER_TYPE))
11115     return NULL_TREE;
11116   else
11117     {
11118       const char *p1 = c_getstr (s1), *p2 = c_getstr (s2);
11119
11120       /* If both arguments are constants, evaluate at compile-time.  */
11121       if (p1 && p2)
11122         {
11123           const size_t r = strspn (p1, p2);
11124           return size_int (r);
11125         }
11126
11127       /* If either argument is "", return NULL_TREE.  */
11128       if ((p1 && *p1 == '\0') || (p2 && *p2 == '\0'))
11129         /* Evaluate and ignore both arguments in case either one has
11130            side-effects.  */
11131         return omit_two_operands_loc (loc, size_type_node, size_zero_node,
11132                                   s1, s2);
11133       return NULL_TREE;
11134     }
11135 }
11136
11137 /* Simplify a call to the strcspn builtin.  S1 and S2 are the arguments
11138    to the call.
11139
11140    Return NULL_TREE if no simplification was possible, otherwise return the
11141    simplified form of the call as a tree.
11142
11143    The simplified form may be a constant or other expression which
11144    computes the same value, but in a more efficient manner (including
11145    calls to other builtin functions).
11146
11147    The call may contain arguments which need to be evaluated, but
11148    which are not useful to determine the result of the call.  In
11149    this case we return a chain of COMPOUND_EXPRs.  The LHS of each
11150    COMPOUND_EXPR will be an argument which must be evaluated.
11151    COMPOUND_EXPRs are chained through their RHS.  The RHS of the last
11152    COMPOUND_EXPR in the chain will contain the tree for the simplified
11153    form of the builtin function call.  */
11154
11155 static tree
11156 fold_builtin_strcspn (location_t loc, tree s1, tree s2)
11157 {
11158   if (!validate_arg (s1, POINTER_TYPE)
11159       || !validate_arg (s2, POINTER_TYPE))
11160     return NULL_TREE;
11161   else
11162     {
11163       const char *p1 = c_getstr (s1), *p2 = c_getstr (s2);
11164
11165       /* If both arguments are constants, evaluate at compile-time.  */
11166       if (p1 && p2)
11167         {
11168           const size_t r = strcspn (p1, p2);
11169           return size_int (r);
11170         }
11171
11172       /* If the first argument is "", return NULL_TREE.  */
11173       if (p1 && *p1 == '\0')
11174         {
11175           /* Evaluate and ignore argument s2 in case it has
11176              side-effects.  */
11177           return omit_one_operand_loc (loc, size_type_node,
11178                                    size_zero_node, s2);
11179         }
11180
11181       /* If the second argument is "", return __builtin_strlen(s1).  */
11182       if (p2 && *p2 == '\0')
11183         {
11184           tree fn = implicit_built_in_decls[BUILT_IN_STRLEN];
11185
11186           /* If the replacement _DECL isn't initialized, don't do the
11187              transformation.  */
11188           if (!fn)
11189             return NULL_TREE;
11190
11191           return build_call_expr_loc (loc, fn, 1, s1);
11192         }
11193       return NULL_TREE;
11194     }
11195 }
11196
11197 /* Fold a call to the fputs builtin.  ARG0 and ARG1 are the arguments
11198    to the call.  IGNORE is true if the value returned
11199    by the builtin will be ignored.  UNLOCKED is true is true if this
11200    actually a call to fputs_unlocked.  If LEN in non-NULL, it represents
11201    the known length of the string.  Return NULL_TREE if no simplification
11202    was possible.  */
11203
11204 tree
11205 fold_builtin_fputs (location_t loc, tree arg0, tree arg1,
11206                     bool ignore, bool unlocked, tree len)
11207 {
11208   /* If we're using an unlocked function, assume the other unlocked
11209      functions exist explicitly.  */
11210   tree const fn_fputc = unlocked ? built_in_decls[BUILT_IN_FPUTC_UNLOCKED]
11211     : implicit_built_in_decls[BUILT_IN_FPUTC];
11212   tree const fn_fwrite = unlocked ? built_in_decls[BUILT_IN_FWRITE_UNLOCKED]
11213     : implicit_built_in_decls[BUILT_IN_FWRITE];
11214
11215   /* If the return value is used, don't do the transformation.  */
11216   if (!ignore)
11217     return NULL_TREE;
11218
11219   /* Verify the arguments in the original call.  */
11220   if (!validate_arg (arg0, POINTER_TYPE)
11221       || !validate_arg (arg1, POINTER_TYPE))
11222     return NULL_TREE;
11223
11224   if (! len)
11225     len = c_strlen (arg0, 0);
11226
11227   /* Get the length of the string passed to fputs.  If the length
11228      can't be determined, punt.  */
11229   if (!len
11230       || TREE_CODE (len) != INTEGER_CST)
11231     return NULL_TREE;
11232
11233   switch (compare_tree_int (len, 1))
11234     {
11235     case -1: /* length is 0, delete the call entirely .  */
11236       return omit_one_operand_loc (loc, integer_type_node,
11237                                integer_zero_node, arg1);;
11238
11239     case 0: /* length is 1, call fputc.  */
11240       {
11241         const char *p = c_getstr (arg0);
11242
11243         if (p != NULL)
11244           {
11245             if (fn_fputc)
11246               return build_call_expr_loc (loc, fn_fputc, 2,
11247                                           build_int_cst
11248                                             (integer_type_node, p[0]), arg1);
11249             else
11250               return NULL_TREE;
11251           }
11252       }
11253       /* FALLTHROUGH */
11254     case 1: /* length is greater than 1, call fwrite.  */
11255       {
11256         /* If optimizing for size keep fputs.  */
11257         if (optimize_function_for_size_p (cfun))
11258           return NULL_TREE;
11259         /* New argument list transforming fputs(string, stream) to
11260            fwrite(string, 1, len, stream).  */
11261         if (fn_fwrite)
11262           return build_call_expr_loc (loc, fn_fwrite, 4, arg0,
11263                                   size_one_node, len, arg1);
11264         else
11265           return NULL_TREE;
11266       }
11267     default:
11268       gcc_unreachable ();
11269     }
11270   return NULL_TREE;
11271 }
11272
11273 /* Fold the next_arg or va_start call EXP. Returns true if there was an error
11274    produced.  False otherwise.  This is done so that we don't output the error
11275    or warning twice or three times.  */
11276
11277 bool
11278 fold_builtin_next_arg (tree exp, bool va_start_p)
11279 {
11280   tree fntype = TREE_TYPE (current_function_decl);
11281   int nargs = call_expr_nargs (exp);
11282   tree arg;
11283
11284   if (!stdarg_p (fntype))
11285     {
11286       error ("%<va_start%> used in function with fixed args");
11287       return true;
11288     }
11289
11290   if (va_start_p)
11291     {
11292       if (va_start_p && (nargs != 2))
11293         {
11294           error ("wrong number of arguments to function %<va_start%>");
11295           return true;
11296         }
11297       arg = CALL_EXPR_ARG (exp, 1);
11298     }
11299   /* We use __builtin_va_start (ap, 0, 0) or __builtin_next_arg (0, 0)
11300      when we checked the arguments and if needed issued a warning.  */
11301   else
11302     {
11303       if (nargs == 0)
11304         {
11305           /* Evidently an out of date version of <stdarg.h>; can't validate
11306              va_start's second argument, but can still work as intended.  */
11307           warning (0, "%<__builtin_next_arg%> called without an argument");
11308           return true;
11309         }
11310       else if (nargs > 1)
11311         {
11312           error ("wrong number of arguments to function %<__builtin_next_arg%>");
11313           return true;
11314         }
11315       arg = CALL_EXPR_ARG (exp, 0);
11316     }
11317
11318   if (TREE_CODE (arg) == SSA_NAME)
11319     arg = SSA_NAME_VAR (arg);
11320
11321   /* We destructively modify the call to be __builtin_va_start (ap, 0)
11322      or __builtin_next_arg (0) the first time we see it, after checking
11323      the arguments and if needed issuing a warning.  */
11324   if (!integer_zerop (arg))
11325     {
11326       tree last_parm = tree_last (DECL_ARGUMENTS (current_function_decl));
11327
11328       /* Strip off all nops for the sake of the comparison.  This
11329          is not quite the same as STRIP_NOPS.  It does more.
11330          We must also strip off INDIRECT_EXPR for C++ reference
11331          parameters.  */
11332       while (CONVERT_EXPR_P (arg)
11333              || TREE_CODE (arg) == INDIRECT_REF)
11334         arg = TREE_OPERAND (arg, 0);
11335       if (arg != last_parm)
11336         {
11337           /* FIXME: Sometimes with the tree optimizers we can get the
11338              not the last argument even though the user used the last
11339              argument.  We just warn and set the arg to be the last
11340              argument so that we will get wrong-code because of
11341              it.  */
11342           warning (0, "second parameter of %<va_start%> not last named argument");
11343         }
11344
11345       /* Undefined by C99 7.15.1.4p4 (va_start):
11346          "If the parameter parmN is declared with the register storage
11347          class, with a function or array type, or with a type that is
11348          not compatible with the type that results after application of
11349          the default argument promotions, the behavior is undefined."
11350       */
11351       else if (DECL_REGISTER (arg))
11352         warning (0, "undefined behaviour when second parameter of "
11353                  "%<va_start%> is declared with %<register%> storage");
11354
11355       /* We want to verify the second parameter just once before the tree
11356          optimizers are run and then avoid keeping it in the tree,
11357          as otherwise we could warn even for correct code like:
11358          void foo (int i, ...)
11359          { va_list ap; i++; va_start (ap, i); va_end (ap); }  */
11360       if (va_start_p)
11361         CALL_EXPR_ARG (exp, 1) = integer_zero_node;
11362       else
11363         CALL_EXPR_ARG (exp, 0) = integer_zero_node;
11364     }
11365   return false;
11366 }
11367
11368
11369 /* Simplify a call to the sprintf builtin with arguments DEST, FMT, and ORIG.
11370    ORIG may be null if this is a 2-argument call.  We don't attempt to
11371    simplify calls with more than 3 arguments.
11372
11373    Return NULL_TREE if no simplification was possible, otherwise return the
11374    simplified form of the call as a tree.  If IGNORED is true, it means that
11375    the caller does not use the returned value of the function.  */
11376
11377 static tree
11378 fold_builtin_sprintf (location_t loc, tree dest, tree fmt,
11379                       tree orig, int ignored)
11380 {
11381   tree call, retval;
11382   const char *fmt_str = NULL;
11383
11384   /* Verify the required arguments in the original call.  We deal with two
11385      types of sprintf() calls: 'sprintf (str, fmt)' and
11386      'sprintf (dest, "%s", orig)'.  */
11387   if (!validate_arg (dest, POINTER_TYPE)
11388       || !validate_arg (fmt, POINTER_TYPE))
11389     return NULL_TREE;
11390   if (orig && !validate_arg (orig, POINTER_TYPE))
11391     return NULL_TREE;
11392
11393   /* Check whether the format is a literal string constant.  */
11394   fmt_str = c_getstr (fmt);
11395   if (fmt_str == NULL)
11396     return NULL_TREE;
11397
11398   call = NULL_TREE;
11399   retval = NULL_TREE;
11400
11401   if (!init_target_chars ())
11402     return NULL_TREE;
11403
11404   /* If the format doesn't contain % args or %%, use strcpy.  */
11405   if (strchr (fmt_str, target_percent) == NULL)
11406     {
11407       tree fn = implicit_built_in_decls[BUILT_IN_STRCPY];
11408
11409       if (!fn)
11410         return NULL_TREE;
11411
11412       /* Don't optimize sprintf (buf, "abc", ptr++).  */
11413       if (orig)
11414         return NULL_TREE;
11415
11416       /* Convert sprintf (str, fmt) into strcpy (str, fmt) when
11417          'format' is known to contain no % formats.  */
11418       call = build_call_expr_loc (loc, fn, 2, dest, fmt);
11419       if (!ignored)
11420         retval = build_int_cst (integer_type_node, strlen (fmt_str));
11421     }
11422
11423   /* If the format is "%s", use strcpy if the result isn't used.  */
11424   else if (fmt_str && strcmp (fmt_str, target_percent_s) == 0)
11425     {
11426       tree fn;
11427       fn = implicit_built_in_decls[BUILT_IN_STRCPY];
11428
11429       if (!fn)
11430         return NULL_TREE;
11431
11432       /* Don't crash on sprintf (str1, "%s").  */
11433       if (!orig)
11434         return NULL_TREE;
11435
11436       /* Convert sprintf (str1, "%s", str2) into strcpy (str1, str2).  */
11437       if (!ignored)
11438         {
11439           retval = c_strlen (orig, 1);
11440           if (!retval || TREE_CODE (retval) != INTEGER_CST)
11441             return NULL_TREE;
11442         }
11443       call = build_call_expr_loc (loc, fn, 2, dest, orig);
11444     }
11445
11446   if (call && retval)
11447     {
11448       retval = fold_convert_loc
11449         (loc, TREE_TYPE (TREE_TYPE (implicit_built_in_decls[BUILT_IN_SPRINTF])),
11450          retval);
11451       return build2 (COMPOUND_EXPR, TREE_TYPE (retval), call, retval);
11452     }
11453   else
11454     return call;
11455 }
11456
11457 /* Simplify a call to the snprintf builtin with arguments DEST, DESTSIZE,
11458    FMT, and ORIG.  ORIG may be null if this is a 3-argument call.  We don't
11459    attempt to simplify calls with more than 4 arguments.
11460
11461    Return NULL_TREE if no simplification was possible, otherwise return the
11462    simplified form of the call as a tree.  If IGNORED is true, it means that
11463    the caller does not use the returned value of the function.  */
11464
11465 static tree
11466 fold_builtin_snprintf (location_t loc, tree dest, tree destsize, tree fmt,
11467                        tree orig, int ignored)
11468 {
11469   tree call, retval;
11470   const char *fmt_str = NULL;
11471   unsigned HOST_WIDE_INT destlen;
11472
11473   /* Verify the required arguments in the original call.  We deal with two
11474      types of snprintf() calls: 'snprintf (str, cst, fmt)' and
11475      'snprintf (dest, cst, "%s", orig)'.  */
11476   if (!validate_arg (dest, POINTER_TYPE)
11477       || !validate_arg (destsize, INTEGER_TYPE)
11478       || !validate_arg (fmt, POINTER_TYPE))
11479     return NULL_TREE;
11480   if (orig && !validate_arg (orig, POINTER_TYPE))
11481     return NULL_TREE;
11482
11483   if (!host_integerp (destsize, 1))
11484     return NULL_TREE;
11485
11486   /* Check whether the format is a literal string constant.  */
11487   fmt_str = c_getstr (fmt);
11488   if (fmt_str == NULL)
11489     return NULL_TREE;
11490
11491   call = NULL_TREE;
11492   retval = NULL_TREE;
11493
11494   if (!init_target_chars ())
11495     return NULL_TREE;
11496
11497   destlen = tree_low_cst (destsize, 1);
11498
11499   /* If the format doesn't contain % args or %%, use strcpy.  */
11500   if (strchr (fmt_str, target_percent) == NULL)
11501     {
11502       tree fn = implicit_built_in_decls[BUILT_IN_STRCPY];
11503       size_t len = strlen (fmt_str);
11504
11505       /* Don't optimize snprintf (buf, 4, "abc", ptr++).  */
11506       if (orig)
11507         return NULL_TREE;
11508
11509       /* We could expand this as
11510          memcpy (str, fmt, cst - 1); str[cst - 1] = '\0';
11511          or to
11512          memcpy (str, fmt_with_nul_at_cstm1, cst);
11513          but in the former case that might increase code size
11514          and in the latter case grow .rodata section too much.
11515          So punt for now.  */
11516       if (len >= destlen)
11517         return NULL_TREE;
11518
11519       if (!fn)
11520         return NULL_TREE;
11521
11522       /* Convert snprintf (str, cst, fmt) into strcpy (str, fmt) when
11523          'format' is known to contain no % formats and
11524          strlen (fmt) < cst.  */
11525       call = build_call_expr_loc (loc, fn, 2, dest, fmt);
11526
11527       if (!ignored)
11528         retval = build_int_cst (integer_type_node, strlen (fmt_str));
11529     }
11530
11531   /* If the format is "%s", use strcpy if the result isn't used.  */
11532   else if (fmt_str && strcmp (fmt_str, target_percent_s) == 0)
11533     {
11534       tree fn = implicit_built_in_decls[BUILT_IN_STRCPY];
11535       unsigned HOST_WIDE_INT origlen;
11536
11537       /* Don't crash on snprintf (str1, cst, "%s").  */
11538       if (!orig)
11539         return NULL_TREE;
11540
11541       retval = c_strlen (orig, 1);
11542       if (!retval || !host_integerp (retval, 1))  
11543         return NULL_TREE;
11544
11545       origlen = tree_low_cst (retval, 1);
11546       /* We could expand this as
11547          memcpy (str1, str2, cst - 1); str1[cst - 1] = '\0';
11548          or to
11549          memcpy (str1, str2_with_nul_at_cstm1, cst);
11550          but in the former case that might increase code size
11551          and in the latter case grow .rodata section too much.
11552          So punt for now.  */
11553       if (origlen >= destlen)
11554         return NULL_TREE;
11555
11556       /* Convert snprintf (str1, cst, "%s", str2) into
11557          strcpy (str1, str2) if strlen (str2) < cst.  */
11558       if (!fn)
11559         return NULL_TREE;
11560
11561       call = build_call_expr_loc (loc, fn, 2, dest, orig);
11562
11563       if (ignored)
11564         retval = NULL_TREE;
11565     }
11566
11567   if (call && retval)
11568     {
11569       tree fn = built_in_decls[BUILT_IN_SNPRINTF];
11570       retval = fold_convert_loc (loc, TREE_TYPE (TREE_TYPE (fn)), retval);
11571       return build2 (COMPOUND_EXPR, TREE_TYPE (retval), call, retval);
11572     }
11573   else
11574     return call;
11575 }
11576
11577 /* Expand a call EXP to __builtin_object_size.  */
11578
11579 rtx
11580 expand_builtin_object_size (tree exp)
11581 {
11582   tree ost;
11583   int object_size_type;
11584   tree fndecl = get_callee_fndecl (exp);
11585
11586   if (!validate_arglist (exp, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
11587     {
11588       error ("%Kfirst argument of %D must be a pointer, second integer constant",
11589              exp, fndecl);
11590       expand_builtin_trap ();
11591       return const0_rtx;
11592     }
11593
11594   ost = CALL_EXPR_ARG (exp, 1);
11595   STRIP_NOPS (ost);
11596
11597   if (TREE_CODE (ost) != INTEGER_CST
11598       || tree_int_cst_sgn (ost) < 0
11599       || compare_tree_int (ost, 3) > 0)
11600     {
11601       error ("%Klast argument of %D is not integer constant between 0 and 3",
11602              exp, fndecl);
11603       expand_builtin_trap ();
11604       return const0_rtx;
11605     }
11606
11607   object_size_type = tree_low_cst (ost, 0);
11608
11609   return object_size_type < 2 ? constm1_rtx : const0_rtx;
11610 }
11611
11612 /* Expand EXP, a call to the __mem{cpy,pcpy,move,set}_chk builtin.
11613    FCODE is the BUILT_IN_* to use.
11614    Return NULL_RTX if we failed; the caller should emit a normal call,
11615    otherwise try to get the result in TARGET, if convenient (and in
11616    mode MODE if that's convenient).  */
11617
11618 static rtx
11619 expand_builtin_memory_chk (tree exp, rtx target, enum machine_mode mode,
11620                            enum built_in_function fcode)
11621 {
11622   tree dest, src, len, size;
11623
11624   if (!validate_arglist (exp,
11625                          POINTER_TYPE,
11626                          fcode == BUILT_IN_MEMSET_CHK
11627                          ? INTEGER_TYPE : POINTER_TYPE,
11628                          INTEGER_TYPE, INTEGER_TYPE, VOID_TYPE))
11629     return NULL_RTX;
11630
11631   dest = CALL_EXPR_ARG (exp, 0);
11632   src = CALL_EXPR_ARG (exp, 1);
11633   len = CALL_EXPR_ARG (exp, 2);
11634   size = CALL_EXPR_ARG (exp, 3);
11635
11636   if (! host_integerp (size, 1))
11637     return NULL_RTX;
11638
11639   if (host_integerp (len, 1) || integer_all_onesp (size))
11640     {
11641       tree fn;
11642
11643       if (! integer_all_onesp (size) && tree_int_cst_lt (size, len))
11644         {
11645           warning_at (tree_nonartificial_location (exp),
11646                       0, "%Kcall to %D will always overflow destination buffer",
11647                       exp, get_callee_fndecl (exp));
11648           return NULL_RTX;
11649         }
11650
11651       fn = NULL_TREE;
11652       /* If __builtin_mem{cpy,pcpy,move,set}_chk is used, assume
11653          mem{cpy,pcpy,move,set} is available.  */
11654       switch (fcode)
11655         {
11656         case BUILT_IN_MEMCPY_CHK:
11657           fn = built_in_decls[BUILT_IN_MEMCPY];
11658           break;
11659         case BUILT_IN_MEMPCPY_CHK:
11660           fn = built_in_decls[BUILT_IN_MEMPCPY];
11661           break;
11662         case BUILT_IN_MEMMOVE_CHK:
11663           fn = built_in_decls[BUILT_IN_MEMMOVE];
11664           break;
11665         case BUILT_IN_MEMSET_CHK:
11666           fn = built_in_decls[BUILT_IN_MEMSET];
11667           break;
11668         default:
11669           break;
11670         }
11671
11672       if (! fn)
11673         return NULL_RTX;
11674
11675       fn = build_call_nofold_loc (EXPR_LOCATION (exp), fn, 3, dest, src, len);
11676       gcc_assert (TREE_CODE (fn) == CALL_EXPR);
11677       CALL_EXPR_TAILCALL (fn) = CALL_EXPR_TAILCALL (exp);
11678       return expand_expr (fn, target, mode, EXPAND_NORMAL);
11679     }
11680   else if (fcode == BUILT_IN_MEMSET_CHK)
11681     return NULL_RTX;
11682   else
11683     {
11684       unsigned int dest_align
11685         = get_pointer_alignment (dest, BIGGEST_ALIGNMENT);
11686
11687       /* If DEST is not a pointer type, call the normal function.  */
11688       if (dest_align == 0)
11689         return NULL_RTX;
11690
11691       /* If SRC and DEST are the same (and not volatile), do nothing.  */
11692       if (operand_equal_p (src, dest, 0))
11693         {
11694           tree expr;
11695
11696           if (fcode != BUILT_IN_MEMPCPY_CHK)
11697             {
11698               /* Evaluate and ignore LEN in case it has side-effects.  */
11699               expand_expr (len, const0_rtx, VOIDmode, EXPAND_NORMAL);
11700               return expand_expr (dest, target, mode, EXPAND_NORMAL);
11701             }
11702
11703           expr = fold_build2 (POINTER_PLUS_EXPR, TREE_TYPE (dest), dest, len);
11704           return expand_expr (expr, target, mode, EXPAND_NORMAL);
11705         }
11706
11707       /* __memmove_chk special case.  */
11708       if (fcode == BUILT_IN_MEMMOVE_CHK)
11709         {
11710           unsigned int src_align
11711             = get_pointer_alignment (src, BIGGEST_ALIGNMENT);
11712
11713           if (src_align == 0)
11714             return NULL_RTX;
11715
11716           /* If src is categorized for a readonly section we can use
11717              normal __memcpy_chk.  */
11718           if (readonly_data_expr (src))
11719             {
11720               tree fn = built_in_decls[BUILT_IN_MEMCPY_CHK];
11721               if (!fn)
11722                 return NULL_RTX;
11723               fn = build_call_nofold_loc (EXPR_LOCATION (exp), fn, 4,
11724                                           dest, src, len, size);
11725               gcc_assert (TREE_CODE (fn) == CALL_EXPR);
11726               CALL_EXPR_TAILCALL (fn) = CALL_EXPR_TAILCALL (exp);
11727               return expand_expr (fn, target, mode, EXPAND_NORMAL);
11728             }
11729         }
11730       return NULL_RTX;
11731     }
11732 }
11733
11734 /* Emit warning if a buffer overflow is detected at compile time.  */
11735
11736 static void
11737 maybe_emit_chk_warning (tree exp, enum built_in_function fcode)
11738 {
11739   int is_strlen = 0;
11740   tree len, size;
11741   location_t loc = tree_nonartificial_location (exp);
11742
11743   switch (fcode)
11744     {
11745     case BUILT_IN_STRCPY_CHK:
11746     case BUILT_IN_STPCPY_CHK:
11747     /* For __strcat_chk the warning will be emitted only if overflowing
11748        by at least strlen (dest) + 1 bytes.  */
11749     case BUILT_IN_STRCAT_CHK:
11750       len = CALL_EXPR_ARG (exp, 1);
11751       size = CALL_EXPR_ARG (exp, 2);
11752       is_strlen = 1;
11753       break;
11754     case BUILT_IN_STRNCAT_CHK:
11755     case BUILT_IN_STRNCPY_CHK:
11756       len = CALL_EXPR_ARG (exp, 2);
11757       size = CALL_EXPR_ARG (exp, 3);
11758       break;
11759     case BUILT_IN_SNPRINTF_CHK:
11760     case BUILT_IN_VSNPRINTF_CHK:
11761       len = CALL_EXPR_ARG (exp, 1);
11762       size = CALL_EXPR_ARG (exp, 3);
11763       break;
11764     default:
11765       gcc_unreachable ();
11766     }
11767
11768   if (!len || !size)
11769     return;
11770
11771   if (! host_integerp (size, 1) || integer_all_onesp (size))
11772     return;
11773
11774   if (is_strlen)
11775     {
11776       len = c_strlen (len, 1);
11777       if (! len || ! host_integerp (len, 1) || tree_int_cst_lt (len, size))
11778         return;
11779     }
11780   else if (fcode == BUILT_IN_STRNCAT_CHK)
11781     {
11782       tree src = CALL_EXPR_ARG (exp, 1);
11783       if (! src || ! host_integerp (len, 1) || tree_int_cst_lt (len, size))
11784         return;
11785       src = c_strlen (src, 1);
11786       if (! src || ! host_integerp (src, 1))
11787         {
11788           warning_at (loc, 0, "%Kcall to %D might overflow destination buffer",
11789                       exp, get_callee_fndecl (exp));
11790           return;
11791         }
11792       else if (tree_int_cst_lt (src, size))
11793         return;
11794     }
11795   else if (! host_integerp (len, 1) || ! tree_int_cst_lt (size, len))
11796     return;
11797
11798   warning_at (loc, 0, "%Kcall to %D will always overflow destination buffer",
11799               exp, get_callee_fndecl (exp));
11800 }
11801
11802 /* Emit warning if a buffer overflow is detected at compile time
11803    in __sprintf_chk/__vsprintf_chk calls.  */
11804
11805 static void
11806 maybe_emit_sprintf_chk_warning (tree exp, enum built_in_function fcode)
11807 {
11808   tree size, len, fmt;
11809   const char *fmt_str;
11810   int nargs = call_expr_nargs (exp);
11811
11812   /* Verify the required arguments in the original call.  */
11813
11814   if (nargs < 4)
11815     return;
11816   size = CALL_EXPR_ARG (exp, 2);
11817   fmt = CALL_EXPR_ARG (exp, 3);
11818
11819   if (! host_integerp (size, 1) || integer_all_onesp (size))
11820     return;
11821
11822   /* Check whether the format is a literal string constant.  */
11823   fmt_str = c_getstr (fmt);
11824   if (fmt_str == NULL)
11825     return;
11826
11827   if (!init_target_chars ())
11828     return;
11829
11830   /* If the format doesn't contain % args or %%, we know its size.  */
11831   if (strchr (fmt_str, target_percent) == 0)
11832     len = build_int_cstu (size_type_node, strlen (fmt_str));
11833   /* If the format is "%s" and first ... argument is a string literal,
11834      we know it too.  */
11835   else if (fcode == BUILT_IN_SPRINTF_CHK
11836            && strcmp (fmt_str, target_percent_s) == 0)
11837     {
11838       tree arg;
11839
11840       if (nargs < 5)
11841         return;
11842       arg = CALL_EXPR_ARG (exp, 4);
11843       if (! POINTER_TYPE_P (TREE_TYPE (arg)))
11844         return;
11845
11846       len = c_strlen (arg, 1);
11847       if (!len || ! host_integerp (len, 1))
11848         return;
11849     }
11850   else
11851     return;
11852
11853   if (! tree_int_cst_lt (len, size))
11854     warning_at (tree_nonartificial_location (exp),
11855                 0, "%Kcall to %D will always overflow destination buffer",
11856                 exp, get_callee_fndecl (exp));
11857 }
11858
11859 /* Emit warning if a free is called with address of a variable.  */
11860
11861 static void
11862 maybe_emit_free_warning (tree exp)
11863 {
11864   tree arg = CALL_EXPR_ARG (exp, 0);
11865
11866   STRIP_NOPS (arg);
11867   if (TREE_CODE (arg) != ADDR_EXPR)
11868     return;
11869
11870   arg = get_base_address (TREE_OPERAND (arg, 0));
11871   if (arg == NULL || INDIRECT_REF_P (arg) || TREE_CODE (arg) == MEM_REF)
11872     return;
11873
11874   if (SSA_VAR_P (arg))
11875     warning_at (tree_nonartificial_location (exp),
11876                 0, "%Kattempt to free a non-heap object %qD", exp, arg);
11877   else
11878     warning_at (tree_nonartificial_location (exp),
11879                 0, "%Kattempt to free a non-heap object", exp);
11880 }
11881
11882 /* Fold a call to __builtin_object_size with arguments PTR and OST,
11883    if possible.  */
11884
11885 tree
11886 fold_builtin_object_size (tree ptr, tree ost)
11887 {
11888   unsigned HOST_WIDE_INT bytes;
11889   int object_size_type;
11890
11891   if (!validate_arg (ptr, POINTER_TYPE)
11892       || !validate_arg (ost, INTEGER_TYPE))
11893     return NULL_TREE;
11894
11895   STRIP_NOPS (ost);
11896
11897   if (TREE_CODE (ost) != INTEGER_CST
11898       || tree_int_cst_sgn (ost) < 0
11899       || compare_tree_int (ost, 3) > 0)
11900     return NULL_TREE;
11901
11902   object_size_type = tree_low_cst (ost, 0);
11903
11904   /* __builtin_object_size doesn't evaluate side-effects in its arguments;
11905      if there are any side-effects, it returns (size_t) -1 for types 0 and 1
11906      and (size_t) 0 for types 2 and 3.  */
11907   if (TREE_SIDE_EFFECTS (ptr))
11908     return build_int_cst_type (size_type_node, object_size_type < 2 ? -1 : 0);
11909
11910   if (TREE_CODE (ptr) == ADDR_EXPR)
11911     {
11912       bytes = compute_builtin_object_size (ptr, object_size_type);
11913       if (double_int_fits_to_tree_p (size_type_node,
11914                                      uhwi_to_double_int (bytes)))
11915         return build_int_cstu (size_type_node, bytes);
11916     }
11917   else if (TREE_CODE (ptr) == SSA_NAME)
11918     {
11919       /* If object size is not known yet, delay folding until
11920        later.  Maybe subsequent passes will help determining
11921        it.  */
11922       bytes = compute_builtin_object_size (ptr, object_size_type);
11923       if (bytes != (unsigned HOST_WIDE_INT) (object_size_type < 2 ? -1 : 0)
11924           && double_int_fits_to_tree_p (size_type_node,
11925                                         uhwi_to_double_int (bytes)))
11926         return build_int_cstu (size_type_node, bytes);
11927     }
11928
11929   return NULL_TREE;
11930 }
11931
11932 /* Fold a call to the __mem{cpy,pcpy,move,set}_chk builtin.
11933    DEST, SRC, LEN, and SIZE are the arguments to the call.
11934    IGNORE is true, if return value can be ignored.  FCODE is the BUILT_IN_*
11935    code of the builtin.  If MAXLEN is not NULL, it is maximum length
11936    passed as third argument.  */
11937
11938 tree
11939 fold_builtin_memory_chk (location_t loc, tree fndecl,
11940                          tree dest, tree src, tree len, tree size,
11941                          tree maxlen, bool ignore,
11942                          enum built_in_function fcode)
11943 {
11944   tree fn;
11945
11946   if (!validate_arg (dest, POINTER_TYPE)
11947       || !validate_arg (src,
11948                         (fcode == BUILT_IN_MEMSET_CHK
11949                          ? INTEGER_TYPE : POINTER_TYPE))
11950       || !validate_arg (len, INTEGER_TYPE)
11951       || !validate_arg (size, INTEGER_TYPE))
11952     return NULL_TREE;
11953
11954   /* If SRC and DEST are the same (and not volatile), return DEST
11955      (resp. DEST+LEN for __mempcpy_chk).  */
11956   if (fcode != BUILT_IN_MEMSET_CHK && operand_equal_p (src, dest, 0))
11957     {
11958       if (fcode != BUILT_IN_MEMPCPY_CHK)
11959         return omit_one_operand_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)),
11960                                  dest, len);
11961       else
11962         {
11963           tree temp = fold_build2_loc (loc, POINTER_PLUS_EXPR, TREE_TYPE (dest),
11964                                    dest, len);
11965           return fold_convert_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)), temp);
11966         }
11967     }
11968
11969   if (! host_integerp (size, 1))
11970     return NULL_TREE;
11971
11972   if (! integer_all_onesp (size))
11973     {
11974       if (! host_integerp (len, 1))
11975         {
11976           /* If LEN is not constant, try MAXLEN too.
11977              For MAXLEN only allow optimizing into non-_ocs function
11978              if SIZE is >= MAXLEN, never convert to __ocs_fail ().  */
11979           if (maxlen == NULL_TREE || ! host_integerp (maxlen, 1))
11980             {
11981               if (fcode == BUILT_IN_MEMPCPY_CHK && ignore)
11982                 {
11983                   /* (void) __mempcpy_chk () can be optimized into
11984                      (void) __memcpy_chk ().  */
11985                   fn = built_in_decls[BUILT_IN_MEMCPY_CHK];
11986                   if (!fn)
11987                     return NULL_TREE;
11988
11989                   return build_call_expr_loc (loc, fn, 4, dest, src, len, size);
11990                 }
11991               return NULL_TREE;
11992             }
11993         }
11994       else
11995         maxlen = len;
11996
11997       if (tree_int_cst_lt (size, maxlen))
11998         return NULL_TREE;
11999     }
12000
12001   fn = NULL_TREE;
12002   /* If __builtin_mem{cpy,pcpy,move,set}_chk is used, assume
12003      mem{cpy,pcpy,move,set} is available.  */
12004   switch (fcode)
12005     {
12006     case BUILT_IN_MEMCPY_CHK:
12007       fn = built_in_decls[BUILT_IN_MEMCPY];
12008       break;
12009     case BUILT_IN_MEMPCPY_CHK:
12010       fn = built_in_decls[BUILT_IN_MEMPCPY];
12011       break;
12012     case BUILT_IN_MEMMOVE_CHK:
12013       fn = built_in_decls[BUILT_IN_MEMMOVE];
12014       break;
12015     case BUILT_IN_MEMSET_CHK:
12016       fn = built_in_decls[BUILT_IN_MEMSET];
12017       break;
12018     default:
12019       break;
12020     }
12021
12022   if (!fn)
12023     return NULL_TREE;
12024
12025   return build_call_expr_loc (loc, fn, 3, dest, src, len);
12026 }
12027
12028 /* Fold a call to the __st[rp]cpy_chk builtin.
12029    DEST, SRC, and SIZE are the arguments to the call.
12030    IGNORE is true if return value can be ignored.  FCODE is the BUILT_IN_*
12031    code of the builtin.  If MAXLEN is not NULL, it is maximum length of
12032    strings passed as second argument.  */
12033
12034 tree
12035 fold_builtin_stxcpy_chk (location_t loc, tree fndecl, tree dest,
12036                          tree src, tree size,
12037                          tree maxlen, bool ignore,
12038                          enum built_in_function fcode)
12039 {
12040   tree len, fn;
12041
12042   if (!validate_arg (dest, POINTER_TYPE)
12043       || !validate_arg (src, POINTER_TYPE)
12044       || !validate_arg (size, INTEGER_TYPE))
12045     return NULL_TREE;
12046
12047   /* If SRC and DEST are the same (and not volatile), return DEST.  */
12048   if (fcode == BUILT_IN_STRCPY_CHK && operand_equal_p (src, dest, 0))
12049     return fold_convert_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)), dest);
12050
12051   if (! host_integerp (size, 1))
12052     return NULL_TREE;
12053
12054   if (! integer_all_onesp (size))
12055     {
12056       len = c_strlen (src, 1);
12057       if (! len || ! host_integerp (len, 1))
12058         {
12059           /* If LEN is not constant, try MAXLEN too.
12060              For MAXLEN only allow optimizing into non-_ocs function
12061              if SIZE is >= MAXLEN, never convert to __ocs_fail ().  */
12062           if (maxlen == NULL_TREE || ! host_integerp (maxlen, 1))
12063             {
12064               if (fcode == BUILT_IN_STPCPY_CHK)
12065                 {
12066                   if (! ignore)
12067                     return NULL_TREE;
12068
12069                   /* If return value of __stpcpy_chk is ignored,
12070                      optimize into __strcpy_chk.  */
12071                   fn = built_in_decls[BUILT_IN_STRCPY_CHK];
12072                   if (!fn)
12073                     return NULL_TREE;
12074
12075                   return build_call_expr_loc (loc, fn, 3, dest, src, size);
12076                 }
12077
12078               if (! len || TREE_SIDE_EFFECTS (len))
12079                 return NULL_TREE;
12080
12081               /* If c_strlen returned something, but not a constant,
12082                  transform __strcpy_chk into __memcpy_chk.  */
12083               fn = built_in_decls[BUILT_IN_MEMCPY_CHK];
12084               if (!fn)
12085                 return NULL_TREE;
12086
12087               len = size_binop_loc (loc, PLUS_EXPR, len, ssize_int (1));
12088               return fold_convert_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)),
12089                                        build_call_expr_loc (loc, fn, 4,
12090                                                         dest, src, len, size));
12091             }
12092         }
12093       else
12094         maxlen = len;
12095
12096       if (! tree_int_cst_lt (maxlen, size))
12097         return NULL_TREE;
12098     }
12099
12100   /* If __builtin_st{r,p}cpy_chk is used, assume st{r,p}cpy is available.  */
12101   fn = built_in_decls[fcode == BUILT_IN_STPCPY_CHK
12102                       ? BUILT_IN_STPCPY : BUILT_IN_STRCPY];
12103   if (!fn)
12104     return NULL_TREE;
12105
12106   return build_call_expr_loc (loc, fn, 2, dest, src);
12107 }
12108
12109 /* Fold a call to the __strncpy_chk builtin.  DEST, SRC, LEN, and SIZE
12110    are the arguments to the call.  If MAXLEN is not NULL, it is maximum
12111    length passed as third argument.  */
12112
12113 tree
12114 fold_builtin_strncpy_chk (location_t loc, tree dest, tree src,
12115                           tree len, tree size, tree maxlen)
12116 {
12117   tree fn;
12118
12119   if (!validate_arg (dest, POINTER_TYPE)
12120       || !validate_arg (src, POINTER_TYPE)
12121       || !validate_arg (len, INTEGER_TYPE)
12122       || !validate_arg (size, INTEGER_TYPE))
12123     return NULL_TREE;
12124
12125   if (! host_integerp (size, 1))
12126     return NULL_TREE;
12127
12128   if (! integer_all_onesp (size))
12129     {
12130       if (! host_integerp (len, 1))
12131         {
12132           /* If LEN is not constant, try MAXLEN too.
12133              For MAXLEN only allow optimizing into non-_ocs function
12134              if SIZE is >= MAXLEN, never convert to __ocs_fail ().  */
12135           if (maxlen == NULL_TREE || ! host_integerp (maxlen, 1))
12136             return NULL_TREE;
12137         }
12138       else
12139         maxlen = len;
12140
12141       if (tree_int_cst_lt (size, maxlen))
12142         return NULL_TREE;
12143     }
12144
12145   /* If __builtin_strncpy_chk is used, assume strncpy is available.  */
12146   fn = built_in_decls[BUILT_IN_STRNCPY];
12147   if (!fn)
12148     return NULL_TREE;
12149
12150   return build_call_expr_loc (loc, fn, 3, dest, src, len);
12151 }
12152
12153 /* Fold a call to the __strcat_chk builtin FNDECL.  DEST, SRC, and SIZE
12154    are the arguments to the call.  */
12155
12156 static tree
12157 fold_builtin_strcat_chk (location_t loc, tree fndecl, tree dest,
12158                          tree src, tree size)
12159 {
12160   tree fn;
12161   const char *p;
12162
12163   if (!validate_arg (dest, POINTER_TYPE)
12164       || !validate_arg (src, POINTER_TYPE)
12165       || !validate_arg (size, INTEGER_TYPE))
12166     return NULL_TREE;
12167
12168   p = c_getstr (src);
12169   /* If the SRC parameter is "", return DEST.  */
12170   if (p && *p == '\0')
12171     return omit_one_operand_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)), dest, src);
12172
12173   if (! host_integerp (size, 1) || ! integer_all_onesp (size))
12174     return NULL_TREE;
12175
12176   /* If __builtin_strcat_chk is used, assume strcat is available.  */
12177   fn = built_in_decls[BUILT_IN_STRCAT];
12178   if (!fn)
12179     return NULL_TREE;
12180
12181   return build_call_expr_loc (loc, fn, 2, dest, src);
12182 }
12183
12184 /* Fold a call to the __strncat_chk builtin with arguments DEST, SRC,
12185    LEN, and SIZE.  */
12186
12187 static tree
12188 fold_builtin_strncat_chk (location_t loc, tree fndecl,
12189                           tree dest, tree src, tree len, tree size)
12190 {
12191   tree fn;
12192   const char *p;
12193
12194   if (!validate_arg (dest, POINTER_TYPE)
12195       || !validate_arg (src, POINTER_TYPE)
12196       || !validate_arg (size, INTEGER_TYPE)
12197       || !validate_arg (size, INTEGER_TYPE))
12198     return NULL_TREE;
12199
12200   p = c_getstr (src);
12201   /* If the SRC parameter is "" or if LEN is 0, return DEST.  */
12202   if (p && *p == '\0')
12203     return omit_one_operand_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)), dest, len);
12204   else if (integer_zerop (len))
12205     return omit_one_operand_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)), dest, src);
12206
12207   if (! host_integerp (size, 1))
12208     return NULL_TREE;
12209
12210   if (! integer_all_onesp (size))
12211     {
12212       tree src_len = c_strlen (src, 1);
12213       if (src_len
12214           && host_integerp (src_len, 1)
12215           && host_integerp (len, 1)
12216           && ! tree_int_cst_lt (len, src_len))
12217         {
12218           /* If LEN >= strlen (SRC), optimize into __strcat_chk.  */
12219           fn = built_in_decls[BUILT_IN_STRCAT_CHK];
12220           if (!fn)
12221             return NULL_TREE;
12222
12223           return build_call_expr_loc (loc, fn, 3, dest, src, size);
12224         }
12225       return NULL_TREE;
12226     }
12227
12228   /* If __builtin_strncat_chk is used, assume strncat is available.  */
12229   fn = built_in_decls[BUILT_IN_STRNCAT];
12230   if (!fn)
12231     return NULL_TREE;
12232
12233   return build_call_expr_loc (loc, fn, 3, dest, src, len);
12234 }
12235
12236 /* Fold a call EXP to __{,v}sprintf_chk having NARGS passed as ARGS.
12237    Return NULL_TREE if a normal call should be emitted rather than
12238    expanding the function inline.  FCODE is either BUILT_IN_SPRINTF_CHK
12239    or BUILT_IN_VSPRINTF_CHK.  */
12240
12241 static tree
12242 fold_builtin_sprintf_chk_1 (location_t loc, int nargs, tree *args,
12243                             enum built_in_function fcode)
12244 {
12245   tree dest, size, len, fn, fmt, flag;
12246   const char *fmt_str;
12247
12248   /* Verify the required arguments in the original call.  */
12249   if (nargs < 4)
12250     return NULL_TREE;
12251   dest = args[0];
12252   if (!validate_arg (dest, POINTER_TYPE))
12253     return NULL_TREE;
12254   flag = args[1];
12255   if (!validate_arg (flag, INTEGER_TYPE))
12256     return NULL_TREE;
12257   size = args[2];
12258   if (!validate_arg (size, INTEGER_TYPE))
12259     return NULL_TREE;
12260   fmt = args[3];
12261   if (!validate_arg (fmt, POINTER_TYPE))
12262     return NULL_TREE;
12263
12264   if (! host_integerp (size, 1))
12265     return NULL_TREE;
12266
12267   len = NULL_TREE;
12268
12269   if (!init_target_chars ())
12270     return NULL_TREE;
12271
12272   /* Check whether the format is a literal string constant.  */
12273   fmt_str = c_getstr (fmt);
12274   if (fmt_str != NULL)
12275     {
12276       /* If the format doesn't contain % args or %%, we know the size.  */
12277       if (strchr (fmt_str, target_percent) == 0)
12278         {
12279           if (fcode != BUILT_IN_SPRINTF_CHK || nargs == 4)
12280             len = build_int_cstu (size_type_node, strlen (fmt_str));
12281         }
12282       /* If the format is "%s" and first ... argument is a string literal,
12283          we know the size too.  */
12284       else if (fcode == BUILT_IN_SPRINTF_CHK
12285                && strcmp (fmt_str, target_percent_s) == 0)
12286         {
12287           tree arg;
12288
12289           if (nargs == 5)
12290             {
12291               arg = args[4];
12292               if (validate_arg (arg, POINTER_TYPE))
12293                 {
12294                   len = c_strlen (arg, 1);
12295                   if (! len || ! host_integerp (len, 1))
12296                     len = NULL_TREE;
12297                 }
12298             }
12299         }
12300     }
12301
12302   if (! integer_all_onesp (size))
12303     {
12304       if (! len || ! tree_int_cst_lt (len, size))
12305         return NULL_TREE;
12306     }
12307
12308   /* Only convert __{,v}sprintf_chk to {,v}sprintf if flag is 0
12309      or if format doesn't contain % chars or is "%s".  */
12310   if (! integer_zerop (flag))
12311     {
12312       if (fmt_str == NULL)
12313         return NULL_TREE;
12314       if (strchr (fmt_str, target_percent) != NULL
12315           && strcmp (fmt_str, target_percent_s))
12316         return NULL_TREE;
12317     }
12318
12319   /* If __builtin_{,v}sprintf_chk is used, assume {,v}sprintf is available.  */
12320   fn = built_in_decls[fcode == BUILT_IN_VSPRINTF_CHK
12321                       ? BUILT_IN_VSPRINTF : BUILT_IN_SPRINTF];
12322   if (!fn)
12323     return NULL_TREE;
12324
12325   return rewrite_call_expr_array (loc, nargs, args, 4, fn, 2, dest, fmt);
12326 }
12327
12328 /* Fold a call EXP to __{,v}sprintf_chk.  Return NULL_TREE if
12329    a normal call should be emitted rather than expanding the function
12330    inline.  FCODE is either BUILT_IN_SPRINTF_CHK or BUILT_IN_VSPRINTF_CHK.  */
12331
12332 static tree
12333 fold_builtin_sprintf_chk (location_t loc, tree exp,
12334                           enum built_in_function fcode)
12335 {
12336   return fold_builtin_sprintf_chk_1 (loc, call_expr_nargs (exp),
12337                                      CALL_EXPR_ARGP (exp), fcode);
12338 }
12339
12340 /* Fold a call EXP to {,v}snprintf having NARGS passed as ARGS.  Return
12341    NULL_TREE if a normal call should be emitted rather than expanding
12342    the function inline.  FCODE is either BUILT_IN_SNPRINTF_CHK or
12343    BUILT_IN_VSNPRINTF_CHK.  If MAXLEN is not NULL, it is maximum length
12344    passed as second argument.  */
12345
12346 static tree
12347 fold_builtin_snprintf_chk_1 (location_t loc, int nargs, tree *args,
12348                              tree maxlen, enum built_in_function fcode)
12349 {
12350   tree dest, size, len, fn, fmt, flag;
12351   const char *fmt_str;
12352
12353   /* Verify the required arguments in the original call.  */
12354   if (nargs < 5)
12355     return NULL_TREE;
12356   dest = args[0];
12357   if (!validate_arg (dest, POINTER_TYPE))
12358     return NULL_TREE;
12359   len = args[1];
12360   if (!validate_arg (len, INTEGER_TYPE))
12361     return NULL_TREE;
12362   flag = args[2];
12363   if (!validate_arg (flag, INTEGER_TYPE))
12364     return NULL_TREE;
12365   size = args[3];
12366   if (!validate_arg (size, INTEGER_TYPE))
12367     return NULL_TREE;
12368   fmt = args[4];
12369   if (!validate_arg (fmt, POINTER_TYPE))
12370     return NULL_TREE;
12371
12372   if (! host_integerp (size, 1))
12373     return NULL_TREE;
12374
12375   if (! integer_all_onesp (size))
12376     {
12377       if (! host_integerp (len, 1))
12378         {
12379           /* If LEN is not constant, try MAXLEN too.
12380              For MAXLEN only allow optimizing into non-_ocs function
12381              if SIZE is >= MAXLEN, never convert to __ocs_fail ().  */
12382           if (maxlen == NULL_TREE || ! host_integerp (maxlen, 1))
12383             return NULL_TREE;
12384         }
12385       else
12386         maxlen = len;
12387
12388       if (tree_int_cst_lt (size, maxlen))
12389         return NULL_TREE;
12390     }
12391
12392   if (!init_target_chars ())
12393     return NULL_TREE;
12394
12395   /* Only convert __{,v}snprintf_chk to {,v}snprintf if flag is 0
12396      or if format doesn't contain % chars or is "%s".  */
12397   if (! integer_zerop (flag))
12398     {
12399       fmt_str = c_getstr (fmt);
12400       if (fmt_str == NULL)
12401         return NULL_TREE;
12402       if (strchr (fmt_str, target_percent) != NULL
12403           && strcmp (fmt_str, target_percent_s))
12404         return NULL_TREE;
12405     }
12406
12407   /* If __builtin_{,v}snprintf_chk is used, assume {,v}snprintf is
12408      available.  */
12409   fn = built_in_decls[fcode == BUILT_IN_VSNPRINTF_CHK
12410                       ? BUILT_IN_VSNPRINTF : BUILT_IN_SNPRINTF];
12411   if (!fn)
12412     return NULL_TREE;
12413
12414   return rewrite_call_expr_array (loc, nargs, args, 5, fn, 3, dest, len, fmt);
12415 }
12416
12417 /* Fold a call EXP to {,v}snprintf.  Return NULL_TREE if
12418    a normal call should be emitted rather than expanding the function
12419    inline.  FCODE is either BUILT_IN_SNPRINTF_CHK or
12420    BUILT_IN_VSNPRINTF_CHK.  If MAXLEN is not NULL, it is maximum length
12421    passed as second argument.  */
12422
12423 tree
12424 fold_builtin_snprintf_chk (location_t loc, tree exp, tree maxlen,
12425                            enum built_in_function fcode)
12426 {
12427   return fold_builtin_snprintf_chk_1 (loc, call_expr_nargs (exp),
12428                                       CALL_EXPR_ARGP (exp), maxlen, fcode);
12429 }
12430
12431 /* Fold a call to the {,v}printf{,_unlocked} and __{,v}printf_chk builtins.
12432    FMT and ARG are the arguments to the call; we don't fold cases with
12433    more than 2 arguments, and ARG may be null if this is a 1-argument case.
12434
12435    Return NULL_TREE if no simplification was possible, otherwise return the
12436    simplified form of the call as a tree.  FCODE is the BUILT_IN_*
12437    code of the function to be simplified.  */
12438
12439 static tree
12440 fold_builtin_printf (location_t loc, tree fndecl, tree fmt,
12441                      tree arg, bool ignore,
12442                      enum built_in_function fcode)
12443 {
12444   tree fn_putchar, fn_puts, newarg, call = NULL_TREE;
12445   const char *fmt_str = NULL;
12446
12447   /* If the return value is used, don't do the transformation.  */
12448   if (! ignore)
12449     return NULL_TREE;
12450
12451   /* Verify the required arguments in the original call.  */
12452   if (!validate_arg (fmt, POINTER_TYPE))
12453     return NULL_TREE;
12454
12455   /* Check whether the format is a literal string constant.  */
12456   fmt_str = c_getstr (fmt);
12457   if (fmt_str == NULL)
12458     return NULL_TREE;
12459
12460   if (fcode == BUILT_IN_PRINTF_UNLOCKED)
12461     {
12462       /* If we're using an unlocked function, assume the other
12463          unlocked functions exist explicitly.  */
12464       fn_putchar = built_in_decls[BUILT_IN_PUTCHAR_UNLOCKED];
12465       fn_puts = built_in_decls[BUILT_IN_PUTS_UNLOCKED];
12466     }
12467   else
12468     {
12469       fn_putchar = implicit_built_in_decls[BUILT_IN_PUTCHAR];
12470       fn_puts = implicit_built_in_decls[BUILT_IN_PUTS];
12471     }
12472
12473   if (!init_target_chars ())
12474     return NULL_TREE;
12475
12476   if (strcmp (fmt_str, target_percent_s) == 0
12477       || strchr (fmt_str, target_percent) == NULL)
12478     {
12479       const char *str;
12480
12481       if (strcmp (fmt_str, target_percent_s) == 0)
12482         {
12483           if (fcode == BUILT_IN_VPRINTF || fcode == BUILT_IN_VPRINTF_CHK)
12484             return NULL_TREE;
12485
12486           if (!arg || !validate_arg (arg, POINTER_TYPE))
12487             return NULL_TREE;
12488
12489           str = c_getstr (arg);
12490           if (str == NULL)
12491             return NULL_TREE;
12492         }
12493       else
12494         {
12495           /* The format specifier doesn't contain any '%' characters.  */
12496           if (fcode != BUILT_IN_VPRINTF && fcode != BUILT_IN_VPRINTF_CHK
12497               && arg)
12498             return NULL_TREE;
12499           str = fmt_str;
12500         }
12501
12502       /* If the string was "", printf does nothing.  */
12503       if (str[0] == '\0')
12504         return build_int_cst (TREE_TYPE (TREE_TYPE (fndecl)), 0);
12505
12506       /* If the string has length of 1, call putchar.  */
12507       if (str[1] == '\0')
12508         {
12509           /* Given printf("c"), (where c is any one character,)
12510              convert "c"[0] to an int and pass that to the replacement
12511              function.  */
12512           newarg = build_int_cst (integer_type_node, str[0]);
12513           if (fn_putchar)
12514             call = build_call_expr_loc (loc, fn_putchar, 1, newarg);
12515         }
12516       else
12517         {
12518           /* If the string was "string\n", call puts("string").  */
12519           size_t len = strlen (str);
12520           if ((unsigned char)str[len - 1] == target_newline
12521               && (size_t) (int) len == len
12522               && (int) len > 0)
12523             {
12524               char *newstr;
12525               tree offset_node, string_cst;
12526
12527               /* Create a NUL-terminated string that's one char shorter
12528                  than the original, stripping off the trailing '\n'.  */
12529               newarg = build_string_literal (len, str);
12530               string_cst = string_constant (newarg, &offset_node);
12531               gcc_checking_assert (string_cst
12532                                    && (TREE_STRING_LENGTH (string_cst)
12533                                        == (int) len)
12534                                    && integer_zerop (offset_node)
12535                                    && (unsigned char)
12536                                       TREE_STRING_POINTER (string_cst)[len - 1]
12537                                       == target_newline);
12538               /* build_string_literal creates a new STRING_CST,
12539                  modify it in place to avoid double copying.  */
12540               newstr = CONST_CAST (char *, TREE_STRING_POINTER (string_cst));
12541               newstr[len - 1] = '\0';
12542               if (fn_puts)
12543                 call = build_call_expr_loc (loc, fn_puts, 1, newarg);
12544             }
12545           else
12546             /* We'd like to arrange to call fputs(string,stdout) here,
12547                but we need stdout and don't have a way to get it yet.  */
12548             return NULL_TREE;
12549         }
12550     }
12551
12552   /* The other optimizations can be done only on the non-va_list variants.  */
12553   else if (fcode == BUILT_IN_VPRINTF || fcode == BUILT_IN_VPRINTF_CHK)
12554     return NULL_TREE;
12555
12556   /* If the format specifier was "%s\n", call __builtin_puts(arg).  */
12557   else if (strcmp (fmt_str, target_percent_s_newline) == 0)
12558     {
12559       if (!arg || !validate_arg (arg, POINTER_TYPE))
12560         return NULL_TREE;
12561       if (fn_puts)
12562         call = build_call_expr_loc (loc, fn_puts, 1, arg);
12563     }
12564
12565   /* If the format specifier was "%c", call __builtin_putchar(arg).  */
12566   else if (strcmp (fmt_str, target_percent_c) == 0)
12567     {
12568       if (!arg || !validate_arg (arg, INTEGER_TYPE))
12569         return NULL_TREE;
12570       if (fn_putchar)
12571         call = build_call_expr_loc (loc, fn_putchar, 1, arg);
12572     }
12573
12574   if (!call)
12575     return NULL_TREE;
12576
12577   return fold_convert_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)), call);
12578 }
12579
12580 /* Fold a call to the {,v}fprintf{,_unlocked} and __{,v}printf_chk builtins.
12581    FP, FMT, and ARG are the arguments to the call.  We don't fold calls with
12582    more than 3 arguments, and ARG may be null in the 2-argument case.
12583
12584    Return NULL_TREE if no simplification was possible, otherwise return the
12585    simplified form of the call as a tree.  FCODE is the BUILT_IN_*
12586    code of the function to be simplified.  */
12587
12588 static tree
12589 fold_builtin_fprintf (location_t loc, tree fndecl, tree fp,
12590                       tree fmt, tree arg, bool ignore,
12591                       enum built_in_function fcode)
12592 {
12593   tree fn_fputc, fn_fputs, call = NULL_TREE;
12594   const char *fmt_str = NULL;
12595
12596   /* If the return value is used, don't do the transformation.  */
12597   if (! ignore)
12598     return NULL_TREE;
12599
12600   /* Verify the required arguments in the original call.  */
12601   if (!validate_arg (fp, POINTER_TYPE))
12602     return NULL_TREE;
12603   if (!validate_arg (fmt, POINTER_TYPE))
12604     return NULL_TREE;
12605
12606   /* Check whether the format is a literal string constant.  */
12607   fmt_str = c_getstr (fmt);
12608   if (fmt_str == NULL)
12609     return NULL_TREE;
12610
12611   if (fcode == BUILT_IN_FPRINTF_UNLOCKED)
12612     {
12613       /* If we're using an unlocked function, assume the other
12614          unlocked functions exist explicitly.  */
12615       fn_fputc = built_in_decls[BUILT_IN_FPUTC_UNLOCKED];
12616       fn_fputs = built_in_decls[BUILT_IN_FPUTS_UNLOCKED];
12617     }
12618   else
12619     {
12620       fn_fputc = implicit_built_in_decls[BUILT_IN_FPUTC];
12621       fn_fputs = implicit_built_in_decls[BUILT_IN_FPUTS];
12622     }
12623
12624   if (!init_target_chars ())
12625     return NULL_TREE;
12626
12627   /* If the format doesn't contain % args or %%, use strcpy.  */
12628   if (strchr (fmt_str, target_percent) == NULL)
12629     {
12630       if (fcode != BUILT_IN_VFPRINTF && fcode != BUILT_IN_VFPRINTF_CHK
12631           && arg)
12632         return NULL_TREE;
12633
12634       /* If the format specifier was "", fprintf does nothing.  */
12635       if (fmt_str[0] == '\0')
12636         {
12637           /* If FP has side-effects, just wait until gimplification is
12638              done.  */
12639           if (TREE_SIDE_EFFECTS (fp))
12640             return NULL_TREE;
12641
12642           return build_int_cst (TREE_TYPE (TREE_TYPE (fndecl)), 0);
12643         }
12644
12645       /* When "string" doesn't contain %, replace all cases of
12646          fprintf (fp, string) with fputs (string, fp).  The fputs
12647          builtin will take care of special cases like length == 1.  */
12648       if (fn_fputs)
12649         call = build_call_expr_loc (loc, fn_fputs, 2, fmt, fp);
12650     }
12651
12652   /* The other optimizations can be done only on the non-va_list variants.  */
12653   else if (fcode == BUILT_IN_VFPRINTF || fcode == BUILT_IN_VFPRINTF_CHK)
12654     return NULL_TREE;
12655
12656   /* If the format specifier was "%s", call __builtin_fputs (arg, fp).  */
12657   else if (strcmp (fmt_str, target_percent_s) == 0)
12658     {
12659       if (!arg || !validate_arg (arg, POINTER_TYPE))
12660         return NULL_TREE;
12661       if (fn_fputs)
12662         call = build_call_expr_loc (loc, fn_fputs, 2, arg, fp);
12663     }
12664
12665   /* If the format specifier was "%c", call __builtin_fputc (arg, fp).  */
12666   else if (strcmp (fmt_str, target_percent_c) == 0)
12667     {
12668       if (!arg || !validate_arg (arg, INTEGER_TYPE))
12669         return NULL_TREE;
12670       if (fn_fputc)
12671         call = build_call_expr_loc (loc, fn_fputc, 2, arg, fp);
12672     }
12673
12674   if (!call)
12675     return NULL_TREE;
12676   return fold_convert_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)), call);
12677 }
12678
12679 /* Initialize format string characters in the target charset.  */
12680
12681 static bool
12682 init_target_chars (void)
12683 {
12684   static bool init;
12685   if (!init)
12686     {
12687       target_newline = lang_hooks.to_target_charset ('\n');
12688       target_percent = lang_hooks.to_target_charset ('%');
12689       target_c = lang_hooks.to_target_charset ('c');
12690       target_s = lang_hooks.to_target_charset ('s');
12691       if (target_newline == 0 || target_percent == 0 || target_c == 0
12692           || target_s == 0)
12693         return false;
12694
12695       target_percent_c[0] = target_percent;
12696       target_percent_c[1] = target_c;
12697       target_percent_c[2] = '\0';
12698
12699       target_percent_s[0] = target_percent;
12700       target_percent_s[1] = target_s;
12701       target_percent_s[2] = '\0';
12702
12703       target_percent_s_newline[0] = target_percent;
12704       target_percent_s_newline[1] = target_s;
12705       target_percent_s_newline[2] = target_newline;
12706       target_percent_s_newline[3] = '\0';
12707
12708       init = true;
12709     }
12710   return true;
12711 }
12712
12713 /* Helper function for do_mpfr_arg*().  Ensure M is a normal number
12714    and no overflow/underflow occurred.  INEXACT is true if M was not
12715    exactly calculated.  TYPE is the tree type for the result.  This
12716    function assumes that you cleared the MPFR flags and then
12717    calculated M to see if anything subsequently set a flag prior to
12718    entering this function.  Return NULL_TREE if any checks fail.  */
12719
12720 static tree
12721 do_mpfr_ckconv (mpfr_srcptr m, tree type, int inexact)
12722 {
12723   /* Proceed iff we get a normal number, i.e. not NaN or Inf and no
12724      overflow/underflow occurred.  If -frounding-math, proceed iff the
12725      result of calling FUNC was exact.  */
12726   if (mpfr_number_p (m) && !mpfr_overflow_p () && !mpfr_underflow_p ()
12727       && (!flag_rounding_math || !inexact))
12728     {
12729       REAL_VALUE_TYPE rr;
12730
12731       real_from_mpfr (&rr, m, type, GMP_RNDN);
12732       /* Proceed iff GCC's REAL_VALUE_TYPE can hold the MPFR value,
12733          check for overflow/underflow.  If the REAL_VALUE_TYPE is zero
12734          but the mpft_t is not, then we underflowed in the
12735          conversion.  */
12736       if (real_isfinite (&rr)
12737           && (rr.cl == rvc_zero) == (mpfr_zero_p (m) != 0))
12738         {
12739           REAL_VALUE_TYPE rmode;
12740
12741           real_convert (&rmode, TYPE_MODE (type), &rr);
12742           /* Proceed iff the specified mode can hold the value.  */
12743           if (real_identical (&rmode, &rr))
12744             return build_real (type, rmode);
12745         }
12746     }
12747   return NULL_TREE;
12748 }
12749
12750 /* Helper function for do_mpc_arg*().  Ensure M is a normal complex
12751    number and no overflow/underflow occurred.  INEXACT is true if M
12752    was not exactly calculated.  TYPE is the tree type for the result.
12753    This function assumes that you cleared the MPFR flags and then
12754    calculated M to see if anything subsequently set a flag prior to
12755    entering this function.  Return NULL_TREE if any checks fail, if
12756    FORCE_CONVERT is true, then bypass the checks.  */
12757
12758 static tree
12759 do_mpc_ckconv (mpc_srcptr m, tree type, int inexact, int force_convert)
12760 {
12761   /* Proceed iff we get a normal number, i.e. not NaN or Inf and no
12762      overflow/underflow occurred.  If -frounding-math, proceed iff the
12763      result of calling FUNC was exact.  */
12764   if (force_convert
12765       || (mpfr_number_p (mpc_realref (m)) && mpfr_number_p (mpc_imagref (m))
12766           && !mpfr_overflow_p () && !mpfr_underflow_p ()
12767           && (!flag_rounding_math || !inexact)))
12768     {
12769       REAL_VALUE_TYPE re, im;
12770
12771       real_from_mpfr (&re, mpc_realref (m), TREE_TYPE (type), GMP_RNDN);
12772       real_from_mpfr (&im, mpc_imagref (m), TREE_TYPE (type), GMP_RNDN);
12773       /* Proceed iff GCC's REAL_VALUE_TYPE can hold the MPFR values,
12774          check for overflow/underflow.  If the REAL_VALUE_TYPE is zero
12775          but the mpft_t is not, then we underflowed in the
12776          conversion.  */
12777       if (force_convert
12778           || (real_isfinite (&re) && real_isfinite (&im)
12779               && (re.cl == rvc_zero) == (mpfr_zero_p (mpc_realref (m)) != 0)
12780               && (im.cl == rvc_zero) == (mpfr_zero_p (mpc_imagref (m)) != 0)))
12781         {
12782           REAL_VALUE_TYPE re_mode, im_mode;
12783
12784           real_convert (&re_mode, TYPE_MODE (TREE_TYPE (type)), &re);
12785           real_convert (&im_mode, TYPE_MODE (TREE_TYPE (type)), &im);
12786           /* Proceed iff the specified mode can hold the value.  */
12787           if (force_convert
12788               || (real_identical (&re_mode, &re)
12789                   && real_identical (&im_mode, &im)))
12790             return build_complex (type, build_real (TREE_TYPE (type), re_mode),
12791                                   build_real (TREE_TYPE (type), im_mode));
12792         }
12793     }
12794   return NULL_TREE;
12795 }
12796
12797 /* If argument ARG is a REAL_CST, call the one-argument mpfr function
12798    FUNC on it and return the resulting value as a tree with type TYPE.
12799    If MIN and/or MAX are not NULL, then the supplied ARG must be
12800    within those bounds.  If INCLUSIVE is true, then MIN/MAX are
12801    acceptable values, otherwise they are not.  The mpfr precision is
12802    set to the precision of TYPE.  We assume that function FUNC returns
12803    zero if the result could be calculated exactly within the requested
12804    precision.  */
12805
12806 static tree
12807 do_mpfr_arg1 (tree arg, tree type, int (*func)(mpfr_ptr, mpfr_srcptr, mp_rnd_t),
12808               const REAL_VALUE_TYPE *min, const REAL_VALUE_TYPE *max,
12809               bool inclusive)
12810 {
12811   tree result = NULL_TREE;
12812
12813   STRIP_NOPS (arg);
12814
12815   /* To proceed, MPFR must exactly represent the target floating point
12816      format, which only happens when the target base equals two.  */
12817   if (REAL_MODE_FORMAT (TYPE_MODE (type))->b == 2
12818       && TREE_CODE (arg) == REAL_CST && !TREE_OVERFLOW (arg))
12819     {
12820       const REAL_VALUE_TYPE *const ra = &TREE_REAL_CST (arg);
12821
12822       if (real_isfinite (ra)
12823           && (!min || real_compare (inclusive ? GE_EXPR: GT_EXPR , ra, min))
12824           && (!max || real_compare (inclusive ? LE_EXPR: LT_EXPR , ra, max)))
12825         {
12826           const struct real_format *fmt = REAL_MODE_FORMAT (TYPE_MODE (type));
12827           const int prec = fmt->p;
12828           const mp_rnd_t rnd = fmt->round_towards_zero? GMP_RNDZ : GMP_RNDN;
12829           int inexact;
12830           mpfr_t m;
12831
12832           mpfr_init2 (m, prec);
12833           mpfr_from_real (m, ra, GMP_RNDN);
12834           mpfr_clear_flags ();
12835           inexact = func (m, m, rnd);
12836           result = do_mpfr_ckconv (m, type, inexact);
12837           mpfr_clear (m);
12838         }
12839     }
12840
12841   return result;
12842 }
12843
12844 /* If argument ARG is a REAL_CST, call the two-argument mpfr function
12845    FUNC on it and return the resulting value as a tree with type TYPE.
12846    The mpfr precision is set to the precision of TYPE.  We assume that
12847    function FUNC returns zero if the result could be calculated
12848    exactly within the requested precision.  */
12849
12850 static tree
12851 do_mpfr_arg2 (tree arg1, tree arg2, tree type,
12852               int (*func)(mpfr_ptr, mpfr_srcptr, mpfr_srcptr, mp_rnd_t))
12853 {
12854   tree result = NULL_TREE;
12855
12856   STRIP_NOPS (arg1);
12857   STRIP_NOPS (arg2);
12858
12859   /* To proceed, MPFR must exactly represent the target floating point
12860      format, which only happens when the target base equals two.  */
12861   if (REAL_MODE_FORMAT (TYPE_MODE (type))->b == 2
12862       && TREE_CODE (arg1) == REAL_CST && !TREE_OVERFLOW (arg1)
12863       && TREE_CODE (arg2) == REAL_CST && !TREE_OVERFLOW (arg2))
12864     {
12865       const REAL_VALUE_TYPE *const ra1 = &TREE_REAL_CST (arg1);
12866       const REAL_VALUE_TYPE *const ra2 = &TREE_REAL_CST (arg2);
12867
12868       if (real_isfinite (ra1) && real_isfinite (ra2))
12869         {
12870           const struct real_format *fmt = REAL_MODE_FORMAT (TYPE_MODE (type));
12871           const int prec = fmt->p;
12872           const mp_rnd_t rnd = fmt->round_towards_zero? GMP_RNDZ : GMP_RNDN;
12873           int inexact;
12874           mpfr_t m1, m2;
12875
12876           mpfr_inits2 (prec, m1, m2, NULL);
12877           mpfr_from_real (m1, ra1, GMP_RNDN);
12878           mpfr_from_real (m2, ra2, GMP_RNDN);
12879           mpfr_clear_flags ();
12880           inexact = func (m1, m1, m2, rnd);
12881           result = do_mpfr_ckconv (m1, type, inexact);
12882           mpfr_clears (m1, m2, NULL);
12883         }
12884     }
12885
12886   return result;
12887 }
12888
12889 /* If argument ARG is a REAL_CST, call the three-argument mpfr function
12890    FUNC on it and return the resulting value as a tree with type TYPE.
12891    The mpfr precision is set to the precision of TYPE.  We assume that
12892    function FUNC returns zero if the result could be calculated
12893    exactly within the requested precision.  */
12894
12895 static tree
12896 do_mpfr_arg3 (tree arg1, tree arg2, tree arg3, tree type,
12897               int (*func)(mpfr_ptr, mpfr_srcptr, mpfr_srcptr, mpfr_srcptr, mp_rnd_t))
12898 {
12899   tree result = NULL_TREE;
12900
12901   STRIP_NOPS (arg1);
12902   STRIP_NOPS (arg2);
12903   STRIP_NOPS (arg3);
12904
12905   /* To proceed, MPFR must exactly represent the target floating point
12906      format, which only happens when the target base equals two.  */
12907   if (REAL_MODE_FORMAT (TYPE_MODE (type))->b == 2
12908       && TREE_CODE (arg1) == REAL_CST && !TREE_OVERFLOW (arg1)
12909       && TREE_CODE (arg2) == REAL_CST && !TREE_OVERFLOW (arg2)
12910       && TREE_CODE (arg3) == REAL_CST && !TREE_OVERFLOW (arg3))
12911     {
12912       const REAL_VALUE_TYPE *const ra1 = &TREE_REAL_CST (arg1);
12913       const REAL_VALUE_TYPE *const ra2 = &TREE_REAL_CST (arg2);
12914       const REAL_VALUE_TYPE *const ra3 = &TREE_REAL_CST (arg3);
12915
12916       if (real_isfinite (ra1) && real_isfinite (ra2) && real_isfinite (ra3))
12917         {
12918           const struct real_format *fmt = REAL_MODE_FORMAT (TYPE_MODE (type));
12919           const int prec = fmt->p;
12920           const mp_rnd_t rnd = fmt->round_towards_zero? GMP_RNDZ : GMP_RNDN;
12921           int inexact;
12922           mpfr_t m1, m2, m3;
12923
12924           mpfr_inits2 (prec, m1, m2, m3, NULL);
12925           mpfr_from_real (m1, ra1, GMP_RNDN);
12926           mpfr_from_real (m2, ra2, GMP_RNDN);
12927           mpfr_from_real (m3, ra3, GMP_RNDN);
12928           mpfr_clear_flags ();
12929           inexact = func (m1, m1, m2, m3, rnd);
12930           result = do_mpfr_ckconv (m1, type, inexact);
12931           mpfr_clears (m1, m2, m3, NULL);
12932         }
12933     }
12934
12935   return result;
12936 }
12937
12938 /* If argument ARG is a REAL_CST, call mpfr_sin_cos() on it and set
12939    the pointers *(ARG_SINP) and *(ARG_COSP) to the resulting values.
12940    If ARG_SINP and ARG_COSP are NULL then the result is returned
12941    as a complex value.
12942    The type is taken from the type of ARG and is used for setting the
12943    precision of the calculation and results.  */
12944
12945 static tree
12946 do_mpfr_sincos (tree arg, tree arg_sinp, tree arg_cosp)
12947 {
12948   tree const type = TREE_TYPE (arg);
12949   tree result = NULL_TREE;
12950
12951   STRIP_NOPS (arg);
12952
12953   /* To proceed, MPFR must exactly represent the target floating point
12954      format, which only happens when the target base equals two.  */
12955   if (REAL_MODE_FORMAT (TYPE_MODE (type))->b == 2
12956       && TREE_CODE (arg) == REAL_CST
12957       && !TREE_OVERFLOW (arg))
12958     {
12959       const REAL_VALUE_TYPE *const ra = &TREE_REAL_CST (arg);
12960
12961       if (real_isfinite (ra))
12962         {
12963           const struct real_format *fmt = REAL_MODE_FORMAT (TYPE_MODE (type));
12964           const int prec = fmt->p;
12965           const mp_rnd_t rnd = fmt->round_towards_zero? GMP_RNDZ : GMP_RNDN;
12966           tree result_s, result_c;
12967           int inexact;
12968           mpfr_t m, ms, mc;
12969
12970           mpfr_inits2 (prec, m, ms, mc, NULL);
12971           mpfr_from_real (m, ra, GMP_RNDN);
12972           mpfr_clear_flags ();
12973           inexact = mpfr_sin_cos (ms, mc, m, rnd);
12974           result_s = do_mpfr_ckconv (ms, type, inexact);
12975           result_c = do_mpfr_ckconv (mc, type, inexact);
12976           mpfr_clears (m, ms, mc, NULL);
12977           if (result_s && result_c)
12978             {
12979               /* If we are to return in a complex value do so.  */
12980               if (!arg_sinp && !arg_cosp)
12981                 return build_complex (build_complex_type (type),
12982                                       result_c, result_s);
12983
12984               /* Dereference the sin/cos pointer arguments.  */
12985               arg_sinp = build_fold_indirect_ref (arg_sinp);
12986               arg_cosp = build_fold_indirect_ref (arg_cosp);
12987               /* Proceed if valid pointer type were passed in.  */
12988               if (TYPE_MAIN_VARIANT (TREE_TYPE (arg_sinp)) == TYPE_MAIN_VARIANT (type)
12989                   && TYPE_MAIN_VARIANT (TREE_TYPE (arg_cosp)) == TYPE_MAIN_VARIANT (type))
12990                 {
12991                   /* Set the values. */
12992                   result_s = fold_build2 (MODIFY_EXPR, type, arg_sinp,
12993                                           result_s);
12994                   TREE_SIDE_EFFECTS (result_s) = 1;
12995                   result_c = fold_build2 (MODIFY_EXPR, type, arg_cosp,
12996                                           result_c);
12997                   TREE_SIDE_EFFECTS (result_c) = 1;
12998                   /* Combine the assignments into a compound expr.  */
12999                   result = non_lvalue (fold_build2 (COMPOUND_EXPR, type,
13000                                                     result_s, result_c));
13001                 }
13002             }
13003         }
13004     }
13005   return result;
13006 }
13007
13008 /* If argument ARG1 is an INTEGER_CST and ARG2 is a REAL_CST, call the
13009    two-argument mpfr order N Bessel function FUNC on them and return
13010    the resulting value as a tree with type TYPE.  The mpfr precision
13011    is set to the precision of TYPE.  We assume that function FUNC
13012    returns zero if the result could be calculated exactly within the
13013    requested precision.  */
13014 static tree
13015 do_mpfr_bessel_n (tree arg1, tree arg2, tree type,
13016                   int (*func)(mpfr_ptr, long, mpfr_srcptr, mp_rnd_t),
13017                   const REAL_VALUE_TYPE *min, bool inclusive)
13018 {
13019   tree result = NULL_TREE;
13020
13021   STRIP_NOPS (arg1);
13022   STRIP_NOPS (arg2);
13023
13024   /* To proceed, MPFR must exactly represent the target floating point
13025      format, which only happens when the target base equals two.  */
13026   if (REAL_MODE_FORMAT (TYPE_MODE (type))->b == 2
13027       && host_integerp (arg1, 0)
13028       && TREE_CODE (arg2) == REAL_CST && !TREE_OVERFLOW (arg2))
13029     {
13030       const HOST_WIDE_INT n = tree_low_cst(arg1, 0);
13031       const REAL_VALUE_TYPE *const ra = &TREE_REAL_CST (arg2);
13032
13033       if (n == (long)n
13034           && real_isfinite (ra)
13035           && (!min || real_compare (inclusive ? GE_EXPR: GT_EXPR , ra, min)))
13036         {
13037           const struct real_format *fmt = REAL_MODE_FORMAT (TYPE_MODE (type));
13038           const int prec = fmt->p;
13039           const mp_rnd_t rnd = fmt->round_towards_zero? GMP_RNDZ : GMP_RNDN;
13040           int inexact;
13041           mpfr_t m;
13042
13043           mpfr_init2 (m, prec);
13044           mpfr_from_real (m, ra, GMP_RNDN);
13045           mpfr_clear_flags ();
13046           inexact = func (m, n, m, rnd);
13047           result = do_mpfr_ckconv (m, type, inexact);
13048           mpfr_clear (m);
13049         }
13050     }
13051
13052   return result;
13053 }
13054
13055 /* If arguments ARG0 and ARG1 are REAL_CSTs, call mpfr_remquo() to set
13056    the pointer *(ARG_QUO) and return the result.  The type is taken
13057    from the type of ARG0 and is used for setting the precision of the
13058    calculation and results.  */
13059
13060 static tree
13061 do_mpfr_remquo (tree arg0, tree arg1, tree arg_quo)
13062 {
13063   tree const type = TREE_TYPE (arg0);
13064   tree result = NULL_TREE;
13065
13066   STRIP_NOPS (arg0);
13067   STRIP_NOPS (arg1);
13068
13069   /* To proceed, MPFR must exactly represent the target floating point
13070      format, which only happens when the target base equals two.  */
13071   if (REAL_MODE_FORMAT (TYPE_MODE (type))->b == 2
13072       && TREE_CODE (arg0) == REAL_CST && !TREE_OVERFLOW (arg0)
13073       && TREE_CODE (arg1) == REAL_CST && !TREE_OVERFLOW (arg1))
13074     {
13075       const REAL_VALUE_TYPE *const ra0 = TREE_REAL_CST_PTR (arg0);
13076       const REAL_VALUE_TYPE *const ra1 = TREE_REAL_CST_PTR (arg1);
13077
13078       if (real_isfinite (ra0) && real_isfinite (ra1))
13079         {
13080           const struct real_format *fmt = REAL_MODE_FORMAT (TYPE_MODE (type));
13081           const int prec = fmt->p;
13082           const mp_rnd_t rnd = fmt->round_towards_zero? GMP_RNDZ : GMP_RNDN;
13083           tree result_rem;
13084           long integer_quo;
13085           mpfr_t m0, m1;
13086
13087           mpfr_inits2 (prec, m0, m1, NULL);
13088           mpfr_from_real (m0, ra0, GMP_RNDN);
13089           mpfr_from_real (m1, ra1, GMP_RNDN);
13090           mpfr_clear_flags ();
13091           mpfr_remquo (m0, &integer_quo, m0, m1, rnd);
13092           /* Remquo is independent of the rounding mode, so pass
13093              inexact=0 to do_mpfr_ckconv().  */
13094           result_rem = do_mpfr_ckconv (m0, type, /*inexact=*/ 0);
13095           mpfr_clears (m0, m1, NULL);
13096           if (result_rem)
13097             {
13098               /* MPFR calculates quo in the host's long so it may
13099                  return more bits in quo than the target int can hold
13100                  if sizeof(host long) > sizeof(target int).  This can
13101                  happen even for native compilers in LP64 mode.  In
13102                  these cases, modulo the quo value with the largest
13103                  number that the target int can hold while leaving one
13104                  bit for the sign.  */
13105               if (sizeof (integer_quo) * CHAR_BIT > INT_TYPE_SIZE)
13106                 integer_quo %= (long)(1UL << (INT_TYPE_SIZE - 1));
13107
13108               /* Dereference the quo pointer argument.  */
13109               arg_quo = build_fold_indirect_ref (arg_quo);
13110               /* Proceed iff a valid pointer type was passed in.  */
13111               if (TYPE_MAIN_VARIANT (TREE_TYPE (arg_quo)) == integer_type_node)
13112                 {
13113                   /* Set the value. */
13114                   tree result_quo
13115                     = fold_build2 (MODIFY_EXPR, TREE_TYPE (arg_quo), arg_quo,
13116                                    build_int_cst (TREE_TYPE (arg_quo),
13117                                                   integer_quo));
13118                   TREE_SIDE_EFFECTS (result_quo) = 1;
13119                   /* Combine the quo assignment with the rem.  */
13120                   result = non_lvalue (fold_build2 (COMPOUND_EXPR, type,
13121                                                     result_quo, result_rem));
13122                 }
13123             }
13124         }
13125     }
13126   return result;
13127 }
13128
13129 /* If ARG is a REAL_CST, call mpfr_lgamma() on it and return the
13130    resulting value as a tree with type TYPE.  The mpfr precision is
13131    set to the precision of TYPE.  We assume that this mpfr function
13132    returns zero if the result could be calculated exactly within the
13133    requested precision.  In addition, the integer pointer represented
13134    by ARG_SG will be dereferenced and set to the appropriate signgam
13135    (-1,1) value.  */
13136
13137 static tree
13138 do_mpfr_lgamma_r (tree arg, tree arg_sg, tree type)
13139 {
13140   tree result = NULL_TREE;
13141
13142   STRIP_NOPS (arg);
13143
13144   /* To proceed, MPFR must exactly represent the target floating point
13145      format, which only happens when the target base equals two.  Also
13146      verify ARG is a constant and that ARG_SG is an int pointer.  */
13147   if (REAL_MODE_FORMAT (TYPE_MODE (type))->b == 2
13148       && TREE_CODE (arg) == REAL_CST && !TREE_OVERFLOW (arg)
13149       && TREE_CODE (TREE_TYPE (arg_sg)) == POINTER_TYPE
13150       && TYPE_MAIN_VARIANT (TREE_TYPE (TREE_TYPE (arg_sg))) == integer_type_node)
13151     {
13152       const REAL_VALUE_TYPE *const ra = TREE_REAL_CST_PTR (arg);
13153
13154       /* In addition to NaN and Inf, the argument cannot be zero or a
13155          negative integer.  */
13156       if (real_isfinite (ra)
13157           && ra->cl != rvc_zero
13158           && !(real_isneg(ra) && real_isinteger(ra, TYPE_MODE (type))))
13159         {
13160           const struct real_format *fmt = REAL_MODE_FORMAT (TYPE_MODE (type));
13161           const int prec = fmt->p;
13162           const mp_rnd_t rnd = fmt->round_towards_zero? GMP_RNDZ : GMP_RNDN;
13163           int inexact, sg;
13164           mpfr_t m;
13165           tree result_lg;
13166
13167           mpfr_init2 (m, prec);
13168           mpfr_from_real (m, ra, GMP_RNDN);
13169           mpfr_clear_flags ();
13170           inexact = mpfr_lgamma (m, &sg, m, rnd);
13171           result_lg = do_mpfr_ckconv (m, type, inexact);
13172           mpfr_clear (m);
13173           if (result_lg)
13174             {
13175               tree result_sg;
13176
13177               /* Dereference the arg_sg pointer argument.  */
13178               arg_sg = build_fold_indirect_ref (arg_sg);
13179               /* Assign the signgam value into *arg_sg. */
13180               result_sg = fold_build2 (MODIFY_EXPR,
13181                                        TREE_TYPE (arg_sg), arg_sg,
13182                                        build_int_cst (TREE_TYPE (arg_sg), sg));
13183               TREE_SIDE_EFFECTS (result_sg) = 1;
13184               /* Combine the signgam assignment with the lgamma result.  */
13185               result = non_lvalue (fold_build2 (COMPOUND_EXPR, type,
13186                                                 result_sg, result_lg));
13187             }
13188         }
13189     }
13190
13191   return result;
13192 }
13193
13194 /* If argument ARG is a COMPLEX_CST, call the one-argument mpc
13195    function FUNC on it and return the resulting value as a tree with
13196    type TYPE.  The mpfr precision is set to the precision of TYPE.  We
13197    assume that function FUNC returns zero if the result could be
13198    calculated exactly within the requested precision.  */
13199
13200 static tree
13201 do_mpc_arg1 (tree arg, tree type, int (*func)(mpc_ptr, mpc_srcptr, mpc_rnd_t))
13202 {
13203   tree result = NULL_TREE;
13204
13205   STRIP_NOPS (arg);
13206
13207   /* To proceed, MPFR must exactly represent the target floating point
13208      format, which only happens when the target base equals two.  */
13209   if (TREE_CODE (arg) == COMPLEX_CST && !TREE_OVERFLOW (arg)
13210       && TREE_CODE (TREE_TYPE (TREE_TYPE (arg))) == REAL_TYPE
13211       && REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (TREE_TYPE (arg))))->b == 2)
13212     {
13213       const REAL_VALUE_TYPE *const re = TREE_REAL_CST_PTR (TREE_REALPART (arg));
13214       const REAL_VALUE_TYPE *const im = TREE_REAL_CST_PTR (TREE_IMAGPART (arg));
13215
13216       if (real_isfinite (re) && real_isfinite (im))
13217         {
13218           const struct real_format *const fmt =
13219             REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (type)));
13220           const int prec = fmt->p;
13221           const mp_rnd_t rnd = fmt->round_towards_zero ? GMP_RNDZ : GMP_RNDN;
13222           const mpc_rnd_t crnd = fmt->round_towards_zero ? MPC_RNDZZ : MPC_RNDNN;
13223           int inexact;
13224           mpc_t m;
13225
13226           mpc_init2 (m, prec);
13227           mpfr_from_real (mpc_realref(m), re, rnd);
13228           mpfr_from_real (mpc_imagref(m), im, rnd);
13229           mpfr_clear_flags ();
13230           inexact = func (m, m, crnd);
13231           result = do_mpc_ckconv (m, type, inexact, /*force_convert=*/ 0);
13232           mpc_clear (m);
13233         }
13234     }
13235
13236   return result;
13237 }
13238
13239 /* If arguments ARG0 and ARG1 are a COMPLEX_CST, call the two-argument
13240    mpc function FUNC on it and return the resulting value as a tree
13241    with type TYPE.  The mpfr precision is set to the precision of
13242    TYPE.  We assume that function FUNC returns zero if the result
13243    could be calculated exactly within the requested precision.  If
13244    DO_NONFINITE is true, then fold expressions containing Inf or NaN
13245    in the arguments and/or results.  */
13246
13247 tree
13248 do_mpc_arg2 (tree arg0, tree arg1, tree type, int do_nonfinite,
13249              int (*func)(mpc_ptr, mpc_srcptr, mpc_srcptr, mpc_rnd_t))
13250 {
13251   tree result = NULL_TREE;
13252
13253   STRIP_NOPS (arg0);
13254   STRIP_NOPS (arg1);
13255
13256   /* To proceed, MPFR must exactly represent the target floating point
13257      format, which only happens when the target base equals two.  */
13258   if (TREE_CODE (arg0) == COMPLEX_CST && !TREE_OVERFLOW (arg0)
13259       && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE
13260       && TREE_CODE (arg1) == COMPLEX_CST && !TREE_OVERFLOW (arg1)
13261       && TREE_CODE (TREE_TYPE (TREE_TYPE (arg1))) == REAL_TYPE
13262       && REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (TREE_TYPE (arg0))))->b == 2)
13263     {
13264       const REAL_VALUE_TYPE *const re0 = TREE_REAL_CST_PTR (TREE_REALPART (arg0));
13265       const REAL_VALUE_TYPE *const im0 = TREE_REAL_CST_PTR (TREE_IMAGPART (arg0));
13266       const REAL_VALUE_TYPE *const re1 = TREE_REAL_CST_PTR (TREE_REALPART (arg1));
13267       const REAL_VALUE_TYPE *const im1 = TREE_REAL_CST_PTR (TREE_IMAGPART (arg1));
13268
13269       if (do_nonfinite
13270           || (real_isfinite (re0) && real_isfinite (im0)
13271               && real_isfinite (re1) && real_isfinite (im1)))
13272         {
13273           const struct real_format *const fmt =
13274             REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (type)));
13275           const int prec = fmt->p;
13276           const mp_rnd_t rnd = fmt->round_towards_zero ? GMP_RNDZ : GMP_RNDN;
13277           const mpc_rnd_t crnd = fmt->round_towards_zero ? MPC_RNDZZ : MPC_RNDNN;
13278           int inexact;
13279           mpc_t m0, m1;
13280
13281           mpc_init2 (m0, prec);
13282           mpc_init2 (m1, prec);
13283           mpfr_from_real (mpc_realref(m0), re0, rnd);
13284           mpfr_from_real (mpc_imagref(m0), im0, rnd);
13285           mpfr_from_real (mpc_realref(m1), re1, rnd);
13286           mpfr_from_real (mpc_imagref(m1), im1, rnd);
13287           mpfr_clear_flags ();
13288           inexact = func (m0, m0, m1, crnd);
13289           result = do_mpc_ckconv (m0, type, inexact, do_nonfinite);
13290           mpc_clear (m0);
13291           mpc_clear (m1);
13292         }
13293     }
13294
13295   return result;
13296 }
13297
13298 /* Fold a call STMT to __{,v}sprintf_chk.  Return NULL_TREE if
13299    a normal call should be emitted rather than expanding the function
13300    inline.  FCODE is either BUILT_IN_SPRINTF_CHK or BUILT_IN_VSPRINTF_CHK.  */
13301
13302 static tree
13303 gimple_fold_builtin_sprintf_chk (gimple stmt, enum built_in_function fcode)
13304 {
13305   int nargs = gimple_call_num_args (stmt);
13306
13307   return fold_builtin_sprintf_chk_1 (gimple_location (stmt), nargs,
13308                                      (nargs > 0
13309                                       ? gimple_call_arg_ptr (stmt, 0)
13310                                       : &error_mark_node), fcode);
13311 }
13312
13313 /* Fold a call STMT to {,v}snprintf.  Return NULL_TREE if
13314    a normal call should be emitted rather than expanding the function
13315    inline.  FCODE is either BUILT_IN_SNPRINTF_CHK or
13316    BUILT_IN_VSNPRINTF_CHK.  If MAXLEN is not NULL, it is maximum length
13317    passed as second argument.  */
13318
13319 tree
13320 gimple_fold_builtin_snprintf_chk (gimple stmt, tree maxlen,
13321                                   enum built_in_function fcode)
13322 {
13323   int nargs = gimple_call_num_args (stmt);
13324
13325   return fold_builtin_snprintf_chk_1 (gimple_location (stmt), nargs,
13326                                       (nargs > 0
13327                                        ? gimple_call_arg_ptr (stmt, 0)
13328                                        : &error_mark_node), maxlen, fcode);
13329 }
13330
13331 /* Builtins with folding operations that operate on "..." arguments
13332    need special handling; we need to store the arguments in a convenient
13333    data structure before attempting any folding.  Fortunately there are
13334    only a few builtins that fall into this category.  FNDECL is the
13335    function, EXP is the CALL_EXPR for the call, and IGNORE is true if the
13336    result of the function call is ignored.  */
13337
13338 static tree
13339 gimple_fold_builtin_varargs (tree fndecl, gimple stmt,
13340                              bool ignore ATTRIBUTE_UNUSED)
13341 {
13342   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
13343   tree ret = NULL_TREE;
13344
13345   switch (fcode)
13346     {
13347     case BUILT_IN_SPRINTF_CHK:
13348     case BUILT_IN_VSPRINTF_CHK:
13349       ret = gimple_fold_builtin_sprintf_chk (stmt, fcode);
13350       break;
13351
13352     case BUILT_IN_SNPRINTF_CHK:
13353     case BUILT_IN_VSNPRINTF_CHK:
13354       ret = gimple_fold_builtin_snprintf_chk (stmt, NULL_TREE, fcode);
13355
13356     default:
13357       break;
13358     }
13359   if (ret)
13360     {
13361       ret = build1 (NOP_EXPR, TREE_TYPE (ret), ret);
13362       TREE_NO_WARNING (ret) = 1;
13363       return ret;
13364     }
13365   return NULL_TREE;
13366 }
13367
13368 /* A wrapper function for builtin folding that prevents warnings for
13369    "statement without effect" and the like, caused by removing the
13370    call node earlier than the warning is generated.  */
13371
13372 tree
13373 fold_call_stmt (gimple stmt, bool ignore)
13374 {
13375   tree ret = NULL_TREE;
13376   tree fndecl = gimple_call_fndecl (stmt);
13377   location_t loc = gimple_location (stmt);
13378   if (fndecl
13379       && TREE_CODE (fndecl) == FUNCTION_DECL
13380       && DECL_BUILT_IN (fndecl)
13381       && !gimple_call_va_arg_pack_p (stmt))
13382     {
13383       int nargs = gimple_call_num_args (stmt);
13384       tree *args = (nargs > 0
13385                     ? gimple_call_arg_ptr (stmt, 0)
13386                     : &error_mark_node);
13387
13388       if (avoid_folding_inline_builtin (fndecl))
13389         return NULL_TREE;
13390       if (DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_MD)
13391         {
13392           return targetm.fold_builtin (fndecl, nargs, args, ignore);
13393         }
13394       else
13395         {
13396           if (nargs <= MAX_ARGS_TO_FOLD_BUILTIN)
13397             ret = fold_builtin_n (loc, fndecl, args, nargs, ignore);
13398           if (!ret)
13399             ret = gimple_fold_builtin_varargs (fndecl, stmt, ignore);
13400           if (ret)
13401             {
13402               /* Propagate location information from original call to
13403                  expansion of builtin.  Otherwise things like
13404                  maybe_emit_chk_warning, that operate on the expansion
13405                  of a builtin, will use the wrong location information.  */
13406               if (gimple_has_location (stmt))
13407                 {
13408                   tree realret = ret;
13409                   if (TREE_CODE (ret) == NOP_EXPR)
13410                     realret = TREE_OPERAND (ret, 0);
13411                   if (CAN_HAVE_LOCATION_P (realret)
13412                       && !EXPR_HAS_LOCATION (realret))
13413                     SET_EXPR_LOCATION (realret, loc);
13414                   return realret;
13415                 }
13416               return ret;
13417             }
13418         }
13419     }
13420   return NULL_TREE;
13421 }
13422
13423 /* Look up the function in built_in_decls that corresponds to DECL
13424    and set ASMSPEC as its user assembler name.  DECL must be a
13425    function decl that declares a builtin.  */
13426
13427 void
13428 set_builtin_user_assembler_name (tree decl, const char *asmspec)
13429 {
13430   tree builtin;
13431   gcc_assert (TREE_CODE (decl) == FUNCTION_DECL
13432               && DECL_BUILT_IN_CLASS (decl) == BUILT_IN_NORMAL
13433               && asmspec != 0);
13434
13435   builtin = built_in_decls [DECL_FUNCTION_CODE (decl)];
13436   set_user_assembler_name (builtin, asmspec);
13437   switch (DECL_FUNCTION_CODE (decl))
13438     {
13439     case BUILT_IN_MEMCPY:
13440       init_block_move_fn (asmspec);
13441       memcpy_libfunc = set_user_assembler_libfunc ("memcpy", asmspec);
13442       break;
13443     case BUILT_IN_MEMSET:
13444       init_block_clear_fn (asmspec);
13445       memset_libfunc = set_user_assembler_libfunc ("memset", asmspec);
13446       break;
13447     case BUILT_IN_MEMMOVE:
13448       memmove_libfunc = set_user_assembler_libfunc ("memmove", asmspec);
13449       break;
13450     case BUILT_IN_MEMCMP:
13451       memcmp_libfunc = set_user_assembler_libfunc ("memcmp", asmspec);
13452       break;
13453     case BUILT_IN_ABORT:
13454       abort_libfunc = set_user_assembler_libfunc ("abort", asmspec);
13455       break;
13456     case BUILT_IN_FFS:
13457       if (INT_TYPE_SIZE < BITS_PER_WORD)
13458         {
13459           set_user_assembler_libfunc ("ffs", asmspec);
13460           set_optab_libfunc (ffs_optab, mode_for_size (INT_TYPE_SIZE,
13461                                                        MODE_INT, 0), "ffs");
13462         }
13463       break;
13464     default:
13465       break;
13466     }
13467 }
13468
13469 /* Return true if DECL is a builtin that expands to a constant or similarly
13470    simple code.  */
13471 bool
13472 is_simple_builtin (tree decl)
13473 {
13474   if (decl && DECL_BUILT_IN_CLASS (decl) == BUILT_IN_NORMAL)
13475     switch (DECL_FUNCTION_CODE (decl))
13476       {
13477         /* Builtins that expand to constants.  */
13478       case BUILT_IN_CONSTANT_P:
13479       case BUILT_IN_EXPECT:
13480       case BUILT_IN_OBJECT_SIZE:
13481       case BUILT_IN_UNREACHABLE:
13482         /* Simple register moves or loads from stack.  */
13483       case BUILT_IN_ASSUME_ALIGNED:
13484       case BUILT_IN_RETURN_ADDRESS:
13485       case BUILT_IN_EXTRACT_RETURN_ADDR:
13486       case BUILT_IN_FROB_RETURN_ADDR:
13487       case BUILT_IN_RETURN:
13488       case BUILT_IN_AGGREGATE_INCOMING_ADDRESS:
13489       case BUILT_IN_FRAME_ADDRESS:
13490       case BUILT_IN_VA_END:
13491       case BUILT_IN_STACK_SAVE:
13492       case BUILT_IN_STACK_RESTORE:
13493         /* Exception state returns or moves registers around.  */
13494       case BUILT_IN_EH_FILTER:
13495       case BUILT_IN_EH_POINTER:
13496       case BUILT_IN_EH_COPY_VALUES:
13497         return true;
13498
13499       default:
13500         return false;
13501       }
13502
13503   return false;
13504 }
13505
13506 /* Return true if DECL is a builtin that is not expensive, i.e., they are
13507    most probably expanded inline into reasonably simple code.  This is a
13508    superset of is_simple_builtin.  */
13509 bool
13510 is_inexpensive_builtin (tree decl)
13511 {
13512   if (!decl)
13513     return false;
13514   else if (DECL_BUILT_IN_CLASS (decl) == BUILT_IN_MD)
13515     return true;
13516   else if (DECL_BUILT_IN_CLASS (decl) == BUILT_IN_NORMAL)
13517     switch (DECL_FUNCTION_CODE (decl))
13518       {
13519       case BUILT_IN_ABS:
13520       case BUILT_IN_ALLOCA:
13521       case BUILT_IN_BSWAP32:
13522       case BUILT_IN_BSWAP64:
13523       case BUILT_IN_CLZ:
13524       case BUILT_IN_CLZIMAX:
13525       case BUILT_IN_CLZL:
13526       case BUILT_IN_CLZLL:
13527       case BUILT_IN_CTZ:
13528       case BUILT_IN_CTZIMAX:
13529       case BUILT_IN_CTZL:
13530       case BUILT_IN_CTZLL:
13531       case BUILT_IN_FFS:
13532       case BUILT_IN_FFSIMAX:
13533       case BUILT_IN_FFSL:
13534       case BUILT_IN_FFSLL:
13535       case BUILT_IN_IMAXABS:
13536       case BUILT_IN_FINITE:
13537       case BUILT_IN_FINITEF:
13538       case BUILT_IN_FINITEL:
13539       case BUILT_IN_FINITED32:
13540       case BUILT_IN_FINITED64:
13541       case BUILT_IN_FINITED128:
13542       case BUILT_IN_FPCLASSIFY:
13543       case BUILT_IN_ISFINITE:
13544       case BUILT_IN_ISINF_SIGN:
13545       case BUILT_IN_ISINF:
13546       case BUILT_IN_ISINFF:
13547       case BUILT_IN_ISINFL:
13548       case BUILT_IN_ISINFD32:
13549       case BUILT_IN_ISINFD64:
13550       case BUILT_IN_ISINFD128:
13551       case BUILT_IN_ISNAN:
13552       case BUILT_IN_ISNANF:
13553       case BUILT_IN_ISNANL:
13554       case BUILT_IN_ISNAND32:
13555       case BUILT_IN_ISNAND64:
13556       case BUILT_IN_ISNAND128:
13557       case BUILT_IN_ISNORMAL:
13558       case BUILT_IN_ISGREATER:
13559       case BUILT_IN_ISGREATEREQUAL:
13560       case BUILT_IN_ISLESS:
13561       case BUILT_IN_ISLESSEQUAL:
13562       case BUILT_IN_ISLESSGREATER:
13563       case BUILT_IN_ISUNORDERED:
13564       case BUILT_IN_VA_ARG_PACK:
13565       case BUILT_IN_VA_ARG_PACK_LEN:
13566       case BUILT_IN_VA_COPY:
13567       case BUILT_IN_TRAP:
13568       case BUILT_IN_SAVEREGS:
13569       case BUILT_IN_POPCOUNTL:
13570       case BUILT_IN_POPCOUNTLL:
13571       case BUILT_IN_POPCOUNTIMAX:
13572       case BUILT_IN_POPCOUNT:
13573       case BUILT_IN_PARITYL:
13574       case BUILT_IN_PARITYLL:
13575       case BUILT_IN_PARITYIMAX:
13576       case BUILT_IN_PARITY:
13577       case BUILT_IN_LABS:
13578       case BUILT_IN_LLABS:
13579       case BUILT_IN_PREFETCH:
13580         return true;
13581
13582       default:
13583         return is_simple_builtin (decl);
13584       }
13585
13586   return false;
13587 }