OSDN Git Service

2009-11-07 David Binderman <dcb314@hotmail.com>
[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
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 "real.h"
28 #include "rtl.h"
29 #include "tree.h"
30 #include "gimple.h"
31 #include "flags.h"
32 #include "regs.h"
33 #include "hard-reg-set.h"
34 #include "except.h"
35 #include "function.h"
36 #include "insn-config.h"
37 #include "expr.h"
38 #include "optabs.h"
39 #include "libfuncs.h"
40 #include "recog.h"
41 #include "output.h"
42 #include "typeclass.h"
43 #include "toplev.h"
44 #include "predict.h"
45 #include "tm_p.h"
46 #include "target.h"
47 #include "langhooks.h"
48 #include "basic-block.h"
49 #include "tree-mudflap.h"
50 #include "tree-flow.h"
51 #include "value-prof.h"
52 #include "diagnostic.h"
53
54 #ifndef SLOW_UNALIGNED_ACCESS
55 #define SLOW_UNALIGNED_ACCESS(MODE, ALIGN) STRICT_ALIGNMENT
56 #endif
57
58 #ifndef PAD_VARARGS_DOWN
59 #define PAD_VARARGS_DOWN BYTES_BIG_ENDIAN
60 #endif
61 #ifdef HAVE_mpc
62 static tree do_mpc_arg1 (tree, tree, int (*)(mpc_ptr, mpc_srcptr, mpc_rnd_t));
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_interclass_mathfn (tree, rtx, rtx);
106 static rtx expand_builtin_sincos (tree);
107 static rtx expand_builtin_cexpi (tree, rtx, rtx);
108 static rtx expand_builtin_int_roundingfn (tree, rtx);
109 static rtx expand_builtin_int_roundingfn_2 (tree, rtx);
110 static rtx expand_builtin_args_info (tree);
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, rtx);
133 static rtx expand_builtin_unop (enum machine_mode, tree, rtx, rtx, optab);
134 static rtx expand_builtin_frame_address (tree, tree);
135 static rtx expand_builtin_printf (tree, rtx, enum machine_mode, bool);
136 static rtx expand_builtin_fprintf (tree, rtx, enum machine_mode, bool);
137 static rtx expand_builtin_sprintf (tree, rtx, enum machine_mode);
138 static tree stabilize_va_list_loc (location_t, tree, int);
139 static rtx expand_builtin_expect (tree, rtx);
140 static tree fold_builtin_constant_p (tree);
141 static tree fold_builtin_expect (location_t, tree, tree);
142 static tree fold_builtin_classify_type (tree);
143 static tree fold_builtin_strlen (location_t, tree);
144 static tree fold_builtin_inf (location_t, tree, int);
145 static tree fold_builtin_nan (tree, tree, int);
146 static tree rewrite_call_expr (location_t, tree, int, tree, int, ...);
147 static bool validate_arg (const_tree, enum tree_code code);
148 static bool integer_valued_real_p (tree);
149 static tree fold_trunc_transparent_mathfn (location_t, tree, tree);
150 static bool readonly_data_expr (tree);
151 static rtx expand_builtin_fabs (tree, rtx, rtx);
152 static rtx expand_builtin_signbit (tree, rtx);
153 static tree fold_builtin_sqrt (location_t, tree, tree);
154 static tree fold_builtin_cbrt (location_t, tree, tree);
155 static tree fold_builtin_pow (location_t, tree, tree, tree, tree);
156 static tree fold_builtin_powi (location_t, tree, tree, tree, tree);
157 static tree fold_builtin_cos (location_t, tree, tree, tree);
158 static tree fold_builtin_cosh (location_t, tree, tree, tree);
159 static tree fold_builtin_tan (tree, tree);
160 static tree fold_builtin_trunc (location_t, tree, tree);
161 static tree fold_builtin_floor (location_t, tree, tree);
162 static tree fold_builtin_ceil (location_t, tree, tree);
163 static tree fold_builtin_round (location_t, tree, tree);
164 static tree fold_builtin_int_roundingfn (location_t, tree, tree);
165 static tree fold_builtin_bitop (tree, tree);
166 static tree fold_builtin_memory_op (location_t, tree, tree, tree, tree, bool, int);
167 static tree fold_builtin_strchr (location_t, tree, tree, tree);
168 static tree fold_builtin_memchr (location_t, tree, tree, tree, tree);
169 static tree fold_builtin_memcmp (location_t, tree, tree, tree);
170 static tree fold_builtin_strcmp (location_t, tree, tree);
171 static tree fold_builtin_strncmp (location_t, tree, tree, tree);
172 static tree fold_builtin_signbit (location_t, tree, tree);
173 static tree fold_builtin_copysign (location_t, tree, tree, tree, tree);
174 static tree fold_builtin_isascii (location_t, tree);
175 static tree fold_builtin_toascii (location_t, tree);
176 static tree fold_builtin_isdigit (location_t, tree);
177 static tree fold_builtin_fabs (location_t, tree, tree);
178 static tree fold_builtin_abs (location_t, tree, tree);
179 static tree fold_builtin_unordered_cmp (location_t, tree, tree, tree, enum tree_code,
180                                         enum tree_code);
181 static tree fold_builtin_n (location_t, tree, tree *, int, bool);
182 static tree fold_builtin_0 (location_t, tree, bool);
183 static tree fold_builtin_1 (location_t, tree, tree, bool);
184 static tree fold_builtin_2 (location_t, tree, tree, tree, bool);
185 static tree fold_builtin_3 (location_t, tree, tree, tree, tree, bool);
186 static tree fold_builtin_4 (location_t, tree, tree, tree, tree, tree, bool);
187 static tree fold_builtin_varargs (location_t, tree, tree, bool);
188
189 static tree fold_builtin_strpbrk (location_t, tree, tree, tree);
190 static tree fold_builtin_strstr (location_t, tree, tree, tree);
191 static tree fold_builtin_strrchr (location_t, tree, tree, tree);
192 static tree fold_builtin_strcat (location_t, tree, tree);
193 static tree fold_builtin_strncat (location_t, tree, tree, tree);
194 static tree fold_builtin_strspn (location_t, tree, tree);
195 static tree fold_builtin_strcspn (location_t, tree, tree);
196 static tree fold_builtin_sprintf (location_t, tree, tree, tree, int);
197
198 static rtx expand_builtin_object_size (tree);
199 static rtx expand_builtin_memory_chk (tree, rtx, enum machine_mode,
200                                       enum built_in_function);
201 static void maybe_emit_chk_warning (tree, enum built_in_function);
202 static void maybe_emit_sprintf_chk_warning (tree, enum built_in_function);
203 static void maybe_emit_free_warning (tree);
204 static tree fold_builtin_object_size (tree, tree);
205 static tree fold_builtin_strcat_chk (location_t, tree, tree, tree, tree);
206 static tree fold_builtin_strncat_chk (location_t, tree, tree, tree, tree, tree);
207 static tree fold_builtin_sprintf_chk (location_t, tree, enum built_in_function);
208 static tree fold_builtin_printf (location_t, tree, tree, tree, bool, enum built_in_function);
209 static tree fold_builtin_fprintf (location_t, tree, tree, tree, tree, bool,
210                                   enum built_in_function);
211 static bool init_target_chars (void);
212
213 static unsigned HOST_WIDE_INT target_newline;
214 static unsigned HOST_WIDE_INT target_percent;
215 static unsigned HOST_WIDE_INT target_c;
216 static unsigned HOST_WIDE_INT target_s;
217 static char target_percent_c[3];
218 static char target_percent_s[3];
219 static char target_percent_s_newline[4];
220 static tree do_mpfr_arg1 (tree, tree, int (*)(mpfr_ptr, mpfr_srcptr, mp_rnd_t),
221                           const REAL_VALUE_TYPE *, const REAL_VALUE_TYPE *, bool);
222 static tree do_mpfr_arg2 (tree, tree, tree,
223                           int (*)(mpfr_ptr, mpfr_srcptr, mpfr_srcptr, mp_rnd_t));
224 static tree do_mpfr_arg3 (tree, tree, tree, tree,
225                           int (*)(mpfr_ptr, mpfr_srcptr, mpfr_srcptr, mpfr_srcptr, mp_rnd_t));
226 static tree do_mpfr_sincos (tree, tree, tree);
227 static tree do_mpfr_bessel_n (tree, tree, tree,
228                               int (*)(mpfr_ptr, long, mpfr_srcptr, mp_rnd_t),
229                               const REAL_VALUE_TYPE *, bool);
230 static tree do_mpfr_remquo (tree, tree, tree);
231 static tree do_mpfr_lgamma_r (tree, tree, tree);
232
233 /* Return true if NAME starts with __builtin_ or __sync_.  */
234
235 bool
236 is_builtin_name (const char *name)
237 {
238   if (strncmp (name, "__builtin_", 10) == 0)
239     return true;
240   if (strncmp (name, "__sync_", 7) == 0)
241     return true;
242   return false;
243 }
244
245
246 /* Return true if DECL is a function symbol representing a built-in.  */
247
248 bool
249 is_builtin_fn (tree decl)
250 {
251   return TREE_CODE (decl) == FUNCTION_DECL && DECL_BUILT_IN (decl);
252 }
253
254
255 /* Return true if NODE should be considered for inline expansion regardless
256    of the optimization level.  This means whenever a function is invoked with
257    its "internal" name, which normally contains the prefix "__builtin".  */
258
259 static bool
260 called_as_built_in (tree node)
261 {
262   /* Note that we must use DECL_NAME, not DECL_ASSEMBLER_NAME_SET_P since
263      we want the name used to call the function, not the name it
264      will have. */
265   const char *name = IDENTIFIER_POINTER (DECL_NAME (node));
266   return is_builtin_name (name);
267 }
268
269 /* Return the alignment in bits of EXP, an object.
270    Don't return more than MAX_ALIGN no matter what, ALIGN is the inital
271    guessed alignment e.g. from type alignment.  */
272
273 int
274 get_object_alignment (tree exp, unsigned int align, unsigned int max_align)
275 {
276   unsigned int inner;
277
278   inner = max_align;
279   if (handled_component_p (exp))
280    {
281       HOST_WIDE_INT bitsize, bitpos;
282       tree offset;
283       enum machine_mode mode; 
284       int unsignedp, volatilep;
285
286       exp = get_inner_reference (exp, &bitsize, &bitpos, &offset,
287                                  &mode, &unsignedp, &volatilep, true);
288       if (bitpos)
289         inner = MIN (inner, (unsigned) (bitpos & -bitpos));
290       while (offset)
291         {
292           tree next_offset;
293
294           if (TREE_CODE (offset) == PLUS_EXPR)
295             {
296               next_offset = TREE_OPERAND (offset, 0);
297               offset = TREE_OPERAND (offset, 1);
298             }
299           else
300             next_offset = NULL;
301           if (host_integerp (offset, 1))
302             {
303               /* Any overflow in calculating offset_bits won't change
304                  the alignment.  */
305               unsigned offset_bits
306                 = ((unsigned) tree_low_cst (offset, 1) * BITS_PER_UNIT);
307
308               if (offset_bits)
309                 inner = MIN (inner, (offset_bits & -offset_bits));
310             }
311           else if (TREE_CODE (offset) == MULT_EXPR
312                    && host_integerp (TREE_OPERAND (offset, 1), 1))
313             {
314               /* Any overflow in calculating offset_factor won't change
315                  the alignment.  */
316               unsigned offset_factor
317                 = ((unsigned) tree_low_cst (TREE_OPERAND (offset, 1), 1)
318                    * BITS_PER_UNIT);
319
320               if (offset_factor)
321                 inner = MIN (inner, (offset_factor & -offset_factor));
322             }
323           else
324             {
325               inner = MIN (inner, BITS_PER_UNIT);
326               break;
327             }
328           offset = next_offset;
329         }
330     }
331   if (DECL_P (exp))
332     align = MIN (inner, DECL_ALIGN (exp));
333 #ifdef CONSTANT_ALIGNMENT
334   else if (CONSTANT_CLASS_P (exp))
335     align = MIN (inner, (unsigned)CONSTANT_ALIGNMENT (exp, align));
336 #endif
337   else if (TREE_CODE (exp) == VIEW_CONVERT_EXPR
338            || TREE_CODE (exp) == INDIRECT_REF)
339     align = MIN (TYPE_ALIGN (TREE_TYPE (exp)), inner);
340   else
341     align = MIN (align, inner);
342   return MIN (align, max_align);
343 }
344
345 /* Returns true iff we can trust that alignment information has been
346    calculated properly.  */
347
348 bool
349 can_trust_pointer_alignment (void)
350 {
351   /* We rely on TER to compute accurate alignment information.  */
352   return (optimize && flag_tree_ter);
353 }
354
355 /* Return the alignment in bits of EXP, a pointer valued expression.
356    But don't return more than MAX_ALIGN no matter what.
357    The alignment returned is, by default, the alignment of the thing that
358    EXP points to.  If it is not a POINTER_TYPE, 0 is returned.
359
360    Otherwise, look at the expression to see if we can do better, i.e., if the
361    expression is actually pointing at an object whose alignment is tighter.  */
362
363 int
364 get_pointer_alignment (tree exp, unsigned int max_align)
365 {
366   unsigned int align, inner;
367
368   if (!can_trust_pointer_alignment ())
369     return 0;
370
371   if (!POINTER_TYPE_P (TREE_TYPE (exp)))
372     return 0;
373
374   align = TYPE_ALIGN (TREE_TYPE (TREE_TYPE (exp)));
375   align = MIN (align, max_align);
376
377   while (1)
378     {
379       switch (TREE_CODE (exp))
380         {
381         CASE_CONVERT:
382           exp = TREE_OPERAND (exp, 0);
383           if (! POINTER_TYPE_P (TREE_TYPE (exp)))
384             return align;
385
386           inner = TYPE_ALIGN (TREE_TYPE (TREE_TYPE (exp)));
387           align = MIN (inner, max_align);
388           break;
389
390         case POINTER_PLUS_EXPR:
391           /* If sum of pointer + int, restrict our maximum alignment to that
392              imposed by the integer.  If not, we can't do any better than
393              ALIGN.  */
394           if (! host_integerp (TREE_OPERAND (exp, 1), 1))
395             return align;
396
397           while (((tree_low_cst (TREE_OPERAND (exp, 1), 1))
398                   & (max_align / BITS_PER_UNIT - 1))
399                  != 0)
400             max_align >>= 1;
401
402           exp = TREE_OPERAND (exp, 0);
403           break;
404
405         case ADDR_EXPR:
406           /* See what we are pointing at and look at its alignment.  */
407           return get_object_alignment (TREE_OPERAND (exp, 0), align, max_align);
408
409         default:
410           return align;
411         }
412     }
413 }
414
415 /* Compute the length of a C string.  TREE_STRING_LENGTH is not the right
416    way, because it could contain a zero byte in the middle.
417    TREE_STRING_LENGTH is the size of the character array, not the string.
418
419    ONLY_VALUE should be nonzero if the result is not going to be emitted
420    into the instruction stream and zero if it is going to be expanded.
421    E.g. with i++ ? "foo" : "bar", if ONLY_VALUE is nonzero, constant 3
422    is returned, otherwise NULL, since
423    len = c_strlen (src, 1); if (len) expand_expr (len, ...); would not
424    evaluate the side-effects.
425
426    The value returned is of type `ssizetype'.
427
428    Unfortunately, string_constant can't access the values of const char
429    arrays with initializers, so neither can we do so here.  */
430
431 tree
432 c_strlen (tree src, int only_value)
433 {
434   tree offset_node;
435   HOST_WIDE_INT offset;
436   int max;
437   const char *ptr;
438
439   STRIP_NOPS (src);
440   if (TREE_CODE (src) == COND_EXPR
441       && (only_value || !TREE_SIDE_EFFECTS (TREE_OPERAND (src, 0))))
442     {
443       tree len1, len2;
444
445       len1 = c_strlen (TREE_OPERAND (src, 1), only_value);
446       len2 = c_strlen (TREE_OPERAND (src, 2), only_value);
447       if (tree_int_cst_equal (len1, len2))
448         return len1;
449     }
450
451   if (TREE_CODE (src) == COMPOUND_EXPR
452       && (only_value || !TREE_SIDE_EFFECTS (TREE_OPERAND (src, 0))))
453     return c_strlen (TREE_OPERAND (src, 1), only_value);
454
455   src = string_constant (src, &offset_node);
456   if (src == 0)
457     return NULL_TREE;
458
459   max = TREE_STRING_LENGTH (src) - 1;
460   ptr = TREE_STRING_POINTER (src);
461
462   if (offset_node && TREE_CODE (offset_node) != INTEGER_CST)
463     {
464       /* If the string has an internal zero byte (e.g., "foo\0bar"), we can't
465          compute the offset to the following null if we don't know where to
466          start searching for it.  */
467       int i;
468
469       for (i = 0; i < max; i++)
470         if (ptr[i] == 0)
471           return NULL_TREE;
472
473       /* We don't know the starting offset, but we do know that the string
474          has no internal zero bytes.  We can assume that the offset falls
475          within the bounds of the string; otherwise, the programmer deserves
476          what he gets.  Subtract the offset from the length of the string,
477          and return that.  This would perhaps not be valid if we were dealing
478          with named arrays in addition to literal string constants.  */
479
480       return size_diffop_loc (input_location, size_int (max), offset_node);
481     }
482
483   /* We have a known offset into the string.  Start searching there for
484      a null character if we can represent it as a single HOST_WIDE_INT.  */
485   if (offset_node == 0)
486     offset = 0;
487   else if (! host_integerp (offset_node, 0))
488     offset = -1;
489   else
490     offset = tree_low_cst (offset_node, 0);
491
492   /* If the offset is known to be out of bounds, warn, and call strlen at
493      runtime.  */
494   if (offset < 0 || offset > max)
495     {
496      /* Suppress multiple warnings for propagated constant strings.  */
497       if (! TREE_NO_WARNING (src))
498         {
499           warning (0, "offset outside bounds of constant string");
500           TREE_NO_WARNING (src) = 1;
501         }
502       return NULL_TREE;
503     }
504
505   /* Use strlen to search for the first zero byte.  Since any strings
506      constructed with build_string will have nulls appended, we win even
507      if we get handed something like (char[4])"abcd".
508
509      Since OFFSET is our starting index into the string, no further
510      calculation is needed.  */
511   return ssize_int (strlen (ptr + offset));
512 }
513
514 /* Return a char pointer for a C string if it is a string constant
515    or sum of string constant and integer constant.  */
516
517 static const char *
518 c_getstr (tree src)
519 {
520   tree offset_node;
521
522   src = string_constant (src, &offset_node);
523   if (src == 0)
524     return 0;
525
526   if (offset_node == 0)
527     return TREE_STRING_POINTER (src);
528   else if (!host_integerp (offset_node, 1)
529            || compare_tree_int (offset_node, TREE_STRING_LENGTH (src) - 1) > 0)
530     return 0;
531
532   return TREE_STRING_POINTER (src) + tree_low_cst (offset_node, 1);
533 }
534
535 /* Return a CONST_INT or CONST_DOUBLE corresponding to target reading
536    GET_MODE_BITSIZE (MODE) bits from string constant STR.  */
537
538 static rtx
539 c_readstr (const char *str, enum machine_mode mode)
540 {
541   HOST_WIDE_INT c[2];
542   HOST_WIDE_INT ch;
543   unsigned int i, j;
544
545   gcc_assert (GET_MODE_CLASS (mode) == MODE_INT);
546
547   c[0] = 0;
548   c[1] = 0;
549   ch = 1;
550   for (i = 0; i < GET_MODE_SIZE (mode); i++)
551     {
552       j = i;
553       if (WORDS_BIG_ENDIAN)
554         j = GET_MODE_SIZE (mode) - i - 1;
555       if (BYTES_BIG_ENDIAN != WORDS_BIG_ENDIAN
556           && GET_MODE_SIZE (mode) > UNITS_PER_WORD)
557         j = j + UNITS_PER_WORD - 2 * (j % UNITS_PER_WORD) - 1;
558       j *= BITS_PER_UNIT;
559       gcc_assert (j <= 2 * HOST_BITS_PER_WIDE_INT);
560
561       if (ch)
562         ch = (unsigned char) str[i];
563       c[j / HOST_BITS_PER_WIDE_INT] |= ch << (j % HOST_BITS_PER_WIDE_INT);
564     }
565   return immed_double_const (c[0], c[1], mode);
566 }
567
568 /* Cast a target constant CST to target CHAR and if that value fits into
569    host char type, return zero and put that value into variable pointed to by
570    P.  */
571
572 static int
573 target_char_cast (tree cst, char *p)
574 {
575   unsigned HOST_WIDE_INT val, hostval;
576
577   if (!host_integerp (cst, 1)
578       || CHAR_TYPE_SIZE > HOST_BITS_PER_WIDE_INT)
579     return 1;
580
581   val = tree_low_cst (cst, 1);
582   if (CHAR_TYPE_SIZE < HOST_BITS_PER_WIDE_INT)
583     val &= (((unsigned HOST_WIDE_INT) 1) << CHAR_TYPE_SIZE) - 1;
584
585   hostval = val;
586   if (HOST_BITS_PER_CHAR < HOST_BITS_PER_WIDE_INT)
587     hostval &= (((unsigned HOST_WIDE_INT) 1) << HOST_BITS_PER_CHAR) - 1;
588
589   if (val != hostval)
590     return 1;
591
592   *p = hostval;
593   return 0;
594 }
595
596 /* Similar to save_expr, but assumes that arbitrary code is not executed
597    in between the multiple evaluations.  In particular, we assume that a
598    non-addressable local variable will not be modified.  */
599
600 static tree
601 builtin_save_expr (tree exp)
602 {
603   if (TREE_ADDRESSABLE (exp) == 0
604       && (TREE_CODE (exp) == PARM_DECL
605           || (TREE_CODE (exp) == VAR_DECL && !TREE_STATIC (exp))))
606     return exp;
607
608   return save_expr (exp);
609 }
610
611 /* Given TEM, a pointer to a stack frame, follow the dynamic chain COUNT
612    times to get the address of either a higher stack frame, or a return
613    address located within it (depending on FNDECL_CODE).  */
614
615 static rtx
616 expand_builtin_return_addr (enum built_in_function fndecl_code, int count)
617 {
618   int i;
619
620 #ifdef INITIAL_FRAME_ADDRESS_RTX
621   rtx tem = INITIAL_FRAME_ADDRESS_RTX;
622 #else
623   rtx tem;
624
625   /* For a zero count with __builtin_return_address, we don't care what
626      frame address we return, because target-specific definitions will
627      override us.  Therefore frame pointer elimination is OK, and using
628      the soft frame pointer is OK.
629
630      For a nonzero count, or a zero count with __builtin_frame_address,
631      we require a stable offset from the current frame pointer to the
632      previous one, so we must use the hard frame pointer, and
633      we must disable frame pointer elimination.  */
634   if (count == 0 && fndecl_code == BUILT_IN_RETURN_ADDRESS)
635     tem = frame_pointer_rtx;
636   else
637     {
638       tem = hard_frame_pointer_rtx;
639
640       /* Tell reload not to eliminate the frame pointer.  */
641       crtl->accesses_prior_frames = 1;
642     }
643 #endif
644
645   /* Some machines need special handling before we can access
646      arbitrary frames.  For example, on the SPARC, we must first flush
647      all register windows to the stack.  */
648 #ifdef SETUP_FRAME_ADDRESSES
649   if (count > 0)
650     SETUP_FRAME_ADDRESSES ();
651 #endif
652
653   /* On the SPARC, the return address is not in the frame, it is in a
654      register.  There is no way to access it off of the current frame
655      pointer, but it can be accessed off the previous frame pointer by
656      reading the value from the register window save area.  */
657 #ifdef RETURN_ADDR_IN_PREVIOUS_FRAME
658   if (fndecl_code == BUILT_IN_RETURN_ADDRESS)
659     count--;
660 #endif
661
662   /* Scan back COUNT frames to the specified frame.  */
663   for (i = 0; i < count; i++)
664     {
665       /* Assume the dynamic chain pointer is in the word that the
666          frame address points to, unless otherwise specified.  */
667 #ifdef DYNAMIC_CHAIN_ADDRESS
668       tem = DYNAMIC_CHAIN_ADDRESS (tem);
669 #endif
670       tem = memory_address (Pmode, tem);
671       tem = gen_frame_mem (Pmode, tem);
672       tem = copy_to_reg (tem);
673     }
674
675   /* For __builtin_frame_address, return what we've got.  But, on
676      the SPARC for example, we may have to add a bias.  */
677   if (fndecl_code == BUILT_IN_FRAME_ADDRESS)
678 #ifdef FRAME_ADDR_RTX
679     return FRAME_ADDR_RTX (tem);
680 #else
681     return tem;
682 #endif
683
684   /* For __builtin_return_address, get the return address from that frame.  */
685 #ifdef RETURN_ADDR_RTX
686   tem = RETURN_ADDR_RTX (count, tem);
687 #else
688   tem = memory_address (Pmode,
689                         plus_constant (tem, GET_MODE_SIZE (Pmode)));
690   tem = gen_frame_mem (Pmode, tem);
691 #endif
692   return tem;
693 }
694
695 /* Alias set used for setjmp buffer.  */
696 static alias_set_type setjmp_alias_set = -1;
697
698 /* Construct the leading half of a __builtin_setjmp call.  Control will
699    return to RECEIVER_LABEL.  This is also called directly by the SJLJ
700    exception handling code.  */
701
702 void
703 expand_builtin_setjmp_setup (rtx buf_addr, rtx receiver_label)
704 {
705   enum machine_mode sa_mode = STACK_SAVEAREA_MODE (SAVE_NONLOCAL);
706   rtx stack_save;
707   rtx mem;
708
709   if (setjmp_alias_set == -1)
710     setjmp_alias_set = new_alias_set ();
711
712   buf_addr = convert_memory_address (Pmode, buf_addr);
713
714   buf_addr = force_reg (Pmode, force_operand (buf_addr, NULL_RTX));
715
716   /* We store the frame pointer and the address of receiver_label in
717      the buffer and use the rest of it for the stack save area, which
718      is machine-dependent.  */
719
720   mem = gen_rtx_MEM (Pmode, buf_addr);
721   set_mem_alias_set (mem, setjmp_alias_set);
722   emit_move_insn (mem, targetm.builtin_setjmp_frame_value ());
723
724   mem = gen_rtx_MEM (Pmode, plus_constant (buf_addr, GET_MODE_SIZE (Pmode))),
725   set_mem_alias_set (mem, setjmp_alias_set);
726
727   emit_move_insn (validize_mem (mem),
728                   force_reg (Pmode, gen_rtx_LABEL_REF (Pmode, receiver_label)));
729
730   stack_save = gen_rtx_MEM (sa_mode,
731                             plus_constant (buf_addr,
732                                            2 * GET_MODE_SIZE (Pmode)));
733   set_mem_alias_set (stack_save, setjmp_alias_set);
734   emit_stack_save (SAVE_NONLOCAL, &stack_save, NULL_RTX);
735
736   /* If there is further processing to do, do it.  */
737 #ifdef HAVE_builtin_setjmp_setup
738   if (HAVE_builtin_setjmp_setup)
739     emit_insn (gen_builtin_setjmp_setup (buf_addr));
740 #endif
741
742   /* Tell optimize_save_area_alloca that extra work is going to
743      need to go on during alloca.  */
744   cfun->calls_setjmp = 1;
745
746   /* We have a nonlocal label.   */
747   cfun->has_nonlocal_label = 1;
748 }
749
750 /* Construct the trailing part of a __builtin_setjmp call.  This is
751    also called directly by the SJLJ exception handling code.  */
752
753 void
754 expand_builtin_setjmp_receiver (rtx receiver_label ATTRIBUTE_UNUSED)
755 {
756   rtx chain;
757
758   /* Clobber the FP when we get here, so we have to make sure it's
759      marked as used by this function.  */
760   emit_use (hard_frame_pointer_rtx);
761
762   /* Mark the static chain as clobbered here so life information
763      doesn't get messed up for it.  */
764   chain = targetm.calls.static_chain (current_function_decl, true);
765   if (chain && REG_P (chain))
766     emit_clobber (chain);
767
768   /* Now put in the code to restore the frame pointer, and argument
769      pointer, if needed.  */
770 #ifdef HAVE_nonlocal_goto
771   if (! HAVE_nonlocal_goto)
772 #endif
773     {
774       emit_move_insn (virtual_stack_vars_rtx, hard_frame_pointer_rtx);
775       /* This might change the hard frame pointer in ways that aren't
776          apparent to early optimization passes, so force a clobber.  */
777       emit_clobber (hard_frame_pointer_rtx);
778     }
779
780 #if ARG_POINTER_REGNUM != HARD_FRAME_POINTER_REGNUM
781   if (fixed_regs[ARG_POINTER_REGNUM])
782     {
783 #ifdef ELIMINABLE_REGS
784       size_t i;
785       static const struct elims {const int from, to;} elim_regs[] = ELIMINABLE_REGS;
786
787       for (i = 0; i < ARRAY_SIZE (elim_regs); i++)
788         if (elim_regs[i].from == ARG_POINTER_REGNUM
789             && elim_regs[i].to == HARD_FRAME_POINTER_REGNUM)
790           break;
791
792       if (i == ARRAY_SIZE (elim_regs))
793 #endif
794         {
795           /* Now restore our arg pointer from the address at which it
796              was saved in our stack frame.  */
797           emit_move_insn (crtl->args.internal_arg_pointer,
798                           copy_to_reg (get_arg_pointer_save_area ()));
799         }
800     }
801 #endif
802
803 #ifdef HAVE_builtin_setjmp_receiver
804   if (HAVE_builtin_setjmp_receiver)
805     emit_insn (gen_builtin_setjmp_receiver (receiver_label));
806   else
807 #endif
808 #ifdef HAVE_nonlocal_goto_receiver
809     if (HAVE_nonlocal_goto_receiver)
810       emit_insn (gen_nonlocal_goto_receiver ());
811     else
812 #endif
813       { /* Nothing */ }
814
815   /* We must not allow the code we just generated to be reordered by
816      scheduling.  Specifically, the update of the frame pointer must
817      happen immediately, not later.  */
818   emit_insn (gen_blockage ());
819 }
820
821 /* __builtin_longjmp is passed a pointer to an array of five words (not
822    all will be used on all machines).  It operates similarly to the C
823    library function of the same name, but is more efficient.  Much of
824    the code below is copied from the handling of non-local gotos.  */
825
826 static void
827 expand_builtin_longjmp (rtx buf_addr, rtx value)
828 {
829   rtx fp, lab, stack, insn, last;
830   enum machine_mode sa_mode = STACK_SAVEAREA_MODE (SAVE_NONLOCAL);
831
832   /* DRAP is needed for stack realign if longjmp is expanded to current 
833      function  */
834   if (SUPPORTS_STACK_ALIGNMENT)
835     crtl->need_drap = true;
836
837   if (setjmp_alias_set == -1)
838     setjmp_alias_set = new_alias_set ();
839
840   buf_addr = convert_memory_address (Pmode, buf_addr);
841
842   buf_addr = force_reg (Pmode, buf_addr);
843
844   /* We require that the user must pass a second argument of 1, because
845      that is what builtin_setjmp will return.  */
846   gcc_assert (value == const1_rtx);
847
848   last = get_last_insn ();
849 #ifdef HAVE_builtin_longjmp
850   if (HAVE_builtin_longjmp)
851     emit_insn (gen_builtin_longjmp (buf_addr));
852   else
853 #endif
854     {
855       fp = gen_rtx_MEM (Pmode, buf_addr);
856       lab = gen_rtx_MEM (Pmode, plus_constant (buf_addr,
857                                                GET_MODE_SIZE (Pmode)));
858
859       stack = gen_rtx_MEM (sa_mode, plus_constant (buf_addr,
860                                                    2 * GET_MODE_SIZE (Pmode)));
861       set_mem_alias_set (fp, setjmp_alias_set);
862       set_mem_alias_set (lab, setjmp_alias_set);
863       set_mem_alias_set (stack, setjmp_alias_set);
864
865       /* Pick up FP, label, and SP from the block and jump.  This code is
866          from expand_goto in stmt.c; see there for detailed comments.  */
867 #ifdef HAVE_nonlocal_goto
868       if (HAVE_nonlocal_goto)
869         /* We have to pass a value to the nonlocal_goto pattern that will
870            get copied into the static_chain pointer, but it does not matter
871            what that value is, because builtin_setjmp does not use it.  */
872         emit_insn (gen_nonlocal_goto (value, lab, stack, fp));
873       else
874 #endif
875         {
876           lab = copy_to_reg (lab);
877
878           emit_clobber (gen_rtx_MEM (BLKmode, gen_rtx_SCRATCH (VOIDmode)));
879           emit_clobber (gen_rtx_MEM (BLKmode, hard_frame_pointer_rtx));
880
881           emit_move_insn (hard_frame_pointer_rtx, fp);
882           emit_stack_restore (SAVE_NONLOCAL, stack, NULL_RTX);
883
884           emit_use (hard_frame_pointer_rtx);
885           emit_use (stack_pointer_rtx);
886           emit_indirect_jump (lab);
887         }
888     }
889
890   /* Search backwards and mark the jump insn as a non-local goto.
891      Note that this precludes the use of __builtin_longjmp to a
892      __builtin_setjmp target in the same function.  However, we've
893      already cautioned the user that these functions are for
894      internal exception handling use only.  */
895   for (insn = get_last_insn (); insn; insn = PREV_INSN (insn))
896     {
897       gcc_assert (insn != last);
898
899       if (JUMP_P (insn))
900         {
901           add_reg_note (insn, REG_NON_LOCAL_GOTO, const0_rtx);
902           break;
903         }
904       else if (CALL_P (insn))
905         break;
906     }
907 }
908
909 /* Expand a call to __builtin_nonlocal_goto.  We're passed the target label
910    and the address of the save area.  */
911
912 static rtx
913 expand_builtin_nonlocal_goto (tree exp)
914 {
915   tree t_label, t_save_area;
916   rtx r_label, r_save_area, r_fp, r_sp, insn;
917
918   if (!validate_arglist (exp, POINTER_TYPE, POINTER_TYPE, VOID_TYPE))
919     return NULL_RTX;
920
921   t_label = CALL_EXPR_ARG (exp, 0);
922   t_save_area = CALL_EXPR_ARG (exp, 1);
923
924   r_label = expand_normal (t_label);
925   r_label = convert_memory_address (Pmode, r_label);
926   r_save_area = expand_normal (t_save_area);
927   r_save_area = convert_memory_address (Pmode, r_save_area);
928   /* Copy the address of the save location to a register just in case it was based
929     on the frame pointer.   */
930   r_save_area = copy_to_reg (r_save_area);
931   r_fp = gen_rtx_MEM (Pmode, r_save_area);
932   r_sp = gen_rtx_MEM (STACK_SAVEAREA_MODE (SAVE_NONLOCAL),
933                       plus_constant (r_save_area, GET_MODE_SIZE (Pmode)));
934
935   crtl->has_nonlocal_goto = 1;
936
937 #ifdef HAVE_nonlocal_goto
938   /* ??? We no longer need to pass the static chain value, afaik.  */
939   if (HAVE_nonlocal_goto)
940     emit_insn (gen_nonlocal_goto (const0_rtx, r_label, r_sp, r_fp));
941   else
942 #endif
943     {
944       r_label = copy_to_reg (r_label);
945
946       emit_clobber (gen_rtx_MEM (BLKmode, gen_rtx_SCRATCH (VOIDmode)));
947       emit_clobber (gen_rtx_MEM (BLKmode, hard_frame_pointer_rtx));
948
949       /* Restore frame pointer for containing function.
950          This sets the actual hard register used for the frame pointer
951          to the location of the function's incoming static chain info.
952          The non-local goto handler will then adjust it to contain the
953          proper value and reload the argument pointer, if needed.  */
954       emit_move_insn (hard_frame_pointer_rtx, r_fp);
955       emit_stack_restore (SAVE_NONLOCAL, r_sp, NULL_RTX);
956
957       /* USE of hard_frame_pointer_rtx added for consistency;
958          not clear if really needed.  */
959       emit_use (hard_frame_pointer_rtx);
960       emit_use (stack_pointer_rtx);
961
962       /* If the architecture is using a GP register, we must
963          conservatively assume that the target function makes use of it.
964          The prologue of functions with nonlocal gotos must therefore
965          initialize the GP register to the appropriate value, and we
966          must then make sure that this value is live at the point
967          of the jump.  (Note that this doesn't necessarily apply
968          to targets with a nonlocal_goto pattern; they are free
969          to implement it in their own way.  Note also that this is
970          a no-op if the GP register is a global invariant.)  */
971       if ((unsigned) PIC_OFFSET_TABLE_REGNUM != INVALID_REGNUM
972           && fixed_regs[PIC_OFFSET_TABLE_REGNUM])
973         emit_use (pic_offset_table_rtx);
974
975       emit_indirect_jump (r_label);
976     }
977
978   /* Search backwards to the jump insn and mark it as a
979      non-local goto.  */
980   for (insn = get_last_insn (); insn; insn = PREV_INSN (insn))
981     {
982       if (JUMP_P (insn))
983         {
984           add_reg_note (insn, REG_NON_LOCAL_GOTO, const0_rtx);
985           break;
986         }
987       else if (CALL_P (insn))
988         break;
989     }
990
991   return const0_rtx;
992 }
993
994 /* __builtin_update_setjmp_buf is passed a pointer to an array of five words
995    (not all will be used on all machines) that was passed to __builtin_setjmp.
996    It updates the stack pointer in that block to correspond to the current
997    stack pointer.  */
998
999 static void
1000 expand_builtin_update_setjmp_buf (rtx buf_addr)
1001 {
1002   enum machine_mode sa_mode = Pmode;
1003   rtx stack_save;
1004
1005
1006 #ifdef HAVE_save_stack_nonlocal
1007   if (HAVE_save_stack_nonlocal)
1008     sa_mode = insn_data[(int) CODE_FOR_save_stack_nonlocal].operand[0].mode;
1009 #endif
1010 #ifdef STACK_SAVEAREA_MODE
1011   sa_mode = STACK_SAVEAREA_MODE (SAVE_NONLOCAL);
1012 #endif
1013
1014   stack_save
1015     = gen_rtx_MEM (sa_mode,
1016                    memory_address
1017                    (sa_mode,
1018                     plus_constant (buf_addr, 2 * GET_MODE_SIZE (Pmode))));
1019
1020 #ifdef HAVE_setjmp
1021   if (HAVE_setjmp)
1022     emit_insn (gen_setjmp ());
1023 #endif
1024
1025   emit_stack_save (SAVE_NONLOCAL, &stack_save, NULL_RTX);
1026 }
1027
1028 /* Expand a call to __builtin_prefetch.  For a target that does not support
1029    data prefetch, evaluate the memory address argument in case it has side
1030    effects.  */
1031
1032 static void
1033 expand_builtin_prefetch (tree exp)
1034 {
1035   tree arg0, arg1, arg2;
1036   int nargs;
1037   rtx op0, op1, op2;
1038
1039   if (!validate_arglist (exp, POINTER_TYPE, 0))
1040     return;
1041
1042   arg0 = CALL_EXPR_ARG (exp, 0);
1043
1044   /* Arguments 1 and 2 are optional; argument 1 (read/write) defaults to
1045      zero (read) and argument 2 (locality) defaults to 3 (high degree of
1046      locality).  */
1047   nargs = call_expr_nargs (exp);
1048   if (nargs > 1)
1049     arg1 = CALL_EXPR_ARG (exp, 1);
1050   else
1051     arg1 = integer_zero_node;
1052   if (nargs > 2)
1053     arg2 = CALL_EXPR_ARG (exp, 2);
1054   else
1055     arg2 = build_int_cst (NULL_TREE, 3);
1056
1057   /* Argument 0 is an address.  */
1058   op0 = expand_expr (arg0, NULL_RTX, Pmode, EXPAND_NORMAL);
1059
1060   /* Argument 1 (read/write flag) must be a compile-time constant int.  */
1061   if (TREE_CODE (arg1) != INTEGER_CST)
1062     {
1063       error ("second argument to %<__builtin_prefetch%> must be a constant");
1064       arg1 = integer_zero_node;
1065     }
1066   op1 = expand_normal (arg1);
1067   /* Argument 1 must be either zero or one.  */
1068   if (INTVAL (op1) != 0 && INTVAL (op1) != 1)
1069     {
1070       warning (0, "invalid second argument to %<__builtin_prefetch%>;"
1071                " using zero");
1072       op1 = const0_rtx;
1073     }
1074
1075   /* Argument 2 (locality) must be a compile-time constant int.  */
1076   if (TREE_CODE (arg2) != INTEGER_CST)
1077     {
1078       error ("third argument to %<__builtin_prefetch%> must be a constant");
1079       arg2 = integer_zero_node;
1080     }
1081   op2 = expand_normal (arg2);
1082   /* Argument 2 must be 0, 1, 2, or 3.  */
1083   if (INTVAL (op2) < 0 || INTVAL (op2) > 3)
1084     {
1085       warning (0, "invalid third argument to %<__builtin_prefetch%>; using zero");
1086       op2 = const0_rtx;
1087     }
1088
1089 #ifdef HAVE_prefetch
1090   if (HAVE_prefetch)
1091     {
1092       if ((! (*insn_data[(int) CODE_FOR_prefetch].operand[0].predicate)
1093              (op0,
1094               insn_data[(int) CODE_FOR_prefetch].operand[0].mode))
1095           || (GET_MODE (op0) != Pmode))
1096         {
1097           op0 = convert_memory_address (Pmode, op0);
1098           op0 = force_reg (Pmode, op0);
1099         }
1100       emit_insn (gen_prefetch (op0, op1, op2));
1101     }
1102 #endif
1103
1104   /* Don't do anything with direct references to volatile memory, but
1105      generate code to handle other side effects.  */
1106   if (!MEM_P (op0) && side_effects_p (op0))
1107     emit_insn (op0);
1108 }
1109
1110 /* Get a MEM rtx for expression EXP which is the address of an operand
1111    to be used in a string instruction (cmpstrsi, movmemsi, ..).  LEN is
1112    the maximum length of the block of memory that might be accessed or
1113    NULL if unknown.  */
1114
1115 static rtx
1116 get_memory_rtx (tree exp, tree len)
1117 {
1118   tree orig_exp = exp;
1119   rtx addr, mem;
1120   HOST_WIDE_INT off;
1121
1122   /* When EXP is not resolved SAVE_EXPR, MEM_ATTRS can be still derived
1123      from its expression, for expr->a.b only <variable>.a.b is recorded.  */
1124   if (TREE_CODE (exp) == SAVE_EXPR && !SAVE_EXPR_RESOLVED_P (exp))
1125     exp = TREE_OPERAND (exp, 0);
1126
1127   addr = expand_expr (orig_exp, NULL_RTX, ptr_mode, EXPAND_NORMAL);
1128   mem = gen_rtx_MEM (BLKmode, memory_address (BLKmode, addr));
1129
1130   /* Get an expression we can use to find the attributes to assign to MEM.
1131      If it is an ADDR_EXPR, use the operand.  Otherwise, dereference it if
1132      we can.  First remove any nops.  */
1133   while (CONVERT_EXPR_P (exp)
1134          && POINTER_TYPE_P (TREE_TYPE (TREE_OPERAND (exp, 0))))
1135     exp = TREE_OPERAND (exp, 0);
1136
1137   off = 0;
1138   if (TREE_CODE (exp) == POINTER_PLUS_EXPR
1139       && TREE_CODE (TREE_OPERAND (exp, 0)) == ADDR_EXPR
1140       && host_integerp (TREE_OPERAND (exp, 1), 0)
1141       && (off = tree_low_cst (TREE_OPERAND (exp, 1), 0)) > 0)
1142     exp = TREE_OPERAND (TREE_OPERAND (exp, 0), 0);
1143   else if (TREE_CODE (exp) == ADDR_EXPR)
1144     exp = TREE_OPERAND (exp, 0);
1145   else if (POINTER_TYPE_P (TREE_TYPE (exp)))
1146     exp = build1 (INDIRECT_REF, TREE_TYPE (TREE_TYPE (exp)), exp);
1147   else
1148     exp = NULL;
1149
1150   /* Honor attributes derived from exp, except for the alias set
1151      (as builtin stringops may alias with anything) and the size
1152      (as stringops may access multiple array elements).  */
1153   if (exp)
1154     {
1155       set_mem_attributes (mem, exp, 0);
1156
1157       if (off)
1158         mem = adjust_automodify_address_nv (mem, BLKmode, NULL, off);
1159
1160       /* Allow the string and memory builtins to overflow from one
1161          field into another, see http://gcc.gnu.org/PR23561.
1162          Thus avoid COMPONENT_REFs in MEM_EXPR unless we know the whole
1163          memory accessed by the string or memory builtin will fit
1164          within the field.  */
1165       if (MEM_EXPR (mem) && TREE_CODE (MEM_EXPR (mem)) == COMPONENT_REF)
1166         {
1167           tree mem_expr = MEM_EXPR (mem);
1168           HOST_WIDE_INT offset = -1, length = -1;
1169           tree inner = exp;
1170
1171           while (TREE_CODE (inner) == ARRAY_REF
1172                  || CONVERT_EXPR_P (inner)
1173                  || TREE_CODE (inner) == VIEW_CONVERT_EXPR
1174                  || TREE_CODE (inner) == SAVE_EXPR)
1175             inner = TREE_OPERAND (inner, 0);
1176
1177           gcc_assert (TREE_CODE (inner) == COMPONENT_REF);
1178
1179           if (MEM_OFFSET (mem)
1180               && CONST_INT_P (MEM_OFFSET (mem)))
1181             offset = INTVAL (MEM_OFFSET (mem));
1182
1183           if (offset >= 0 && len && host_integerp (len, 0))
1184             length = tree_low_cst (len, 0);
1185
1186           while (TREE_CODE (inner) == COMPONENT_REF)
1187             {
1188               tree field = TREE_OPERAND (inner, 1);
1189               gcc_assert (TREE_CODE (mem_expr) == COMPONENT_REF);
1190               gcc_assert (field == TREE_OPERAND (mem_expr, 1));
1191
1192               /* Bitfields are generally not byte-addressable.  */
1193               gcc_assert (!DECL_BIT_FIELD (field)
1194                           || ((tree_low_cst (DECL_FIELD_BIT_OFFSET (field), 1)
1195                                % BITS_PER_UNIT) == 0
1196                               && host_integerp (DECL_SIZE (field), 0)
1197                               && (TREE_INT_CST_LOW (DECL_SIZE (field))
1198                                   % BITS_PER_UNIT) == 0));
1199
1200               /* If we can prove that the memory starting at XEXP (mem, 0) and
1201                  ending at XEXP (mem, 0) + LENGTH will fit into this field, we
1202                  can keep the COMPONENT_REF in MEM_EXPR.  But be careful with
1203                  fields without DECL_SIZE_UNIT like flexible array members.  */
1204               if (length >= 0
1205                   && DECL_SIZE_UNIT (field)
1206                   && host_integerp (DECL_SIZE_UNIT (field), 0))
1207                 {
1208                   HOST_WIDE_INT size
1209                     = TREE_INT_CST_LOW (DECL_SIZE_UNIT (field));
1210                   if (offset <= size
1211                       && length <= size
1212                       && offset + length <= size)
1213                     break;
1214                 }
1215
1216               if (offset >= 0
1217                   && host_integerp (DECL_FIELD_OFFSET (field), 0))
1218                 offset += TREE_INT_CST_LOW (DECL_FIELD_OFFSET (field))
1219                           + tree_low_cst (DECL_FIELD_BIT_OFFSET (field), 1)
1220                             / BITS_PER_UNIT;
1221               else
1222                 {
1223                   offset = -1;
1224                   length = -1;
1225                 }
1226
1227               mem_expr = TREE_OPERAND (mem_expr, 0);
1228               inner = TREE_OPERAND (inner, 0);
1229             }
1230
1231           if (mem_expr == NULL)
1232             offset = -1;
1233           if (mem_expr != MEM_EXPR (mem))
1234             {
1235               set_mem_expr (mem, mem_expr);
1236               set_mem_offset (mem, offset >= 0 ? GEN_INT (offset) : NULL_RTX);
1237             }
1238         }
1239       set_mem_alias_set (mem, 0);
1240       set_mem_size (mem, NULL_RTX);
1241     }
1242
1243   return mem;
1244 }
1245 \f
1246 /* Built-in functions to perform an untyped call and return.  */
1247
1248 /* For each register that may be used for calling a function, this
1249    gives a mode used to copy the register's value.  VOIDmode indicates
1250    the register is not used for calling a function.  If the machine
1251    has register windows, this gives only the outbound registers.
1252    INCOMING_REGNO gives the corresponding inbound register.  */
1253 static enum machine_mode apply_args_mode[FIRST_PSEUDO_REGISTER];
1254
1255 /* For each register that may be used for returning values, this gives
1256    a mode used to copy the register's value.  VOIDmode indicates the
1257    register is not used for returning values.  If the machine has
1258    register windows, this gives only the outbound registers.
1259    INCOMING_REGNO gives the corresponding inbound register.  */
1260 static enum machine_mode apply_result_mode[FIRST_PSEUDO_REGISTER];
1261
1262 /* For each register that may be used for calling a function, this
1263    gives the offset of that register into the block returned by
1264    __builtin_apply_args.  0 indicates that the register is not
1265    used for calling a function.  */
1266 /* static int apply_args_reg_offset[FIRST_PSEUDO_REGISTER]; not used */
1267
1268 /* Return the size required for the block returned by __builtin_apply_args,
1269    and initialize apply_args_mode.  */
1270
1271 static int
1272 apply_args_size (void)
1273 {
1274   static int size = -1;
1275   int align;
1276   unsigned int regno;
1277   enum machine_mode mode;
1278
1279   /* The values computed by this function never change.  */
1280   if (size < 0)
1281     {
1282       /* The first value is the incoming arg-pointer.  */
1283       size = GET_MODE_SIZE (Pmode);
1284
1285       /* The second value is the structure value address unless this is
1286          passed as an "invisible" first argument.  */
1287       if (targetm.calls.struct_value_rtx (cfun ? TREE_TYPE (cfun->decl) : 0, 0))
1288         size += GET_MODE_SIZE (Pmode);
1289
1290       for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
1291         if (FUNCTION_ARG_REGNO_P (regno))
1292           {
1293             mode = reg_raw_mode[regno];
1294
1295             gcc_assert (mode != VOIDmode);
1296
1297             align = GET_MODE_ALIGNMENT (mode) / BITS_PER_UNIT;
1298             if (size % align != 0)
1299               size = CEIL (size, align) * align;
1300             size += GET_MODE_SIZE (mode);
1301             apply_args_mode[regno] = mode;
1302           }
1303         else
1304           {
1305             apply_args_mode[regno] = VOIDmode;
1306           }
1307     }
1308   return size;
1309 }
1310
1311 /* Return the size required for the block returned by __builtin_apply,
1312    and initialize apply_result_mode.  */
1313
1314 static int
1315 apply_result_size (void)
1316 {
1317   static int size = -1;
1318   int align, regno;
1319   enum machine_mode mode;
1320
1321   /* The values computed by this function never change.  */
1322   if (size < 0)
1323     {
1324       size = 0;
1325
1326       for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
1327         if (FUNCTION_VALUE_REGNO_P (regno))
1328           {
1329             mode = reg_raw_mode[regno];
1330
1331             gcc_assert (mode != VOIDmode);
1332
1333             align = GET_MODE_ALIGNMENT (mode) / BITS_PER_UNIT;
1334             if (size % align != 0)
1335               size = CEIL (size, align) * align;
1336             size += GET_MODE_SIZE (mode);
1337             apply_result_mode[regno] = mode;
1338           }
1339         else
1340           apply_result_mode[regno] = VOIDmode;
1341
1342       /* Allow targets that use untyped_call and untyped_return to override
1343          the size so that machine-specific information can be stored here.  */
1344 #ifdef APPLY_RESULT_SIZE
1345       size = APPLY_RESULT_SIZE;
1346 #endif
1347     }
1348   return size;
1349 }
1350
1351 #if defined (HAVE_untyped_call) || defined (HAVE_untyped_return)
1352 /* Create a vector describing the result block RESULT.  If SAVEP is true,
1353    the result block is used to save the values; otherwise it is used to
1354    restore the values.  */
1355
1356 static rtx
1357 result_vector (int savep, rtx result)
1358 {
1359   int regno, size, align, nelts;
1360   enum machine_mode mode;
1361   rtx reg, mem;
1362   rtx *savevec = XALLOCAVEC (rtx, FIRST_PSEUDO_REGISTER);
1363
1364   size = nelts = 0;
1365   for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
1366     if ((mode = apply_result_mode[regno]) != VOIDmode)
1367       {
1368         align = GET_MODE_ALIGNMENT (mode) / BITS_PER_UNIT;
1369         if (size % align != 0)
1370           size = CEIL (size, align) * align;
1371         reg = gen_rtx_REG (mode, savep ? regno : INCOMING_REGNO (regno));
1372         mem = adjust_address (result, mode, size);
1373         savevec[nelts++] = (savep
1374                             ? gen_rtx_SET (VOIDmode, mem, reg)
1375                             : gen_rtx_SET (VOIDmode, reg, mem));
1376         size += GET_MODE_SIZE (mode);
1377       }
1378   return gen_rtx_PARALLEL (VOIDmode, gen_rtvec_v (nelts, savevec));
1379 }
1380 #endif /* HAVE_untyped_call or HAVE_untyped_return */
1381
1382 /* Save the state required to perform an untyped call with the same
1383    arguments as were passed to the current function.  */
1384
1385 static rtx
1386 expand_builtin_apply_args_1 (void)
1387 {
1388   rtx registers, tem;
1389   int size, align, regno;
1390   enum machine_mode mode;
1391   rtx struct_incoming_value = targetm.calls.struct_value_rtx (cfun ? TREE_TYPE (cfun->decl) : 0, 1);
1392
1393   /* Create a block where the arg-pointer, structure value address,
1394      and argument registers can be saved.  */
1395   registers = assign_stack_local (BLKmode, apply_args_size (), -1);
1396
1397   /* Walk past the arg-pointer and structure value address.  */
1398   size = GET_MODE_SIZE (Pmode);
1399   if (targetm.calls.struct_value_rtx (cfun ? TREE_TYPE (cfun->decl) : 0, 0))
1400     size += GET_MODE_SIZE (Pmode);
1401
1402   /* Save each register used in calling a function to the block.  */
1403   for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
1404     if ((mode = apply_args_mode[regno]) != VOIDmode)
1405       {
1406         align = GET_MODE_ALIGNMENT (mode) / BITS_PER_UNIT;
1407         if (size % align != 0)
1408           size = CEIL (size, align) * align;
1409
1410         tem = gen_rtx_REG (mode, INCOMING_REGNO (regno));
1411
1412         emit_move_insn (adjust_address (registers, mode, size), tem);
1413         size += GET_MODE_SIZE (mode);
1414       }
1415
1416   /* Save the arg pointer to the block.  */
1417   tem = copy_to_reg (crtl->args.internal_arg_pointer);
1418 #ifdef STACK_GROWS_DOWNWARD
1419   /* We need the pointer as the caller actually passed them to us, not
1420      as we might have pretended they were passed.  Make sure it's a valid
1421      operand, as emit_move_insn isn't expected to handle a PLUS.  */
1422   tem
1423     = force_operand (plus_constant (tem, crtl->args.pretend_args_size),
1424                      NULL_RTX);
1425 #endif
1426   emit_move_insn (adjust_address (registers, Pmode, 0), tem);
1427
1428   size = GET_MODE_SIZE (Pmode);
1429
1430   /* Save the structure value address unless this is passed as an
1431      "invisible" first argument.  */
1432   if (struct_incoming_value)
1433     {
1434       emit_move_insn (adjust_address (registers, Pmode, size),
1435                       copy_to_reg (struct_incoming_value));
1436       size += GET_MODE_SIZE (Pmode);
1437     }
1438
1439   /* Return the address of the block.  */
1440   return copy_addr_to_reg (XEXP (registers, 0));
1441 }
1442
1443 /* __builtin_apply_args returns block of memory allocated on
1444    the stack into which is stored the arg pointer, structure
1445    value address, static chain, and all the registers that might
1446    possibly be used in performing a function call.  The code is
1447    moved to the start of the function so the incoming values are
1448    saved.  */
1449
1450 static rtx
1451 expand_builtin_apply_args (void)
1452 {
1453   /* Don't do __builtin_apply_args more than once in a function.
1454      Save the result of the first call and reuse it.  */
1455   if (apply_args_value != 0)
1456     return apply_args_value;
1457   {
1458     /* When this function is called, it means that registers must be
1459        saved on entry to this function.  So we migrate the
1460        call to the first insn of this function.  */
1461     rtx temp;
1462     rtx seq;
1463
1464     start_sequence ();
1465     temp = expand_builtin_apply_args_1 ();
1466     seq = get_insns ();
1467     end_sequence ();
1468
1469     apply_args_value = temp;
1470
1471     /* Put the insns after the NOTE that starts the function.
1472        If this is inside a start_sequence, make the outer-level insn
1473        chain current, so the code is placed at the start of the
1474        function.  If internal_arg_pointer is a non-virtual pseudo,
1475        it needs to be placed after the function that initializes
1476        that pseudo.  */
1477     push_topmost_sequence ();
1478     if (REG_P (crtl->args.internal_arg_pointer)
1479         && REGNO (crtl->args.internal_arg_pointer) > LAST_VIRTUAL_REGISTER)
1480       emit_insn_before (seq, parm_birth_insn);
1481     else
1482       emit_insn_before (seq, NEXT_INSN (entry_of_function ()));
1483     pop_topmost_sequence ();
1484     return temp;
1485   }
1486 }
1487
1488 /* Perform an untyped call and save the state required to perform an
1489    untyped return of whatever value was returned by the given function.  */
1490
1491 static rtx
1492 expand_builtin_apply (rtx function, rtx arguments, rtx argsize)
1493 {
1494   int size, align, regno;
1495   enum machine_mode mode;
1496   rtx incoming_args, result, reg, dest, src, call_insn;
1497   rtx old_stack_level = 0;
1498   rtx call_fusage = 0;
1499   rtx struct_value = targetm.calls.struct_value_rtx (cfun ? TREE_TYPE (cfun->decl) : 0, 0);
1500
1501   arguments = convert_memory_address (Pmode, arguments);
1502
1503   /* Create a block where the return registers can be saved.  */
1504   result = assign_stack_local (BLKmode, apply_result_size (), -1);
1505
1506   /* Fetch the arg pointer from the ARGUMENTS block.  */
1507   incoming_args = gen_reg_rtx (Pmode);
1508   emit_move_insn (incoming_args, gen_rtx_MEM (Pmode, arguments));
1509 #ifndef STACK_GROWS_DOWNWARD
1510   incoming_args = expand_simple_binop (Pmode, MINUS, incoming_args, argsize,
1511                                        incoming_args, 0, OPTAB_LIB_WIDEN);
1512 #endif
1513
1514   /* Push a new argument block and copy the arguments.  Do not allow
1515      the (potential) memcpy call below to interfere with our stack
1516      manipulations.  */
1517   do_pending_stack_adjust ();
1518   NO_DEFER_POP;
1519
1520   /* Save the stack with nonlocal if available.  */
1521 #ifdef HAVE_save_stack_nonlocal
1522   if (HAVE_save_stack_nonlocal)
1523     emit_stack_save (SAVE_NONLOCAL, &old_stack_level, NULL_RTX);
1524   else
1525 #endif
1526     emit_stack_save (SAVE_BLOCK, &old_stack_level, NULL_RTX);
1527
1528   /* Allocate a block of memory onto the stack and copy the memory
1529      arguments to the outgoing arguments address.  */
1530   allocate_dynamic_stack_space (argsize, 0, BITS_PER_UNIT);
1531
1532   /* Set DRAP flag to true, even though allocate_dynamic_stack_space
1533      may have already set current_function_calls_alloca to true.
1534      current_function_calls_alloca won't be set if argsize is zero,
1535      so we have to guarantee need_drap is true here.  */
1536   if (SUPPORTS_STACK_ALIGNMENT)
1537     crtl->need_drap = true;
1538
1539   dest = virtual_outgoing_args_rtx;
1540 #ifndef STACK_GROWS_DOWNWARD
1541   if (CONST_INT_P (argsize))
1542     dest = plus_constant (dest, -INTVAL (argsize));
1543   else
1544     dest = gen_rtx_PLUS (Pmode, dest, negate_rtx (Pmode, argsize));
1545 #endif
1546   dest = gen_rtx_MEM (BLKmode, dest);
1547   set_mem_align (dest, PARM_BOUNDARY);
1548   src = gen_rtx_MEM (BLKmode, incoming_args);
1549   set_mem_align (src, PARM_BOUNDARY);
1550   emit_block_move (dest, src, argsize, BLOCK_OP_NORMAL);
1551
1552   /* Refer to the argument block.  */
1553   apply_args_size ();
1554   arguments = gen_rtx_MEM (BLKmode, arguments);
1555   set_mem_align (arguments, PARM_BOUNDARY);
1556
1557   /* Walk past the arg-pointer and structure value address.  */
1558   size = GET_MODE_SIZE (Pmode);
1559   if (struct_value)
1560     size += GET_MODE_SIZE (Pmode);
1561
1562   /* Restore each of the registers previously saved.  Make USE insns
1563      for each of these registers for use in making the call.  */
1564   for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
1565     if ((mode = apply_args_mode[regno]) != VOIDmode)
1566       {
1567         align = GET_MODE_ALIGNMENT (mode) / BITS_PER_UNIT;
1568         if (size % align != 0)
1569           size = CEIL (size, align) * align;
1570         reg = gen_rtx_REG (mode, regno);
1571         emit_move_insn (reg, adjust_address (arguments, mode, size));
1572         use_reg (&call_fusage, reg);
1573         size += GET_MODE_SIZE (mode);
1574       }
1575
1576   /* Restore the structure value address unless this is passed as an
1577      "invisible" first argument.  */
1578   size = GET_MODE_SIZE (Pmode);
1579   if (struct_value)
1580     {
1581       rtx value = gen_reg_rtx (Pmode);
1582       emit_move_insn (value, adjust_address (arguments, Pmode, size));
1583       emit_move_insn (struct_value, value);
1584       if (REG_P (struct_value))
1585         use_reg (&call_fusage, struct_value);
1586       size += GET_MODE_SIZE (Pmode);
1587     }
1588
1589   /* All arguments and registers used for the call are set up by now!  */
1590   function = prepare_call_address (NULL, function, NULL, &call_fusage, 0, 0);
1591
1592   /* Ensure address is valid.  SYMBOL_REF is already valid, so no need,
1593      and we don't want to load it into a register as an optimization,
1594      because prepare_call_address already did it if it should be done.  */
1595   if (GET_CODE (function) != SYMBOL_REF)
1596     function = memory_address (FUNCTION_MODE, function);
1597
1598   /* Generate the actual call instruction and save the return value.  */
1599 #ifdef HAVE_untyped_call
1600   if (HAVE_untyped_call)
1601     emit_call_insn (gen_untyped_call (gen_rtx_MEM (FUNCTION_MODE, function),
1602                                       result, result_vector (1, result)));
1603   else
1604 #endif
1605 #ifdef HAVE_call_value
1606   if (HAVE_call_value)
1607     {
1608       rtx valreg = 0;
1609
1610       /* Locate the unique return register.  It is not possible to
1611          express a call that sets more than one return register using
1612          call_value; use untyped_call for that.  In fact, untyped_call
1613          only needs to save the return registers in the given block.  */
1614       for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
1615         if ((mode = apply_result_mode[regno]) != VOIDmode)
1616           {
1617             gcc_assert (!valreg); /* HAVE_untyped_call required.  */
1618
1619             valreg = gen_rtx_REG (mode, regno);
1620           }
1621
1622       emit_call_insn (GEN_CALL_VALUE (valreg,
1623                                       gen_rtx_MEM (FUNCTION_MODE, function),
1624                                       const0_rtx, NULL_RTX, const0_rtx));
1625
1626       emit_move_insn (adjust_address (result, GET_MODE (valreg), 0), valreg);
1627     }
1628   else
1629 #endif
1630     gcc_unreachable ();
1631
1632   /* Find the CALL insn we just emitted, and attach the register usage
1633      information.  */
1634   call_insn = last_call_insn ();
1635   add_function_usage_to (call_insn, call_fusage);
1636
1637   /* Restore the stack.  */
1638 #ifdef HAVE_save_stack_nonlocal
1639   if (HAVE_save_stack_nonlocal)
1640     emit_stack_restore (SAVE_NONLOCAL, old_stack_level, NULL_RTX);
1641   else
1642 #endif
1643     emit_stack_restore (SAVE_BLOCK, old_stack_level, NULL_RTX);
1644
1645   OK_DEFER_POP;
1646
1647   /* Return the address of the result block.  */
1648   result = copy_addr_to_reg (XEXP (result, 0));
1649   return convert_memory_address (ptr_mode, result);
1650 }
1651
1652 /* Perform an untyped return.  */
1653
1654 static void
1655 expand_builtin_return (rtx result)
1656 {
1657   int size, align, regno;
1658   enum machine_mode mode;
1659   rtx reg;
1660   rtx call_fusage = 0;
1661
1662   result = convert_memory_address (Pmode, result);
1663
1664   apply_result_size ();
1665   result = gen_rtx_MEM (BLKmode, result);
1666
1667 #ifdef HAVE_untyped_return
1668   if (HAVE_untyped_return)
1669     {
1670       emit_jump_insn (gen_untyped_return (result, result_vector (0, result)));
1671       emit_barrier ();
1672       return;
1673     }
1674 #endif
1675
1676   /* Restore the return value and note that each value is used.  */
1677   size = 0;
1678   for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
1679     if ((mode = apply_result_mode[regno]) != VOIDmode)
1680       {
1681         align = GET_MODE_ALIGNMENT (mode) / BITS_PER_UNIT;
1682         if (size % align != 0)
1683           size = CEIL (size, align) * align;
1684         reg = gen_rtx_REG (mode, INCOMING_REGNO (regno));
1685         emit_move_insn (reg, adjust_address (result, mode, size));
1686
1687         push_to_sequence (call_fusage);
1688         emit_use (reg);
1689         call_fusage = get_insns ();
1690         end_sequence ();
1691         size += GET_MODE_SIZE (mode);
1692       }
1693
1694   /* Put the USE insns before the return.  */
1695   emit_insn (call_fusage);
1696
1697   /* Return whatever values was restored by jumping directly to the end
1698      of the function.  */
1699   expand_naked_return ();
1700 }
1701
1702 /* Used by expand_builtin_classify_type and fold_builtin_classify_type.  */
1703
1704 static enum type_class
1705 type_to_class (tree type)
1706 {
1707   switch (TREE_CODE (type))
1708     {
1709     case VOID_TYPE:        return void_type_class;
1710     case INTEGER_TYPE:     return integer_type_class;
1711     case ENUMERAL_TYPE:    return enumeral_type_class;
1712     case BOOLEAN_TYPE:     return boolean_type_class;
1713     case POINTER_TYPE:     return pointer_type_class;
1714     case REFERENCE_TYPE:   return reference_type_class;
1715     case OFFSET_TYPE:      return offset_type_class;
1716     case REAL_TYPE:        return real_type_class;
1717     case COMPLEX_TYPE:     return complex_type_class;
1718     case FUNCTION_TYPE:    return function_type_class;
1719     case METHOD_TYPE:      return method_type_class;
1720     case RECORD_TYPE:      return record_type_class;
1721     case UNION_TYPE:
1722     case QUAL_UNION_TYPE:  return union_type_class;
1723     case ARRAY_TYPE:       return (TYPE_STRING_FLAG (type)
1724                                    ? string_type_class : array_type_class);
1725     case LANG_TYPE:        return lang_type_class;
1726     default:               return no_type_class;
1727     }
1728 }
1729
1730 /* Expand a call EXP to __builtin_classify_type.  */
1731
1732 static rtx
1733 expand_builtin_classify_type (tree exp)
1734 {
1735   if (call_expr_nargs (exp))
1736     return GEN_INT (type_to_class (TREE_TYPE (CALL_EXPR_ARG (exp, 0))));
1737   return GEN_INT (no_type_class);
1738 }
1739
1740 /* This helper macro, meant to be used in mathfn_built_in below,
1741    determines which among a set of three builtin math functions is
1742    appropriate for a given type mode.  The `F' and `L' cases are
1743    automatically generated from the `double' case.  */
1744 #define CASE_MATHFN(BUILT_IN_MATHFN) \
1745   case BUILT_IN_MATHFN: case BUILT_IN_MATHFN##F: case BUILT_IN_MATHFN##L: \
1746   fcode = BUILT_IN_MATHFN; fcodef = BUILT_IN_MATHFN##F ; \
1747   fcodel = BUILT_IN_MATHFN##L ; break;
1748 /* Similar to above, but appends _R after any F/L suffix.  */
1749 #define CASE_MATHFN_REENT(BUILT_IN_MATHFN) \
1750   case BUILT_IN_MATHFN##_R: case BUILT_IN_MATHFN##F_R: case BUILT_IN_MATHFN##L_R: \
1751   fcode = BUILT_IN_MATHFN##_R; fcodef = BUILT_IN_MATHFN##F_R ; \
1752   fcodel = BUILT_IN_MATHFN##L_R ; break;
1753
1754 /* Return mathematic function equivalent to FN but operating directly
1755    on TYPE, if available.  If IMPLICIT is true find the function in
1756    implicit_built_in_decls[], otherwise use built_in_decls[].  If we
1757    can't do the conversion, return zero.  */
1758
1759 static tree
1760 mathfn_built_in_1 (tree type, enum built_in_function fn, bool implicit)
1761 {
1762   tree const *const fn_arr
1763     = implicit ? implicit_built_in_decls : built_in_decls;
1764   enum built_in_function fcode, fcodef, fcodel;
1765
1766   switch (fn)
1767     {
1768       CASE_MATHFN (BUILT_IN_ACOS)
1769       CASE_MATHFN (BUILT_IN_ACOSH)
1770       CASE_MATHFN (BUILT_IN_ASIN)
1771       CASE_MATHFN (BUILT_IN_ASINH)
1772       CASE_MATHFN (BUILT_IN_ATAN)
1773       CASE_MATHFN (BUILT_IN_ATAN2)
1774       CASE_MATHFN (BUILT_IN_ATANH)
1775       CASE_MATHFN (BUILT_IN_CBRT)
1776       CASE_MATHFN (BUILT_IN_CEIL)
1777       CASE_MATHFN (BUILT_IN_CEXPI)
1778       CASE_MATHFN (BUILT_IN_COPYSIGN)
1779       CASE_MATHFN (BUILT_IN_COS)
1780       CASE_MATHFN (BUILT_IN_COSH)
1781       CASE_MATHFN (BUILT_IN_DREM)
1782       CASE_MATHFN (BUILT_IN_ERF)
1783       CASE_MATHFN (BUILT_IN_ERFC)
1784       CASE_MATHFN (BUILT_IN_EXP)
1785       CASE_MATHFN (BUILT_IN_EXP10)
1786       CASE_MATHFN (BUILT_IN_EXP2)
1787       CASE_MATHFN (BUILT_IN_EXPM1)
1788       CASE_MATHFN (BUILT_IN_FABS)
1789       CASE_MATHFN (BUILT_IN_FDIM)
1790       CASE_MATHFN (BUILT_IN_FLOOR)
1791       CASE_MATHFN (BUILT_IN_FMA)
1792       CASE_MATHFN (BUILT_IN_FMAX)
1793       CASE_MATHFN (BUILT_IN_FMIN)
1794       CASE_MATHFN (BUILT_IN_FMOD)
1795       CASE_MATHFN (BUILT_IN_FREXP)
1796       CASE_MATHFN (BUILT_IN_GAMMA)
1797       CASE_MATHFN_REENT (BUILT_IN_GAMMA) /* GAMMA_R */
1798       CASE_MATHFN (BUILT_IN_HUGE_VAL)
1799       CASE_MATHFN (BUILT_IN_HYPOT)
1800       CASE_MATHFN (BUILT_IN_ILOGB)
1801       CASE_MATHFN (BUILT_IN_INF)
1802       CASE_MATHFN (BUILT_IN_ISINF)
1803       CASE_MATHFN (BUILT_IN_J0)
1804       CASE_MATHFN (BUILT_IN_J1)
1805       CASE_MATHFN (BUILT_IN_JN)
1806       CASE_MATHFN (BUILT_IN_LCEIL)
1807       CASE_MATHFN (BUILT_IN_LDEXP)
1808       CASE_MATHFN (BUILT_IN_LFLOOR)
1809       CASE_MATHFN (BUILT_IN_LGAMMA)
1810       CASE_MATHFN_REENT (BUILT_IN_LGAMMA) /* LGAMMA_R */
1811       CASE_MATHFN (BUILT_IN_LLCEIL)
1812       CASE_MATHFN (BUILT_IN_LLFLOOR)
1813       CASE_MATHFN (BUILT_IN_LLRINT)
1814       CASE_MATHFN (BUILT_IN_LLROUND)
1815       CASE_MATHFN (BUILT_IN_LOG)
1816       CASE_MATHFN (BUILT_IN_LOG10)
1817       CASE_MATHFN (BUILT_IN_LOG1P)
1818       CASE_MATHFN (BUILT_IN_LOG2)
1819       CASE_MATHFN (BUILT_IN_LOGB)
1820       CASE_MATHFN (BUILT_IN_LRINT)
1821       CASE_MATHFN (BUILT_IN_LROUND)
1822       CASE_MATHFN (BUILT_IN_MODF)
1823       CASE_MATHFN (BUILT_IN_NAN)
1824       CASE_MATHFN (BUILT_IN_NANS)
1825       CASE_MATHFN (BUILT_IN_NEARBYINT)
1826       CASE_MATHFN (BUILT_IN_NEXTAFTER)
1827       CASE_MATHFN (BUILT_IN_NEXTTOWARD)
1828       CASE_MATHFN (BUILT_IN_POW)
1829       CASE_MATHFN (BUILT_IN_POWI)
1830       CASE_MATHFN (BUILT_IN_POW10)
1831       CASE_MATHFN (BUILT_IN_REMAINDER)
1832       CASE_MATHFN (BUILT_IN_REMQUO)
1833       CASE_MATHFN (BUILT_IN_RINT)
1834       CASE_MATHFN (BUILT_IN_ROUND)
1835       CASE_MATHFN (BUILT_IN_SCALB)
1836       CASE_MATHFN (BUILT_IN_SCALBLN)
1837       CASE_MATHFN (BUILT_IN_SCALBN)
1838       CASE_MATHFN (BUILT_IN_SIGNBIT)
1839       CASE_MATHFN (BUILT_IN_SIGNIFICAND)
1840       CASE_MATHFN (BUILT_IN_SIN)
1841       CASE_MATHFN (BUILT_IN_SINCOS)
1842       CASE_MATHFN (BUILT_IN_SINH)
1843       CASE_MATHFN (BUILT_IN_SQRT)
1844       CASE_MATHFN (BUILT_IN_TAN)
1845       CASE_MATHFN (BUILT_IN_TANH)
1846       CASE_MATHFN (BUILT_IN_TGAMMA)
1847       CASE_MATHFN (BUILT_IN_TRUNC)
1848       CASE_MATHFN (BUILT_IN_Y0)
1849       CASE_MATHFN (BUILT_IN_Y1)
1850       CASE_MATHFN (BUILT_IN_YN)
1851
1852       default:
1853         return NULL_TREE;
1854       }
1855
1856   if (TYPE_MAIN_VARIANT (type) == double_type_node)
1857     return fn_arr[fcode];
1858   else if (TYPE_MAIN_VARIANT (type) == float_type_node)
1859     return fn_arr[fcodef];
1860   else if (TYPE_MAIN_VARIANT (type) == long_double_type_node)
1861     return fn_arr[fcodel];
1862   else
1863     return NULL_TREE;
1864 }
1865
1866 /* Like mathfn_built_in_1(), but always use the implicit array.  */
1867
1868 tree
1869 mathfn_built_in (tree type, enum built_in_function fn)
1870 {
1871   return mathfn_built_in_1 (type, fn, /*implicit=*/ 1);
1872 }
1873
1874 /* If errno must be maintained, expand the RTL to check if the result,
1875    TARGET, of a built-in function call, EXP, is NaN, and if so set
1876    errno to EDOM.  */
1877
1878 static void
1879 expand_errno_check (tree exp, rtx target)
1880 {
1881   rtx lab = gen_label_rtx ();
1882
1883   /* Test the result; if it is NaN, set errno=EDOM because
1884      the argument was not in the domain.  */
1885   do_compare_rtx_and_jump (target, target, EQ, 0, GET_MODE (target),
1886                            NULL_RTX, NULL_RTX, lab);
1887
1888 #ifdef TARGET_EDOM
1889   /* If this built-in doesn't throw an exception, set errno directly.  */
1890   if (TREE_NOTHROW (TREE_OPERAND (CALL_EXPR_FN (exp), 0)))
1891     {
1892 #ifdef GEN_ERRNO_RTX
1893       rtx errno_rtx = GEN_ERRNO_RTX;
1894 #else
1895       rtx errno_rtx
1896           = gen_rtx_MEM (word_mode, gen_rtx_SYMBOL_REF (Pmode, "errno"));
1897 #endif
1898       emit_move_insn (errno_rtx, GEN_INT (TARGET_EDOM));
1899       emit_label (lab);
1900       return;
1901     }
1902 #endif
1903
1904   /* Make sure the library call isn't expanded as a tail call.  */
1905   CALL_EXPR_TAILCALL (exp) = 0;
1906
1907   /* We can't set errno=EDOM directly; let the library call do it.
1908      Pop the arguments right away in case the call gets deleted.  */
1909   NO_DEFER_POP;
1910   expand_call (exp, target, 0);
1911   OK_DEFER_POP;
1912   emit_label (lab);
1913 }
1914
1915 /* Expand a call to one of the builtin math functions (sqrt, exp, or log).
1916    Return NULL_RTX if a normal call should be emitted rather than expanding
1917    the function in-line.  EXP is the expression that is a call to the builtin
1918    function; if convenient, the result should be placed in TARGET.
1919    SUBTARGET may be used as the target for computing one of EXP's operands.  */
1920
1921 static rtx
1922 expand_builtin_mathfn (tree exp, rtx target, rtx subtarget)
1923 {
1924   optab builtin_optab;
1925   rtx op0, insns;
1926   tree fndecl = get_callee_fndecl (exp);
1927   enum machine_mode mode;
1928   bool errno_set = false;
1929   tree arg;
1930
1931   if (!validate_arglist (exp, REAL_TYPE, VOID_TYPE))
1932     return NULL_RTX;
1933
1934   arg = CALL_EXPR_ARG (exp, 0);
1935
1936   switch (DECL_FUNCTION_CODE (fndecl))
1937     {
1938     CASE_FLT_FN (BUILT_IN_SQRT):
1939       errno_set = ! tree_expr_nonnegative_p (arg);
1940       builtin_optab = sqrt_optab;
1941       break;
1942     CASE_FLT_FN (BUILT_IN_EXP):
1943       errno_set = true; builtin_optab = exp_optab; break;
1944     CASE_FLT_FN (BUILT_IN_EXP10):
1945     CASE_FLT_FN (BUILT_IN_POW10):
1946       errno_set = true; builtin_optab = exp10_optab; break;
1947     CASE_FLT_FN (BUILT_IN_EXP2):
1948       errno_set = true; builtin_optab = exp2_optab; break;
1949     CASE_FLT_FN (BUILT_IN_EXPM1):
1950       errno_set = true; builtin_optab = expm1_optab; break;
1951     CASE_FLT_FN (BUILT_IN_LOGB):
1952       errno_set = true; builtin_optab = logb_optab; break;
1953     CASE_FLT_FN (BUILT_IN_LOG):
1954       errno_set = true; builtin_optab = log_optab; break;
1955     CASE_FLT_FN (BUILT_IN_LOG10):
1956       errno_set = true; builtin_optab = log10_optab; break;
1957     CASE_FLT_FN (BUILT_IN_LOG2):
1958       errno_set = true; builtin_optab = log2_optab; break;
1959     CASE_FLT_FN (BUILT_IN_LOG1P):
1960       errno_set = true; builtin_optab = log1p_optab; break;
1961     CASE_FLT_FN (BUILT_IN_ASIN):
1962       builtin_optab = asin_optab; break;
1963     CASE_FLT_FN (BUILT_IN_ACOS):
1964       builtin_optab = acos_optab; break;
1965     CASE_FLT_FN (BUILT_IN_TAN):
1966       builtin_optab = tan_optab; break;
1967     CASE_FLT_FN (BUILT_IN_ATAN):
1968       builtin_optab = atan_optab; break;
1969     CASE_FLT_FN (BUILT_IN_FLOOR):
1970       builtin_optab = floor_optab; break;
1971     CASE_FLT_FN (BUILT_IN_CEIL):
1972       builtin_optab = ceil_optab; break;
1973     CASE_FLT_FN (BUILT_IN_TRUNC):
1974       builtin_optab = btrunc_optab; break;
1975     CASE_FLT_FN (BUILT_IN_ROUND):
1976       builtin_optab = round_optab; break;
1977     CASE_FLT_FN (BUILT_IN_NEARBYINT):
1978       builtin_optab = nearbyint_optab;
1979       if (flag_trapping_math)
1980         break;
1981       /* Else fallthrough and expand as rint.  */
1982     CASE_FLT_FN (BUILT_IN_RINT):
1983       builtin_optab = rint_optab; break;
1984     CASE_FLT_FN (BUILT_IN_SIGNIFICAND):
1985       builtin_optab = significand_optab; break;
1986     default:
1987       gcc_unreachable ();
1988     }
1989
1990   /* Make a suitable register to place result in.  */
1991   mode = TYPE_MODE (TREE_TYPE (exp));
1992
1993   if (! flag_errno_math || ! HONOR_NANS (mode))
1994     errno_set = false;
1995
1996   /* Before working hard, check whether the instruction is available.  */
1997   if (optab_handler (builtin_optab, mode)->insn_code != CODE_FOR_nothing)
1998     {
1999       target = gen_reg_rtx (mode);
2000
2001       /* Wrap the computation of the argument in a SAVE_EXPR, as we may
2002          need to expand the argument again.  This way, we will not perform
2003          side-effects more the once.  */
2004       CALL_EXPR_ARG (exp, 0) = arg = builtin_save_expr (arg);
2005
2006       op0 = expand_expr (arg, subtarget, VOIDmode, EXPAND_NORMAL);
2007
2008       start_sequence ();
2009
2010       /* Compute into TARGET.
2011          Set TARGET to wherever the result comes back.  */
2012       target = expand_unop (mode, builtin_optab, op0, target, 0);
2013
2014       if (target != 0)
2015         {
2016           if (errno_set)
2017             expand_errno_check (exp, target);
2018
2019           /* Output the entire sequence.  */
2020           insns = get_insns ();
2021           end_sequence ();
2022           emit_insn (insns);
2023           return target;
2024         }
2025
2026       /* If we were unable to expand via the builtin, stop the sequence
2027          (without outputting the insns) and call to the library function
2028          with the stabilized argument list.  */
2029       end_sequence ();
2030     }
2031
2032   return expand_call (exp, target, target == const0_rtx);
2033 }
2034
2035 /* Expand a call to the builtin binary math functions (pow and atan2).
2036    Return NULL_RTX if a normal call should be emitted rather than expanding the
2037    function in-line.  EXP is the expression that is a call to the builtin
2038    function; if convenient, the result should be placed in TARGET.
2039    SUBTARGET may be used as the target for computing one of EXP's
2040    operands.  */
2041
2042 static rtx
2043 expand_builtin_mathfn_2 (tree exp, rtx target, rtx subtarget)
2044 {
2045   optab builtin_optab;
2046   rtx op0, op1, insns;
2047   int op1_type = REAL_TYPE;
2048   tree fndecl = get_callee_fndecl (exp);
2049   tree arg0, arg1;
2050   enum machine_mode mode;
2051   bool errno_set = true;
2052
2053   switch (DECL_FUNCTION_CODE (fndecl))
2054     {
2055     CASE_FLT_FN (BUILT_IN_SCALBN):
2056     CASE_FLT_FN (BUILT_IN_SCALBLN):
2057     CASE_FLT_FN (BUILT_IN_LDEXP):
2058       op1_type = INTEGER_TYPE;
2059     default:
2060       break;
2061     }
2062
2063   if (!validate_arglist (exp, REAL_TYPE, op1_type, VOID_TYPE))
2064     return NULL_RTX;
2065
2066   arg0 = CALL_EXPR_ARG (exp, 0);
2067   arg1 = CALL_EXPR_ARG (exp, 1);
2068
2069   switch (DECL_FUNCTION_CODE (fndecl))
2070     {
2071     CASE_FLT_FN (BUILT_IN_POW):
2072       builtin_optab = pow_optab; break;
2073     CASE_FLT_FN (BUILT_IN_ATAN2):
2074       builtin_optab = atan2_optab; break;
2075     CASE_FLT_FN (BUILT_IN_SCALB):
2076       if (REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (exp)))->b != 2)
2077         return 0;
2078       builtin_optab = scalb_optab; break;
2079     CASE_FLT_FN (BUILT_IN_SCALBN):
2080     CASE_FLT_FN (BUILT_IN_SCALBLN):
2081       if (REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (exp)))->b != 2)
2082         return 0;
2083     /* Fall through... */
2084     CASE_FLT_FN (BUILT_IN_LDEXP):
2085       builtin_optab = ldexp_optab; break;
2086     CASE_FLT_FN (BUILT_IN_FMOD):
2087       builtin_optab = fmod_optab; break;
2088     CASE_FLT_FN (BUILT_IN_REMAINDER):
2089     CASE_FLT_FN (BUILT_IN_DREM):
2090       builtin_optab = remainder_optab; break;
2091     default:
2092       gcc_unreachable ();
2093     }
2094
2095   /* Make a suitable register to place result in.  */
2096   mode = TYPE_MODE (TREE_TYPE (exp));
2097
2098   /* Before working hard, check whether the instruction is available.  */
2099   if (optab_handler (builtin_optab, mode)->insn_code == CODE_FOR_nothing)
2100     return NULL_RTX;
2101
2102   target = gen_reg_rtx (mode);
2103
2104   if (! flag_errno_math || ! HONOR_NANS (mode))
2105     errno_set = false;
2106
2107   /* Always stabilize the argument list.  */
2108   CALL_EXPR_ARG (exp, 0) = arg0 = builtin_save_expr (arg0);
2109   CALL_EXPR_ARG (exp, 1) = arg1 = builtin_save_expr (arg1);
2110
2111   op0 = expand_expr (arg0, subtarget, VOIDmode, EXPAND_NORMAL);
2112   op1 = expand_normal (arg1);
2113
2114   start_sequence ();
2115
2116   /* Compute into TARGET.
2117      Set TARGET to wherever the result comes back.  */
2118   target = expand_binop (mode, builtin_optab, op0, op1,
2119                          target, 0, OPTAB_DIRECT);
2120
2121   /* If we were unable to expand via the builtin, stop the sequence
2122      (without outputting the insns) and call to the library function
2123      with the stabilized argument list.  */
2124   if (target == 0)
2125     {
2126       end_sequence ();
2127       return expand_call (exp, target, target == const0_rtx);
2128     }
2129
2130   if (errno_set)
2131     expand_errno_check (exp, target);
2132
2133   /* Output the entire sequence.  */
2134   insns = get_insns ();
2135   end_sequence ();
2136   emit_insn (insns);
2137
2138   return target;
2139 }
2140
2141 /* Expand a call to the builtin sin and cos math functions.
2142    Return NULL_RTX if a normal call should be emitted rather than expanding the
2143    function in-line.  EXP is the expression that is a call to the builtin
2144    function; if convenient, the result should be placed in TARGET.
2145    SUBTARGET may be used as the target for computing one of EXP's
2146    operands.  */
2147
2148 static rtx
2149 expand_builtin_mathfn_3 (tree exp, rtx target, rtx subtarget)
2150 {
2151   optab builtin_optab;
2152   rtx op0, insns;
2153   tree fndecl = get_callee_fndecl (exp);
2154   enum machine_mode mode;
2155   tree arg;
2156
2157   if (!validate_arglist (exp, REAL_TYPE, VOID_TYPE))
2158     return NULL_RTX;
2159
2160   arg = CALL_EXPR_ARG (exp, 0);
2161
2162   switch (DECL_FUNCTION_CODE (fndecl))
2163     {
2164     CASE_FLT_FN (BUILT_IN_SIN):
2165     CASE_FLT_FN (BUILT_IN_COS):
2166       builtin_optab = sincos_optab; break;
2167     default:
2168       gcc_unreachable ();
2169     }
2170
2171   /* Make a suitable register to place result in.  */
2172   mode = TYPE_MODE (TREE_TYPE (exp));
2173
2174   /* Check if sincos insn is available, otherwise fallback
2175      to sin or cos insn.  */
2176   if (optab_handler (builtin_optab, mode)->insn_code == CODE_FOR_nothing)
2177     switch (DECL_FUNCTION_CODE (fndecl))
2178       {
2179       CASE_FLT_FN (BUILT_IN_SIN):
2180         builtin_optab = sin_optab; break;
2181       CASE_FLT_FN (BUILT_IN_COS):
2182         builtin_optab = cos_optab; break;
2183       default:
2184         gcc_unreachable ();
2185       }
2186
2187   /* Before working hard, check whether the instruction is available.  */
2188   if (optab_handler (builtin_optab, mode)->insn_code != CODE_FOR_nothing)
2189     {
2190       target = gen_reg_rtx (mode);
2191
2192       /* Wrap the computation of the argument in a SAVE_EXPR, as we may
2193          need to expand the argument again.  This way, we will not perform
2194          side-effects more the once.  */
2195       CALL_EXPR_ARG (exp, 0) = arg = builtin_save_expr (arg);
2196
2197       op0 = expand_expr (arg, subtarget, VOIDmode, EXPAND_NORMAL);
2198
2199       start_sequence ();
2200
2201       /* Compute into TARGET.
2202          Set TARGET to wherever the result comes back.  */
2203       if (builtin_optab == sincos_optab)
2204         {
2205           int result;
2206
2207           switch (DECL_FUNCTION_CODE (fndecl))
2208             {
2209             CASE_FLT_FN (BUILT_IN_SIN):
2210               result = expand_twoval_unop (builtin_optab, op0, 0, target, 0);
2211               break;
2212             CASE_FLT_FN (BUILT_IN_COS):
2213               result = expand_twoval_unop (builtin_optab, op0, target, 0, 0);
2214               break;
2215             default:
2216               gcc_unreachable ();
2217             }
2218           gcc_assert (result);
2219         }
2220       else
2221         {
2222           target = expand_unop (mode, builtin_optab, op0, target, 0);
2223         }
2224
2225       if (target != 0)
2226         {
2227           /* Output the entire sequence.  */
2228           insns = get_insns ();
2229           end_sequence ();
2230           emit_insn (insns);
2231           return target;
2232         }
2233
2234       /* If we were unable to expand via the builtin, stop the sequence
2235          (without outputting the insns) and call to the library function
2236          with the stabilized argument list.  */
2237       end_sequence ();
2238     }
2239
2240   target = expand_call (exp, target, target == const0_rtx);
2241
2242   return target;
2243 }
2244
2245 /* Given an interclass math builtin decl FNDECL and it's argument ARG
2246    return an RTL instruction code that implements the functionality.
2247    If that isn't possible or available return CODE_FOR_nothing.  */
2248
2249 static enum insn_code
2250 interclass_mathfn_icode (tree arg, tree fndecl)
2251 {
2252   bool errno_set = false;
2253   optab builtin_optab = 0;
2254   enum machine_mode mode;
2255
2256   switch (DECL_FUNCTION_CODE (fndecl))
2257     {
2258     CASE_FLT_FN (BUILT_IN_ILOGB):
2259       errno_set = true; builtin_optab = ilogb_optab; break;
2260     CASE_FLT_FN (BUILT_IN_ISINF):
2261       builtin_optab = isinf_optab; break;
2262     case BUILT_IN_ISNORMAL:
2263     case BUILT_IN_ISFINITE:
2264     CASE_FLT_FN (BUILT_IN_FINITE):
2265     case BUILT_IN_FINITED32:
2266     case BUILT_IN_FINITED64:
2267     case BUILT_IN_FINITED128:
2268     case BUILT_IN_ISINFD32:
2269     case BUILT_IN_ISINFD64:
2270     case BUILT_IN_ISINFD128:
2271       /* These builtins have no optabs (yet).  */
2272       break;
2273     default:
2274       gcc_unreachable ();
2275     }
2276
2277   /* There's no easy way to detect the case we need to set EDOM.  */
2278   if (flag_errno_math && errno_set)
2279     return CODE_FOR_nothing;
2280
2281   /* Optab mode depends on the mode of the input argument.  */
2282   mode = TYPE_MODE (TREE_TYPE (arg));
2283
2284   if (builtin_optab)
2285     return optab_handler (builtin_optab, mode)->insn_code;
2286   return CODE_FOR_nothing;
2287 }
2288
2289 /* Expand a call to one of the builtin math functions that operate on
2290    floating point argument and output an integer result (ilogb, isinf,
2291    isnan, etc).
2292    Return 0 if a normal call should be emitted rather than expanding the
2293    function in-line.  EXP is the expression that is a call to the builtin
2294    function; if convenient, the result should be placed in TARGET.
2295    SUBTARGET may be used as the target for computing one of EXP's operands.  */
2296
2297 static rtx
2298 expand_builtin_interclass_mathfn (tree exp, rtx target, rtx subtarget)
2299 {
2300   enum insn_code icode = CODE_FOR_nothing;
2301   rtx op0;
2302   tree fndecl = get_callee_fndecl (exp);
2303   enum machine_mode mode;
2304   tree arg;
2305
2306   if (!validate_arglist (exp, REAL_TYPE, VOID_TYPE))
2307     return NULL_RTX;
2308
2309   arg = CALL_EXPR_ARG (exp, 0);
2310   icode = interclass_mathfn_icode (arg, fndecl);
2311   mode = TYPE_MODE (TREE_TYPE (arg));
2312
2313   if (icode != CODE_FOR_nothing)
2314     {
2315       /* Make a suitable register to place result in.  */
2316       if (!target
2317           || GET_MODE (target) != TYPE_MODE (TREE_TYPE (exp)))
2318          target = gen_reg_rtx (TYPE_MODE (TREE_TYPE (exp)));
2319
2320       gcc_assert (insn_data[icode].operand[0].predicate
2321                   (target, GET_MODE (target)));
2322
2323       /* Wrap the computation of the argument in a SAVE_EXPR, as we may
2324          need to expand the argument again.  This way, we will not perform
2325          side-effects more the once.  */
2326       CALL_EXPR_ARG (exp, 0) = arg = builtin_save_expr (arg);
2327
2328       op0 = expand_expr (arg, subtarget, VOIDmode, EXPAND_NORMAL);
2329
2330       if (mode != GET_MODE (op0))
2331         op0 = convert_to_mode (mode, op0, 0);
2332
2333       /* Compute into TARGET.
2334          Set TARGET to wherever the result comes back.  */
2335       emit_unop_insn (icode, target, op0, UNKNOWN);
2336       return target;
2337     }
2338
2339   return NULL_RTX;
2340 }
2341
2342 /* Expand a call to the builtin sincos math function.
2343    Return NULL_RTX if a normal call should be emitted rather than expanding the
2344    function in-line.  EXP is the expression that is a call to the builtin
2345    function.  */
2346
2347 static rtx
2348 expand_builtin_sincos (tree exp)
2349 {
2350   rtx op0, op1, op2, target1, target2;
2351   enum machine_mode mode;
2352   tree arg, sinp, cosp;
2353   int result;
2354   location_t loc = EXPR_LOCATION (exp);
2355
2356   if (!validate_arglist (exp, REAL_TYPE,
2357                          POINTER_TYPE, POINTER_TYPE, VOID_TYPE))
2358     return NULL_RTX;
2359
2360   arg = CALL_EXPR_ARG (exp, 0);
2361   sinp = CALL_EXPR_ARG (exp, 1);
2362   cosp = CALL_EXPR_ARG (exp, 2);
2363
2364   /* Make a suitable register to place result in.  */
2365   mode = TYPE_MODE (TREE_TYPE (arg));
2366
2367   /* Check if sincos insn is available, otherwise emit the call.  */
2368   if (optab_handler (sincos_optab, mode)->insn_code == CODE_FOR_nothing)
2369     return NULL_RTX;
2370
2371   target1 = gen_reg_rtx (mode);
2372   target2 = gen_reg_rtx (mode);
2373
2374   op0 = expand_normal (arg);
2375   op1 = expand_normal (build_fold_indirect_ref_loc (loc, sinp));
2376   op2 = expand_normal (build_fold_indirect_ref_loc (loc, cosp));
2377
2378   /* Compute into target1 and target2.
2379      Set TARGET to wherever the result comes back.  */
2380   result = expand_twoval_unop (sincos_optab, op0, target2, target1, 0);
2381   gcc_assert (result);
2382
2383   /* Move target1 and target2 to the memory locations indicated
2384      by op1 and op2.  */
2385   emit_move_insn (op1, target1);
2386   emit_move_insn (op2, target2);
2387
2388   return const0_rtx;
2389 }
2390
2391 /* Expand a call to the internal cexpi builtin to the sincos math function.
2392    EXP is the expression that is a call to the builtin function; if convenient,
2393    the result should be placed in TARGET.  SUBTARGET may be used as the target
2394    for computing one of EXP's operands.  */
2395
2396 static rtx
2397 expand_builtin_cexpi (tree exp, rtx target, rtx subtarget)
2398 {
2399   tree fndecl = get_callee_fndecl (exp);
2400   tree arg, type;
2401   enum machine_mode mode;
2402   rtx op0, op1, op2;
2403   location_t loc = EXPR_LOCATION (exp);
2404
2405   if (!validate_arglist (exp, REAL_TYPE, VOID_TYPE))
2406     return NULL_RTX;
2407
2408   arg = CALL_EXPR_ARG (exp, 0);
2409   type = TREE_TYPE (arg);
2410   mode = TYPE_MODE (TREE_TYPE (arg));
2411
2412   /* Try expanding via a sincos optab, fall back to emitting a libcall
2413      to sincos or cexp.  We are sure we have sincos or cexp because cexpi
2414      is only generated from sincos, cexp or if we have either of them.  */
2415   if (optab_handler (sincos_optab, mode)->insn_code != CODE_FOR_nothing)
2416     {
2417       op1 = gen_reg_rtx (mode);
2418       op2 = gen_reg_rtx (mode);
2419
2420       op0 = expand_expr (arg, subtarget, VOIDmode, EXPAND_NORMAL);
2421
2422       /* Compute into op1 and op2.  */
2423       expand_twoval_unop (sincos_optab, op0, op2, op1, 0);
2424     }
2425   else if (TARGET_HAS_SINCOS)
2426     {
2427       tree call, fn = NULL_TREE;
2428       tree top1, top2;
2429       rtx op1a, op2a;
2430
2431       if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPIF)
2432         fn = built_in_decls[BUILT_IN_SINCOSF];
2433       else if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPI)
2434         fn = built_in_decls[BUILT_IN_SINCOS];
2435       else if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPIL)
2436         fn = built_in_decls[BUILT_IN_SINCOSL];
2437       else
2438         gcc_unreachable ();
2439  
2440       op1 = assign_temp (TREE_TYPE (arg), 0, 1, 1);
2441       op2 = assign_temp (TREE_TYPE (arg), 0, 1, 1);
2442       op1a = copy_to_mode_reg (Pmode, XEXP (op1, 0));
2443       op2a = copy_to_mode_reg (Pmode, XEXP (op2, 0));
2444       top1 = make_tree (build_pointer_type (TREE_TYPE (arg)), op1a);
2445       top2 = make_tree (build_pointer_type (TREE_TYPE (arg)), op2a);
2446
2447       /* Make sure not to fold the sincos call again.  */
2448       call = build1 (ADDR_EXPR, build_pointer_type (TREE_TYPE (fn)), fn);
2449       expand_normal (build_call_nary (TREE_TYPE (TREE_TYPE (fn)),
2450                                       call, 3, arg, top1, top2));
2451     }
2452   else
2453     {
2454       tree call, fn = NULL_TREE, narg;
2455       tree ctype = build_complex_type (type);
2456
2457       if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPIF)
2458         fn = built_in_decls[BUILT_IN_CEXPF];
2459       else if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPI)
2460         fn = built_in_decls[BUILT_IN_CEXP];
2461       else if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPIL)
2462         fn = built_in_decls[BUILT_IN_CEXPL];
2463       else
2464         gcc_unreachable ();
2465
2466       /* If we don't have a decl for cexp create one.  This is the
2467          friendliest fallback if the user calls __builtin_cexpi
2468          without full target C99 function support.  */
2469       if (fn == NULL_TREE)
2470         {
2471           tree fntype;
2472           const char *name = NULL;
2473
2474           if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPIF)
2475             name = "cexpf";
2476           else if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPI)
2477             name = "cexp";
2478           else if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPIL)
2479             name = "cexpl";
2480
2481           fntype = build_function_type_list (ctype, ctype, NULL_TREE);
2482           fn = build_fn_decl (name, fntype);
2483         }
2484
2485       narg = fold_build2_loc (loc, COMPLEX_EXPR, ctype,
2486                           build_real (type, dconst0), arg);
2487
2488       /* Make sure not to fold the cexp call again.  */
2489       call = build1 (ADDR_EXPR, build_pointer_type (TREE_TYPE (fn)), fn);
2490       return expand_expr (build_call_nary (ctype, call, 1, narg), 
2491                           target, VOIDmode, EXPAND_NORMAL);
2492     }
2493
2494   /* Now build the proper return type.  */
2495   return expand_expr (build2 (COMPLEX_EXPR, build_complex_type (type),
2496                               make_tree (TREE_TYPE (arg), op2),
2497                               make_tree (TREE_TYPE (arg), op1)),
2498                       target, VOIDmode, EXPAND_NORMAL);
2499 }
2500
2501 /* Conveniently construct a function call expression.  FNDECL names the
2502    function to be called, N is the number of arguments, and the "..."
2503    parameters are the argument expressions.  Unlike build_call_exr
2504    this doesn't fold the call, hence it will always return a CALL_EXPR.  */
2505
2506 static tree
2507 build_call_nofold_loc (location_t loc, tree fndecl, int n, ...)
2508 {
2509   va_list ap;
2510   tree fntype = TREE_TYPE (fndecl);
2511   tree fn = build1 (ADDR_EXPR, build_pointer_type (fntype), fndecl);
2512
2513   va_start (ap, n);
2514   fn = build_call_valist (TREE_TYPE (fntype), fn, n, ap);
2515   va_end (ap);
2516   SET_EXPR_LOCATION (fn, loc);
2517   return fn;
2518 }
2519 #define build_call_nofold(...) \
2520   build_call_nofold_loc (UNKNOWN_LOCATION, __VA_ARGS__)
2521
2522 /* Expand a call to one of the builtin rounding functions gcc defines
2523    as an extension (lfloor and lceil).  As these are gcc extensions we
2524    do not need to worry about setting errno to EDOM.
2525    If expanding via optab fails, lower expression to (int)(floor(x)).
2526    EXP is the expression that is a call to the builtin function;
2527    if convenient, the result should be placed in TARGET.  */
2528
2529 static rtx
2530 expand_builtin_int_roundingfn (tree exp, rtx target)
2531 {
2532   convert_optab builtin_optab;
2533   rtx op0, insns, tmp;
2534   tree fndecl = get_callee_fndecl (exp);
2535   enum built_in_function fallback_fn;
2536   tree fallback_fndecl;
2537   enum machine_mode mode;
2538   tree arg;
2539
2540   if (!validate_arglist (exp, REAL_TYPE, VOID_TYPE))
2541     gcc_unreachable ();
2542
2543   arg = CALL_EXPR_ARG (exp, 0);
2544
2545   switch (DECL_FUNCTION_CODE (fndecl))
2546     {
2547     CASE_FLT_FN (BUILT_IN_LCEIL):
2548     CASE_FLT_FN (BUILT_IN_LLCEIL):
2549       builtin_optab = lceil_optab;
2550       fallback_fn = BUILT_IN_CEIL;
2551       break;
2552
2553     CASE_FLT_FN (BUILT_IN_LFLOOR):
2554     CASE_FLT_FN (BUILT_IN_LLFLOOR):
2555       builtin_optab = lfloor_optab;
2556       fallback_fn = BUILT_IN_FLOOR;
2557       break;
2558
2559     default:
2560       gcc_unreachable ();
2561     }
2562
2563   /* Make a suitable register to place result in.  */
2564   mode = TYPE_MODE (TREE_TYPE (exp));
2565
2566   target = gen_reg_rtx (mode);
2567
2568   /* Wrap the computation of the argument in a SAVE_EXPR, as we may
2569      need to expand the argument again.  This way, we will not perform
2570      side-effects more the once.  */
2571   CALL_EXPR_ARG (exp, 0) = arg = builtin_save_expr (arg);
2572
2573   op0 = expand_expr (arg, NULL, VOIDmode, EXPAND_NORMAL);
2574
2575   start_sequence ();
2576
2577   /* Compute into TARGET.  */
2578   if (expand_sfix_optab (target, op0, builtin_optab))
2579     {
2580       /* Output the entire sequence.  */
2581       insns = get_insns ();
2582       end_sequence ();
2583       emit_insn (insns);
2584       return target;
2585     }
2586
2587   /* If we were unable to expand via the builtin, stop the sequence
2588      (without outputting the insns).  */
2589   end_sequence ();
2590
2591   /* Fall back to floating point rounding optab.  */
2592   fallback_fndecl = mathfn_built_in (TREE_TYPE (arg), fallback_fn);
2593
2594   /* For non-C99 targets we may end up without a fallback fndecl here
2595      if the user called __builtin_lfloor directly.  In this case emit
2596      a call to the floor/ceil variants nevertheless.  This should result
2597      in the best user experience for not full C99 targets.  */
2598   if (fallback_fndecl == NULL_TREE)
2599     {
2600       tree fntype;
2601       const char *name = NULL;
2602
2603       switch (DECL_FUNCTION_CODE (fndecl))
2604         {
2605         case BUILT_IN_LCEIL:
2606         case BUILT_IN_LLCEIL:
2607           name = "ceil";
2608           break;
2609         case BUILT_IN_LCEILF:
2610         case BUILT_IN_LLCEILF:
2611           name = "ceilf";
2612           break;
2613         case BUILT_IN_LCEILL:
2614         case BUILT_IN_LLCEILL:
2615           name = "ceill";
2616           break;
2617         case BUILT_IN_LFLOOR:
2618         case BUILT_IN_LLFLOOR:
2619           name = "floor";
2620           break;
2621         case BUILT_IN_LFLOORF:
2622         case BUILT_IN_LLFLOORF:
2623           name = "floorf";
2624           break;
2625         case BUILT_IN_LFLOORL:
2626         case BUILT_IN_LLFLOORL:
2627           name = "floorl";
2628           break;
2629         default:
2630           gcc_unreachable ();
2631         }
2632
2633       fntype = build_function_type_list (TREE_TYPE (arg),
2634                                          TREE_TYPE (arg), NULL_TREE);
2635       fallback_fndecl = build_fn_decl (name, fntype);
2636     }
2637
2638   exp = build_call_nofold (fallback_fndecl, 1, arg);
2639
2640   tmp = expand_normal (exp);
2641
2642   /* Truncate the result of floating point optab to integer
2643      via expand_fix ().  */
2644   target = gen_reg_rtx (mode);
2645   expand_fix (target, tmp, 0);
2646
2647   return target;
2648 }
2649
2650 /* Expand a call to one of the builtin math functions doing integer
2651    conversion (lrint).
2652    Return 0 if a normal call should be emitted rather than expanding the
2653    function in-line.  EXP is the expression that is a call to the builtin
2654    function; if convenient, the result should be placed in TARGET.  */
2655
2656 static rtx
2657 expand_builtin_int_roundingfn_2 (tree exp, rtx target)
2658 {
2659   convert_optab builtin_optab;
2660   rtx op0, insns;
2661   tree fndecl = get_callee_fndecl (exp);
2662   tree arg;
2663   enum machine_mode mode;
2664
2665   /* There's no easy way to detect the case we need to set EDOM.  */
2666   if (flag_errno_math)
2667     return NULL_RTX;
2668
2669   if (!validate_arglist (exp, REAL_TYPE, VOID_TYPE))
2670      gcc_unreachable ();
2671  
2672   arg = CALL_EXPR_ARG (exp, 0);
2673
2674   switch (DECL_FUNCTION_CODE (fndecl))
2675     {
2676     CASE_FLT_FN (BUILT_IN_LRINT):
2677     CASE_FLT_FN (BUILT_IN_LLRINT):
2678       builtin_optab = lrint_optab; break;
2679     CASE_FLT_FN (BUILT_IN_LROUND):
2680     CASE_FLT_FN (BUILT_IN_LLROUND):
2681       builtin_optab = lround_optab; break;
2682     default:
2683       gcc_unreachable ();
2684     }
2685
2686   /* Make a suitable register to place result in.  */
2687   mode = TYPE_MODE (TREE_TYPE (exp));
2688
2689   target = gen_reg_rtx (mode);
2690
2691   /* Wrap the computation of the argument in a SAVE_EXPR, as we may
2692      need to expand the argument again.  This way, we will not perform
2693      side-effects more the once.  */
2694   CALL_EXPR_ARG (exp, 0) = arg = builtin_save_expr (arg);
2695
2696   op0 = expand_expr (arg, NULL, VOIDmode, EXPAND_NORMAL);
2697
2698   start_sequence ();
2699
2700   if (expand_sfix_optab (target, op0, builtin_optab))
2701     {
2702       /* Output the entire sequence.  */
2703       insns = get_insns ();
2704       end_sequence ();
2705       emit_insn (insns);
2706       return target;
2707     }
2708
2709   /* If we were unable to expand via the builtin, stop the sequence
2710      (without outputting the insns) and call to the library function
2711      with the stabilized argument list.  */
2712   end_sequence ();
2713
2714   target = expand_call (exp, target, target == const0_rtx);
2715
2716   return target;
2717 }
2718
2719 /* To evaluate powi(x,n), the floating point value x raised to the
2720    constant integer exponent n, we use a hybrid algorithm that
2721    combines the "window method" with look-up tables.  For an
2722    introduction to exponentiation algorithms and "addition chains",
2723    see section 4.6.3, "Evaluation of Powers" of Donald E. Knuth,
2724    "Seminumerical Algorithms", Vol. 2, "The Art of Computer Programming",
2725    3rd Edition, 1998, and Daniel M. Gordon, "A Survey of Fast Exponentiation
2726    Methods", Journal of Algorithms, Vol. 27, pp. 129-146, 1998.  */
2727
2728 /* Provide a default value for POWI_MAX_MULTS, the maximum number of
2729    multiplications to inline before calling the system library's pow
2730    function.  powi(x,n) requires at worst 2*bits(n)-2 multiplications,
2731    so this default never requires calling pow, powf or powl.  */
2732
2733 #ifndef POWI_MAX_MULTS
2734 #define POWI_MAX_MULTS  (2*HOST_BITS_PER_WIDE_INT-2)
2735 #endif
2736
2737 /* The size of the "optimal power tree" lookup table.  All
2738    exponents less than this value are simply looked up in the
2739    powi_table below.  This threshold is also used to size the
2740    cache of pseudo registers that hold intermediate results.  */
2741 #define POWI_TABLE_SIZE 256
2742
2743 /* The size, in bits of the window, used in the "window method"
2744    exponentiation algorithm.  This is equivalent to a radix of
2745    (1<<POWI_WINDOW_SIZE) in the corresponding "m-ary method".  */
2746 #define POWI_WINDOW_SIZE 3
2747
2748 /* The following table is an efficient representation of an
2749    "optimal power tree".  For each value, i, the corresponding
2750    value, j, in the table states than an optimal evaluation
2751    sequence for calculating pow(x,i) can be found by evaluating
2752    pow(x,j)*pow(x,i-j).  An optimal power tree for the first
2753    100 integers is given in Knuth's "Seminumerical algorithms".  */
2754
2755 static const unsigned char powi_table[POWI_TABLE_SIZE] =
2756   {
2757       0,   1,   1,   2,   2,   3,   3,   4,  /*   0 -   7 */
2758       4,   6,   5,   6,   6,  10,   7,   9,  /*   8 -  15 */
2759       8,  16,   9,  16,  10,  12,  11,  13,  /*  16 -  23 */
2760      12,  17,  13,  18,  14,  24,  15,  26,  /*  24 -  31 */
2761      16,  17,  17,  19,  18,  33,  19,  26,  /*  32 -  39 */
2762      20,  25,  21,  40,  22,  27,  23,  44,  /*  40 -  47 */
2763      24,  32,  25,  34,  26,  29,  27,  44,  /*  48 -  55 */
2764      28,  31,  29,  34,  30,  60,  31,  36,  /*  56 -  63 */
2765      32,  64,  33,  34,  34,  46,  35,  37,  /*  64 -  71 */
2766      36,  65,  37,  50,  38,  48,  39,  69,  /*  72 -  79 */
2767      40,  49,  41,  43,  42,  51,  43,  58,  /*  80 -  87 */
2768      44,  64,  45,  47,  46,  59,  47,  76,  /*  88 -  95 */
2769      48,  65,  49,  66,  50,  67,  51,  66,  /*  96 - 103 */
2770      52,  70,  53,  74,  54, 104,  55,  74,  /* 104 - 111 */
2771      56,  64,  57,  69,  58,  78,  59,  68,  /* 112 - 119 */
2772      60,  61,  61,  80,  62,  75,  63,  68,  /* 120 - 127 */
2773      64,  65,  65, 128,  66, 129,  67,  90,  /* 128 - 135 */
2774      68,  73,  69, 131,  70,  94,  71,  88,  /* 136 - 143 */
2775      72, 128,  73,  98,  74, 132,  75, 121,  /* 144 - 151 */
2776      76, 102,  77, 124,  78, 132,  79, 106,  /* 152 - 159 */
2777      80,  97,  81, 160,  82,  99,  83, 134,  /* 160 - 167 */
2778      84,  86,  85,  95,  86, 160,  87, 100,  /* 168 - 175 */
2779      88, 113,  89,  98,  90, 107,  91, 122,  /* 176 - 183 */
2780      92, 111,  93, 102,  94, 126,  95, 150,  /* 184 - 191 */
2781      96, 128,  97, 130,  98, 133,  99, 195,  /* 192 - 199 */
2782     100, 128, 101, 123, 102, 164, 103, 138,  /* 200 - 207 */
2783     104, 145, 105, 146, 106, 109, 107, 149,  /* 208 - 215 */
2784     108, 200, 109, 146, 110, 170, 111, 157,  /* 216 - 223 */
2785     112, 128, 113, 130, 114, 182, 115, 132,  /* 224 - 231 */
2786     116, 200, 117, 132, 118, 158, 119, 206,  /* 232 - 239 */
2787     120, 240, 121, 162, 122, 147, 123, 152,  /* 240 - 247 */
2788     124, 166, 125, 214, 126, 138, 127, 153,  /* 248 - 255 */
2789   };
2790
2791
2792 /* Return the number of multiplications required to calculate
2793    powi(x,n) where n is less than POWI_TABLE_SIZE.  This is a
2794    subroutine of powi_cost.  CACHE is an array indicating
2795    which exponents have already been calculated.  */
2796
2797 static int
2798 powi_lookup_cost (unsigned HOST_WIDE_INT n, bool *cache)
2799 {
2800   /* If we've already calculated this exponent, then this evaluation
2801      doesn't require any additional multiplications.  */
2802   if (cache[n])
2803     return 0;
2804
2805   cache[n] = true;
2806   return powi_lookup_cost (n - powi_table[n], cache)
2807          + powi_lookup_cost (powi_table[n], cache) + 1;
2808 }
2809
2810 /* Return the number of multiplications required to calculate
2811    powi(x,n) for an arbitrary x, given the exponent N.  This
2812    function needs to be kept in sync with expand_powi below.  */
2813
2814 static int
2815 powi_cost (HOST_WIDE_INT n)
2816 {
2817   bool cache[POWI_TABLE_SIZE];
2818   unsigned HOST_WIDE_INT digit;
2819   unsigned HOST_WIDE_INT val;
2820   int result;
2821
2822   if (n == 0)
2823     return 0;
2824
2825   /* Ignore the reciprocal when calculating the cost.  */
2826   val = (n < 0) ? -n : n;
2827
2828   /* Initialize the exponent cache.  */
2829   memset (cache, 0, POWI_TABLE_SIZE * sizeof (bool));
2830   cache[1] = true;
2831
2832   result = 0;
2833
2834   while (val >= POWI_TABLE_SIZE)
2835     {
2836       if (val & 1)
2837         {
2838           digit = val & ((1 << POWI_WINDOW_SIZE) - 1);
2839           result += powi_lookup_cost (digit, cache)
2840                     + POWI_WINDOW_SIZE + 1;
2841           val >>= POWI_WINDOW_SIZE;
2842         }
2843       else
2844         {
2845           val >>= 1;
2846           result++;
2847         }
2848     }
2849
2850   return result + powi_lookup_cost (val, cache);
2851 }
2852
2853 /* Recursive subroutine of expand_powi.  This function takes the array,
2854    CACHE, of already calculated exponents and an exponent N and returns
2855    an RTX that corresponds to CACHE[1]**N, as calculated in mode MODE.  */
2856
2857 static rtx
2858 expand_powi_1 (enum machine_mode mode, unsigned HOST_WIDE_INT n, rtx *cache)
2859 {
2860   unsigned HOST_WIDE_INT digit;
2861   rtx target, result;
2862   rtx op0, op1;
2863
2864   if (n < POWI_TABLE_SIZE)
2865     {
2866       if (cache[n])
2867         return cache[n];
2868
2869       target = gen_reg_rtx (mode);
2870       cache[n] = target;
2871
2872       op0 = expand_powi_1 (mode, n - powi_table[n], cache);
2873       op1 = expand_powi_1 (mode, powi_table[n], cache);
2874     }
2875   else if (n & 1)
2876     {
2877       target = gen_reg_rtx (mode);
2878       digit = n & ((1 << POWI_WINDOW_SIZE) - 1);
2879       op0 = expand_powi_1 (mode, n - digit, cache);
2880       op1 = expand_powi_1 (mode, digit, cache);
2881     }
2882   else
2883     {
2884       target = gen_reg_rtx (mode);
2885       op0 = expand_powi_1 (mode, n >> 1, cache);
2886       op1 = op0;
2887     }
2888
2889   result = expand_mult (mode, op0, op1, target, 0);
2890   if (result != target)
2891     emit_move_insn (target, result);
2892   return target;
2893 }
2894
2895 /* Expand the RTL to evaluate powi(x,n) in mode MODE.  X is the
2896    floating point operand in mode MODE, and N is the exponent.  This
2897    function needs to be kept in sync with powi_cost above.  */
2898
2899 static rtx
2900 expand_powi (rtx x, enum machine_mode mode, HOST_WIDE_INT n)
2901 {
2902   rtx cache[POWI_TABLE_SIZE];
2903   rtx result;
2904
2905   if (n == 0)
2906     return CONST1_RTX (mode);
2907
2908   memset (cache, 0, sizeof (cache));
2909   cache[1] = x;
2910
2911   result = expand_powi_1 (mode, (n < 0) ? -n : n, cache);
2912
2913   /* If the original exponent was negative, reciprocate the result.  */
2914   if (n < 0)
2915     result = expand_binop (mode, sdiv_optab, CONST1_RTX (mode),
2916                            result, NULL_RTX, 0, OPTAB_LIB_WIDEN);
2917
2918   return result;
2919 }
2920
2921 /* Expand a call to the pow built-in mathematical function.  Return NULL_RTX if
2922    a normal call should be emitted rather than expanding the function
2923    in-line.  EXP is the expression that is a call to the builtin
2924    function; if convenient, the result should be placed in TARGET.  */
2925
2926 static rtx
2927 expand_builtin_pow (tree exp, rtx target, rtx subtarget)
2928 {
2929   tree arg0, arg1;
2930   tree fn, narg0;
2931   tree type = TREE_TYPE (exp);
2932   REAL_VALUE_TYPE cint, c, c2;
2933   HOST_WIDE_INT n;
2934   rtx op, op2;
2935   enum machine_mode mode = TYPE_MODE (type);
2936
2937   if (! validate_arglist (exp, REAL_TYPE, REAL_TYPE, VOID_TYPE))
2938     return NULL_RTX;
2939
2940   arg0 = CALL_EXPR_ARG (exp, 0);
2941   arg1 = CALL_EXPR_ARG (exp, 1);
2942
2943   if (TREE_CODE (arg1) != REAL_CST
2944       || TREE_OVERFLOW (arg1))
2945     return expand_builtin_mathfn_2 (exp, target, subtarget);
2946
2947   /* Handle constant exponents.  */
2948
2949   /* For integer valued exponents we can expand to an optimal multiplication
2950      sequence using expand_powi.  */
2951   c = TREE_REAL_CST (arg1);
2952   n = real_to_integer (&c);
2953   real_from_integer (&cint, VOIDmode, n, n < 0 ? -1 : 0, 0);
2954   if (real_identical (&c, &cint)
2955       && ((n >= -1 && n <= 2)
2956           || (flag_unsafe_math_optimizations
2957               && optimize_insn_for_speed_p ()
2958               && powi_cost (n) <= POWI_MAX_MULTS)))
2959     {
2960       op = expand_expr (arg0, subtarget, VOIDmode, EXPAND_NORMAL);
2961       if (n != 1)
2962         {
2963           op = force_reg (mode, op);
2964           op = expand_powi (op, mode, n);
2965         }
2966       return op;
2967     }
2968
2969   narg0 = builtin_save_expr (arg0);
2970
2971   /* If the exponent is not integer valued, check if it is half of an integer.
2972      In this case we can expand to sqrt (x) * x**(n/2).  */
2973   fn = mathfn_built_in (type, BUILT_IN_SQRT);
2974   if (fn != NULL_TREE)
2975     {
2976       real_arithmetic (&c2, MULT_EXPR, &c, &dconst2);
2977       n = real_to_integer (&c2);
2978       real_from_integer (&cint, VOIDmode, n, n < 0 ? -1 : 0, 0);
2979       if (real_identical (&c2, &cint)
2980           && ((flag_unsafe_math_optimizations
2981                && optimize_insn_for_speed_p ()
2982                && powi_cost (n/2) <= POWI_MAX_MULTS)
2983               || n == 1))
2984         {
2985           tree call_expr = build_call_nofold (fn, 1, narg0);
2986           /* Use expand_expr in case the newly built call expression
2987              was folded to a non-call.  */
2988           op = expand_expr (call_expr, subtarget, mode, EXPAND_NORMAL);
2989           if (n != 1)
2990             {
2991               op2 = expand_expr (narg0, subtarget, VOIDmode, EXPAND_NORMAL);
2992               op2 = force_reg (mode, op2);
2993               op2 = expand_powi (op2, mode, abs (n / 2));
2994               op = expand_simple_binop (mode, MULT, op, op2, NULL_RTX,
2995                                         0, OPTAB_LIB_WIDEN);
2996               /* If the original exponent was negative, reciprocate the
2997                  result.  */
2998               if (n < 0)
2999                 op = expand_binop (mode, sdiv_optab, CONST1_RTX (mode),
3000                                    op, NULL_RTX, 0, OPTAB_LIB_WIDEN);
3001             }
3002           return op;
3003         }
3004     }
3005
3006   /* Try if the exponent is a third of an integer.  In this case
3007      we can expand to x**(n/3) * cbrt(x)**(n%3).  As cbrt (x) is
3008      different from pow (x, 1./3.) due to rounding and behavior
3009      with negative x we need to constrain this transformation to
3010      unsafe math and positive x or finite math.  */
3011   fn = mathfn_built_in (type, BUILT_IN_CBRT);
3012   if (fn != NULL_TREE
3013       && flag_unsafe_math_optimizations
3014       && (tree_expr_nonnegative_p (arg0)
3015           || !HONOR_NANS (mode)))
3016     {
3017       REAL_VALUE_TYPE dconst3;
3018       real_from_integer (&dconst3, VOIDmode, 3, 0, 0);
3019       real_arithmetic (&c2, MULT_EXPR, &c, &dconst3);
3020       real_round (&c2, mode, &c2);
3021       n = real_to_integer (&c2);
3022       real_from_integer (&cint, VOIDmode, n, n < 0 ? -1 : 0, 0);
3023       real_arithmetic (&c2, RDIV_EXPR, &cint, &dconst3);
3024       real_convert (&c2, mode, &c2);
3025       if (real_identical (&c2, &c)
3026           && ((optimize_insn_for_speed_p ()
3027                && powi_cost (n/3) <= POWI_MAX_MULTS)
3028               || n == 1))
3029         {
3030           tree call_expr = build_call_nofold (fn, 1,narg0);
3031           op = expand_builtin (call_expr, NULL_RTX, subtarget, mode, 0);
3032           if (abs (n) % 3 == 2)
3033             op = expand_simple_binop (mode, MULT, op, op, op,
3034                                       0, OPTAB_LIB_WIDEN);
3035           if (n != 1)
3036             {
3037               op2 = expand_expr (narg0, subtarget, VOIDmode, EXPAND_NORMAL);
3038               op2 = force_reg (mode, op2);
3039               op2 = expand_powi (op2, mode, abs (n / 3));
3040               op = expand_simple_binop (mode, MULT, op, op2, NULL_RTX,
3041                                         0, OPTAB_LIB_WIDEN);
3042               /* If the original exponent was negative, reciprocate the
3043                  result.  */
3044               if (n < 0)
3045                 op = expand_binop (mode, sdiv_optab, CONST1_RTX (mode),
3046                                    op, NULL_RTX, 0, OPTAB_LIB_WIDEN);
3047             }
3048           return op;
3049         }
3050     }
3051
3052   /* Fall back to optab expansion.  */
3053   return expand_builtin_mathfn_2 (exp, target, subtarget);
3054 }
3055
3056 /* Expand a call to the powi built-in mathematical function.  Return NULL_RTX if
3057    a normal call should be emitted rather than expanding the function
3058    in-line.  EXP is the expression that is a call to the builtin
3059    function; if convenient, the result should be placed in TARGET.  */
3060
3061 static rtx
3062 expand_builtin_powi (tree exp, rtx target, rtx subtarget)
3063 {
3064   tree arg0, arg1;
3065   rtx op0, op1;
3066   enum machine_mode mode;
3067   enum machine_mode mode2;
3068
3069   if (! validate_arglist (exp, REAL_TYPE, INTEGER_TYPE, VOID_TYPE))
3070     return NULL_RTX;
3071
3072   arg0 = CALL_EXPR_ARG (exp, 0);
3073   arg1 = CALL_EXPR_ARG (exp, 1);
3074   mode = TYPE_MODE (TREE_TYPE (exp));
3075
3076   /* Handle constant power.  */
3077
3078   if (TREE_CODE (arg1) == INTEGER_CST
3079       && !TREE_OVERFLOW (arg1))
3080     {
3081       HOST_WIDE_INT n = TREE_INT_CST_LOW (arg1);
3082
3083       /* If the exponent is -1, 0, 1 or 2, then expand_powi is exact.
3084          Otherwise, check the number of multiplications required.  */
3085       if ((TREE_INT_CST_HIGH (arg1) == 0
3086            || TREE_INT_CST_HIGH (arg1) == -1)
3087           && ((n >= -1 && n <= 2)
3088               || (optimize_insn_for_speed_p ()
3089                   && powi_cost (n) <= POWI_MAX_MULTS)))
3090         {
3091           op0 = expand_expr (arg0, subtarget, VOIDmode, EXPAND_NORMAL);
3092           op0 = force_reg (mode, op0);
3093           return expand_powi (op0, mode, n);
3094         }
3095     }
3096
3097   /* Emit a libcall to libgcc.  */
3098
3099   /* Mode of the 2nd argument must match that of an int.  */
3100   mode2 = mode_for_size (INT_TYPE_SIZE, MODE_INT, 0);
3101
3102   if (target == NULL_RTX)
3103     target = gen_reg_rtx (mode);
3104
3105   op0 = expand_expr (arg0, subtarget, mode, EXPAND_NORMAL);
3106   if (GET_MODE (op0) != mode)
3107     op0 = convert_to_mode (mode, op0, 0);
3108   op1 = expand_expr (arg1, NULL_RTX, mode2, EXPAND_NORMAL);
3109   if (GET_MODE (op1) != mode2)
3110     op1 = convert_to_mode (mode2, op1, 0);
3111
3112   target = emit_library_call_value (optab_libfunc (powi_optab, mode),
3113                                     target, LCT_CONST, mode, 2,
3114                                     op0, mode, op1, mode2);
3115
3116   return target;
3117 }
3118
3119 /* Expand expression EXP which is a call to the strlen builtin.  Return 
3120    NULL_RTX if we failed the caller should emit a normal call, otherwise
3121    try to get the result in TARGET, if convenient.  */
3122
3123 static rtx
3124 expand_builtin_strlen (tree exp, rtx target,
3125                        enum machine_mode target_mode)
3126 {
3127   if (!validate_arglist (exp, POINTER_TYPE, VOID_TYPE))
3128     return NULL_RTX;
3129   else
3130     {
3131       rtx pat;
3132       tree len;
3133       tree src = CALL_EXPR_ARG (exp, 0);
3134       rtx result, src_reg, char_rtx, before_strlen;
3135       enum machine_mode insn_mode = target_mode, char_mode;
3136       enum insn_code icode = CODE_FOR_nothing;
3137       int align;
3138
3139       /* If the length can be computed at compile-time, return it.  */
3140       len = c_strlen (src, 0);
3141       if (len)
3142         return expand_expr (len, target, target_mode, EXPAND_NORMAL);
3143
3144       /* If the length can be computed at compile-time and is constant
3145          integer, but there are side-effects in src, evaluate
3146          src for side-effects, then return len.
3147          E.g. x = strlen (i++ ? "xfoo" + 1 : "bar");
3148          can be optimized into: i++; x = 3;  */
3149       len = c_strlen (src, 1);
3150       if (len && TREE_CODE (len) == INTEGER_CST)
3151         {
3152           expand_expr (src, const0_rtx, VOIDmode, EXPAND_NORMAL);
3153           return expand_expr (len, target, target_mode, EXPAND_NORMAL);
3154         }
3155
3156       align = get_pointer_alignment (src, BIGGEST_ALIGNMENT) / BITS_PER_UNIT;
3157
3158       /* If SRC is not a pointer type, don't do this operation inline.  */
3159       if (align == 0)
3160         return NULL_RTX;
3161
3162       /* Bail out if we can't compute strlen in the right mode.  */
3163       while (insn_mode != VOIDmode)
3164         {
3165           icode = optab_handler (strlen_optab, insn_mode)->insn_code;
3166           if (icode != CODE_FOR_nothing)
3167             break;
3168
3169           insn_mode = GET_MODE_WIDER_MODE (insn_mode);
3170         }
3171       if (insn_mode == VOIDmode)
3172         return NULL_RTX;
3173
3174       /* Make a place to write the result of the instruction.  */
3175       result = target;
3176       if (! (result != 0
3177              && REG_P (result)
3178              && GET_MODE (result) == insn_mode
3179              && REGNO (result) >= FIRST_PSEUDO_REGISTER))
3180         result = gen_reg_rtx (insn_mode);
3181
3182       /* Make a place to hold the source address.  We will not expand
3183          the actual source until we are sure that the expansion will
3184          not fail -- there are trees that cannot be expanded twice.  */
3185       src_reg = gen_reg_rtx (Pmode);
3186
3187       /* Mark the beginning of the strlen sequence so we can emit the
3188          source operand later.  */
3189       before_strlen = get_last_insn ();
3190
3191       char_rtx = const0_rtx;
3192       char_mode = insn_data[(int) icode].operand[2].mode;
3193       if (! (*insn_data[(int) icode].operand[2].predicate) (char_rtx,
3194                                                             char_mode))
3195         char_rtx = copy_to_mode_reg (char_mode, char_rtx);
3196
3197       pat = GEN_FCN (icode) (result, gen_rtx_MEM (BLKmode, src_reg),
3198                              char_rtx, GEN_INT (align));
3199       if (! pat)
3200         return NULL_RTX;
3201       emit_insn (pat);
3202
3203       /* Now that we are assured of success, expand the source.  */
3204       start_sequence ();
3205       pat = expand_expr (src, src_reg, ptr_mode, EXPAND_NORMAL);
3206       if (pat != src_reg)
3207         emit_move_insn (src_reg, pat);
3208       pat = get_insns ();
3209       end_sequence ();
3210
3211       if (before_strlen)
3212         emit_insn_after (pat, before_strlen);
3213       else
3214         emit_insn_before (pat, get_insns ());
3215
3216       /* Return the value in the proper mode for this function.  */
3217       if (GET_MODE (result) == target_mode)
3218         target = result;
3219       else if (target != 0)
3220         convert_move (target, result, 0);
3221       else
3222         target = convert_to_mode (target_mode, result, 0);
3223
3224       return target;
3225     }
3226 }
3227
3228 /* Callback routine for store_by_pieces.  Read GET_MODE_BITSIZE (MODE)
3229    bytes from constant string DATA + OFFSET and return it as target
3230    constant.  */
3231
3232 static rtx
3233 builtin_memcpy_read_str (void *data, HOST_WIDE_INT offset,
3234                          enum machine_mode mode)
3235 {
3236   const char *str = (const char *) data;
3237
3238   gcc_assert (offset >= 0
3239               && ((unsigned HOST_WIDE_INT) offset + GET_MODE_SIZE (mode)
3240                   <= strlen (str) + 1));
3241
3242   return c_readstr (str + offset, mode);
3243 }
3244
3245 /* Expand a call EXP to the memcpy builtin.
3246    Return NULL_RTX if we failed, the caller should emit a normal call,
3247    otherwise try to get the result in TARGET, if convenient (and in
3248    mode MODE if that's convenient).  */
3249
3250 static rtx
3251 expand_builtin_memcpy (tree exp, rtx target)
3252 {
3253   if (!validate_arglist (exp,
3254                          POINTER_TYPE, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
3255     return NULL_RTX;
3256   else
3257     {
3258       tree dest = CALL_EXPR_ARG (exp, 0);
3259       tree src = CALL_EXPR_ARG (exp, 1);
3260       tree len = CALL_EXPR_ARG (exp, 2);
3261       const char *src_str;
3262       unsigned int src_align = get_pointer_alignment (src, BIGGEST_ALIGNMENT);
3263       unsigned int dest_align
3264         = get_pointer_alignment (dest, BIGGEST_ALIGNMENT);
3265       rtx dest_mem, src_mem, dest_addr, len_rtx;
3266       HOST_WIDE_INT expected_size = -1;
3267       unsigned int expected_align = 0;
3268       tree_ann_common_t ann;
3269
3270       /* If DEST is not a pointer type, call the normal function.  */
3271       if (dest_align == 0)
3272         return NULL_RTX;
3273
3274       /* If either SRC is not a pointer type, don't do this
3275          operation in-line.  */
3276       if (src_align == 0)
3277         return NULL_RTX;
3278  
3279       ann = tree_common_ann (exp);
3280       if (ann)
3281         stringop_block_profile (ann->stmt, &expected_align, &expected_size);
3282
3283       if (expected_align < dest_align)
3284         expected_align = dest_align;
3285       dest_mem = get_memory_rtx (dest, len);
3286       set_mem_align (dest_mem, dest_align);
3287       len_rtx = expand_normal (len);
3288       src_str = c_getstr (src);
3289
3290       /* If SRC is a string constant and block move would be done
3291          by pieces, we can avoid loading the string from memory
3292          and only stored the computed constants.  */
3293       if (src_str
3294           && CONST_INT_P (len_rtx)
3295           && (unsigned HOST_WIDE_INT) INTVAL (len_rtx) <= strlen (src_str) + 1
3296           && can_store_by_pieces (INTVAL (len_rtx), builtin_memcpy_read_str,
3297                                   CONST_CAST (char *, src_str),
3298                                   dest_align, false))
3299         {
3300           dest_mem = store_by_pieces (dest_mem, INTVAL (len_rtx),
3301                                       builtin_memcpy_read_str,
3302                                       CONST_CAST (char *, src_str),
3303                                       dest_align, false, 0);
3304           dest_mem = force_operand (XEXP (dest_mem, 0), target);
3305           dest_mem = convert_memory_address (ptr_mode, dest_mem);
3306           return dest_mem;
3307         }
3308
3309       src_mem = get_memory_rtx (src, len);
3310       set_mem_align (src_mem, src_align);
3311
3312       /* Copy word part most expediently.  */
3313       dest_addr = emit_block_move_hints (dest_mem, src_mem, len_rtx,
3314                                          CALL_EXPR_TAILCALL (exp)
3315                                          ? BLOCK_OP_TAILCALL : BLOCK_OP_NORMAL,
3316                                          expected_align, expected_size);
3317
3318       if (dest_addr == 0)
3319         {
3320           dest_addr = force_operand (XEXP (dest_mem, 0), target);
3321           dest_addr = convert_memory_address (ptr_mode, dest_addr);
3322         }
3323       return dest_addr;
3324     }
3325 }
3326
3327 /* Expand a call EXP to the mempcpy builtin.
3328    Return NULL_RTX if we failed; the caller should emit a normal call,
3329    otherwise try to get the result in TARGET, if convenient (and in
3330    mode MODE if that's convenient).  If ENDP is 0 return the
3331    destination pointer, if ENDP is 1 return the end pointer ala
3332    mempcpy, and if ENDP is 2 return the end pointer minus one ala
3333    stpcpy.  */
3334
3335 static rtx
3336 expand_builtin_mempcpy (tree exp, rtx target, enum machine_mode mode)
3337 {
3338   if (!validate_arglist (exp,
3339                          POINTER_TYPE, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
3340     return NULL_RTX;
3341   else
3342     {
3343       tree dest = CALL_EXPR_ARG (exp, 0);
3344       tree src = CALL_EXPR_ARG (exp, 1);
3345       tree len = CALL_EXPR_ARG (exp, 2);
3346       return expand_builtin_mempcpy_args (dest, src, len,
3347                                           target, mode, /*endp=*/ 1);
3348     }
3349 }
3350
3351 /* Helper function to do the actual work for expand_builtin_mempcpy.  The
3352    arguments to the builtin_mempcpy call DEST, SRC, and LEN are broken out
3353    so that this can also be called without constructing an actual CALL_EXPR.
3354    The other arguments and return value are the same as for
3355    expand_builtin_mempcpy.  */
3356
3357 static rtx
3358 expand_builtin_mempcpy_args (tree dest, tree src, tree len,
3359                              rtx target, enum machine_mode mode, int endp)
3360 {
3361     /* If return value is ignored, transform mempcpy into memcpy.  */
3362   if (target == const0_rtx && implicit_built_in_decls[BUILT_IN_MEMCPY])
3363     {
3364       tree fn = implicit_built_in_decls[BUILT_IN_MEMCPY];
3365       tree result = build_call_nofold (fn, 3, dest, src, len);
3366       return expand_expr (result, target, mode, EXPAND_NORMAL);
3367     }
3368   else
3369     {
3370       const char *src_str;
3371       unsigned int src_align = get_pointer_alignment (src, BIGGEST_ALIGNMENT);
3372       unsigned int dest_align
3373         = get_pointer_alignment (dest, BIGGEST_ALIGNMENT);
3374       rtx dest_mem, src_mem, len_rtx;
3375
3376       /* If either SRC or DEST is not a pointer type, don't do this
3377          operation in-line.  */
3378       if (dest_align == 0 || src_align == 0)
3379         return NULL_RTX;
3380
3381       /* If LEN is not constant, call the normal function.  */
3382       if (! host_integerp (len, 1))
3383         return NULL_RTX;
3384
3385       len_rtx = expand_normal (len);
3386       src_str = c_getstr (src);
3387
3388       /* If SRC is a string constant and block move would be done
3389          by pieces, we can avoid loading the string from memory
3390          and only stored the computed constants.  */
3391       if (src_str
3392           && CONST_INT_P (len_rtx)
3393           && (unsigned HOST_WIDE_INT) INTVAL (len_rtx) <= strlen (src_str) + 1
3394           && can_store_by_pieces (INTVAL (len_rtx), builtin_memcpy_read_str,
3395                                   CONST_CAST (char *, src_str),
3396                                   dest_align, false))
3397         {
3398           dest_mem = get_memory_rtx (dest, len);
3399           set_mem_align (dest_mem, dest_align);
3400           dest_mem = store_by_pieces (dest_mem, INTVAL (len_rtx),
3401                                       builtin_memcpy_read_str,
3402                                       CONST_CAST (char *, src_str),
3403                                       dest_align, false, endp);
3404           dest_mem = force_operand (XEXP (dest_mem, 0), NULL_RTX);
3405           dest_mem = convert_memory_address (ptr_mode, dest_mem);
3406           return dest_mem;
3407         }
3408
3409       if (CONST_INT_P (len_rtx)
3410           && can_move_by_pieces (INTVAL (len_rtx),
3411                                  MIN (dest_align, src_align)))
3412         {
3413           dest_mem = get_memory_rtx (dest, len);
3414           set_mem_align (dest_mem, dest_align);
3415           src_mem = get_memory_rtx (src, len);
3416           set_mem_align (src_mem, src_align);
3417           dest_mem = move_by_pieces (dest_mem, src_mem, INTVAL (len_rtx),
3418                                      MIN (dest_align, src_align), endp);
3419           dest_mem = force_operand (XEXP (dest_mem, 0), NULL_RTX);
3420           dest_mem = convert_memory_address (ptr_mode, dest_mem);
3421           return dest_mem;
3422         }
3423
3424       return NULL_RTX;
3425     }
3426 }
3427
3428 #ifndef HAVE_movstr
3429 # define HAVE_movstr 0
3430 # define CODE_FOR_movstr CODE_FOR_nothing
3431 #endif
3432
3433 /* Expand into a movstr instruction, if one is available.  Return NULL_RTX if
3434    we failed, the caller should emit a normal call, otherwise try to
3435    get the result in TARGET, if convenient.  If ENDP is 0 return the
3436    destination pointer, if ENDP is 1 return the end pointer ala
3437    mempcpy, and if ENDP is 2 return the end pointer minus one ala
3438    stpcpy.  */
3439
3440 static rtx
3441 expand_movstr (tree dest, tree src, rtx target, int endp)
3442 {
3443   rtx end;
3444   rtx dest_mem;
3445   rtx src_mem;
3446   rtx insn;
3447   const struct insn_data * data;
3448
3449   if (!HAVE_movstr)
3450     return NULL_RTX;
3451
3452   dest_mem = get_memory_rtx (dest, NULL);
3453   src_mem = get_memory_rtx (src, NULL);
3454   if (!endp)
3455     {
3456       target = force_reg (Pmode, XEXP (dest_mem, 0));
3457       dest_mem = replace_equiv_address (dest_mem, target);
3458       end = gen_reg_rtx (Pmode);
3459     }
3460   else
3461     {
3462       if (target == 0 || target == const0_rtx)
3463         {
3464           end = gen_reg_rtx (Pmode);
3465           if (target == 0)
3466             target = end;
3467         }
3468       else
3469         end = target;
3470     }
3471
3472   data = insn_data + CODE_FOR_movstr;
3473
3474   if (data->operand[0].mode != VOIDmode)
3475     end = gen_lowpart (data->operand[0].mode, end);
3476
3477   insn = data->genfun (end, dest_mem, src_mem);
3478
3479   gcc_assert (insn);
3480
3481   emit_insn (insn);
3482
3483   /* movstr is supposed to set end to the address of the NUL
3484      terminator.  If the caller requested a mempcpy-like return value,
3485      adjust it.  */
3486   if (endp == 1 && target != const0_rtx)
3487     {
3488       rtx tem = plus_constant (gen_lowpart (GET_MODE (target), end), 1);
3489       emit_move_insn (target, force_operand (tem, NULL_RTX));
3490     }
3491
3492   return target;
3493 }
3494
3495 /* Expand expression EXP, which is a call to the strcpy builtin.  Return 
3496    NULL_RTX if we failed the caller should emit a normal call, otherwise 
3497    try to get the result in TARGET, if convenient (and in mode MODE if that's
3498    convenient).  */
3499
3500 static rtx
3501 expand_builtin_strcpy (tree exp, rtx target)
3502 {
3503   if (validate_arglist (exp, POINTER_TYPE, POINTER_TYPE, VOID_TYPE))
3504    {
3505      tree dest = CALL_EXPR_ARG (exp, 0);
3506      tree src = CALL_EXPR_ARG (exp, 1);
3507      return expand_builtin_strcpy_args (dest, src, target);
3508    }
3509    return NULL_RTX;
3510 }
3511
3512 /* Helper function to do the actual work for expand_builtin_strcpy.  The
3513    arguments to the builtin_strcpy call DEST and SRC are broken out
3514    so that this can also be called without constructing an actual CALL_EXPR.
3515    The other arguments and return value are the same as for
3516    expand_builtin_strcpy.  */
3517
3518 static rtx
3519 expand_builtin_strcpy_args (tree dest, tree src, rtx target)
3520 {
3521   return expand_movstr (dest, src, target, /*endp=*/0);
3522 }
3523
3524 /* Expand a call EXP to the stpcpy builtin.
3525    Return NULL_RTX if we failed the caller should emit a normal call,
3526    otherwise try to get the result in TARGET, if convenient (and in
3527    mode MODE if that's convenient).  */
3528
3529 static rtx
3530 expand_builtin_stpcpy (tree exp, rtx target, enum machine_mode mode)
3531 {
3532   tree dst, src;
3533   location_t loc = EXPR_LOCATION (exp);
3534
3535   if (!validate_arglist (exp, POINTER_TYPE, POINTER_TYPE, VOID_TYPE))
3536     return NULL_RTX;
3537
3538   dst = CALL_EXPR_ARG (exp, 0);
3539   src = CALL_EXPR_ARG (exp, 1);
3540
3541   /* If return value is ignored, transform stpcpy into strcpy.  */
3542   if (target == const0_rtx && implicit_built_in_decls[BUILT_IN_STRCPY])
3543     {
3544       tree fn = implicit_built_in_decls[BUILT_IN_STRCPY];
3545       tree result = build_call_nofold (fn, 2, dst, src);
3546       return expand_expr (result, target, mode, EXPAND_NORMAL);
3547     }
3548   else
3549     {
3550       tree len, lenp1;
3551       rtx ret;
3552
3553       /* Ensure we get an actual string whose length can be evaluated at
3554          compile-time, not an expression containing a string.  This is
3555          because the latter will potentially produce pessimized code
3556          when used to produce the return value.  */
3557       if (! c_getstr (src) || ! (len = c_strlen (src, 0)))
3558         return expand_movstr (dst, src, target, /*endp=*/2);
3559
3560       lenp1 = size_binop_loc (loc, PLUS_EXPR, len, ssize_int (1));
3561       ret = expand_builtin_mempcpy_args (dst, src, lenp1,
3562                                          target, mode, /*endp=*/2);
3563
3564       if (ret)
3565         return ret;
3566
3567       if (TREE_CODE (len) == INTEGER_CST)
3568         {
3569           rtx len_rtx = expand_normal (len);
3570
3571           if (CONST_INT_P (len_rtx))
3572             {
3573               ret = expand_builtin_strcpy_args (dst, src, target);
3574
3575               if (ret)
3576                 {
3577                   if (! target)
3578                     {
3579                       if (mode != VOIDmode)
3580                         target = gen_reg_rtx (mode);
3581                       else
3582                         target = gen_reg_rtx (GET_MODE (ret));
3583                     }
3584                   if (GET_MODE (target) != GET_MODE (ret))
3585                     ret = gen_lowpart (GET_MODE (target), ret);
3586
3587                   ret = plus_constant (ret, INTVAL (len_rtx));
3588                   ret = emit_move_insn (target, force_operand (ret, NULL_RTX));
3589                   gcc_assert (ret);
3590
3591                   return target;
3592                 }
3593             }
3594         }
3595
3596       return expand_movstr (dst, src, target, /*endp=*/2);
3597     }
3598 }
3599
3600 /* Callback routine for store_by_pieces.  Read GET_MODE_BITSIZE (MODE)
3601    bytes from constant string DATA + OFFSET and return it as target
3602    constant.  */
3603
3604 rtx
3605 builtin_strncpy_read_str (void *data, HOST_WIDE_INT offset,
3606                           enum machine_mode mode)
3607 {
3608   const char *str = (const char *) data;
3609
3610   if ((unsigned HOST_WIDE_INT) offset > strlen (str))
3611     return const0_rtx;
3612
3613   return c_readstr (str + offset, mode);
3614 }
3615
3616 /* Expand expression EXP, which is a call to the strncpy builtin.  Return 
3617    NULL_RTX if we failed the caller should emit a normal call.  */
3618
3619 static rtx
3620 expand_builtin_strncpy (tree exp, rtx target)
3621 {
3622   location_t loc = EXPR_LOCATION (exp);
3623
3624   if (validate_arglist (exp,
3625                         POINTER_TYPE, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
3626     {
3627       tree dest = CALL_EXPR_ARG (exp, 0);
3628       tree src = CALL_EXPR_ARG (exp, 1);
3629       tree len = CALL_EXPR_ARG (exp, 2);
3630       tree slen = c_strlen (src, 1);
3631
3632       /* We must be passed a constant len and src parameter.  */
3633       if (!host_integerp (len, 1) || !slen || !host_integerp (slen, 1))
3634         return NULL_RTX;
3635
3636       slen = size_binop_loc (loc, PLUS_EXPR, slen, ssize_int (1));
3637
3638       /* We're required to pad with trailing zeros if the requested
3639          len is greater than strlen(s2)+1.  In that case try to
3640          use store_by_pieces, if it fails, punt.  */
3641       if (tree_int_cst_lt (slen, len))
3642         {
3643           unsigned int dest_align
3644             = get_pointer_alignment (dest, BIGGEST_ALIGNMENT);
3645           const char *p = c_getstr (src);
3646           rtx dest_mem;
3647
3648           if (!p || dest_align == 0 || !host_integerp (len, 1)
3649               || !can_store_by_pieces (tree_low_cst (len, 1),
3650                                        builtin_strncpy_read_str,
3651                                        CONST_CAST (char *, p),
3652                                        dest_align, false))
3653             return NULL_RTX;
3654
3655           dest_mem = get_memory_rtx (dest, len);
3656           store_by_pieces (dest_mem, tree_low_cst (len, 1),
3657                            builtin_strncpy_read_str,
3658                            CONST_CAST (char *, p), dest_align, false, 0);
3659           dest_mem = force_operand (XEXP (dest_mem, 0), target);
3660           dest_mem = convert_memory_address (ptr_mode, dest_mem);
3661           return dest_mem;
3662         }
3663     }
3664   return NULL_RTX;
3665 }
3666
3667 /* Callback routine for store_by_pieces.  Read GET_MODE_BITSIZE (MODE)
3668    bytes from constant string DATA + OFFSET and return it as target
3669    constant.  */
3670
3671 rtx
3672 builtin_memset_read_str (void *data, HOST_WIDE_INT offset ATTRIBUTE_UNUSED,
3673                          enum machine_mode mode)
3674 {
3675   const char *c = (const char *) data;
3676   char *p = XALLOCAVEC (char, GET_MODE_SIZE (mode));
3677
3678   memset (p, *c, GET_MODE_SIZE (mode));
3679
3680   return c_readstr (p, mode);
3681 }
3682
3683 /* Callback routine for store_by_pieces.  Return the RTL of a register
3684    containing GET_MODE_SIZE (MODE) consecutive copies of the unsigned
3685    char value given in the RTL register data.  For example, if mode is
3686    4 bytes wide, return the RTL for 0x01010101*data.  */
3687
3688 static rtx
3689 builtin_memset_gen_str (void *data, HOST_WIDE_INT offset ATTRIBUTE_UNUSED,
3690                         enum machine_mode mode)
3691 {
3692   rtx target, coeff;
3693   size_t size;
3694   char *p;
3695
3696   size = GET_MODE_SIZE (mode);
3697   if (size == 1)
3698     return (rtx) data;
3699
3700   p = XALLOCAVEC (char, size);
3701   memset (p, 1, size);
3702   coeff = c_readstr (p, mode);
3703
3704   target = convert_to_mode (mode, (rtx) data, 1);
3705   target = expand_mult (mode, target, coeff, NULL_RTX, 1);
3706   return force_reg (mode, target);
3707 }
3708
3709 /* Expand expression EXP, which is a call to the memset builtin.  Return 
3710    NULL_RTX if we failed the caller should emit a normal call, otherwise 
3711    try to get the result in TARGET, if convenient (and in mode MODE if that's
3712    convenient).  */
3713
3714 static rtx
3715 expand_builtin_memset (tree exp, rtx target, enum machine_mode mode)
3716 {
3717   if (!validate_arglist (exp,
3718                          POINTER_TYPE, INTEGER_TYPE, INTEGER_TYPE, VOID_TYPE))
3719     return NULL_RTX;
3720   else
3721     {
3722       tree dest = CALL_EXPR_ARG (exp, 0);
3723       tree val = CALL_EXPR_ARG (exp, 1);
3724       tree len = CALL_EXPR_ARG (exp, 2);
3725       return expand_builtin_memset_args (dest, val, len, target, mode, exp);
3726     }
3727 }
3728
3729 /* Helper function to do the actual work for expand_builtin_memset.  The
3730    arguments to the builtin_memset call DEST, VAL, and LEN are broken out
3731    so that this can also be called without constructing an actual CALL_EXPR.
3732    The other arguments and return value are the same as for
3733    expand_builtin_memset.  */
3734
3735 static rtx
3736 expand_builtin_memset_args (tree dest, tree val, tree len,
3737                             rtx target, enum machine_mode mode, tree orig_exp)
3738 {
3739   tree fndecl, fn;
3740   enum built_in_function fcode;
3741   char c;
3742   unsigned int dest_align;
3743   rtx dest_mem, dest_addr, len_rtx;
3744   HOST_WIDE_INT expected_size = -1;
3745   unsigned int expected_align = 0;
3746   tree_ann_common_t ann;
3747
3748   dest_align = get_pointer_alignment (dest, BIGGEST_ALIGNMENT);
3749
3750   /* If DEST is not a pointer type, don't do this operation in-line.  */
3751   if (dest_align == 0)
3752     return NULL_RTX;
3753
3754   ann = tree_common_ann (orig_exp);
3755   if (ann)
3756     stringop_block_profile (ann->stmt, &expected_align, &expected_size);
3757
3758   if (expected_align < dest_align)
3759     expected_align = dest_align;
3760
3761   /* If the LEN parameter is zero, return DEST.  */
3762   if (integer_zerop (len))
3763     {
3764       /* Evaluate and ignore VAL in case it has side-effects.  */
3765       expand_expr (val, const0_rtx, VOIDmode, EXPAND_NORMAL);
3766       return expand_expr (dest, target, mode, EXPAND_NORMAL);
3767     }
3768
3769   /* Stabilize the arguments in case we fail.  */
3770   dest = builtin_save_expr (dest);
3771   val = builtin_save_expr (val);
3772   len = builtin_save_expr (len);
3773
3774   len_rtx = expand_normal (len);
3775   dest_mem = get_memory_rtx (dest, len);
3776
3777   if (TREE_CODE (val) != INTEGER_CST)
3778     {
3779       rtx val_rtx;
3780
3781       val_rtx = expand_normal (val);
3782       val_rtx = convert_to_mode (TYPE_MODE (unsigned_char_type_node),
3783                                  val_rtx, 0);
3784
3785       /* Assume that we can memset by pieces if we can store
3786        * the coefficients by pieces (in the required modes).
3787        * We can't pass builtin_memset_gen_str as that emits RTL.  */
3788       c = 1;
3789       if (host_integerp (len, 1)
3790           && can_store_by_pieces (tree_low_cst (len, 1),
3791                                   builtin_memset_read_str, &c, dest_align,
3792                                   true))
3793         {
3794           val_rtx = force_reg (TYPE_MODE (unsigned_char_type_node),
3795                                val_rtx);
3796           store_by_pieces (dest_mem, tree_low_cst (len, 1),
3797                            builtin_memset_gen_str, val_rtx, dest_align,
3798                            true, 0);
3799         }
3800       else if (!set_storage_via_setmem (dest_mem, len_rtx, val_rtx,
3801                                         dest_align, expected_align,
3802                                         expected_size))
3803         goto do_libcall;
3804       
3805       dest_mem = force_operand (XEXP (dest_mem, 0), NULL_RTX);
3806       dest_mem = convert_memory_address (ptr_mode, dest_mem);
3807       return dest_mem;
3808     }
3809
3810   if (target_char_cast (val, &c))
3811     goto do_libcall;
3812
3813   if (c)
3814     {
3815       if (host_integerp (len, 1)
3816           && can_store_by_pieces (tree_low_cst (len, 1),
3817                                   builtin_memset_read_str, &c, dest_align,
3818                                   true))
3819         store_by_pieces (dest_mem, tree_low_cst (len, 1),
3820                          builtin_memset_read_str, &c, dest_align, true, 0);
3821       else if (!set_storage_via_setmem (dest_mem, len_rtx, GEN_INT (c),
3822                                         dest_align, expected_align,
3823                                         expected_size))
3824         goto do_libcall;
3825       
3826       dest_mem = force_operand (XEXP (dest_mem, 0), NULL_RTX);
3827       dest_mem = convert_memory_address (ptr_mode, dest_mem);
3828       return dest_mem;
3829     }
3830
3831   set_mem_align (dest_mem, dest_align);
3832   dest_addr = clear_storage_hints (dest_mem, len_rtx,
3833                                    CALL_EXPR_TAILCALL (orig_exp)
3834                                    ? BLOCK_OP_TAILCALL : BLOCK_OP_NORMAL,
3835                                    expected_align, expected_size);
3836
3837   if (dest_addr == 0)
3838     {
3839       dest_addr = force_operand (XEXP (dest_mem, 0), NULL_RTX);
3840       dest_addr = convert_memory_address (ptr_mode, dest_addr);
3841     }
3842
3843   return dest_addr;
3844
3845  do_libcall:
3846   fndecl = get_callee_fndecl (orig_exp);
3847   fcode = DECL_FUNCTION_CODE (fndecl);
3848   if (fcode == BUILT_IN_MEMSET)
3849     fn = build_call_nofold (fndecl, 3, dest, val, len);
3850   else if (fcode == BUILT_IN_BZERO)
3851     fn = build_call_nofold (fndecl, 2, dest, len);
3852   else
3853     gcc_unreachable ();
3854   gcc_assert (TREE_CODE (fn) == CALL_EXPR);
3855   CALL_EXPR_TAILCALL (fn) = CALL_EXPR_TAILCALL (orig_exp);
3856   return expand_call (fn, target, target == const0_rtx);
3857 }
3858
3859 /* Expand expression EXP, which is a call to the bzero builtin.  Return 
3860    NULL_RTX if we failed the caller should emit a normal call.  */
3861
3862 static rtx
3863 expand_builtin_bzero (tree exp)
3864 {
3865   tree dest, size;
3866   location_t loc = EXPR_LOCATION (exp);
3867
3868   if (!validate_arglist (exp, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
3869     return NULL_RTX;
3870
3871   dest = CALL_EXPR_ARG (exp, 0);
3872   size = CALL_EXPR_ARG (exp, 1);
3873
3874   /* New argument list transforming bzero(ptr x, int y) to
3875      memset(ptr x, int 0, size_t y).   This is done this way
3876      so that if it isn't expanded inline, we fallback to
3877      calling bzero instead of memset.  */
3878
3879   return expand_builtin_memset_args (dest, integer_zero_node,
3880                                      fold_convert_loc (loc, sizetype, size),
3881                                      const0_rtx, VOIDmode, exp);
3882 }
3883
3884 /* Expand expression EXP, which is a call to the memcmp built-in function.
3885    Return NULL_RTX if we failed and the
3886    caller should emit a normal call, otherwise try to get the result in
3887    TARGET, if convenient (and in mode MODE, if that's convenient).  */
3888
3889 static rtx
3890 expand_builtin_memcmp (tree exp, ATTRIBUTE_UNUSED rtx target,
3891                        ATTRIBUTE_UNUSED enum machine_mode mode)
3892 {
3893   location_t loc ATTRIBUTE_UNUSED = EXPR_LOCATION (exp);
3894
3895   if (!validate_arglist (exp,
3896                          POINTER_TYPE, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
3897     return NULL_RTX;
3898
3899 #if defined HAVE_cmpmemsi || defined HAVE_cmpstrnsi
3900   {
3901     rtx arg1_rtx, arg2_rtx, arg3_rtx;
3902     rtx result;
3903     rtx insn;
3904     tree arg1 = CALL_EXPR_ARG (exp, 0);
3905     tree arg2 = CALL_EXPR_ARG (exp, 1);
3906     tree len = CALL_EXPR_ARG (exp, 2);
3907
3908     int arg1_align
3909       = get_pointer_alignment (arg1, BIGGEST_ALIGNMENT) / BITS_PER_UNIT;
3910     int arg2_align
3911       = get_pointer_alignment (arg2, BIGGEST_ALIGNMENT) / BITS_PER_UNIT;
3912     enum machine_mode insn_mode;
3913
3914 #ifdef HAVE_cmpmemsi
3915     if (HAVE_cmpmemsi)
3916       insn_mode = insn_data[(int) CODE_FOR_cmpmemsi].operand[0].mode;
3917     else
3918 #endif
3919 #ifdef HAVE_cmpstrnsi
3920     if (HAVE_cmpstrnsi)
3921       insn_mode = insn_data[(int) CODE_FOR_cmpstrnsi].operand[0].mode;
3922     else
3923 #endif
3924       return NULL_RTX;
3925
3926     /* If we don't have POINTER_TYPE, call the function.  */
3927     if (arg1_align == 0 || arg2_align == 0)
3928       return NULL_RTX;
3929
3930     /* Make a place to write the result of the instruction.  */
3931     result = target;
3932     if (! (result != 0
3933            && REG_P (result) && GET_MODE (result) == insn_mode
3934            && REGNO (result) >= FIRST_PSEUDO_REGISTER))
3935       result = gen_reg_rtx (insn_mode);
3936
3937     arg1_rtx = get_memory_rtx (arg1, len);
3938     arg2_rtx = get_memory_rtx (arg2, len);
3939     arg3_rtx = expand_normal (fold_convert_loc (loc, sizetype, len));
3940
3941     /* Set MEM_SIZE as appropriate.  */
3942     if (CONST_INT_P (arg3_rtx))
3943       {
3944         set_mem_size (arg1_rtx, arg3_rtx);
3945         set_mem_size (arg2_rtx, arg3_rtx);
3946       }
3947
3948 #ifdef HAVE_cmpmemsi
3949     if (HAVE_cmpmemsi)
3950       insn = gen_cmpmemsi (result, arg1_rtx, arg2_rtx, arg3_rtx,
3951                            GEN_INT (MIN (arg1_align, arg2_align)));
3952     else
3953 #endif
3954 #ifdef HAVE_cmpstrnsi
3955     if (HAVE_cmpstrnsi)
3956       insn = gen_cmpstrnsi (result, arg1_rtx, arg2_rtx, arg3_rtx,
3957                             GEN_INT (MIN (arg1_align, arg2_align)));
3958     else
3959 #endif
3960       gcc_unreachable ();
3961
3962     if (insn)
3963       emit_insn (insn);
3964     else
3965       emit_library_call_value (memcmp_libfunc, result, LCT_PURE,
3966                                TYPE_MODE (integer_type_node), 3,
3967                                XEXP (arg1_rtx, 0), Pmode,
3968                                XEXP (arg2_rtx, 0), Pmode,
3969                                convert_to_mode (TYPE_MODE (sizetype), arg3_rtx,
3970                                                 TYPE_UNSIGNED (sizetype)),
3971                                TYPE_MODE (sizetype));
3972
3973     /* Return the value in the proper mode for this function.  */
3974     mode = TYPE_MODE (TREE_TYPE (exp));
3975     if (GET_MODE (result) == mode)
3976       return result;
3977     else if (target != 0)
3978       {
3979         convert_move (target, result, 0);
3980         return target;
3981       }
3982     else
3983       return convert_to_mode (mode, result, 0);
3984   }
3985 #endif
3986
3987   return NULL_RTX;
3988 }
3989
3990 /* Expand expression EXP, which is a call to the strcmp builtin.  Return NULL_RTX
3991    if we failed the caller should emit a normal call, otherwise try to get
3992    the result in TARGET, if convenient.  */
3993
3994 static rtx
3995 expand_builtin_strcmp (tree exp, ATTRIBUTE_UNUSED rtx target)
3996 {
3997   if (!validate_arglist (exp, POINTER_TYPE, POINTER_TYPE, VOID_TYPE))
3998     return NULL_RTX;
3999
4000 #if defined HAVE_cmpstrsi || defined HAVE_cmpstrnsi
4001   if (cmpstr_optab[SImode] != CODE_FOR_nothing
4002       || cmpstrn_optab[SImode] != CODE_FOR_nothing)
4003     {
4004       rtx arg1_rtx, arg2_rtx;
4005       rtx result, insn = NULL_RTX;
4006       tree fndecl, fn;
4007       tree arg1 = CALL_EXPR_ARG (exp, 0);
4008       tree arg2 = CALL_EXPR_ARG (exp, 1);
4009
4010       int arg1_align
4011         = get_pointer_alignment (arg1, BIGGEST_ALIGNMENT) / BITS_PER_UNIT;
4012       int arg2_align
4013         = get_pointer_alignment (arg2, BIGGEST_ALIGNMENT) / BITS_PER_UNIT;
4014
4015       /* If we don't have POINTER_TYPE, call the function.  */
4016       if (arg1_align == 0 || arg2_align == 0)
4017         return NULL_RTX;
4018
4019       /* Stabilize the arguments in case gen_cmpstr(n)si fail.  */
4020       arg1 = builtin_save_expr (arg1);
4021       arg2 = builtin_save_expr (arg2);
4022
4023       arg1_rtx = get_memory_rtx (arg1, NULL);
4024       arg2_rtx = get_memory_rtx (arg2, NULL);
4025
4026 #ifdef HAVE_cmpstrsi
4027       /* Try to call cmpstrsi.  */
4028       if (HAVE_cmpstrsi)
4029         {
4030           enum machine_mode insn_mode
4031             = insn_data[(int) CODE_FOR_cmpstrsi].operand[0].mode;
4032
4033           /* Make a place to write the result of the instruction.  */
4034           result = target;
4035           if (! (result != 0
4036                  && REG_P (result) && GET_MODE (result) == insn_mode
4037                  && REGNO (result) >= FIRST_PSEUDO_REGISTER))
4038             result = gen_reg_rtx (insn_mode);
4039
4040           insn = gen_cmpstrsi (result, arg1_rtx, arg2_rtx,
4041                                GEN_INT (MIN (arg1_align, arg2_align)));
4042         }
4043 #endif
4044 #ifdef HAVE_cmpstrnsi
4045       /* Try to determine at least one length and call cmpstrnsi.  */
4046       if (!insn && HAVE_cmpstrnsi)
4047         {
4048           tree len;
4049           rtx arg3_rtx;
4050
4051           enum machine_mode insn_mode
4052             = insn_data[(int) CODE_FOR_cmpstrnsi].operand[0].mode;
4053           tree len1 = c_strlen (arg1, 1);
4054           tree len2 = c_strlen (arg2, 1);
4055
4056           if (len1)
4057             len1 = size_binop (PLUS_EXPR, ssize_int (1), len1);
4058           if (len2)
4059             len2 = size_binop (PLUS_EXPR, ssize_int (1), len2);
4060
4061           /* If we don't have a constant length for the first, use the length
4062              of the second, if we know it.  We don't require a constant for
4063              this case; some cost analysis could be done if both are available
4064              but neither is constant.  For now, assume they're equally cheap,
4065              unless one has side effects.  If both strings have constant lengths,
4066              use the smaller.  */
4067
4068           if (!len1)
4069             len = len2;
4070           else if (!len2)
4071             len = len1;
4072           else if (TREE_SIDE_EFFECTS (len1))
4073             len = len2;
4074           else if (TREE_SIDE_EFFECTS (len2))
4075             len = len1;
4076           else if (TREE_CODE (len1) != INTEGER_CST)
4077             len = len2;
4078           else if (TREE_CODE (len2) != INTEGER_CST)
4079             len = len1;
4080           else if (tree_int_cst_lt (len1, len2))
4081             len = len1;
4082           else
4083             len = len2;
4084
4085           /* If both arguments have side effects, we cannot optimize.  */
4086           if (!len || TREE_SIDE_EFFECTS (len))
4087             goto do_libcall;
4088
4089           arg3_rtx = expand_normal (len);
4090
4091           /* Make a place to write the result of the instruction.  */
4092           result = target;
4093           if (! (result != 0
4094                  && REG_P (result) && GET_MODE (result) == insn_mode
4095                  && REGNO (result) >= FIRST_PSEUDO_REGISTER))
4096             result = gen_reg_rtx (insn_mode);
4097
4098           insn = gen_cmpstrnsi (result, arg1_rtx, arg2_rtx, arg3_rtx,
4099                                 GEN_INT (MIN (arg1_align, arg2_align)));
4100         }
4101 #endif
4102
4103       if (insn)
4104         {
4105           enum machine_mode mode;
4106           emit_insn (insn);
4107
4108           /* Return the value in the proper mode for this function.  */
4109           mode = TYPE_MODE (TREE_TYPE (exp));
4110           if (GET_MODE (result) == mode)
4111             return result;
4112           if (target == 0)
4113             return convert_to_mode (mode, result, 0);
4114           convert_move (target, result, 0);
4115           return target;
4116         }
4117
4118       /* Expand the library call ourselves using a stabilized argument
4119          list to avoid re-evaluating the function's arguments twice.  */
4120 #ifdef HAVE_cmpstrnsi
4121     do_libcall:
4122 #endif
4123       fndecl = get_callee_fndecl (exp);
4124       fn = build_call_nofold (fndecl, 2, arg1, arg2);
4125       gcc_assert (TREE_CODE (fn) == CALL_EXPR);
4126       CALL_EXPR_TAILCALL (fn) = CALL_EXPR_TAILCALL (exp);
4127       return expand_call (fn, target, target == const0_rtx);
4128     }
4129 #endif
4130   return NULL_RTX;
4131 }
4132
4133 /* Expand expression EXP, which is a call to the strncmp builtin. Return 
4134    NULL_RTX if we failed the caller should emit a normal call, otherwise try to get
4135    the result in TARGET, if convenient.  */
4136
4137 static rtx
4138 expand_builtin_strncmp (tree exp, ATTRIBUTE_UNUSED rtx target,
4139                         ATTRIBUTE_UNUSED enum machine_mode mode)
4140 {
4141   location_t loc ATTRIBUTE_UNUSED = EXPR_LOCATION (exp);
4142
4143   if (!validate_arglist (exp,
4144                          POINTER_TYPE, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
4145     return NULL_RTX;
4146
4147   /* If c_strlen can determine an expression for one of the string
4148      lengths, and it doesn't have side effects, then emit cmpstrnsi
4149      using length MIN(strlen(string)+1, arg3).  */
4150 #ifdef HAVE_cmpstrnsi
4151   if (HAVE_cmpstrnsi)
4152   {
4153     tree len, len1, len2;
4154     rtx arg1_rtx, arg2_rtx, arg3_rtx;
4155     rtx result, insn;
4156     tree fndecl, fn;
4157     tree arg1 = CALL_EXPR_ARG (exp, 0);
4158     tree arg2 = CALL_EXPR_ARG (exp, 1);
4159     tree arg3 = CALL_EXPR_ARG (exp, 2);
4160
4161     int arg1_align
4162       = get_pointer_alignment (arg1, BIGGEST_ALIGNMENT) / BITS_PER_UNIT;
4163     int arg2_align
4164       = get_pointer_alignment (arg2, BIGGEST_ALIGNMENT) / BITS_PER_UNIT;
4165     enum machine_mode insn_mode
4166       = insn_data[(int) CODE_FOR_cmpstrnsi].operand[0].mode;
4167
4168     len1 = c_strlen (arg1, 1);
4169     len2 = c_strlen (arg2, 1);
4170
4171     if (len1)
4172       len1 = size_binop_loc (loc, PLUS_EXPR, ssize_int (1), len1);
4173     if (len2)
4174       len2 = size_binop_loc (loc, PLUS_EXPR, ssize_int (1), len2);
4175
4176     /* If we don't have a constant length for the first, use the length
4177        of the second, if we know it.  We don't require a constant for
4178        this case; some cost analysis could be done if both are available
4179        but neither is constant.  For now, assume they're equally cheap,
4180        unless one has side effects.  If both strings have constant lengths,
4181        use the smaller.  */
4182
4183     if (!len1)
4184       len = len2;
4185     else if (!len2)
4186       len = len1;
4187     else if (TREE_SIDE_EFFECTS (len1))
4188       len = len2;
4189     else if (TREE_SIDE_EFFECTS (len2))
4190       len = len1;
4191     else if (TREE_CODE (len1) != INTEGER_CST)
4192       len = len2;
4193     else if (TREE_CODE (len2) != INTEGER_CST)
4194       len = len1;
4195     else if (tree_int_cst_lt (len1, len2))
4196       len = len1;
4197     else
4198       len = len2;
4199
4200     /* If both arguments have side effects, we cannot optimize.  */
4201     if (!len || TREE_SIDE_EFFECTS (len))
4202       return NULL_RTX;
4203
4204     /* The actual new length parameter is MIN(len,arg3).  */
4205     len = fold_build2_loc (loc, MIN_EXPR, TREE_TYPE (len), len,
4206                        fold_convert_loc (loc, TREE_TYPE (len), arg3));
4207
4208     /* If we don't have POINTER_TYPE, call the function.  */
4209     if (arg1_align == 0 || arg2_align == 0)
4210       return NULL_RTX;
4211
4212     /* Make a place to write the result of the instruction.  */
4213     result = target;
4214     if (! (result != 0
4215            && REG_P (result) && GET_MODE (result) == insn_mode
4216            && REGNO (result) >= FIRST_PSEUDO_REGISTER))
4217       result = gen_reg_rtx (insn_mode);
4218
4219     /* Stabilize the arguments in case gen_cmpstrnsi fails.  */
4220     arg1 = builtin_save_expr (arg1);
4221     arg2 = builtin_save_expr (arg2);
4222     len = builtin_save_expr (len);
4223
4224     arg1_rtx = get_memory_rtx (arg1, len);
4225     arg2_rtx = get_memory_rtx (arg2, len);
4226     arg3_rtx = expand_normal (len);
4227     insn = gen_cmpstrnsi (result, arg1_rtx, arg2_rtx, arg3_rtx,
4228                           GEN_INT (MIN (arg1_align, arg2_align)));
4229     if (insn)
4230       {
4231         emit_insn (insn);
4232
4233         /* Return the value in the proper mode for this function.  */
4234         mode = TYPE_MODE (TREE_TYPE (exp));
4235         if (GET_MODE (result) == mode)
4236           return result;
4237         if (target == 0)
4238           return convert_to_mode (mode, result, 0);
4239         convert_move (target, result, 0);
4240         return target;
4241       }
4242
4243     /* Expand the library call ourselves using a stabilized argument
4244        list to avoid re-evaluating the function's arguments twice.  */
4245     fndecl = get_callee_fndecl (exp);
4246     fn = build_call_nofold (fndecl, 3, arg1, arg2, len);
4247     gcc_assert (TREE_CODE (fn) == CALL_EXPR);
4248     CALL_EXPR_TAILCALL (fn) = CALL_EXPR_TAILCALL (exp);
4249     return expand_call (fn, target, target == const0_rtx);
4250   }
4251 #endif
4252   return NULL_RTX;
4253 }
4254
4255 /* Expand a call to __builtin_saveregs, generating the result in TARGET,
4256    if that's convenient.  */
4257
4258 rtx
4259 expand_builtin_saveregs (void)
4260 {
4261   rtx val, seq;
4262
4263   /* Don't do __builtin_saveregs more than once in a function.
4264      Save the result of the first call and reuse it.  */
4265   if (saveregs_value != 0)
4266     return saveregs_value;
4267
4268   /* When this function is called, it means that registers must be
4269      saved on entry to this function.  So we migrate the call to the
4270      first insn of this function.  */
4271
4272   start_sequence ();
4273
4274   /* Do whatever the machine needs done in this case.  */
4275   val = targetm.calls.expand_builtin_saveregs ();
4276
4277   seq = get_insns ();
4278   end_sequence ();
4279
4280   saveregs_value = val;
4281
4282   /* Put the insns after the NOTE that starts the function.  If this
4283      is inside a start_sequence, make the outer-level insn chain current, so
4284      the code is placed at the start of the function.  */
4285   push_topmost_sequence ();
4286   emit_insn_after (seq, entry_of_function ());
4287   pop_topmost_sequence ();
4288
4289   return val;
4290 }
4291
4292 /* __builtin_args_info (N) returns word N of the arg space info
4293    for the current function.  The number and meanings of words
4294    is controlled by the definition of CUMULATIVE_ARGS.  */
4295
4296 static rtx
4297 expand_builtin_args_info (tree exp)
4298 {
4299   int nwords = sizeof (CUMULATIVE_ARGS) / sizeof (int);
4300   int *word_ptr = (int *) &crtl->args.info;
4301
4302   gcc_assert (sizeof (CUMULATIVE_ARGS) % sizeof (int) == 0);
4303
4304   if (call_expr_nargs (exp) != 0)
4305     {
4306       if (!host_integerp (CALL_EXPR_ARG (exp, 0), 0))
4307         error ("argument of %<__builtin_args_info%> must be constant");
4308       else
4309         {
4310           HOST_WIDE_INT wordnum = tree_low_cst (CALL_EXPR_ARG (exp, 0), 0);
4311
4312           if (wordnum < 0 || wordnum >= nwords)
4313             error ("argument of %<__builtin_args_info%> out of range");
4314           else
4315             return GEN_INT (word_ptr[wordnum]);
4316         }
4317     }
4318   else
4319     error ("missing argument in %<__builtin_args_info%>");
4320
4321   return const0_rtx;
4322 }
4323
4324 /* Expand a call to __builtin_next_arg.  */
4325
4326 static rtx
4327 expand_builtin_next_arg (void)
4328 {
4329   /* Checking arguments is already done in fold_builtin_next_arg
4330      that must be called before this function.  */
4331   return expand_binop (ptr_mode, add_optab,
4332                        crtl->args.internal_arg_pointer,
4333                        crtl->args.arg_offset_rtx,
4334                        NULL_RTX, 0, OPTAB_LIB_WIDEN);
4335 }
4336
4337 /* Make it easier for the backends by protecting the valist argument
4338    from multiple evaluations.  */
4339
4340 static tree
4341 stabilize_va_list_loc (location_t loc, tree valist, int needs_lvalue)
4342 {
4343   tree vatype = targetm.canonical_va_list_type (TREE_TYPE (valist));
4344
4345   gcc_assert (vatype != NULL_TREE);
4346
4347   if (TREE_CODE (vatype) == ARRAY_TYPE)
4348     {
4349       if (TREE_SIDE_EFFECTS (valist))
4350         valist = save_expr (valist);
4351
4352       /* For this case, the backends will be expecting a pointer to
4353          vatype, but it's possible we've actually been given an array
4354          (an actual TARGET_CANONICAL_VA_LIST_TYPE (valist)).
4355          So fix it.  */
4356       if (TREE_CODE (TREE_TYPE (valist)) == ARRAY_TYPE)
4357         {
4358           tree p1 = build_pointer_type (TREE_TYPE (vatype));
4359           valist = build_fold_addr_expr_with_type_loc (loc, valist, p1);
4360         }
4361     }
4362   else
4363     {
4364       tree pt;
4365
4366       if (! needs_lvalue)
4367         {
4368           if (! TREE_SIDE_EFFECTS (valist))
4369             return valist;
4370
4371           pt = build_pointer_type (vatype);
4372           valist = fold_build1_loc (loc, ADDR_EXPR, pt, valist);
4373           TREE_SIDE_EFFECTS (valist) = 1;
4374         }
4375
4376       if (TREE_SIDE_EFFECTS (valist))
4377         valist = save_expr (valist);
4378       valist = build_fold_indirect_ref_loc (loc, valist);
4379     }
4380
4381   return valist;
4382 }
4383
4384 /* The "standard" definition of va_list is void*.  */
4385
4386 tree
4387 std_build_builtin_va_list (void)
4388 {
4389   return ptr_type_node;
4390 }
4391
4392 /* The "standard" abi va_list is va_list_type_node.  */
4393
4394 tree
4395 std_fn_abi_va_list (tree fndecl ATTRIBUTE_UNUSED)
4396 {
4397   return va_list_type_node;
4398 }
4399
4400 /* The "standard" type of va_list is va_list_type_node.  */
4401
4402 tree
4403 std_canonical_va_list_type (tree type)
4404 {
4405   tree wtype, htype;
4406
4407   if (INDIRECT_REF_P (type))
4408     type = TREE_TYPE (type);
4409   else if (POINTER_TYPE_P (type) && POINTER_TYPE_P (TREE_TYPE(type)))
4410     type = TREE_TYPE (type);
4411   wtype = va_list_type_node;
4412   htype = type;
4413   /* Treat structure va_list types.  */
4414   if (TREE_CODE (wtype) == RECORD_TYPE && POINTER_TYPE_P (htype))
4415     htype = TREE_TYPE (htype);
4416   else if (TREE_CODE (wtype) == ARRAY_TYPE)
4417     {
4418       /* If va_list is an array type, the argument may have decayed
4419          to a pointer type, e.g. by being passed to another function.
4420          In that case, unwrap both types so that we can compare the
4421          underlying records.  */
4422       if (TREE_CODE (htype) == ARRAY_TYPE
4423           || POINTER_TYPE_P (htype))
4424         {
4425           wtype = TREE_TYPE (wtype);
4426           htype = TREE_TYPE (htype);
4427         }
4428     }
4429   if (TYPE_MAIN_VARIANT (wtype) == TYPE_MAIN_VARIANT (htype))
4430     return va_list_type_node;
4431
4432   return NULL_TREE;
4433 }
4434
4435 /* The "standard" implementation of va_start: just assign `nextarg' to
4436    the variable.  */
4437
4438 void
4439 std_expand_builtin_va_start (tree valist, rtx nextarg)
4440 {
4441   rtx va_r = expand_expr (valist, NULL_RTX, VOIDmode, EXPAND_WRITE);
4442   convert_move (va_r, nextarg, 0);
4443 }
4444
4445 /* Expand EXP, a call to __builtin_va_start.  */
4446
4447 static rtx
4448 expand_builtin_va_start (tree exp)
4449 {
4450   rtx nextarg;
4451   tree valist;
4452   location_t loc = EXPR_LOCATION (exp);
4453
4454   if (call_expr_nargs (exp) < 2)
4455     {
4456       error_at (loc, "too few arguments to function %<va_start%>");
4457       return const0_rtx;
4458     }
4459
4460   if (fold_builtin_next_arg (exp, true))
4461     return const0_rtx;
4462
4463   nextarg = expand_builtin_next_arg ();
4464   valist = stabilize_va_list_loc (loc, CALL_EXPR_ARG (exp, 0), 1);
4465
4466   if (targetm.expand_builtin_va_start)
4467     targetm.expand_builtin_va_start (valist, nextarg);
4468   else
4469     std_expand_builtin_va_start (valist, nextarg);
4470
4471   return const0_rtx;
4472 }
4473
4474 /* The "standard" implementation of va_arg: read the value from the
4475    current (padded) address and increment by the (padded) size.  */
4476
4477 tree
4478 std_gimplify_va_arg_expr (tree valist, tree type, gimple_seq *pre_p,
4479                           gimple_seq *post_p)
4480 {
4481   tree addr, t, type_size, rounded_size, valist_tmp;
4482   unsigned HOST_WIDE_INT align, boundary;
4483   bool indirect;
4484
4485 #ifdef ARGS_GROW_DOWNWARD
4486   /* All of the alignment and movement below is for args-grow-up machines.
4487      As of 2004, there are only 3 ARGS_GROW_DOWNWARD targets, and they all
4488      implement their own specialized gimplify_va_arg_expr routines.  */
4489   gcc_unreachable ();
4490 #endif
4491
4492   indirect = pass_by_reference (NULL, TYPE_MODE (type), type, false);
4493   if (indirect)
4494     type = build_pointer_type (type);
4495
4496   align = PARM_BOUNDARY / BITS_PER_UNIT;
4497   boundary = FUNCTION_ARG_BOUNDARY (TYPE_MODE (type), type);
4498
4499   /* When we align parameter on stack for caller, if the parameter
4500      alignment is beyond MAX_SUPPORTED_STACK_ALIGNMENT, it will be
4501      aligned at MAX_SUPPORTED_STACK_ALIGNMENT.  We will match callee
4502      here with caller.  */
4503   if (boundary > MAX_SUPPORTED_STACK_ALIGNMENT)
4504     boundary = MAX_SUPPORTED_STACK_ALIGNMENT;
4505
4506   boundary /= BITS_PER_UNIT;
4507
4508   /* Hoist the valist value into a temporary for the moment.  */
4509   valist_tmp = get_initialized_tmp_var (valist, pre_p, NULL);
4510
4511   /* va_list pointer is aligned to PARM_BOUNDARY.  If argument actually
4512      requires greater alignment, we must perform dynamic alignment.  */
4513   if (boundary > align
4514       && !integer_zerop (TYPE_SIZE (type)))
4515     {
4516       t = build2 (MODIFY_EXPR, TREE_TYPE (valist), valist_tmp,
4517                   fold_build2 (POINTER_PLUS_EXPR,
4518                                TREE_TYPE (valist),
4519                                valist_tmp, size_int (boundary - 1)));
4520       gimplify_and_add (t, pre_p);
4521
4522       t = fold_convert (sizetype, valist_tmp);
4523       t = build2 (MODIFY_EXPR, TREE_TYPE (valist), valist_tmp,
4524                   fold_convert (TREE_TYPE (valist),
4525                                 fold_build2 (BIT_AND_EXPR, sizetype, t,
4526                                              size_int (-boundary))));
4527       gimplify_and_add (t, pre_p);
4528     }
4529   else
4530     boundary = align;
4531
4532   /* If the actual alignment is less than the alignment of the type,
4533      adjust the type accordingly so that we don't assume strict alignment
4534      when dereferencing the pointer.  */
4535   boundary *= BITS_PER_UNIT;
4536   if (boundary < TYPE_ALIGN (type))
4537     {
4538       type = build_variant_type_copy (type);
4539       TYPE_ALIGN (type) = boundary;
4540     }
4541
4542   /* Compute the rounded size of the type.  */
4543   type_size = size_in_bytes (type);
4544   rounded_size = round_up (type_size, align);
4545
4546   /* Reduce rounded_size so it's sharable with the postqueue.  */
4547   gimplify_expr (&rounded_size, pre_p, post_p, is_gimple_val, fb_rvalue);
4548
4549   /* Get AP.  */
4550   addr = valist_tmp;
4551   if (PAD_VARARGS_DOWN && !integer_zerop (rounded_size))
4552     {
4553       /* Small args are padded downward.  */
4554       t = fold_build2_loc (input_location, GT_EXPR, sizetype,
4555                        rounded_size, size_int (align));
4556       t = fold_build3 (COND_EXPR, sizetype, t, size_zero_node,
4557                        size_binop (MINUS_EXPR, rounded_size, type_size));
4558       addr = fold_build2 (POINTER_PLUS_EXPR,
4559                           TREE_TYPE (addr), addr, t);
4560     }
4561
4562   /* Compute new value for AP.  */
4563   t = build2 (POINTER_PLUS_EXPR, TREE_TYPE (valist), valist_tmp, rounded_size);
4564   t = build2 (MODIFY_EXPR, TREE_TYPE (valist), valist, t);
4565   gimplify_and_add (t, pre_p);
4566
4567   addr = fold_convert (build_pointer_type (type), addr);
4568
4569   if (indirect)
4570     addr = build_va_arg_indirect_ref (addr);
4571
4572   return build_va_arg_indirect_ref (addr);
4573 }
4574
4575 /* Build an indirect-ref expression over the given TREE, which represents a
4576    piece of a va_arg() expansion.  */
4577 tree
4578 build_va_arg_indirect_ref (tree addr)
4579 {
4580   addr = build_fold_indirect_ref_loc (EXPR_LOCATION (addr), addr);
4581
4582   if (flag_mudflap) /* Don't instrument va_arg INDIRECT_REF.  */
4583     mf_mark (addr);
4584
4585   return addr;
4586 }
4587
4588 /* Return a dummy expression of type TYPE in order to keep going after an
4589    error.  */
4590
4591 static tree
4592 dummy_object (tree type)
4593 {
4594   tree t = build_int_cst (build_pointer_type (type), 0);
4595   return build1 (INDIRECT_REF, type, t);
4596 }
4597
4598 /* Gimplify __builtin_va_arg, aka VA_ARG_EXPR, which is not really a
4599    builtin function, but a very special sort of operator.  */
4600
4601 enum gimplify_status
4602 gimplify_va_arg_expr (tree *expr_p, gimple_seq *pre_p, gimple_seq *post_p)
4603 {
4604   tree promoted_type, have_va_type;
4605   tree valist = TREE_OPERAND (*expr_p, 0);
4606   tree type = TREE_TYPE (*expr_p);
4607   tree t;
4608   location_t loc = EXPR_LOCATION (*expr_p);
4609
4610   /* Verify that valist is of the proper type.  */
4611   have_va_type = TREE_TYPE (valist);
4612   if (have_va_type == error_mark_node)
4613     return GS_ERROR;
4614   have_va_type = targetm.canonical_va_list_type (have_va_type);
4615
4616   if (have_va_type == NULL_TREE)
4617     {
4618       error_at (loc, "first argument to %<va_arg%> not of type %<va_list%>");
4619       return GS_ERROR;
4620     }
4621
4622   /* Generate a diagnostic for requesting data of a type that cannot
4623      be passed through `...' due to type promotion at the call site.  */
4624   if ((promoted_type = lang_hooks.types.type_promotes_to (type))
4625            != type)
4626     {
4627       static bool gave_help;
4628       bool warned;
4629
4630       /* Unfortunately, this is merely undefined, rather than a constraint
4631          violation, so we cannot make this an error.  If this call is never
4632          executed, the program is still strictly conforming.  */
4633       warned = warning_at (loc, 0,
4634                            "%qT is promoted to %qT when passed through %<...%>",
4635                            type, promoted_type);
4636       if (!gave_help && warned)
4637         {
4638           gave_help = true;
4639           inform (loc, "(so you should pass %qT not %qT to %<va_arg%>)",
4640                   promoted_type, type);
4641         }
4642
4643       /* We can, however, treat "undefined" any way we please.
4644          Call abort to encourage the user to fix the program.  */
4645       if (warned)
4646         inform (loc, "if this code is reached, the program will abort");
4647       /* Before the abort, allow the evaluation of the va_list
4648          expression to exit or longjmp.  */
4649       gimplify_and_add (valist, pre_p);
4650       t = build_call_expr_loc (loc,
4651                                implicit_built_in_decls[BUILT_IN_TRAP], 0);
4652       gimplify_and_add (t, pre_p);
4653
4654       /* This is dead code, but go ahead and finish so that the
4655          mode of the result comes out right.  */
4656       *expr_p = dummy_object (type);
4657       return GS_ALL_DONE;
4658     }
4659   else
4660     {
4661       /* Make it easier for the backends by protecting the valist argument
4662          from multiple evaluations.  */
4663       if (TREE_CODE (have_va_type) == ARRAY_TYPE)
4664         {
4665           /* For this case, the backends will be expecting a pointer to
4666              TREE_TYPE (abi), but it's possible we've
4667              actually been given an array (an actual TARGET_FN_ABI_VA_LIST).
4668              So fix it.  */
4669           if (TREE_CODE (TREE_TYPE (valist)) == ARRAY_TYPE)
4670             {
4671               tree p1 = build_pointer_type (TREE_TYPE (have_va_type));
4672               valist = fold_convert_loc (loc, p1,
4673                                          build_fold_addr_expr_loc (loc, valist));
4674             }
4675
4676           gimplify_expr (&valist, pre_p, post_p, is_gimple_val, fb_rvalue);
4677         }
4678       else
4679         gimplify_expr (&valist, pre_p, post_p, is_gimple_min_lval, fb_lvalue);
4680
4681       if (!targetm.gimplify_va_arg_expr)
4682         /* FIXME: Once most targets are converted we should merely
4683            assert this is non-null.  */
4684         return GS_ALL_DONE;
4685
4686       *expr_p = targetm.gimplify_va_arg_expr (valist, type, pre_p, post_p);
4687       return GS_OK;
4688     }
4689 }
4690
4691 /* Expand EXP, a call to __builtin_va_end.  */
4692
4693 static rtx
4694 expand_builtin_va_end (tree exp)
4695 {
4696   tree valist = CALL_EXPR_ARG (exp, 0);
4697
4698   /* Evaluate for side effects, if needed.  I hate macros that don't
4699      do that.  */
4700   if (TREE_SIDE_EFFECTS (valist))
4701     expand_expr (valist, const0_rtx, VOIDmode, EXPAND_NORMAL);
4702
4703   return const0_rtx;
4704 }
4705
4706 /* Expand EXP, a call to __builtin_va_copy.  We do this as a
4707    builtin rather than just as an assignment in stdarg.h because of the
4708    nastiness of array-type va_list types.  */
4709
4710 static rtx
4711 expand_builtin_va_copy (tree exp)
4712 {
4713   tree dst, src, t;
4714   location_t loc = EXPR_LOCATION (exp);
4715
4716   dst = CALL_EXPR_ARG (exp, 0);
4717   src = CALL_EXPR_ARG (exp, 1);
4718
4719   dst = stabilize_va_list_loc (loc, dst, 1);
4720   src = stabilize_va_list_loc (loc, src, 0);
4721
4722   gcc_assert (cfun != NULL && cfun->decl != NULL_TREE);
4723
4724   if (TREE_CODE (targetm.fn_abi_va_list (cfun->decl)) != ARRAY_TYPE)
4725     {
4726       t = build2 (MODIFY_EXPR, targetm.fn_abi_va_list (cfun->decl), dst, src);
4727       TREE_SIDE_EFFECTS (t) = 1;
4728       expand_expr (t, const0_rtx, VOIDmode, EXPAND_NORMAL);
4729     }
4730   else
4731     {
4732       rtx dstb, srcb, size;
4733
4734       /* Evaluate to pointers.  */
4735       dstb = expand_expr (dst, NULL_RTX, Pmode, EXPAND_NORMAL);
4736       srcb = expand_expr (src, NULL_RTX, Pmode, EXPAND_NORMAL);
4737       size = expand_expr (TYPE_SIZE_UNIT (targetm.fn_abi_va_list (cfun->decl)),
4738                   NULL_RTX, VOIDmode, EXPAND_NORMAL);
4739
4740       dstb = convert_memory_address (Pmode, dstb);
4741       srcb = convert_memory_address (Pmode, srcb);
4742
4743       /* "Dereference" to BLKmode memories.  */
4744       dstb = gen_rtx_MEM (BLKmode, dstb);
4745       set_mem_alias_set (dstb, get_alias_set (TREE_TYPE (TREE_TYPE (dst))));
4746       set_mem_align (dstb, TYPE_ALIGN (targetm.fn_abi_va_list (cfun->decl)));
4747       srcb = gen_rtx_MEM (BLKmode, srcb);
4748       set_mem_alias_set (srcb, get_alias_set (TREE_TYPE (TREE_TYPE (src))));
4749       set_mem_align (srcb, TYPE_ALIGN (targetm.fn_abi_va_list (cfun->decl)));
4750
4751       /* Copy.  */
4752       emit_block_move (dstb, srcb, size, BLOCK_OP_NORMAL);
4753     }
4754
4755   return const0_rtx;
4756 }
4757
4758 /* Expand a call to one of the builtin functions __builtin_frame_address or
4759    __builtin_return_address.  */
4760
4761 static rtx
4762 expand_builtin_frame_address (tree fndecl, tree exp)
4763 {
4764   /* The argument must be a nonnegative integer constant.
4765      It counts the number of frames to scan up the stack.
4766      The value is the return address saved in that frame.  */
4767   if (call_expr_nargs (exp) == 0)
4768     /* Warning about missing arg was already issued.  */
4769     return const0_rtx;
4770   else if (! host_integerp (CALL_EXPR_ARG (exp, 0), 1))
4771     {
4772       if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_FRAME_ADDRESS)
4773         error ("invalid argument to %<__builtin_frame_address%>");
4774       else
4775         error ("invalid argument to %<__builtin_return_address%>");
4776       return const0_rtx;
4777     }
4778   else
4779     {
4780       rtx tem
4781         = expand_builtin_return_addr (DECL_FUNCTION_CODE (fndecl),
4782                                       tree_low_cst (CALL_EXPR_ARG (exp, 0), 1));
4783
4784       /* Some ports cannot access arbitrary stack frames.  */
4785       if (tem == NULL)
4786         {
4787           if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_FRAME_ADDRESS)
4788             warning (0, "unsupported argument to %<__builtin_frame_address%>");
4789           else
4790             warning (0, "unsupported argument to %<__builtin_return_address%>");
4791           return const0_rtx;
4792         }
4793
4794       /* For __builtin_frame_address, return what we've got.  */
4795       if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_FRAME_ADDRESS)
4796         return tem;
4797
4798       if (!REG_P (tem)
4799           && ! CONSTANT_P (tem))
4800         tem = copy_to_mode_reg (Pmode, tem);
4801       return tem;
4802     }
4803 }
4804
4805 /* Expand EXP, a call to the alloca builtin.  Return NULL_RTX if
4806    we failed and the caller should emit a normal call, otherwise try to get
4807    the result in TARGET, if convenient.  */
4808
4809 static rtx
4810 expand_builtin_alloca (tree exp, rtx target)
4811 {
4812   rtx op0;
4813   rtx result;
4814
4815   /* Emit normal call if marked not-inlineable.  */
4816   if (CALL_CANNOT_INLINE_P (exp)) 
4817     return NULL_RTX;
4818
4819   if (!validate_arglist (exp, INTEGER_TYPE, VOID_TYPE))
4820     return NULL_RTX;
4821
4822   /* Compute the argument.  */
4823   op0 = expand_normal (CALL_EXPR_ARG (exp, 0));
4824
4825   /* Allocate the desired space.  */
4826   result = allocate_dynamic_stack_space (op0, target, BITS_PER_UNIT);
4827   result = convert_memory_address (ptr_mode, result);
4828
4829   return result;
4830 }
4831
4832 /* Expand a call to a bswap builtin with argument ARG0.  MODE
4833    is the mode to expand with.  */
4834
4835 static rtx
4836 expand_builtin_bswap (tree exp, rtx target, rtx subtarget)
4837 {
4838   enum machine_mode mode;
4839   tree arg;
4840   rtx op0;
4841
4842   if (!validate_arglist (exp, INTEGER_TYPE, VOID_TYPE))
4843     return NULL_RTX;
4844
4845   arg = CALL_EXPR_ARG (exp, 0);
4846   mode = TYPE_MODE (TREE_TYPE (arg));
4847   op0 = expand_expr (arg, subtarget, VOIDmode, EXPAND_NORMAL);
4848
4849   target = expand_unop (mode, bswap_optab, op0, target, 1);
4850
4851   gcc_assert (target);
4852
4853   return convert_to_mode (mode, target, 0);
4854 }
4855
4856 /* Expand a call to a unary builtin in EXP.
4857    Return NULL_RTX if a normal call should be emitted rather than expanding the
4858    function in-line.  If convenient, the result should be placed in TARGET.
4859    SUBTARGET may be used as the target for computing one of EXP's operands.  */
4860
4861 static rtx
4862 expand_builtin_unop (enum machine_mode target_mode, tree exp, rtx target,
4863                      rtx subtarget, optab op_optab)
4864 {
4865   rtx op0;
4866
4867   if (!validate_arglist (exp, INTEGER_TYPE, VOID_TYPE))
4868     return NULL_RTX;
4869
4870   /* Compute the argument.  */
4871   op0 = expand_expr (CALL_EXPR_ARG (exp, 0), subtarget,
4872                      VOIDmode, EXPAND_NORMAL);
4873   /* Compute op, into TARGET if possible.
4874      Set TARGET to wherever the result comes back.  */
4875   target = expand_unop (TYPE_MODE (TREE_TYPE (CALL_EXPR_ARG (exp, 0))),
4876                         op_optab, op0, target, 1);
4877   gcc_assert (target);
4878
4879   return convert_to_mode (target_mode, target, 0);
4880 }
4881
4882 /* Expand a call to __builtin_expect.  We just return our argument 
4883    as the builtin_expect semantic should've been already executed by
4884    tree branch prediction pass. */
4885
4886 static rtx
4887 expand_builtin_expect (tree exp, rtx target)
4888 {
4889   tree arg;
4890
4891   if (call_expr_nargs (exp) < 2)
4892     return const0_rtx;
4893   arg = CALL_EXPR_ARG (exp, 0);
4894
4895   target = expand_expr (arg, target, VOIDmode, EXPAND_NORMAL);
4896   /* When guessing was done, the hints should be already stripped away.  */
4897   gcc_assert (!flag_guess_branch_prob
4898               || optimize == 0 || errorcount || sorrycount);
4899   return target;
4900 }
4901
4902 void
4903 expand_builtin_trap (void)
4904 {
4905 #ifdef HAVE_trap
4906   if (HAVE_trap)
4907     emit_insn (gen_trap ());
4908   else
4909 #endif
4910     emit_library_call (abort_libfunc, LCT_NORETURN, VOIDmode, 0);
4911   emit_barrier ();
4912 }
4913
4914 /* Expand a call to __builtin_unreachable.  We do nothing except emit
4915    a barrier saying that control flow will not pass here.
4916
4917    It is the responsibility of the program being compiled to ensure
4918    that control flow does never reach __builtin_unreachable.  */
4919 static void
4920 expand_builtin_unreachable (void)
4921 {
4922   emit_barrier ();
4923 }
4924
4925 /* Expand EXP, a call to fabs, fabsf or fabsl.
4926    Return NULL_RTX if a normal call should be emitted rather than expanding
4927    the function inline.  If convenient, the result should be placed
4928    in TARGET.  SUBTARGET may be used as the target for computing
4929    the operand.  */
4930
4931 static rtx
4932 expand_builtin_fabs (tree exp, rtx target, rtx subtarget)
4933 {
4934   enum machine_mode mode;
4935   tree arg;
4936   rtx op0;
4937
4938   if (!validate_arglist (exp, REAL_TYPE, VOID_TYPE))
4939     return NULL_RTX;
4940
4941   arg = CALL_EXPR_ARG (exp, 0);
4942   CALL_EXPR_ARG (exp, 0) = arg = builtin_save_expr (arg);
4943   mode = TYPE_MODE (TREE_TYPE (arg));
4944   op0 = expand_expr (arg, subtarget, VOIDmode, EXPAND_NORMAL);
4945   return expand_abs (mode, op0, target, 0, safe_from_p (target, arg, 1));
4946 }
4947
4948 /* Expand EXP, a call to copysign, copysignf, or copysignl.
4949    Return NULL is a normal call should be emitted rather than expanding the
4950    function inline.  If convenient, the result should be placed in TARGET.
4951    SUBTARGET may be used as the target for computing the operand.  */
4952
4953 static rtx
4954 expand_builtin_copysign (tree exp, rtx target, rtx subtarget)
4955 {
4956   rtx op0, op1;
4957   tree arg;
4958
4959   if (!validate_arglist (exp, REAL_TYPE, REAL_TYPE, VOID_TYPE))
4960     return NULL_RTX;
4961
4962   arg = CALL_EXPR_ARG (exp, 0);
4963   op0 = expand_expr (arg, subtarget, VOIDmode, EXPAND_NORMAL);
4964
4965   arg = CALL_EXPR_ARG (exp, 1);
4966   op1 = expand_normal (arg);
4967
4968   return expand_copysign (op0, op1, target);
4969 }
4970
4971 /* Create a new constant string literal and return a char* pointer to it.
4972    The STRING_CST value is the LEN characters at STR.  */
4973 tree
4974 build_string_literal (int len, const char *str)
4975 {
4976   tree t, elem, index, type;
4977
4978   t = build_string (len, str);
4979   elem = build_type_variant (char_type_node, 1, 0);
4980   index = build_index_type (size_int (len - 1));
4981   type = build_array_type (elem, index);
4982   TREE_TYPE (t) = type;
4983   TREE_CONSTANT (t) = 1;
4984   TREE_READONLY (t) = 1;
4985   TREE_STATIC (t) = 1;
4986
4987   type = build_pointer_type (elem);
4988   t = build1 (ADDR_EXPR, type,
4989               build4 (ARRAY_REF, elem,
4990                       t, integer_zero_node, NULL_TREE, NULL_TREE));
4991   return t;
4992 }
4993
4994 /* Expand EXP, a call to printf or printf_unlocked.
4995    Return NULL_RTX if a normal call should be emitted rather than transforming
4996    the function inline.  If convenient, the result should be placed in
4997    TARGET with mode MODE.  UNLOCKED indicates this is a printf_unlocked
4998    call.  */
4999 static rtx
5000 expand_builtin_printf (tree exp, rtx target, enum machine_mode mode,
5001                        bool unlocked)
5002 {
5003   /* If we're using an unlocked function, assume the other unlocked
5004      functions exist explicitly.  */
5005   tree const fn_putchar = unlocked ? built_in_decls[BUILT_IN_PUTCHAR_UNLOCKED]
5006     : implicit_built_in_decls[BUILT_IN_PUTCHAR];
5007   tree const fn_puts = unlocked ? built_in_decls[BUILT_IN_PUTS_UNLOCKED]
5008     : implicit_built_in_decls[BUILT_IN_PUTS];
5009   const char *fmt_str;
5010   tree fn = 0;
5011   tree fmt, arg;
5012   int nargs = call_expr_nargs (exp);
5013
5014   /* If the return value is used, don't do the transformation.  */
5015   if (target != const0_rtx)
5016     return NULL_RTX;
5017
5018   /* Verify the required arguments in the original call.  */
5019   if (nargs == 0)
5020     return NULL_RTX;
5021   fmt = CALL_EXPR_ARG (exp, 0);
5022   if (! POINTER_TYPE_P (TREE_TYPE (fmt)))
5023     return NULL_RTX;
5024
5025   /* Check whether the format is a literal string constant.  */
5026   fmt_str = c_getstr (fmt);
5027   if (fmt_str == NULL)
5028     return NULL_RTX;
5029
5030   if (!init_target_chars ())
5031     return NULL_RTX;
5032
5033   /* If the format specifier was "%s\n", call __builtin_puts(arg).  */
5034   if (strcmp (fmt_str, target_percent_s_newline) == 0)
5035     {
5036       if ((nargs != 2)
5037           || ! POINTER_TYPE_P (TREE_TYPE (CALL_EXPR_ARG (exp, 1))))
5038         return NULL_RTX;
5039       if (fn_puts)
5040         fn = build_call_nofold (fn_puts, 1, CALL_EXPR_ARG (exp, 1));
5041     }
5042   /* If the format specifier was "%c", call __builtin_putchar(arg).  */
5043   else if (strcmp (fmt_str, target_percent_c) == 0)
5044     {
5045       if ((nargs != 2)
5046           || TREE_CODE (TREE_TYPE (CALL_EXPR_ARG (exp, 1))) != INTEGER_TYPE)
5047         return NULL_RTX;
5048       if (fn_putchar)
5049         fn = build_call_nofold (fn_putchar, 1, CALL_EXPR_ARG (exp, 1));
5050     }
5051   else
5052     {
5053       /* We can't handle anything else with % args or %% ... yet.  */
5054       if (strchr (fmt_str, target_percent))
5055         return NULL_RTX;
5056
5057       if (nargs > 1)
5058         return NULL_RTX;
5059
5060       /* If the format specifier was "", printf does nothing.  */
5061       if (fmt_str[0] == '\0')
5062         return const0_rtx;
5063       /* If the format specifier has length of 1, call putchar.  */
5064       if (fmt_str[1] == '\0')
5065         {
5066           /* Given printf("c"), (where c is any one character,)
5067              convert "c"[0] to an int and pass that to the replacement
5068              function.  */
5069           arg = build_int_cst (NULL_TREE, fmt_str[0]);
5070           if (fn_putchar)
5071             fn = build_call_nofold (fn_putchar, 1, arg);
5072         }
5073       else
5074         {
5075           /* If the format specifier was "string\n", call puts("string").  */
5076           size_t len = strlen (fmt_str);
5077           if ((unsigned char)fmt_str[len - 1] == target_newline)
5078             {
5079               /* Create a NUL-terminated string that's one char shorter
5080                  than the original, stripping off the trailing '\n'.  */
5081               char *newstr = XALLOCAVEC (char, len);
5082               memcpy (newstr, fmt_str, len - 1);
5083               newstr[len - 1] = 0;
5084               arg = build_string_literal (len, newstr);
5085               if (fn_puts)
5086                 fn = build_call_nofold (fn_puts, 1, arg);
5087             }
5088           else
5089             /* We'd like to arrange to call fputs(string,stdout) here,
5090                but we need stdout and don't have a way to get it yet.  */
5091             return NULL_RTX;
5092         }
5093     }
5094
5095   if (!fn)
5096     return NULL_RTX;
5097   gcc_assert (TREE_CODE (fn) == CALL_EXPR);
5098   CALL_EXPR_TAILCALL (fn) = CALL_EXPR_TAILCALL (exp);
5099   return expand_expr (fn, target, mode, EXPAND_NORMAL);
5100 }
5101
5102 /* Expand EXP, a call to fprintf or fprintf_unlocked.
5103    Return NULL_RTX if a normal call should be emitted rather than transforming
5104    the function inline.  If convenient, the result should be placed in
5105    TARGET with mode MODE.  UNLOCKED indicates this is a fprintf_unlocked
5106    call.  */
5107 static rtx
5108 expand_builtin_fprintf (tree exp, rtx target, enum machine_mode mode,
5109                         bool unlocked)
5110 {
5111   /* If we're using an unlocked function, assume the other unlocked
5112      functions exist explicitly.  */
5113   tree const fn_fputc = unlocked ? built_in_decls[BUILT_IN_FPUTC_UNLOCKED]
5114     : implicit_built_in_decls[BUILT_IN_FPUTC];
5115   tree const fn_fputs = unlocked ? built_in_decls[BUILT_IN_FPUTS_UNLOCKED]
5116     : implicit_built_in_decls[BUILT_IN_FPUTS];
5117   const char *fmt_str;
5118   tree fn = 0;
5119   tree fmt, fp, arg;
5120   int nargs = call_expr_nargs (exp);
5121
5122   /* If the return value is used, don't do the transformation.  */
5123   if (target != const0_rtx)
5124     return NULL_RTX;
5125
5126   /* Verify the required arguments in the original call.  */
5127   if (nargs < 2)
5128     return NULL_RTX;
5129   fp = CALL_EXPR_ARG (exp, 0);
5130   if (! POINTER_TYPE_P (TREE_TYPE (fp)))
5131     return NULL_RTX;
5132   fmt = CALL_EXPR_ARG (exp, 1);
5133   if (! POINTER_TYPE_P (TREE_TYPE (fmt)))
5134     return NULL_RTX;
5135
5136   /* Check whether the format is a literal string constant.  */
5137   fmt_str = c_getstr (fmt);
5138   if (fmt_str == NULL)
5139     return NULL_RTX;
5140
5141   if (!init_target_chars ())
5142     return NULL_RTX;
5143
5144   /* If the format specifier was "%s", call __builtin_fputs(arg,fp).  */
5145   if (strcmp (fmt_str, target_percent_s) == 0)
5146     {
5147       if ((nargs != 3)
5148           || ! POINTER_TYPE_P (TREE_TYPE (CALL_EXPR_ARG (exp, 2))))
5149         return NULL_RTX;
5150       arg = CALL_EXPR_ARG (exp, 2);
5151       if (fn_fputs)
5152         fn = build_call_nofold (fn_fputs, 2, arg, fp);
5153     }
5154   /* If the format specifier was "%c", call __builtin_fputc(arg,fp).  */
5155   else if (strcmp (fmt_str, target_percent_c) == 0)
5156     {
5157       if ((nargs != 3)
5158           || TREE_CODE (TREE_TYPE (CALL_EXPR_ARG (exp, 2))) != INTEGER_TYPE)
5159         return NULL_RTX;
5160       arg = CALL_EXPR_ARG (exp, 2);
5161       if (fn_fputc)
5162         fn = build_call_nofold (fn_fputc, 2, arg, fp);
5163     }
5164   else
5165     {
5166       /* We can't handle anything else with % args or %% ... yet.  */
5167       if (strchr (fmt_str, target_percent))
5168         return NULL_RTX;
5169
5170       if (nargs > 2)
5171         return NULL_RTX;
5172
5173       /* If the format specifier was "", fprintf does nothing.  */
5174       if (fmt_str[0] == '\0')
5175         {
5176           /* Evaluate and ignore FILE* argument for side-effects.  */
5177           expand_expr (fp, const0_rtx, VOIDmode, EXPAND_NORMAL);
5178           return const0_rtx;
5179         }
5180
5181       /* When "string" doesn't contain %, replace all cases of
5182          fprintf(stream,string) with fputs(string,stream).  The fputs
5183          builtin will take care of special cases like length == 1.  */
5184       if (fn_fputs)
5185         fn = build_call_nofold (fn_fputs, 2, fmt, fp);
5186     }
5187
5188   if (!fn)
5189     return NULL_RTX;
5190   gcc_assert (TREE_CODE (fn) == CALL_EXPR);
5191   CALL_EXPR_TAILCALL (fn) = CALL_EXPR_TAILCALL (exp);
5192   return expand_expr (fn, target, mode, EXPAND_NORMAL);
5193 }
5194
5195 /* Expand a call EXP to sprintf.  Return NULL_RTX if
5196    a normal call should be emitted rather than expanding the function
5197    inline.  If convenient, the result should be placed in TARGET with
5198    mode MODE.  */
5199
5200 static rtx
5201 expand_builtin_sprintf (tree exp, rtx target, enum machine_mode mode)
5202 {
5203   tree dest, fmt;
5204   const char *fmt_str;
5205   int nargs = call_expr_nargs (exp);
5206
5207   /* Verify the required arguments in the original call.  */
5208   if (nargs < 2)
5209     return NULL_RTX;
5210   dest = CALL_EXPR_ARG (exp, 0);
5211   if (! POINTER_TYPE_P (TREE_TYPE (dest)))
5212     return NULL_RTX;
5213   fmt = CALL_EXPR_ARG (exp, 0);
5214   if (! POINTER_TYPE_P (TREE_TYPE (fmt)))
5215     return NULL_RTX;
5216
5217   /* Check whether the format is a literal string constant.  */
5218   fmt_str = c_getstr (fmt);
5219   if (fmt_str == NULL)
5220     return NULL_RTX;
5221
5222   if (!init_target_chars ())
5223     return NULL_RTX;
5224
5225   /* If the format doesn't contain % args or %%, use strcpy.  */
5226   if (strchr (fmt_str, target_percent) == 0)
5227     {
5228       tree fn = implicit_built_in_decls[BUILT_IN_STRCPY];
5229       tree exp;
5230
5231       if ((nargs > 2) || ! fn)
5232         return NULL_RTX;
5233       expand_expr (build_call_nofold (fn, 2, dest, fmt),
5234                    const0_rtx, VOIDmode, EXPAND_NORMAL);
5235       if (target == const0_rtx)
5236         return const0_rtx;
5237       exp = build_int_cst (NULL_TREE, strlen (fmt_str));
5238       return expand_expr (exp, target, mode, EXPAND_NORMAL);
5239     }
5240   /* If the format is "%s", use strcpy if the result isn't used.  */
5241   else if (strcmp (fmt_str, target_percent_s) == 0)
5242     {
5243       tree fn, arg, len;
5244       fn = implicit_built_in_decls[BUILT_IN_STRCPY];
5245
5246       if (! fn)
5247         return NULL_RTX;
5248       if (nargs != 3)
5249         return NULL_RTX;
5250       arg = CALL_EXPR_ARG (exp, 2);
5251       if (! POINTER_TYPE_P (TREE_TYPE (arg)))
5252         return NULL_RTX;
5253
5254       if (target != const0_rtx)
5255         {
5256           len = c_strlen (arg, 1);
5257           if (! len || TREE_CODE (len) != INTEGER_CST)
5258             return NULL_RTX;
5259         }
5260       else
5261         len = NULL_TREE;
5262
5263       expand_expr (build_call_nofold (fn, 2, dest, arg),
5264                    const0_rtx, VOIDmode, EXPAND_NORMAL);
5265
5266       if (target == const0_rtx)
5267         return const0_rtx;
5268       return expand_expr (len, target, mode, EXPAND_NORMAL);
5269     }
5270
5271   return NULL_RTX;
5272 }
5273
5274 /* Expand a call to either the entry or exit function profiler.  */
5275
5276 static rtx
5277 expand_builtin_profile_func (bool exitp)
5278 {
5279   rtx this_rtx, which;
5280
5281   this_rtx = DECL_RTL (current_function_decl);
5282   gcc_assert (MEM_P (this_rtx));
5283   this_rtx = XEXP (this_rtx, 0);
5284
5285   if (exitp)
5286     which = profile_function_exit_libfunc;
5287   else
5288     which = profile_function_entry_libfunc;
5289
5290   emit_library_call (which, LCT_NORMAL, VOIDmode, 2, this_rtx, Pmode,
5291                      expand_builtin_return_addr (BUILT_IN_RETURN_ADDRESS,
5292                                                  0),
5293                      Pmode);
5294
5295   return const0_rtx;
5296 }
5297
5298 /* Expand a call to __builtin___clear_cache.  */
5299
5300 static rtx
5301 expand_builtin___clear_cache (tree exp ATTRIBUTE_UNUSED)
5302 {
5303 #ifndef HAVE_clear_cache
5304 #ifdef CLEAR_INSN_CACHE
5305   /* There is no "clear_cache" insn, and __clear_cache() in libgcc
5306      does something.  Just do the default expansion to a call to
5307      __clear_cache().  */
5308   return NULL_RTX;
5309 #else
5310   /* There is no "clear_cache" insn, and __clear_cache() in libgcc
5311      does nothing.  There is no need to call it.  Do nothing.  */
5312   return const0_rtx;
5313 #endif /* CLEAR_INSN_CACHE */
5314 #else
5315   /* We have a "clear_cache" insn, and it will handle everything.  */
5316   tree begin, end;
5317   rtx begin_rtx, end_rtx;
5318   enum insn_code icode;
5319
5320   /* We must not expand to a library call.  If we did, any
5321      fallback library function in libgcc that might contain a call to
5322      __builtin___clear_cache() would recurse infinitely.  */
5323   if (!validate_arglist (exp, POINTER_TYPE, POINTER_TYPE, VOID_TYPE))
5324     {
5325       error ("both arguments to %<__builtin___clear_cache%> must be pointers");
5326       return const0_rtx;
5327     }
5328
5329   if (HAVE_clear_cache)
5330     {
5331       icode = CODE_FOR_clear_cache;
5332
5333       begin = CALL_EXPR_ARG (exp, 0);
5334       begin_rtx = expand_expr (begin, NULL_RTX, Pmode, EXPAND_NORMAL);
5335       begin_rtx = convert_memory_address (Pmode, begin_rtx);
5336       if (!insn_data[icode].operand[0].predicate (begin_rtx, Pmode))
5337         begin_rtx = copy_to_mode_reg (Pmode, begin_rtx);
5338
5339       end = CALL_EXPR_ARG (exp, 1);
5340       end_rtx = expand_expr (end, NULL_RTX, Pmode, EXPAND_NORMAL);
5341       end_rtx = convert_memory_address (Pmode, end_rtx);
5342       if (!insn_data[icode].operand[1].predicate (end_rtx, Pmode))
5343         end_rtx = copy_to_mode_reg (Pmode, end_rtx);
5344
5345       emit_insn (gen_clear_cache (begin_rtx, end_rtx));
5346     }
5347   return const0_rtx;
5348 #endif /* HAVE_clear_cache */
5349 }
5350
5351 /* Given a trampoline address, make sure it satisfies TRAMPOLINE_ALIGNMENT.  */
5352
5353 static rtx
5354 round_trampoline_addr (rtx tramp)
5355 {
5356   rtx temp, addend, mask;
5357
5358   /* If we don't need too much alignment, we'll have been guaranteed
5359      proper alignment by get_trampoline_type.  */
5360   if (TRAMPOLINE_ALIGNMENT <= STACK_BOUNDARY)
5361     return tramp;
5362
5363   /* Round address up to desired boundary.  */
5364   temp = gen_reg_rtx (Pmode);
5365   addend = GEN_INT (TRAMPOLINE_ALIGNMENT / BITS_PER_UNIT - 1);
5366   mask = GEN_INT (-TRAMPOLINE_ALIGNMENT / BITS_PER_UNIT);
5367
5368   temp  = expand_simple_binop (Pmode, PLUS, tramp, addend,
5369                                temp, 0, OPTAB_LIB_WIDEN);
5370   tramp = expand_simple_binop (Pmode, AND, temp, mask,
5371                                temp, 0, OPTAB_LIB_WIDEN);
5372
5373   return tramp;
5374 }
5375
5376 static rtx
5377 expand_builtin_init_trampoline (tree exp)
5378 {
5379   tree t_tramp, t_func, t_chain;
5380   rtx m_tramp, r_tramp, r_chain, tmp;
5381
5382   if (!validate_arglist (exp, POINTER_TYPE, POINTER_TYPE,
5383                          POINTER_TYPE, VOID_TYPE))
5384     return NULL_RTX;
5385
5386   t_tramp = CALL_EXPR_ARG (exp, 0);
5387   t_func = CALL_EXPR_ARG (exp, 1);
5388   t_chain = CALL_EXPR_ARG (exp, 2);
5389
5390   r_tramp = expand_normal (t_tramp);
5391   m_tramp = gen_rtx_MEM (BLKmode, r_tramp);
5392   MEM_NOTRAP_P (m_tramp) = 1;
5393
5394   /* The TRAMP argument should be the address of a field within the
5395      local function's FRAME decl.  Let's see if we can fill in the
5396      to fill in the MEM_ATTRs for this memory.  */
5397   if (TREE_CODE (t_tramp) == ADDR_EXPR)
5398     set_mem_attributes_minus_bitpos (m_tramp, TREE_OPERAND (t_tramp, 0),
5399                                      true, 0);
5400
5401   tmp = round_trampoline_addr (r_tramp);
5402   if (tmp != r_tramp)
5403     {
5404       m_tramp = change_address (m_tramp, BLKmode, tmp);
5405       set_mem_align (m_tramp, TRAMPOLINE_ALIGNMENT);
5406       set_mem_size (m_tramp, GEN_INT (TRAMPOLINE_SIZE));
5407     }
5408
5409   /* The FUNC argument should be the address of the nested function.
5410      Extract the actual function decl to pass to the hook.  */
5411   gcc_assert (TREE_CODE (t_func) == ADDR_EXPR);
5412   t_func = TREE_OPERAND (t_func, 0);
5413   gcc_assert (TREE_CODE (t_func) == FUNCTION_DECL);
5414
5415   r_chain = expand_normal (t_chain);
5416
5417   /* Generate insns to initialize the trampoline.  */
5418   targetm.calls.trampoline_init (m_tramp, t_func, r_chain);
5419
5420   trampolines_created = 1;
5421   return const0_rtx;
5422 }
5423
5424 static rtx
5425 expand_builtin_adjust_trampoline (tree exp)
5426 {
5427   rtx tramp;
5428
5429   if (!validate_arglist (exp, POINTER_TYPE, VOID_TYPE))
5430     return NULL_RTX;
5431
5432   tramp = expand_normal (CALL_EXPR_ARG (exp, 0));
5433   tramp = round_trampoline_addr (tramp);
5434   if (targetm.calls.trampoline_adjust_address)
5435     tramp = targetm.calls.trampoline_adjust_address (tramp);
5436
5437   return tramp;
5438 }
5439
5440 /* Expand the call EXP to the built-in signbit, signbitf or signbitl
5441    function.  The function first checks whether the back end provides
5442    an insn to implement signbit for the respective mode.  If not, it
5443    checks whether the floating point format of the value is such that
5444    the sign bit can be extracted.  If that is not the case, the
5445    function returns NULL_RTX to indicate that a normal call should be
5446    emitted rather than expanding the function in-line.  EXP is the
5447    expression that is a call to the builtin function; if convenient,
5448    the result should be placed in TARGET.  */
5449 static rtx
5450 expand_builtin_signbit (tree exp, rtx target)
5451 {
5452   const struct real_format *fmt;
5453   enum machine_mode fmode, imode, rmode;
5454   HOST_WIDE_INT hi, lo;
5455   tree arg;
5456   int word, bitpos;
5457   enum insn_code icode;
5458   rtx temp;
5459   location_t loc = EXPR_LOCATION (exp);
5460
5461   if (!validate_arglist (exp, REAL_TYPE, VOID_TYPE))
5462     return NULL_RTX;
5463
5464   arg = CALL_EXPR_ARG (exp, 0);
5465   fmode = TYPE_MODE (TREE_TYPE (arg));
5466   rmode = TYPE_MODE (TREE_TYPE (exp));
5467   fmt = REAL_MODE_FORMAT (fmode);
5468
5469   arg = builtin_save_expr (arg);
5470
5471   /* Expand the argument yielding a RTX expression. */
5472   temp = expand_normal (arg);
5473
5474   /* Check if the back end provides an insn that handles signbit for the
5475      argument's mode. */
5476   icode = signbit_optab->handlers [(int) fmode].insn_code;
5477   if (icode != CODE_FOR_nothing)
5478     {
5479       target = gen_reg_rtx (TYPE_MODE (TREE_TYPE (exp)));
5480       emit_unop_insn (icode, target, temp, UNKNOWN);
5481       return target;
5482     }
5483
5484   /* For floating point formats without a sign bit, implement signbit
5485      as "ARG < 0.0".  */
5486   bitpos = fmt->signbit_ro;
5487   if (bitpos < 0)
5488   {
5489     /* But we can't do this if the format supports signed zero.  */
5490     if (fmt->has_signed_zero && HONOR_SIGNED_ZEROS (fmode))
5491       return NULL_RTX;
5492
5493     arg = fold_build2_loc (loc, LT_EXPR, TREE_TYPE (exp), arg,
5494                        build_real (TREE_TYPE (arg), dconst0));
5495     return expand_expr (arg, target, VOIDmode, EXPAND_NORMAL);
5496   }
5497
5498   if (GET_MODE_SIZE (fmode) <= UNITS_PER_WORD)
5499     {
5500       imode = int_mode_for_mode (fmode);
5501       if (imode == BLKmode)
5502         return NULL_RTX;
5503       temp = gen_lowpart (imode, temp);
5504     }
5505   else
5506     {
5507       imode = word_mode;
5508       /* Handle targets with different FP word orders.  */
5509       if (FLOAT_WORDS_BIG_ENDIAN)
5510         word = (GET_MODE_BITSIZE (fmode) - bitpos) / BITS_PER_WORD;
5511       else
5512         word = bitpos / BITS_PER_WORD;
5513       temp = operand_subword_force (temp, word, fmode);
5514       bitpos = bitpos % BITS_PER_WORD;
5515     }
5516
5517   /* Force the intermediate word_mode (or narrower) result into a
5518      register.  This avoids attempting to create paradoxical SUBREGs
5519      of floating point modes below.  */
5520   temp = force_reg (imode, temp);
5521
5522   /* If the bitpos is within the "result mode" lowpart, the operation
5523      can be implement with a single bitwise AND.  Otherwise, we need
5524      a right shift and an AND.  */
5525
5526   if (bitpos < GET_MODE_BITSIZE (rmode))
5527     {
5528       if (bitpos < HOST_BITS_PER_WIDE_INT)
5529         {
5530           hi = 0;
5531           lo = (HOST_WIDE_INT) 1 << bitpos;
5532         }
5533       else
5534         {
5535           hi = (HOST_WIDE_INT) 1 << (bitpos - HOST_BITS_PER_WIDE_INT);
5536           lo = 0;
5537         }
5538
5539       if (GET_MODE_SIZE (imode) > GET_MODE_SIZE (rmode))
5540         temp = gen_lowpart (rmode, temp);
5541       temp = expand_binop (rmode, and_optab, temp,
5542                            immed_double_const (lo, hi, rmode),
5543                            NULL_RTX, 1, OPTAB_LIB_WIDEN);
5544     }
5545   else
5546     {
5547       /* Perform a logical right shift to place the signbit in the least
5548          significant bit, then truncate the result to the desired mode
5549          and mask just this bit.  */
5550       temp = expand_shift (RSHIFT_EXPR, imode, temp,
5551                            build_int_cst (NULL_TREE, bitpos), NULL_RTX, 1);
5552       temp = gen_lowpart (rmode, temp);
5553       temp = expand_binop (rmode, and_optab, temp, const1_rtx,
5554                            NULL_RTX, 1, OPTAB_LIB_WIDEN);
5555     }
5556
5557   return temp;
5558 }
5559
5560 /* Expand fork or exec calls.  TARGET is the desired target of the
5561    call.  EXP is the call. FN is the
5562    identificator of the actual function.  IGNORE is nonzero if the
5563    value is to be ignored.  */
5564
5565 static rtx
5566 expand_builtin_fork_or_exec (tree fn, tree exp, rtx target, int ignore)
5567 {
5568   tree id, decl;
5569   tree call;
5570
5571   /* If we are not profiling, just call the function.  */
5572   if (!profile_arc_flag)
5573     return NULL_RTX;
5574
5575   /* Otherwise call the wrapper.  This should be equivalent for the rest of
5576      compiler, so the code does not diverge, and the wrapper may run the
5577      code necessary for keeping the profiling sane.  */
5578
5579   switch (DECL_FUNCTION_CODE (fn))
5580     {
5581     case BUILT_IN_FORK:
5582       id = get_identifier ("__gcov_fork");
5583       break;
5584
5585     case BUILT_IN_EXECL:
5586       id = get_identifier ("__gcov_execl");
5587       break;
5588
5589     case BUILT_IN_EXECV:
5590       id = get_identifier ("__gcov_execv");
5591       break;
5592
5593     case BUILT_IN_EXECLP:
5594       id = get_identifier ("__gcov_execlp");
5595       break;
5596
5597     case BUILT_IN_EXECLE:
5598       id = get_identifier ("__gcov_execle");
5599       break;
5600
5601     case BUILT_IN_EXECVP:
5602       id = get_identifier ("__gcov_execvp");
5603       break;
5604
5605     case BUILT_IN_EXECVE:
5606       id = get_identifier ("__gcov_execve");
5607       break;
5608
5609     default:
5610       gcc_unreachable ();
5611     }
5612
5613   decl = build_decl (DECL_SOURCE_LOCATION (fn),
5614                      FUNCTION_DECL, id, TREE_TYPE (fn));
5615   DECL_EXTERNAL (decl) = 1;
5616   TREE_PUBLIC (decl) = 1;
5617   DECL_ARTIFICIAL (decl) = 1;
5618   TREE_NOTHROW (decl) = 1;
5619   DECL_VISIBILITY (decl) = VISIBILITY_DEFAULT;
5620   DECL_VISIBILITY_SPECIFIED (decl) = 1;
5621   call = rewrite_call_expr (EXPR_LOCATION (exp), exp, 0, decl, 0);
5622   return expand_call (call, target, ignore);
5623  }
5624   
5625
5626 \f
5627 /* Reconstitute a mode for a __sync intrinsic operation.  Since the type of
5628    the pointer in these functions is void*, the tree optimizers may remove
5629    casts.  The mode computed in expand_builtin isn't reliable either, due
5630    to __sync_bool_compare_and_swap.
5631
5632    FCODE_DIFF should be fcode - base, where base is the FOO_1 code for the
5633    group of builtins.  This gives us log2 of the mode size.  */
5634
5635 static inline enum machine_mode
5636 get_builtin_sync_mode (int fcode_diff)
5637 {
5638   /* The size is not negotiable, so ask not to get BLKmode in return
5639      if the target indicates that a smaller size would be better.  */
5640   return mode_for_size (BITS_PER_UNIT << fcode_diff, MODE_INT, 0);
5641 }
5642
5643 /* Expand the memory expression LOC and return the appropriate memory operand
5644    for the builtin_sync operations.  */
5645
5646 static rtx
5647 get_builtin_sync_mem (tree loc, enum machine_mode mode)
5648 {
5649   rtx addr, mem;
5650
5651   addr = expand_expr (loc, NULL_RTX, ptr_mode, EXPAND_SUM);
5652   addr = convert_memory_address (Pmode, addr);
5653
5654   /* Note that we explicitly do not want any alias information for this
5655      memory, so that we kill all other live memories.  Otherwise we don't
5656      satisfy the full barrier semantics of the intrinsic.  */
5657   mem = validize_mem (gen_rtx_MEM (mode, addr));
5658
5659   set_mem_align (mem, get_pointer_alignment (loc, BIGGEST_ALIGNMENT));
5660   set_mem_alias_set (mem, ALIAS_SET_MEMORY_BARRIER);
5661   MEM_VOLATILE_P (mem) = 1;
5662
5663   return mem;
5664 }
5665
5666 /* Expand the __sync_xxx_and_fetch and __sync_fetch_and_xxx intrinsics.
5667    EXP is the CALL_EXPR.  CODE is the rtx code
5668    that corresponds to the arithmetic or logical operation from the name;
5669    an exception here is that NOT actually means NAND.  TARGET is an optional
5670    place for us to store the results; AFTER is true if this is the
5671    fetch_and_xxx form.  IGNORE is true if we don't actually care about
5672    the result of the operation at all.  */
5673
5674 static rtx
5675 expand_builtin_sync_operation (enum machine_mode mode, tree exp,
5676                                enum rtx_code code, bool after,
5677                                rtx target, bool ignore)
5678 {
5679   rtx val, mem;
5680   enum machine_mode old_mode;
5681   location_t loc = EXPR_LOCATION (exp);
5682
5683   if (code == NOT && warn_sync_nand)
5684     {
5685       tree fndecl = get_callee_fndecl (exp);
5686       enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
5687
5688       static bool warned_f_a_n, warned_n_a_f;
5689
5690       switch (fcode)
5691         {
5692         case BUILT_IN_FETCH_AND_NAND_1:
5693         case BUILT_IN_FETCH_AND_NAND_2:
5694         case BUILT_IN_FETCH_AND_NAND_4:
5695         case BUILT_IN_FETCH_AND_NAND_8:
5696         case BUILT_IN_FETCH_AND_NAND_16:
5697
5698           if (warned_f_a_n)
5699             break;
5700
5701           fndecl = implicit_built_in_decls[BUILT_IN_FETCH_AND_NAND_N];
5702           inform (loc, "%qD changed semantics in GCC 4.4", fndecl);
5703           warned_f_a_n = true;
5704           break;
5705
5706         case BUILT_IN_NAND_AND_FETCH_1:
5707         case BUILT_IN_NAND_AND_FETCH_2:
5708         case BUILT_IN_NAND_AND_FETCH_4:
5709         case BUILT_IN_NAND_AND_FETCH_8:
5710         case BUILT_IN_NAND_AND_FETCH_16:
5711
5712           if (warned_n_a_f)
5713             break;
5714
5715           fndecl = implicit_built_in_decls[BUILT_IN_NAND_AND_FETCH_N];
5716           inform (loc, "%qD changed semantics in GCC 4.4", fndecl);
5717           warned_n_a_f = true;
5718           break;
5719
5720         default:
5721           gcc_unreachable ();
5722         }
5723     }
5724
5725   /* Expand the operands.  */
5726   mem = get_builtin_sync_mem (CALL_EXPR_ARG (exp, 0), mode);
5727
5728   val = expand_expr (CALL_EXPR_ARG (exp, 1), NULL_RTX, mode, EXPAND_NORMAL);
5729   /* If VAL is promoted to a wider mode, convert it back to MODE.  Take care
5730      of CONST_INTs, where we know the old_mode only from the call argument.  */
5731   old_mode = GET_MODE (val);
5732   if (old_mode == VOIDmode)
5733     old_mode = TYPE_MODE (TREE_TYPE (CALL_EXPR_ARG (exp, 1)));
5734   val = convert_modes (mode, old_mode, val, 1);
5735
5736   if (ignore)
5737     return expand_sync_operation (mem, val, code);
5738   else
5739     return expand_sync_fetch_operation (mem, val, code, after, target);
5740 }
5741
5742 /* Expand the __sync_val_compare_and_swap and __sync_bool_compare_and_swap
5743    intrinsics. EXP is the CALL_EXPR.  IS_BOOL is
5744    true if this is the boolean form.  TARGET is a place for us to store the
5745    results; this is NOT optional if IS_BOOL is true.  */
5746
5747 static rtx
5748 expand_builtin_compare_and_swap (enum machine_mode mode, tree exp,
5749                                  bool is_bool, rtx target)
5750 {
5751   rtx old_val, new_val, mem;
5752   enum machine_mode old_mode;
5753
5754   /* Expand the operands.  */
5755   mem = get_builtin_sync_mem (CALL_EXPR_ARG (exp, 0), mode);
5756
5757
5758   old_val = expand_expr (CALL_EXPR_ARG (exp, 1), NULL_RTX,
5759                          mode, EXPAND_NORMAL);
5760   /* If VAL is promoted to a wider mode, convert it back to MODE.  Take care
5761      of CONST_INTs, where we know the old_mode only from the call argument.  */
5762   old_mode = GET_MODE (old_val);
5763   if (old_mode == VOIDmode)
5764     old_mode = TYPE_MODE (TREE_TYPE (CALL_EXPR_ARG (exp, 1)));
5765   old_val = convert_modes (mode, old_mode, old_val, 1);
5766
5767   new_val = expand_expr (CALL_EXPR_ARG (exp, 2), NULL_RTX,
5768                          mode, EXPAND_NORMAL);
5769   /* If VAL is promoted to a wider mode, convert it back to MODE.  Take care
5770      of CONST_INTs, where we know the old_mode only from the call argument.  */
5771   old_mode = GET_MODE (new_val);
5772   if (old_mode == VOIDmode)
5773     old_mode = TYPE_MODE (TREE_TYPE (CALL_EXPR_ARG (exp, 2)));
5774   new_val = convert_modes (mode, old_mode, new_val, 1);
5775
5776   if (is_bool)
5777     return expand_bool_compare_and_swap (mem, old_val, new_val, target);
5778   else
5779     return expand_val_compare_and_swap (mem, old_val, new_val, target);
5780 }
5781
5782 /* Expand the __sync_lock_test_and_set intrinsic.  Note that the most
5783    general form is actually an atomic exchange, and some targets only
5784    support a reduced form with the second argument being a constant 1.
5785    EXP is the CALL_EXPR; TARGET is an optional place for us to store 
5786    the results.  */
5787
5788 static rtx
5789 expand_builtin_lock_test_and_set (enum machine_mode mode, tree exp,
5790                                   rtx target)
5791 {
5792   rtx val, mem;
5793   enum machine_mode old_mode;
5794
5795   /* Expand the operands.  */
5796   mem = get_builtin_sync_mem (CALL_EXPR_ARG (exp, 0), mode);
5797   val = expand_expr (CALL_EXPR_ARG (exp, 1), NULL_RTX, mode, EXPAND_NORMAL);
5798   /* If VAL is promoted to a wider mode, convert it back to MODE.  Take care
5799      of CONST_INTs, where we know the old_mode only from the call argument.  */
5800   old_mode = GET_MODE (val);
5801   if (old_mode == VOIDmode)
5802     old_mode = TYPE_MODE (TREE_TYPE (CALL_EXPR_ARG (exp, 1)));
5803   val = convert_modes (mode, old_mode, val, 1);
5804
5805   return expand_sync_lock_test_and_set (mem, val, target);
5806 }
5807
5808 /* Expand the __sync_synchronize intrinsic.  */
5809
5810 static void
5811 expand_builtin_synchronize (void)
5812 {
5813   gimple x;
5814   VEC (tree, gc) *v_clobbers;
5815
5816 #ifdef HAVE_memory_barrier
5817   if (HAVE_memory_barrier)
5818     {
5819       emit_insn (gen_memory_barrier ());
5820       return;
5821     }
5822 #endif
5823
5824   if (synchronize_libfunc != NULL_RTX)
5825     {
5826       emit_library_call (synchronize_libfunc, LCT_NORMAL, VOIDmode, 0);
5827       return;
5828     }
5829
5830   /* If no explicit memory barrier instruction is available, create an
5831      empty asm stmt with a memory clobber.  */
5832   v_clobbers = VEC_alloc (tree, gc, 1);
5833   VEC_quick_push (tree, v_clobbers,
5834                   tree_cons (NULL, build_string (6, "memory"), NULL));
5835   x = gimple_build_asm_vec ("", NULL, NULL, v_clobbers, NULL);
5836   gimple_asm_set_volatile (x, true);
5837   expand_asm_stmt (x);
5838 }
5839
5840 /* Expand the __sync_lock_release intrinsic.  EXP is the CALL_EXPR.  */
5841
5842 static void
5843 expand_builtin_lock_release (enum machine_mode mode, tree exp)
5844 {
5845   enum insn_code icode;
5846   rtx mem, insn;
5847   rtx val = const0_rtx;
5848
5849   /* Expand the operands.  */
5850   mem = get_builtin_sync_mem (CALL_EXPR_ARG (exp, 0), mode);
5851
5852   /* If there is an explicit operation in the md file, use it.  */
5853   icode = sync_lock_release[mode];
5854   if (icode != CODE_FOR_nothing)
5855     {
5856       if (!insn_data[icode].operand[1].predicate (val, mode))
5857         val = force_reg (mode, val);
5858
5859       insn = GEN_FCN (icode) (mem, val);
5860       if (insn)
5861         {
5862           emit_insn (insn);
5863           return;
5864         }
5865     }
5866
5867   /* Otherwise we can implement this operation by emitting a barrier
5868      followed by a store of zero.  */
5869   expand_builtin_synchronize ();
5870   emit_move_insn (mem, val);
5871 }
5872 \f
5873 /* Expand an expression EXP that calls a built-in function,
5874    with result going to TARGET if that's convenient
5875    (and in mode MODE if that's convenient).
5876    SUBTARGET may be used as the target for computing one of EXP's operands.
5877    IGNORE is nonzero if the value is to be ignored.  */
5878
5879 rtx
5880 expand_builtin (tree exp, rtx target, rtx subtarget, enum machine_mode mode,
5881                 int ignore)
5882 {
5883   tree fndecl = get_callee_fndecl (exp);
5884   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
5885   enum machine_mode target_mode = TYPE_MODE (TREE_TYPE (exp));
5886
5887   if (DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_MD)
5888     return targetm.expand_builtin (exp, target, subtarget, mode, ignore);
5889
5890   /* When not optimizing, generate calls to library functions for a certain
5891      set of builtins.  */
5892   if (!optimize
5893       && !called_as_built_in (fndecl)
5894       && DECL_ASSEMBLER_NAME_SET_P (fndecl)
5895       && fcode != BUILT_IN_ALLOCA
5896       && fcode != BUILT_IN_FREE)
5897     return expand_call (exp, target, ignore);
5898
5899   /* The built-in function expanders test for target == const0_rtx
5900      to determine whether the function's result will be ignored.  */
5901   if (ignore)
5902     target = const0_rtx;
5903
5904   /* If the result of a pure or const built-in function is ignored, and
5905      none of its arguments are volatile, we can avoid expanding the
5906      built-in call and just evaluate the arguments for side-effects.  */
5907   if (target == const0_rtx
5908       && (DECL_PURE_P (fndecl) || TREE_READONLY (fndecl)))
5909     {
5910       bool volatilep = false;
5911       tree arg;
5912       call_expr_arg_iterator iter;
5913
5914       FOR_EACH_CALL_EXPR_ARG (arg, iter, exp)
5915         if (TREE_THIS_VOLATILE (arg))
5916           {
5917             volatilep = true;
5918             break;
5919           }
5920
5921       if (! volatilep)
5922         {
5923           FOR_EACH_CALL_EXPR_ARG (arg, iter, exp)
5924             expand_expr (arg, const0_rtx, VOIDmode, EXPAND_NORMAL);
5925           return const0_rtx;
5926         }
5927     }
5928
5929   switch (fcode)
5930     {
5931     CASE_FLT_FN (BUILT_IN_FABS):
5932       target = expand_builtin_fabs (exp, target, subtarget);
5933       if (target)
5934         return target;
5935       break;
5936
5937     CASE_FLT_FN (BUILT_IN_COPYSIGN):
5938       target = expand_builtin_copysign (exp, target, subtarget);
5939       if (target)
5940         return target;
5941       break;
5942
5943       /* Just do a normal library call if we were unable to fold
5944          the values.  */
5945     CASE_FLT_FN (BUILT_IN_CABS):
5946       break;
5947
5948     CASE_FLT_FN (BUILT_IN_EXP):
5949     CASE_FLT_FN (BUILT_IN_EXP10):
5950     CASE_FLT_FN (BUILT_IN_POW10):
5951     CASE_FLT_FN (BUILT_IN_EXP2):
5952     CASE_FLT_FN (BUILT_IN_EXPM1):
5953     CASE_FLT_FN (BUILT_IN_LOGB):
5954     CASE_FLT_FN (BUILT_IN_LOG):
5955     CASE_FLT_FN (BUILT_IN_LOG10):
5956     CASE_FLT_FN (BUILT_IN_LOG2):
5957     CASE_FLT_FN (BUILT_IN_LOG1P):
5958     CASE_FLT_FN (BUILT_IN_TAN):
5959     CASE_FLT_FN (BUILT_IN_ASIN):
5960     CASE_FLT_FN (BUILT_IN_ACOS):
5961     CASE_FLT_FN (BUILT_IN_ATAN):
5962     CASE_FLT_FN (BUILT_IN_SIGNIFICAND):
5963       /* Treat these like sqrt only if unsafe math optimizations are allowed,
5964          because of possible accuracy problems.  */
5965       if (! flag_unsafe_math_optimizations)
5966         break;
5967     CASE_FLT_FN (BUILT_IN_SQRT):
5968     CASE_FLT_FN (BUILT_IN_FLOOR):
5969     CASE_FLT_FN (BUILT_IN_CEIL):
5970     CASE_FLT_FN (BUILT_IN_TRUNC):
5971     CASE_FLT_FN (BUILT_IN_ROUND):
5972     CASE_FLT_FN (BUILT_IN_NEARBYINT):
5973     CASE_FLT_FN (BUILT_IN_RINT):
5974       target = expand_builtin_mathfn (exp, target, subtarget);
5975       if (target)
5976         return target;
5977       break;
5978
5979     CASE_FLT_FN (BUILT_IN_ILOGB):
5980       if (! flag_unsafe_math_optimizations)
5981         break;
5982     CASE_FLT_FN (BUILT_IN_ISINF):
5983     CASE_FLT_FN (BUILT_IN_FINITE):
5984     case BUILT_IN_ISFINITE:
5985     case BUILT_IN_ISNORMAL:
5986       target = expand_builtin_interclass_mathfn (exp, target, subtarget);
5987       if (target)
5988         return target;
5989       break;
5990
5991     CASE_FLT_FN (BUILT_IN_LCEIL):
5992     CASE_FLT_FN (BUILT_IN_LLCEIL):
5993     CASE_FLT_FN (BUILT_IN_LFLOOR):
5994     CASE_FLT_FN (BUILT_IN_LLFLOOR):
5995       target = expand_builtin_int_roundingfn (exp, target);
5996       if (target)
5997         return target;
5998       break;
5999
6000     CASE_FLT_FN (BUILT_IN_LRINT):
6001     CASE_FLT_FN (BUILT_IN_LLRINT):
6002     CASE_FLT_FN (BUILT_IN_LROUND):
6003     CASE_FLT_FN (BUILT_IN_LLROUND):
6004       target = expand_builtin_int_roundingfn_2 (exp, target);
6005       if (target)
6006         return target;
6007       break;
6008
6009     CASE_FLT_FN (BUILT_IN_POW):
6010       target = expand_builtin_pow (exp, target, subtarget);
6011       if (target)
6012         return target;
6013       break;
6014
6015     CASE_FLT_FN (BUILT_IN_POWI):
6016       target = expand_builtin_powi (exp, target, subtarget);
6017       if (target)
6018         return target;
6019       break;
6020
6021     CASE_FLT_FN (BUILT_IN_ATAN2):
6022     CASE_FLT_FN (BUILT_IN_LDEXP):
6023     CASE_FLT_FN (BUILT_IN_SCALB):
6024     CASE_FLT_FN (BUILT_IN_SCALBN):
6025     CASE_FLT_FN (BUILT_IN_SCALBLN):
6026       if (! flag_unsafe_math_optimizations)
6027         break;
6028
6029     CASE_FLT_FN (BUILT_IN_FMOD):
6030     CASE_FLT_FN (BUILT_IN_REMAINDER):
6031     CASE_FLT_FN (BUILT_IN_DREM):
6032       target = expand_builtin_mathfn_2 (exp, target, subtarget);
6033       if (target)
6034         return target;
6035       break;
6036
6037     CASE_FLT_FN (BUILT_IN_CEXPI):
6038       target = expand_builtin_cexpi (exp, target, subtarget);
6039       gcc_assert (target);
6040       return target;
6041
6042     CASE_FLT_FN (BUILT_IN_SIN):
6043     CASE_FLT_FN (BUILT_IN_COS):
6044       if (! flag_unsafe_math_optimizations)
6045         break;
6046       target = expand_builtin_mathfn_3 (exp, target, subtarget);
6047       if (target)
6048         return target;
6049       break;
6050
6051     CASE_FLT_FN (BUILT_IN_SINCOS):
6052       if (! flag_unsafe_math_optimizations)
6053         break;
6054       target = expand_builtin_sincos (exp);
6055       if (target)
6056         return target;
6057       break;
6058
6059     case BUILT_IN_APPLY_ARGS:
6060       return expand_builtin_apply_args ();
6061
6062       /* __builtin_apply (FUNCTION, ARGUMENTS, ARGSIZE) invokes
6063          FUNCTION with a copy of the parameters described by
6064          ARGUMENTS, and ARGSIZE.  It returns a block of memory
6065          allocated on the stack into which is stored all the registers
6066          that might possibly be used for returning the result of a
6067          function.  ARGUMENTS is the value returned by
6068          __builtin_apply_args.  ARGSIZE is the number of bytes of
6069          arguments that must be copied.  ??? How should this value be
6070          computed?  We'll also need a safe worst case value for varargs
6071          functions.  */
6072     case BUILT_IN_APPLY:
6073       if (!validate_arglist (exp, POINTER_TYPE,
6074                              POINTER_TYPE, INTEGER_TYPE, VOID_TYPE)
6075           && !validate_arglist (exp, REFERENCE_TYPE,
6076                                 POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
6077         return const0_rtx;
6078       else
6079         {
6080           rtx ops[3];
6081
6082           ops[0] = expand_normal (CALL_EXPR_ARG (exp, 0));
6083           ops[1] = expand_normal (CALL_EXPR_ARG (exp, 1));
6084           ops[2] = expand_normal (CALL_EXPR_ARG (exp, 2));
6085
6086           return expand_builtin_apply (ops[0], ops[1], ops[2]);
6087         }
6088
6089       /* __builtin_return (RESULT) causes the function to return the
6090          value described by RESULT.  RESULT is address of the block of
6091          memory returned by __builtin_apply.  */
6092     case BUILT_IN_RETURN:
6093       if (validate_arglist (exp, POINTER_TYPE, VOID_TYPE))
6094         expand_builtin_return (expand_normal (CALL_EXPR_ARG (exp, 0)));
6095       return const0_rtx;
6096
6097     case BUILT_IN_SAVEREGS:
6098       return expand_builtin_saveregs ();
6099
6100     case BUILT_IN_ARGS_INFO:
6101       return expand_builtin_args_info (exp);
6102
6103     case BUILT_IN_VA_ARG_PACK:
6104       /* All valid uses of __builtin_va_arg_pack () are removed during
6105          inlining.  */
6106       error ("%Kinvalid use of %<__builtin_va_arg_pack ()%>", exp);
6107       return const0_rtx;
6108
6109     case BUILT_IN_VA_ARG_PACK_LEN:
6110       /* All valid uses of __builtin_va_arg_pack_len () are removed during
6111          inlining.  */
6112       error ("%Kinvalid use of %<__builtin_va_arg_pack_len ()%>", exp);
6113       return const0_rtx;
6114
6115       /* Return the address of the first anonymous stack arg.  */
6116     case BUILT_IN_NEXT_ARG:
6117       if (fold_builtin_next_arg (exp, false))
6118         return const0_rtx;
6119       return expand_builtin_next_arg ();
6120
6121     case BUILT_IN_CLEAR_CACHE:
6122       target = expand_builtin___clear_cache (exp);
6123       if (target)
6124         return target;
6125       break;
6126
6127     case BUILT_IN_CLASSIFY_TYPE:
6128       return expand_builtin_classify_type (exp);
6129
6130     case BUILT_IN_CONSTANT_P:
6131       return const0_rtx;
6132
6133     case BUILT_IN_FRAME_ADDRESS:
6134     case BUILT_IN_RETURN_ADDRESS:
6135       return expand_builtin_frame_address (fndecl, exp);
6136
6137     /* Returns the address of the area where the structure is returned.
6138        0 otherwise.  */
6139     case BUILT_IN_AGGREGATE_INCOMING_ADDRESS:
6140       if (call_expr_nargs (exp) != 0
6141           || ! AGGREGATE_TYPE_P (TREE_TYPE (TREE_TYPE (current_function_decl)))
6142           || !MEM_P (DECL_RTL (DECL_RESULT (current_function_decl))))
6143         return const0_rtx;
6144       else
6145         return XEXP (DECL_RTL (DECL_RESULT (current_function_decl)), 0);
6146
6147     case BUILT_IN_ALLOCA:
6148       target = expand_builtin_alloca (exp, target);
6149       if (target)
6150         return target;
6151       break;
6152
6153     case BUILT_IN_STACK_SAVE:
6154       return expand_stack_save ();
6155
6156     case BUILT_IN_STACK_RESTORE:
6157       expand_stack_restore (CALL_EXPR_ARG (exp, 0));
6158       return const0_rtx;
6159
6160     case BUILT_IN_BSWAP32:
6161     case BUILT_IN_BSWAP64:
6162       target = expand_builtin_bswap (exp, target, subtarget);
6163
6164       if (target)
6165         return target;
6166       break;
6167
6168     CASE_INT_FN (BUILT_IN_FFS):
6169     case BUILT_IN_FFSIMAX:
6170       target = expand_builtin_unop (target_mode, exp, target,
6171                                     subtarget, ffs_optab);
6172       if (target)
6173         return target;
6174       break;
6175
6176     CASE_INT_FN (BUILT_IN_CLZ):
6177     case BUILT_IN_CLZIMAX:
6178       target = expand_builtin_unop (target_mode, exp, target,
6179                                     subtarget, clz_optab);
6180       if (target)
6181         return target;
6182       break;
6183
6184     CASE_INT_FN (BUILT_IN_CTZ):
6185     case BUILT_IN_CTZIMAX:
6186       target = expand_builtin_unop (target_mode, exp, target,
6187                                     subtarget, ctz_optab);
6188       if (target)
6189         return target;
6190       break;
6191
6192     CASE_INT_FN (BUILT_IN_POPCOUNT):
6193     case BUILT_IN_POPCOUNTIMAX:
6194       target = expand_builtin_unop (target_mode, exp, target,
6195                                     subtarget, popcount_optab);
6196       if (target)
6197         return target;
6198       break;
6199
6200     CASE_INT_FN (BUILT_IN_PARITY):
6201     case BUILT_IN_PARITYIMAX:
6202       target = expand_builtin_unop (target_mode, exp, target,
6203                                     subtarget, parity_optab);
6204       if (target)
6205         return target;
6206       break;
6207
6208     case BUILT_IN_STRLEN:
6209       target = expand_builtin_strlen (exp, target, target_mode);
6210       if (target)
6211         return target;
6212       break;
6213
6214     case BUILT_IN_STRCPY:
6215       target = expand_builtin_strcpy (exp, target);
6216       if (target)
6217         return target;
6218       break;
6219
6220     case BUILT_IN_STRNCPY:
6221       target = expand_builtin_strncpy (exp, target);
6222       if (target)
6223         return target;
6224       break;
6225
6226     case BUILT_IN_STPCPY:
6227       target = expand_builtin_stpcpy (exp, target, mode);
6228       if (target)
6229         return target;
6230       break;
6231
6232     case BUILT_IN_MEMCPY:
6233       target = expand_builtin_memcpy (exp, target);
6234       if (target)
6235         return target;
6236       break;
6237
6238     case BUILT_IN_MEMPCPY:
6239       target = expand_builtin_mempcpy (exp, target, mode);
6240       if (target)
6241         return target;
6242       break;
6243
6244     case BUILT_IN_MEMSET:
6245       target = expand_builtin_memset (exp, target, mode);
6246       if (target)
6247         return target;
6248       break;
6249
6250     case BUILT_IN_BZERO:
6251       target = expand_builtin_bzero (exp);
6252       if (target)
6253         return target;
6254       break;
6255
6256     case BUILT_IN_STRCMP:
6257       target = expand_builtin_strcmp (exp, target);
6258       if (target)
6259         return target;
6260       break;
6261
6262     case BUILT_IN_STRNCMP:
6263       target = expand_builtin_strncmp (exp, target, mode);
6264       if (target)
6265         return target;
6266       break;
6267
6268     case BUILT_IN_BCMP:
6269     case BUILT_IN_MEMCMP:
6270       target = expand_builtin_memcmp (exp, target, mode);
6271       if (target)
6272         return target;
6273       break;
6274
6275     case BUILT_IN_SETJMP:
6276       /* This should have been lowered to the builtins below.  */
6277       gcc_unreachable ();
6278
6279     case BUILT_IN_SETJMP_SETUP:
6280       /* __builtin_setjmp_setup is passed a pointer to an array of five words
6281           and the receiver label.  */
6282       if (validate_arglist (exp, POINTER_TYPE, POINTER_TYPE, VOID_TYPE))
6283         {
6284           rtx buf_addr = expand_expr (CALL_EXPR_ARG (exp, 0), subtarget,
6285                                       VOIDmode, EXPAND_NORMAL);
6286           tree label = TREE_OPERAND (CALL_EXPR_ARG (exp, 1), 0);
6287           rtx label_r = label_rtx (label);
6288
6289           /* This is copied from the handling of non-local gotos.  */
6290           expand_builtin_setjmp_setup (buf_addr, label_r);
6291           nonlocal_goto_handler_labels
6292             = gen_rtx_EXPR_LIST (VOIDmode, label_r,
6293                                  nonlocal_goto_handler_labels);
6294           /* ??? Do not let expand_label treat us as such since we would
6295              not want to be both on the list of non-local labels and on
6296              the list of forced labels.  */
6297           FORCED_LABEL (label) = 0;
6298           return const0_rtx;
6299         }
6300       break;
6301
6302     case BUILT_IN_SETJMP_DISPATCHER:
6303        /* __builtin_setjmp_dispatcher is passed the dispatcher label.  */
6304       if (validate_arglist (exp, POINTER_TYPE, VOID_TYPE))
6305         {
6306           tree label = TREE_OPERAND (CALL_EXPR_ARG (exp, 0), 0);
6307           rtx label_r = label_rtx (label);
6308
6309           /* Remove the dispatcher label from the list of non-local labels
6310              since the receiver labels have been added to it above.  */
6311           remove_node_from_expr_list (label_r, &nonlocal_goto_handler_labels);
6312           return const0_rtx;
6313         }
6314       break;
6315
6316     case BUILT_IN_SETJMP_RECEIVER:
6317        /* __builtin_setjmp_receiver is passed the receiver label.  */
6318       if (validate_arglist (exp, POINTER_TYPE, VOID_TYPE))
6319         {
6320           tree label = TREE_OPERAND (CALL_EXPR_ARG (exp, 0), 0);
6321           rtx label_r = label_rtx (label);
6322
6323           expand_builtin_setjmp_receiver (label_r);
6324           return const0_rtx;
6325         }
6326       break;
6327
6328       /* __builtin_longjmp is passed a pointer to an array of five words.
6329          It's similar to the C library longjmp function but works with
6330          __builtin_setjmp above.  */
6331     case BUILT_IN_LONGJMP:
6332       if (validate_arglist (exp, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
6333         {
6334           rtx buf_addr = expand_expr (CALL_EXPR_ARG (exp, 0), subtarget,
6335                                       VOIDmode, EXPAND_NORMAL);
6336           rtx value = expand_normal (CALL_EXPR_ARG (exp, 1));
6337
6338           if (value != const1_rtx)
6339             {
6340               error ("%<__builtin_longjmp%> second argument must be 1");
6341               return const0_rtx;
6342             }
6343
6344           expand_builtin_longjmp (buf_addr, value);
6345           return const0_rtx;
6346         }
6347       break;
6348
6349     case BUILT_IN_NONLOCAL_GOTO:
6350       target = expand_builtin_nonlocal_goto (exp);
6351       if (target)
6352         return target;
6353       break;
6354
6355       /* This updates the setjmp buffer that is its argument with the value
6356          of the current stack pointer.  */
6357     case BUILT_IN_UPDATE_SETJMP_BUF:
6358       if (validate_arglist (exp, POINTER_TYPE, VOID_TYPE))
6359         {
6360           rtx buf_addr
6361             = expand_normal (CALL_EXPR_ARG (exp, 0));
6362
6363           expand_builtin_update_setjmp_buf (buf_addr);
6364           return const0_rtx;
6365         }
6366       break;
6367
6368     case BUILT_IN_TRAP:
6369       expand_builtin_trap ();
6370       return const0_rtx;
6371
6372     case BUILT_IN_UNREACHABLE:
6373       expand_builtin_unreachable ();
6374       return const0_rtx;
6375
6376     case BUILT_IN_PRINTF:
6377       target = expand_builtin_printf (exp, target, mode, false);
6378       if (target)
6379         return target;
6380       break;
6381
6382     case BUILT_IN_PRINTF_UNLOCKED:
6383       target = expand_builtin_printf (exp, target, mode, true);
6384       if (target)
6385         return target;
6386       break;
6387
6388     case BUILT_IN_FPRINTF:
6389       target = expand_builtin_fprintf (exp, target, mode, false);
6390       if (target)
6391         return target;
6392       break;
6393
6394     case BUILT_IN_FPRINTF_UNLOCKED:
6395       target = expand_builtin_fprintf (exp, target, mode, true);
6396       if (target)
6397         return target;
6398       break;
6399
6400     case BUILT_IN_SPRINTF:
6401       target = expand_builtin_sprintf (exp, target, mode);
6402       if (target)
6403         return target;
6404       break;
6405
6406     CASE_FLT_FN (BUILT_IN_SIGNBIT):
6407     case BUILT_IN_SIGNBITD32:
6408     case BUILT_IN_SIGNBITD64:
6409     case BUILT_IN_SIGNBITD128:
6410       target = expand_builtin_signbit (exp, target);
6411       if (target)
6412         return target;
6413       break;
6414
6415       /* Various hooks for the DWARF 2 __throw routine.  */
6416     case BUILT_IN_UNWIND_INIT:
6417       expand_builtin_unwind_init ();
6418       return const0_rtx;
6419     case BUILT_IN_DWARF_CFA:
6420       return virtual_cfa_rtx;
6421 #ifdef DWARF2_UNWIND_INFO
6422     case BUILT_IN_DWARF_SP_COLUMN:
6423       return expand_builtin_dwarf_sp_column ();
6424     case BUILT_IN_INIT_DWARF_REG_SIZES:
6425       expand_builtin_init_dwarf_reg_sizes (CALL_EXPR_ARG (exp, 0));
6426       return const0_rtx;
6427 #endif
6428     case BUILT_IN_FROB_RETURN_ADDR:
6429       return expand_builtin_frob_return_addr (CALL_EXPR_ARG (exp, 0));
6430     case BUILT_IN_EXTRACT_RETURN_ADDR:
6431       return expand_builtin_extract_return_addr (CALL_EXPR_ARG (exp, 0));
6432     case BUILT_IN_EH_RETURN:
6433       expand_builtin_eh_return (CALL_EXPR_ARG (exp, 0),
6434                                 CALL_EXPR_ARG (exp, 1));
6435       return const0_rtx;
6436 #ifdef EH_RETURN_DATA_REGNO
6437     case BUILT_IN_EH_RETURN_DATA_REGNO:
6438       return expand_builtin_eh_return_data_regno (exp);
6439 #endif
6440     case BUILT_IN_EXTEND_POINTER:
6441       return expand_builtin_extend_pointer (CALL_EXPR_ARG (exp, 0));
6442     case BUILT_IN_EH_POINTER:
6443       return expand_builtin_eh_pointer (exp);
6444     case BUILT_IN_EH_FILTER:
6445       return expand_builtin_eh_filter (exp);
6446     case BUILT_IN_EH_COPY_VALUES:
6447       return expand_builtin_eh_copy_values (exp);
6448
6449     case BUILT_IN_VA_START:
6450       return expand_builtin_va_start (exp);
6451     case BUILT_IN_VA_END:
6452       return expand_builtin_va_end (exp);
6453     case BUILT_IN_VA_COPY:
6454       return expand_builtin_va_copy (exp);
6455     case BUILT_IN_EXPECT:
6456       return expand_builtin_expect (exp, target);
6457     case BUILT_IN_PREFETCH:
6458       expand_builtin_prefetch (exp);
6459       return const0_rtx;
6460
6461     case BUILT_IN_PROFILE_FUNC_ENTER:
6462       return expand_builtin_profile_func (false);
6463     case BUILT_IN_PROFILE_FUNC_EXIT:
6464       return expand_builtin_profile_func (true);
6465
6466     case BUILT_IN_INIT_TRAMPOLINE:
6467       return expand_builtin_init_trampoline (exp);
6468     case BUILT_IN_ADJUST_TRAMPOLINE:
6469       return expand_builtin_adjust_trampoline (exp);
6470
6471     case BUILT_IN_FORK:
6472     case BUILT_IN_EXECL:
6473     case BUILT_IN_EXECV:
6474     case BUILT_IN_EXECLP:
6475     case BUILT_IN_EXECLE:
6476     case BUILT_IN_EXECVP:
6477     case BUILT_IN_EXECVE:
6478       target = expand_builtin_fork_or_exec (fndecl, exp, target, ignore);
6479       if (target)
6480         return target;
6481       break;
6482
6483     case BUILT_IN_FETCH_AND_ADD_1:
6484     case BUILT_IN_FETCH_AND_ADD_2:
6485     case BUILT_IN_FETCH_AND_ADD_4:
6486     case BUILT_IN_FETCH_AND_ADD_8:
6487     case BUILT_IN_FETCH_AND_ADD_16:
6488       mode = get_builtin_sync_mode (fcode - BUILT_IN_FETCH_AND_ADD_1);
6489       target = expand_builtin_sync_operation (mode, exp, PLUS,
6490                                               false, target, ignore);
6491       if (target)
6492         return target;
6493       break;
6494
6495     case BUILT_IN_FETCH_AND_SUB_1:
6496     case BUILT_IN_FETCH_AND_SUB_2:
6497     case BUILT_IN_FETCH_AND_SUB_4:
6498     case BUILT_IN_FETCH_AND_SUB_8:
6499     case BUILT_IN_FETCH_AND_SUB_16:
6500       mode = get_builtin_sync_mode (fcode - BUILT_IN_FETCH_AND_SUB_1);
6501       target = expand_builtin_sync_operation (mode, exp, MINUS,
6502                                               false, target, ignore);
6503       if (target)
6504         return target;
6505       break;
6506
6507     case BUILT_IN_FETCH_AND_OR_1:
6508     case BUILT_IN_FETCH_AND_OR_2:
6509     case BUILT_IN_FETCH_AND_OR_4:
6510     case BUILT_IN_FETCH_AND_OR_8:
6511     case BUILT_IN_FETCH_AND_OR_16:
6512       mode = get_builtin_sync_mode (fcode - BUILT_IN_FETCH_AND_OR_1);
6513       target = expand_builtin_sync_operation (mode, exp, IOR,
6514                                               false, target, ignore);
6515       if (target)
6516         return target;
6517       break;
6518
6519     case BUILT_IN_FETCH_AND_AND_1:
6520     case BUILT_IN_FETCH_AND_AND_2:
6521     case BUILT_IN_FETCH_AND_AND_4:
6522     case BUILT_IN_FETCH_AND_AND_8:
6523     case BUILT_IN_FETCH_AND_AND_16:
6524       mode = get_builtin_sync_mode (fcode - BUILT_IN_FETCH_AND_AND_1);
6525       target = expand_builtin_sync_operation (mode, exp, AND,
6526                                               false, target, ignore);
6527       if (target)
6528         return target;
6529       break;
6530
6531     case BUILT_IN_FETCH_AND_XOR_1:
6532     case BUILT_IN_FETCH_AND_XOR_2:
6533     case BUILT_IN_FETCH_AND_XOR_4:
6534     case BUILT_IN_FETCH_AND_XOR_8:
6535     case BUILT_IN_FETCH_AND_XOR_16:
6536       mode = get_builtin_sync_mode (fcode - BUILT_IN_FETCH_AND_XOR_1);
6537       target = expand_builtin_sync_operation (mode, exp, XOR,
6538                                               false, target, ignore);
6539       if (target)
6540         return target;
6541       break;
6542
6543     case BUILT_IN_FETCH_AND_NAND_1:
6544     case BUILT_IN_FETCH_AND_NAND_2:
6545     case BUILT_IN_FETCH_AND_NAND_4:
6546     case BUILT_IN_FETCH_AND_NAND_8:
6547     case BUILT_IN_FETCH_AND_NAND_16:
6548       mode = get_builtin_sync_mode (fcode - BUILT_IN_FETCH_AND_NAND_1);
6549       target = expand_builtin_sync_operation (mode, exp, NOT,
6550                                               false, target, ignore);
6551       if (target)
6552         return target;
6553       break;
6554
6555     case BUILT_IN_ADD_AND_FETCH_1:
6556     case BUILT_IN_ADD_AND_FETCH_2:
6557     case BUILT_IN_ADD_AND_FETCH_4:
6558     case BUILT_IN_ADD_AND_FETCH_8:
6559     case BUILT_IN_ADD_AND_FETCH_16:
6560       mode = get_builtin_sync_mode (fcode - BUILT_IN_ADD_AND_FETCH_1);
6561       target = expand_builtin_sync_operation (mode, exp, PLUS,
6562                                               true, target, ignore);
6563       if (target)
6564         return target;
6565       break;
6566
6567     case BUILT_IN_SUB_AND_FETCH_1:
6568     case BUILT_IN_SUB_AND_FETCH_2:
6569     case BUILT_IN_SUB_AND_FETCH_4:
6570     case BUILT_IN_SUB_AND_FETCH_8:
6571     case BUILT_IN_SUB_AND_FETCH_16:
6572       mode = get_builtin_sync_mode (fcode - BUILT_IN_SUB_AND_FETCH_1);
6573       target = expand_builtin_sync_operation (mode, exp, MINUS,
6574                                               true, target, ignore);
6575       if (target)
6576         return target;
6577       break;
6578
6579     case BUILT_IN_OR_AND_FETCH_1:
6580     case BUILT_IN_OR_AND_FETCH_2:
6581     case BUILT_IN_OR_AND_FETCH_4:
6582     case BUILT_IN_OR_AND_FETCH_8:
6583     case BUILT_IN_OR_AND_FETCH_16:
6584       mode = get_builtin_sync_mode (fcode - BUILT_IN_OR_AND_FETCH_1);
6585       target = expand_builtin_sync_operation (mode, exp, IOR,
6586                                               true, target, ignore);
6587       if (target)
6588         return target;
6589       break;
6590
6591     case BUILT_IN_AND_AND_FETCH_1:
6592     case BUILT_IN_AND_AND_FETCH_2:
6593     case BUILT_IN_AND_AND_FETCH_4:
6594     case BUILT_IN_AND_AND_FETCH_8:
6595     case BUILT_IN_AND_AND_FETCH_16:
6596       mode = get_builtin_sync_mode (fcode - BUILT_IN_AND_AND_FETCH_1);
6597       target = expand_builtin_sync_operation (mode, exp, AND,
6598                                               true, target, ignore);
6599       if (target)
6600         return target;
6601       break;
6602
6603     case BUILT_IN_XOR_AND_FETCH_1:
6604     case BUILT_IN_XOR_AND_FETCH_2:
6605     case BUILT_IN_XOR_AND_FETCH_4:
6606     case BUILT_IN_XOR_AND_FETCH_8:
6607     case BUILT_IN_XOR_AND_FETCH_16:
6608       mode = get_builtin_sync_mode (fcode - BUILT_IN_XOR_AND_FETCH_1);
6609       target = expand_builtin_sync_operation (mode, exp, XOR,
6610                                               true, target, ignore);
6611       if (target)
6612         return target;
6613       break;
6614
6615     case BUILT_IN_NAND_AND_FETCH_1:
6616     case BUILT_IN_NAND_AND_FETCH_2:
6617     case BUILT_IN_NAND_AND_FETCH_4:
6618     case BUILT_IN_NAND_AND_FETCH_8:
6619     case BUILT_IN_NAND_AND_FETCH_16:
6620       mode = get_builtin_sync_mode (fcode - BUILT_IN_NAND_AND_FETCH_1);
6621       target = expand_builtin_sync_operation (mode, exp, NOT,
6622                                               true, target, ignore);
6623       if (target)
6624         return target;
6625       break;
6626
6627     case BUILT_IN_BOOL_COMPARE_AND_SWAP_1:
6628     case BUILT_IN_BOOL_COMPARE_AND_SWAP_2:
6629     case BUILT_IN_BOOL_COMPARE_AND_SWAP_4:
6630     case BUILT_IN_BOOL_COMPARE_AND_SWAP_8:
6631     case BUILT_IN_BOOL_COMPARE_AND_SWAP_16:
6632       if (mode == VOIDmode)
6633         mode = TYPE_MODE (boolean_type_node);
6634       if (!target || !register_operand (target, mode))
6635         target = gen_reg_rtx (mode);
6636
6637       mode = get_builtin_sync_mode (fcode - BUILT_IN_BOOL_COMPARE_AND_SWAP_1);
6638       target = expand_builtin_compare_and_swap (mode, exp, true, target);
6639       if (target)
6640         return target;
6641       break;
6642
6643     case BUILT_IN_VAL_COMPARE_AND_SWAP_1:
6644     case BUILT_IN_VAL_COMPARE_AND_SWAP_2:
6645     case BUILT_IN_VAL_COMPARE_AND_SWAP_4:
6646     case BUILT_IN_VAL_COMPARE_AND_SWAP_8:
6647     case BUILT_IN_VAL_COMPARE_AND_SWAP_16:
6648       mode = get_builtin_sync_mode (fcode - BUILT_IN_VAL_COMPARE_AND_SWAP_1);
6649       target = expand_builtin_compare_and_swap (mode, exp, false, target);
6650       if (target)
6651         return target;
6652       break;
6653
6654     case BUILT_IN_LOCK_TEST_AND_SET_1:
6655     case BUILT_IN_LOCK_TEST_AND_SET_2:
6656     case BUILT_IN_LOCK_TEST_AND_SET_4:
6657     case BUILT_IN_LOCK_TEST_AND_SET_8:
6658     case BUILT_IN_LOCK_TEST_AND_SET_16:
6659       mode = get_builtin_sync_mode (fcode - BUILT_IN_LOCK_TEST_AND_SET_1);
6660       target = expand_builtin_lock_test_and_set (mode, exp, target);
6661       if (target)
6662         return target;
6663       break;
6664
6665     case BUILT_IN_LOCK_RELEASE_1:
6666     case BUILT_IN_LOCK_RELEASE_2:
6667     case BUILT_IN_LOCK_RELEASE_4:
6668     case BUILT_IN_LOCK_RELEASE_8:
6669     case BUILT_IN_LOCK_RELEASE_16:
6670       mode = get_builtin_sync_mode (fcode - BUILT_IN_LOCK_RELEASE_1);
6671       expand_builtin_lock_release (mode, exp);
6672       return const0_rtx;
6673
6674     case BUILT_IN_SYNCHRONIZE:
6675       expand_builtin_synchronize ();
6676       return const0_rtx;
6677
6678     case BUILT_IN_OBJECT_SIZE:
6679       return expand_builtin_object_size (exp);
6680
6681     case BUILT_IN_MEMCPY_CHK:
6682     case BUILT_IN_MEMPCPY_CHK:
6683     case BUILT_IN_MEMMOVE_CHK:
6684     case BUILT_IN_MEMSET_CHK:
6685       target = expand_builtin_memory_chk (exp, target, mode, fcode);
6686       if (target)
6687         return target;
6688       break;
6689
6690     case BUILT_IN_STRCPY_CHK:
6691     case BUILT_IN_STPCPY_CHK:
6692     case BUILT_IN_STRNCPY_CHK:
6693     case BUILT_IN_STRCAT_CHK:
6694     case BUILT_IN_STRNCAT_CHK:
6695     case BUILT_IN_SNPRINTF_CHK:
6696     case BUILT_IN_VSNPRINTF_CHK:
6697       maybe_emit_chk_warning (exp, fcode);
6698       break;
6699
6700     case BUILT_IN_SPRINTF_CHK:
6701     case BUILT_IN_VSPRINTF_CHK:
6702       maybe_emit_sprintf_chk_warning (exp, fcode);
6703       break;
6704
6705     case BUILT_IN_FREE:
6706       maybe_emit_free_warning (exp);
6707       break;
6708
6709     default:    /* just do library call, if unknown builtin */
6710       break;
6711     }
6712
6713   /* The switch statement above can drop through to cause the function
6714      to be called normally.  */
6715   return expand_call (exp, target, ignore);
6716 }
6717
6718 /* Determine whether a tree node represents a call to a built-in
6719    function.  If the tree T is a call to a built-in function with
6720    the right number of arguments of the appropriate types, return
6721    the DECL_FUNCTION_CODE of the call, e.g. BUILT_IN_SQRT.
6722    Otherwise the return value is END_BUILTINS.  */
6723
6724 enum built_in_function
6725 builtin_mathfn_code (const_tree t)
6726 {
6727   const_tree fndecl, arg, parmlist;
6728   const_tree argtype, parmtype;
6729   const_call_expr_arg_iterator iter;
6730
6731   if (TREE_CODE (t) != CALL_EXPR
6732       || TREE_CODE (CALL_EXPR_FN (t)) != ADDR_EXPR)
6733     return END_BUILTINS;
6734
6735   fndecl = get_callee_fndecl (t);
6736   if (fndecl == NULL_TREE
6737       || TREE_CODE (fndecl) != FUNCTION_DECL
6738       || ! DECL_BUILT_IN (fndecl)
6739       || DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_MD)
6740     return END_BUILTINS;
6741
6742   parmlist = TYPE_ARG_TYPES (TREE_TYPE (fndecl));
6743   init_const_call_expr_arg_iterator (t, &iter);
6744   for (; parmlist; parmlist = TREE_CHAIN (parmlist))
6745     {
6746       /* If a function doesn't take a variable number of arguments,
6747          the last element in the list will have type `void'.  */
6748       parmtype = TREE_VALUE (parmlist);
6749       if (VOID_TYPE_P (parmtype))
6750         {
6751           if (more_const_call_expr_args_p (&iter))
6752             return END_BUILTINS;
6753           return DECL_FUNCTION_CODE (fndecl);
6754         }
6755
6756       if (! more_const_call_expr_args_p (&iter))
6757         return END_BUILTINS;
6758       
6759       arg = next_const_call_expr_arg (&iter);
6760       argtype = TREE_TYPE (arg);
6761
6762       if (SCALAR_FLOAT_TYPE_P (parmtype))
6763         {
6764           if (! SCALAR_FLOAT_TYPE_P (argtype))
6765             return END_BUILTINS;
6766         }
6767       else if (COMPLEX_FLOAT_TYPE_P (parmtype))
6768         {
6769           if (! COMPLEX_FLOAT_TYPE_P (argtype))
6770             return END_BUILTINS;
6771         }
6772       else if (POINTER_TYPE_P (parmtype))
6773         {
6774           if (! POINTER_TYPE_P (argtype))
6775             return END_BUILTINS;
6776         }
6777       else if (INTEGRAL_TYPE_P (parmtype))
6778         {
6779           if (! INTEGRAL_TYPE_P (argtype))
6780             return END_BUILTINS;
6781         }
6782       else
6783         return END_BUILTINS;
6784     }
6785
6786   /* Variable-length argument list.  */
6787   return DECL_FUNCTION_CODE (fndecl);
6788 }
6789
6790 /* Fold a call to __builtin_constant_p, if we know its argument ARG will
6791    evaluate to a constant.  */
6792
6793 static tree
6794 fold_builtin_constant_p (tree arg)
6795 {
6796   /* We return 1 for a numeric type that's known to be a constant
6797      value at compile-time or for an aggregate type that's a
6798      literal constant.  */
6799   STRIP_NOPS (arg);
6800
6801   /* If we know this is a constant, emit the constant of one.  */
6802   if (CONSTANT_CLASS_P (arg)
6803       || (TREE_CODE (arg) == CONSTRUCTOR
6804           && TREE_CONSTANT (arg)))
6805     return integer_one_node;
6806   if (TREE_CODE (arg) == ADDR_EXPR)
6807     {
6808        tree op = TREE_OPERAND (arg, 0);
6809        if (TREE_CODE (op) == STRING_CST
6810            || (TREE_CODE (op) == ARRAY_REF
6811                && integer_zerop (TREE_OPERAND (op, 1))
6812                && TREE_CODE (TREE_OPERAND (op, 0)) == STRING_CST))
6813          return integer_one_node;
6814     }
6815
6816   /* If this expression has side effects, show we don't know it to be a
6817      constant.  Likewise if it's a pointer or aggregate type since in
6818      those case we only want literals, since those are only optimized
6819      when generating RTL, not later.
6820      And finally, if we are compiling an initializer, not code, we
6821      need to return a definite result now; there's not going to be any
6822      more optimization done.  */
6823   if (TREE_SIDE_EFFECTS (arg)
6824       || AGGREGATE_TYPE_P (TREE_TYPE (arg))
6825       || POINTER_TYPE_P (TREE_TYPE (arg))
6826       || cfun == 0
6827       || folding_initializer)
6828     return integer_zero_node;
6829
6830   return NULL_TREE;
6831 }
6832
6833 /* Create builtin_expect with PRED and EXPECTED as its arguments and
6834    return it as a truthvalue.  */
6835
6836 static tree
6837 build_builtin_expect_predicate (location_t loc, tree pred, tree expected)
6838 {
6839   tree fn, arg_types, pred_type, expected_type, call_expr, ret_type;
6840
6841   fn = built_in_decls[BUILT_IN_EXPECT];
6842   arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
6843   ret_type = TREE_TYPE (TREE_TYPE (fn));
6844   pred_type = TREE_VALUE (arg_types);
6845   expected_type = TREE_VALUE (TREE_CHAIN (arg_types));
6846
6847   pred = fold_convert_loc (loc, pred_type, pred);
6848   expected = fold_convert_loc (loc, expected_type, expected);
6849   call_expr = build_call_expr_loc (loc, fn, 2, pred, expected);
6850
6851   return build2 (NE_EXPR, TREE_TYPE (pred), call_expr,
6852                  build_int_cst (ret_type, 0));
6853 }
6854
6855 /* Fold a call to builtin_expect with arguments ARG0 and ARG1.  Return
6856    NULL_TREE if no simplification is possible.  */
6857
6858 static tree
6859 fold_builtin_expect (location_t loc, tree arg0, tree arg1)
6860 {
6861   tree inner, fndecl;
6862   enum tree_code code;
6863
6864   /* If this is a builtin_expect within a builtin_expect keep the
6865      inner one.  See through a comparison against a constant.  It
6866      might have been added to create a thruthvalue.  */
6867   inner = arg0;
6868   if (COMPARISON_CLASS_P (inner)
6869       && TREE_CODE (TREE_OPERAND (inner, 1)) == INTEGER_CST)
6870     inner = TREE_OPERAND (inner, 0);
6871
6872   if (TREE_CODE (inner) == CALL_EXPR
6873       && (fndecl = get_callee_fndecl (inner))
6874       && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL
6875       && DECL_FUNCTION_CODE (fndecl) == BUILT_IN_EXPECT)
6876     return arg0;
6877
6878   /* Distribute the expected value over short-circuiting operators.
6879      See through the cast from truthvalue_type_node to long.  */
6880   inner = arg0;
6881   while (TREE_CODE (inner) == NOP_EXPR
6882          && INTEGRAL_TYPE_P (TREE_TYPE (inner))
6883          && INTEGRAL_TYPE_P (TREE_TYPE (TREE_OPERAND (inner, 0))))
6884     inner = TREE_OPERAND (inner, 0);
6885
6886   code = TREE_CODE (inner);
6887   if (code == TRUTH_ANDIF_EXPR || code == TRUTH_ORIF_EXPR)
6888     {
6889       tree op0 = TREE_OPERAND (inner, 0);
6890       tree op1 = TREE_OPERAND (inner, 1);
6891
6892       op0 = build_builtin_expect_predicate (loc, op0, arg1);
6893       op1 = build_builtin_expect_predicate (loc, op1, arg1);
6894       inner = build2 (code, TREE_TYPE (inner), op0, op1);
6895
6896       return fold_convert_loc (loc, TREE_TYPE (arg0), inner);
6897     }
6898
6899   /* If the argument isn't invariant then there's nothing else we can do.  */
6900   if (!TREE_CONSTANT (arg0))
6901     return NULL_TREE;
6902
6903   /* If we expect that a comparison against the argument will fold to
6904      a constant return the constant.  In practice, this means a true
6905      constant or the address of a non-weak symbol.  */
6906   inner = arg0;
6907   STRIP_NOPS (inner);
6908   if (TREE_CODE (inner) == ADDR_EXPR)
6909     {
6910       do
6911         {
6912           inner = TREE_OPERAND (inner, 0);
6913         }
6914       while (TREE_CODE (inner) == COMPONENT_REF
6915              || TREE_CODE (inner) == ARRAY_REF);
6916       if ((TREE_CODE (inner) == VAR_DECL
6917            || TREE_CODE (inner) == FUNCTION_DECL)
6918           && DECL_WEAK (inner))
6919         return NULL_TREE;
6920     }
6921
6922   /* Otherwise, ARG0 already has the proper type for the return value.  */
6923   return arg0;
6924 }
6925
6926 /* Fold a call to __builtin_classify_type with argument ARG.  */
6927
6928 static tree
6929 fold_builtin_classify_type (tree arg)
6930 {
6931   if (arg == 0)
6932     return build_int_cst (NULL_TREE, no_type_class);
6933
6934   return build_int_cst (NULL_TREE, type_to_class (TREE_TYPE (arg)));
6935 }
6936
6937 /* Fold a call to __builtin_strlen with argument ARG.  */
6938
6939 static tree
6940 fold_builtin_strlen (location_t loc, tree arg)
6941 {
6942   if (!validate_arg (arg, POINTER_TYPE))
6943     return NULL_TREE;
6944   else
6945     {
6946       tree len = c_strlen (arg, 0);
6947
6948       if (len)
6949         {
6950           /* Convert from the internal "sizetype" type to "size_t".  */
6951           if (size_type_node)
6952             len = fold_convert_loc (loc, size_type_node, len);
6953           return len;
6954         }
6955
6956       return NULL_TREE;
6957     }
6958 }
6959
6960 /* Fold a call to __builtin_inf or __builtin_huge_val.  */
6961
6962 static tree
6963 fold_builtin_inf (location_t loc, tree type, int warn)
6964 {
6965   REAL_VALUE_TYPE real;
6966
6967   /* __builtin_inff is intended to be usable to define INFINITY on all
6968      targets.  If an infinity is not available, INFINITY expands "to a
6969      positive constant of type float that overflows at translation
6970      time", footnote "In this case, using INFINITY will violate the
6971      constraint in 6.4.4 and thus require a diagnostic." (C99 7.12#4).
6972      Thus we pedwarn to ensure this constraint violation is
6973      diagnosed.  */
6974   if (!MODE_HAS_INFINITIES (TYPE_MODE (type)) && warn)
6975     pedwarn (loc, 0, "target format does not support infinity");
6976
6977   real_inf (&real);
6978   return build_real (type, real);
6979 }
6980
6981 /* Fold a call to __builtin_nan or __builtin_nans with argument ARG.  */
6982
6983 static tree
6984 fold_builtin_nan (tree arg, tree type, int quiet)
6985 {
6986   REAL_VALUE_TYPE real;
6987   const char *str;
6988
6989   if (!validate_arg (arg, POINTER_TYPE))
6990     return NULL_TREE;
6991   str = c_getstr (arg);
6992   if (!str)
6993     return NULL_TREE;
6994
6995   if (!real_nan (&real, str, quiet, TYPE_MODE (type)))
6996     return NULL_TREE;
6997
6998   return build_real (type, real);
6999 }
7000
7001 /* Return true if the floating point expression T has an integer value.
7002    We also allow +Inf, -Inf and NaN to be considered integer values.  */
7003
7004 static bool
7005 integer_valued_real_p (tree t)
7006 {
7007   switch (TREE_CODE (t))
7008     {
7009     case FLOAT_EXPR:
7010       return true;
7011
7012     case ABS_EXPR:
7013     case SAVE_EXPR:
7014       return integer_valued_real_p (TREE_OPERAND (t, 0));
7015
7016     case COMPOUND_EXPR:
7017     case MODIFY_EXPR:
7018     case BIND_EXPR:
7019       return integer_valued_real_p (TREE_OPERAND (t, 1));
7020
7021     case PLUS_EXPR:
7022     case MINUS_EXPR:
7023     case MULT_EXPR:
7024     case MIN_EXPR:
7025     case MAX_EXPR:
7026       return integer_valued_real_p (TREE_OPERAND (t, 0))
7027              && integer_valued_real_p (TREE_OPERAND (t, 1));
7028
7029     case COND_EXPR:
7030       return integer_valued_real_p (TREE_OPERAND (t, 1))
7031              && integer_valued_real_p (TREE_OPERAND (t, 2));
7032
7033     case REAL_CST:
7034       return real_isinteger (TREE_REAL_CST_PTR (t), TYPE_MODE (TREE_TYPE (t)));
7035
7036     case NOP_EXPR:
7037       {
7038         tree type = TREE_TYPE (TREE_OPERAND (t, 0));
7039         if (TREE_CODE (type) == INTEGER_TYPE)
7040           return true;
7041         if (TREE_CODE (type) == REAL_TYPE)
7042           return integer_valued_real_p (TREE_OPERAND (t, 0));
7043         break;
7044       }
7045
7046     case CALL_EXPR:
7047       switch (builtin_mathfn_code (t))
7048         {
7049         CASE_FLT_FN (BUILT_IN_CEIL):
7050         CASE_FLT_FN (BUILT_IN_FLOOR):
7051         CASE_FLT_FN (BUILT_IN_NEARBYINT):
7052         CASE_FLT_FN (BUILT_IN_RINT):
7053         CASE_FLT_FN (BUILT_IN_ROUND):
7054         CASE_FLT_FN (BUILT_IN_TRUNC):
7055           return true;
7056
7057         CASE_FLT_FN (BUILT_IN_FMIN):
7058         CASE_FLT_FN (BUILT_IN_FMAX):
7059           return integer_valued_real_p (CALL_EXPR_ARG (t, 0))
7060             && integer_valued_real_p (CALL_EXPR_ARG (t, 1));
7061
7062         default:
7063           break;
7064         }
7065       break;
7066
7067     default:
7068       break;
7069     }
7070   return false;
7071 }
7072
7073 /* FNDECL is assumed to be a builtin where truncation can be propagated
7074    across (for instance floor((double)f) == (double)floorf (f).
7075    Do the transformation for a call with argument ARG.  */
7076
7077 static tree
7078 fold_trunc_transparent_mathfn (location_t loc, tree fndecl, tree arg)
7079 {
7080   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
7081
7082   if (!validate_arg (arg, REAL_TYPE))
7083     return NULL_TREE;
7084
7085   /* Integer rounding functions are idempotent.  */
7086   if (fcode == builtin_mathfn_code (arg))
7087     return arg;
7088
7089   /* If argument is already integer valued, and we don't need to worry
7090      about setting errno, there's no need to perform rounding.  */
7091   if (! flag_errno_math && integer_valued_real_p (arg))
7092     return arg;
7093
7094   if (optimize)
7095     {
7096       tree arg0 = strip_float_extensions (arg);
7097       tree ftype = TREE_TYPE (TREE_TYPE (fndecl));
7098       tree newtype = TREE_TYPE (arg0);
7099       tree decl;
7100
7101       if (TYPE_PRECISION (newtype) < TYPE_PRECISION (ftype)
7102           && (decl = mathfn_built_in (newtype, fcode)))
7103         return fold_convert_loc (loc, ftype,
7104                                  build_call_expr_loc (loc, decl, 1,
7105                                                   fold_convert_loc (loc,
7106                                                                     newtype,
7107                                                                     arg0)));
7108     }
7109   return NULL_TREE;
7110 }
7111
7112 /* FNDECL is assumed to be builtin which can narrow the FP type of
7113    the argument, for instance lround((double)f) -> lroundf (f).
7114    Do the transformation for a call with argument ARG.  */
7115
7116 static tree
7117 fold_fixed_mathfn (location_t loc, tree fndecl, tree arg)
7118 {
7119   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
7120
7121   if (!validate_arg (arg, REAL_TYPE))
7122     return NULL_TREE;
7123
7124   /* If argument is already integer valued, and we don't need to worry
7125      about setting errno, there's no need to perform rounding.  */
7126   if (! flag_errno_math && integer_valued_real_p (arg))
7127     return fold_build1_loc (loc, FIX_TRUNC_EXPR,
7128                         TREE_TYPE (TREE_TYPE (fndecl)), arg);
7129
7130   if (optimize)
7131     {
7132       tree ftype = TREE_TYPE (arg);
7133       tree arg0 = strip_float_extensions (arg);
7134       tree newtype = TREE_TYPE (arg0);
7135       tree decl;
7136
7137       if (TYPE_PRECISION (newtype) < TYPE_PRECISION (ftype)
7138           && (decl = mathfn_built_in (newtype, fcode)))
7139         return build_call_expr_loc (loc, decl, 1,
7140                                 fold_convert_loc (loc, newtype, arg0));
7141     }
7142
7143   /* Canonicalize llround (x) to lround (x) on LP64 targets where
7144      sizeof (long long) == sizeof (long).  */
7145   if (TYPE_PRECISION (long_long_integer_type_node)
7146       == TYPE_PRECISION (long_integer_type_node))
7147     {
7148       tree newfn = NULL_TREE;
7149       switch (fcode)
7150         {
7151         CASE_FLT_FN (BUILT_IN_LLCEIL):
7152           newfn = mathfn_built_in (TREE_TYPE (arg), BUILT_IN_LCEIL);
7153           break;
7154
7155         CASE_FLT_FN (BUILT_IN_LLFLOOR):
7156           newfn = mathfn_built_in (TREE_TYPE (arg), BUILT_IN_LFLOOR);
7157           break;
7158
7159         CASE_FLT_FN (BUILT_IN_LLROUND):
7160           newfn = mathfn_built_in (TREE_TYPE (arg), BUILT_IN_LROUND);
7161           break;
7162
7163         CASE_FLT_FN (BUILT_IN_LLRINT):
7164           newfn = mathfn_built_in (TREE_TYPE (arg), BUILT_IN_LRINT);
7165           break;
7166
7167         default:
7168           break;
7169         }
7170
7171       if (newfn)
7172         {
7173           tree newcall = build_call_expr_loc (loc, newfn, 1, arg);
7174           return fold_convert_loc (loc,
7175                                    TREE_TYPE (TREE_TYPE (fndecl)), newcall);
7176         }
7177     }
7178
7179   return NULL_TREE;
7180 }
7181
7182 /* Fold call to builtin cabs, cabsf or cabsl with argument ARG.  TYPE is the
7183    return type.  Return NULL_TREE if no simplification can be made.  */
7184
7185 static tree
7186 fold_builtin_cabs (location_t loc, tree arg, tree type, tree fndecl)
7187 {
7188   tree res;
7189
7190   if (!validate_arg (arg, COMPLEX_TYPE)
7191       || TREE_CODE (TREE_TYPE (TREE_TYPE (arg))) != REAL_TYPE)
7192     return NULL_TREE;
7193
7194   /* Calculate the result when the argument is a constant.  */
7195   if (TREE_CODE (arg) == COMPLEX_CST
7196       && (res = do_mpfr_arg2 (TREE_REALPART (arg), TREE_IMAGPART (arg),
7197                               type, mpfr_hypot)))
7198     return res;
7199   
7200   if (TREE_CODE (arg) == COMPLEX_EXPR)
7201     {
7202       tree real = TREE_OPERAND (arg, 0);
7203       tree imag = TREE_OPERAND (arg, 1);
7204       
7205       /* If either part is zero, cabs is fabs of the other.  */
7206       if (real_zerop (real))
7207         return fold_build1_loc (loc, ABS_EXPR, type, imag);
7208       if (real_zerop (imag))
7209         return fold_build1_loc (loc, ABS_EXPR, type, real);
7210
7211       /* cabs(x+xi) -> fabs(x)*sqrt(2).  */
7212       if (flag_unsafe_math_optimizations
7213           && operand_equal_p (real, imag, OEP_PURE_SAME))
7214         {
7215           const REAL_VALUE_TYPE sqrt2_trunc
7216             = real_value_truncate (TYPE_MODE (type), dconst_sqrt2 ());
7217           STRIP_NOPS (real);
7218           return fold_build2_loc (loc, MULT_EXPR, type,
7219                               fold_build1_loc (loc, ABS_EXPR, type, real),
7220                               build_real (type, sqrt2_trunc));
7221         }
7222     }
7223
7224   /* Optimize cabs(-z) and cabs(conj(z)) as cabs(z).  */
7225   if (TREE_CODE (arg) == NEGATE_EXPR
7226       || TREE_CODE (arg) == CONJ_EXPR)
7227     return build_call_expr_loc (loc, fndecl, 1, TREE_OPERAND (arg, 0));
7228
7229   /* Don't do this when optimizing for size.  */
7230   if (flag_unsafe_math_optimizations
7231       && optimize && optimize_function_for_speed_p (cfun))
7232     {
7233       tree sqrtfn = mathfn_built_in (type, BUILT_IN_SQRT);
7234
7235       if (sqrtfn != NULL_TREE)
7236         {
7237           tree rpart, ipart, result;
7238
7239           arg = builtin_save_expr (arg);
7240
7241           rpart = fold_build1_loc (loc, REALPART_EXPR, type, arg);
7242           ipart = fold_build1_loc (loc, IMAGPART_EXPR, type, arg);
7243
7244           rpart = builtin_save_expr (rpart);
7245           ipart = builtin_save_expr (ipart);
7246
7247           result = fold_build2_loc (loc, PLUS_EXPR, type,
7248                                 fold_build2_loc (loc, MULT_EXPR, type,
7249                                              rpart, rpart),
7250                                 fold_build2_loc (loc, MULT_EXPR, type,
7251                                              ipart, ipart));
7252
7253           return build_call_expr_loc (loc, sqrtfn, 1, result);
7254         }
7255     }
7256
7257   return NULL_TREE;
7258 }
7259
7260 /* Fold a builtin function call to sqrt, sqrtf, or sqrtl with argument ARG.
7261    Return NULL_TREE if no simplification can be made.  */
7262
7263 static tree
7264 fold_builtin_sqrt (location_t loc, tree arg, tree type)
7265 {
7266
7267   enum built_in_function fcode;
7268   tree res;
7269
7270   if (!validate_arg (arg, REAL_TYPE))
7271     return NULL_TREE;
7272
7273   /* Calculate the result when the argument is a constant.  */
7274   if ((res = do_mpfr_arg1 (arg, type, mpfr_sqrt, &dconst0, NULL, true)))
7275     return res;
7276   
7277   /* Optimize sqrt(expN(x)) = expN(x*0.5).  */
7278   fcode = builtin_mathfn_code (arg);
7279   if (flag_unsafe_math_optimizations && BUILTIN_EXPONENT_P (fcode))
7280     {
7281       tree expfn = TREE_OPERAND (CALL_EXPR_FN (arg), 0);
7282       arg = fold_build2_loc (loc, MULT_EXPR, type,
7283                          CALL_EXPR_ARG (arg, 0),
7284                          build_real (type, dconsthalf));
7285       return build_call_expr_loc (loc, expfn, 1, arg);
7286     }
7287
7288   /* Optimize sqrt(Nroot(x)) -> pow(x,1/(2*N)).  */
7289   if (flag_unsafe_math_optimizations && BUILTIN_ROOT_P (fcode))
7290     {
7291       tree powfn = mathfn_built_in (type, BUILT_IN_POW);
7292
7293       if (powfn)
7294         {
7295           tree arg0 = CALL_EXPR_ARG (arg, 0);
7296           tree tree_root;
7297           /* The inner root was either sqrt or cbrt.  */
7298           /* This was a conditional expression but it triggered a bug
7299              in Sun C 5.5.  */
7300           REAL_VALUE_TYPE dconstroot;
7301           if (BUILTIN_SQRT_P (fcode))
7302             dconstroot = dconsthalf;
7303           else
7304             dconstroot = dconst_third ();
7305
7306           /* Adjust for the outer root.  */
7307           SET_REAL_EXP (&dconstroot, REAL_EXP (&dconstroot) - 1);
7308           dconstroot = real_value_truncate (TYPE_MODE (type), dconstroot);
7309           tree_root = build_real (type, dconstroot);
7310           return build_call_expr_loc (loc, powfn, 2, arg0, tree_root);
7311         }
7312     }
7313
7314   /* Optimize sqrt(pow(x,y)) = pow(|x|,y*0.5).  */
7315   if (flag_unsafe_math_optimizations
7316       && (fcode == BUILT_IN_POW
7317           || fcode == BUILT_IN_POWF
7318           || fcode == BUILT_IN_POWL))
7319     {
7320       tree powfn = TREE_OPERAND (CALL_EXPR_FN (arg), 0);
7321       tree arg0 = CALL_EXPR_ARG (arg, 0);
7322       tree arg1 = CALL_EXPR_ARG (arg, 1);
7323       tree narg1;
7324       if (!tree_expr_nonnegative_p (arg0))
7325         arg0 = build1 (ABS_EXPR, type, arg0);
7326       narg1 = fold_build2_loc (loc, MULT_EXPR, type, arg1,
7327                            build_real (type, dconsthalf));
7328       return build_call_expr_loc (loc, powfn, 2, arg0, narg1);
7329     }
7330
7331   return NULL_TREE;
7332 }
7333
7334 /* Fold a builtin function call to cbrt, cbrtf, or cbrtl with argument ARG.
7335    Return NULL_TREE if no simplification can be made.  */
7336
7337 static tree
7338 fold_builtin_cbrt (location_t loc, tree arg, tree type)
7339 {
7340   const enum built_in_function fcode = builtin_mathfn_code (arg);
7341   tree res;
7342
7343   if (!validate_arg (arg, REAL_TYPE))
7344     return NULL_TREE;
7345
7346   /* Calculate the result when the argument is a constant.  */
7347   if ((res = do_mpfr_arg1 (arg, type, mpfr_cbrt, NULL, NULL, 0)))
7348     return res;
7349
7350   if (flag_unsafe_math_optimizations)
7351     {
7352       /* Optimize cbrt(expN(x)) -> expN(x/3).  */
7353       if (BUILTIN_EXPONENT_P (fcode))
7354         {
7355           tree expfn = TREE_OPERAND (CALL_EXPR_FN (arg), 0);
7356           const REAL_VALUE_TYPE third_trunc =
7357             real_value_truncate (TYPE_MODE (type), dconst_third ());
7358           arg = fold_build2_loc (loc, MULT_EXPR, type,
7359                              CALL_EXPR_ARG (arg, 0),
7360                              build_real (type, third_trunc));
7361           return build_call_expr_loc (loc, expfn, 1, arg);
7362         }
7363
7364       /* Optimize cbrt(sqrt(x)) -> pow(x,1/6).  */
7365       if (BUILTIN_SQRT_P (fcode))
7366         {
7367           tree powfn = mathfn_built_in (type, BUILT_IN_POW);
7368
7369           if (powfn)
7370             {
7371               tree arg0 = CALL_EXPR_ARG (arg, 0);
7372               tree tree_root;
7373               REAL_VALUE_TYPE dconstroot = dconst_third ();
7374
7375               SET_REAL_EXP (&dconstroot, REAL_EXP (&dconstroot) - 1);
7376               dconstroot = real_value_truncate (TYPE_MODE (type), dconstroot);
7377               tree_root = build_real (type, dconstroot);
7378               return build_call_expr_loc (loc, powfn, 2, arg0, tree_root);
7379             }
7380         }
7381
7382       /* Optimize cbrt(cbrt(x)) -> pow(x,1/9) iff x is nonnegative.  */
7383       if (BUILTIN_CBRT_P (fcode))
7384         {
7385           tree arg0 = CALL_EXPR_ARG (arg, 0);
7386           if (tree_expr_nonnegative_p (arg0))
7387             {
7388               tree powfn = mathfn_built_in (type, BUILT_IN_POW);
7389
7390               if (powfn)
7391                 {
7392                   tree tree_root;
7393                   REAL_VALUE_TYPE dconstroot;
7394
7395                   real_arithmetic (&dconstroot, MULT_EXPR,
7396                                    dconst_third_ptr (), dconst_third_ptr ());
7397                   dconstroot = real_value_truncate (TYPE_MODE (type), dconstroot);
7398                   tree_root = build_real (type, dconstroot);
7399                   return build_call_expr_loc (loc, powfn, 2, arg0, tree_root);
7400                 }
7401             }
7402         }
7403
7404       /* Optimize cbrt(pow(x,y)) -> pow(x,y/3) iff x is nonnegative.  */
7405       if (fcode == BUILT_IN_POW 
7406           || fcode == BUILT_IN_POWF
7407           || fcode == BUILT_IN_POWL)
7408         {
7409           tree arg00 = CALL_EXPR_ARG (arg, 0);
7410           tree arg01 = CALL_EXPR_ARG (arg, 1);
7411           if (tree_expr_nonnegative_p (arg00))
7412             {
7413               tree powfn = TREE_OPERAND (CALL_EXPR_FN (arg), 0);
7414               const REAL_VALUE_TYPE dconstroot
7415                 = real_value_truncate (TYPE_MODE (type), dconst_third ());
7416               tree narg01 = fold_build2_loc (loc, MULT_EXPR, type, arg01,
7417                                          build_real (type, dconstroot));
7418               return build_call_expr_loc (loc, powfn, 2, arg00, narg01);
7419             }
7420         }
7421     }
7422   return NULL_TREE;
7423 }
7424
7425 /* Fold function call to builtin cos, cosf, or cosl with argument ARG.
7426    TYPE is the type of the return value.  Return NULL_TREE if no
7427    simplification can be made.  */
7428
7429 static tree
7430 fold_builtin_cos (location_t loc,
7431                   tree arg, tree type, tree fndecl)
7432 {
7433   tree res, narg;
7434
7435   if (!validate_arg (arg, REAL_TYPE))
7436     return NULL_TREE;
7437
7438   /* Calculate the result when the argument is a constant.  */
7439   if ((res = do_mpfr_arg1 (arg, type, mpfr_cos, NULL, NULL, 0)))
7440     return res;
7441   
7442   /* Optimize cos(-x) into cos (x).  */
7443   if ((narg = fold_strip_sign_ops (arg)))
7444     return build_call_expr_loc (loc, fndecl, 1, narg);
7445
7446   return NULL_TREE;
7447 }
7448
7449 /* Fold function call to builtin cosh, coshf, or coshl with argument ARG.
7450    Return NULL_TREE if no simplification can be made.  */
7451
7452 static tree
7453 fold_builtin_cosh (location_t loc, tree arg, tree type, tree fndecl)
7454 {
7455   if (validate_arg (arg, REAL_TYPE))
7456     {
7457       tree res, narg;
7458
7459       /* Calculate the result when the argument is a constant.  */
7460       if ((res = do_mpfr_arg1 (arg, type, mpfr_cosh, NULL, NULL, 0)))
7461         return res;
7462   
7463       /* Optimize cosh(-x) into cosh (x).  */
7464       if ((narg = fold_strip_sign_ops (arg)))
7465         return build_call_expr_loc (loc, fndecl, 1, narg);
7466     }
7467   
7468   return NULL_TREE;
7469 }
7470
7471 /* Fold function call to builtin ccos (or ccosh if HYPER is TRUE) with
7472    argument ARG.  TYPE is the type of the return value.  Return
7473    NULL_TREE if no simplification can be made.  */
7474
7475 static tree
7476 fold_builtin_ccos (location_t loc,
7477                    tree arg, tree type ATTRIBUTE_UNUSED, tree fndecl,
7478                    bool hyper ATTRIBUTE_UNUSED)
7479 {
7480   if (validate_arg (arg, COMPLEX_TYPE)
7481       && TREE_CODE (TREE_TYPE (TREE_TYPE (arg))) == REAL_TYPE)
7482     {
7483       tree tmp;
7484
7485 #ifdef HAVE_mpc
7486       /* Calculate the result when the argument is a constant.  */
7487       if ((tmp = do_mpc_arg1 (arg, type, (hyper ? mpc_cosh : mpc_cos))))
7488         return tmp;
7489 #endif
7490   
7491       /* Optimize fn(-x) into fn(x).  */
7492       if ((tmp = fold_strip_sign_ops (arg)))
7493         return build_call_expr_loc (loc, fndecl, 1, tmp);
7494     }
7495
7496   return NULL_TREE;
7497 }
7498
7499 /* Fold function call to builtin tan, tanf, or tanl with argument ARG.
7500    Return NULL_TREE if no simplification can be made.  */
7501
7502 static tree
7503 fold_builtin_tan (tree arg, tree type)
7504 {
7505   enum built_in_function fcode;
7506   tree res;
7507
7508   if (!validate_arg (arg, REAL_TYPE))
7509     return NULL_TREE;
7510
7511   /* Calculate the result when the argument is a constant.  */
7512   if ((res = do_mpfr_arg1 (arg, type, mpfr_tan, NULL, NULL, 0)))
7513     return res;
7514   
7515   /* Optimize tan(atan(x)) = x.  */
7516   fcode = builtin_mathfn_code (arg);
7517   if (flag_unsafe_math_optimizations
7518       && (fcode == BUILT_IN_ATAN
7519           || fcode == BUILT_IN_ATANF
7520           || fcode == BUILT_IN_ATANL))
7521     return CALL_EXPR_ARG (arg, 0);
7522
7523   return NULL_TREE;
7524 }
7525
7526 /* Fold function call to builtin sincos, sincosf, or sincosl.  Return
7527    NULL_TREE if no simplification can be made.  */
7528
7529 static tree
7530 fold_builtin_sincos (location_t loc,
7531                      tree arg0, tree arg1, tree arg2)
7532 {
7533   tree type;
7534   tree res, fn, call;
7535
7536   if (!validate_arg (arg0, REAL_TYPE)
7537       || !validate_arg (arg1, POINTER_TYPE)
7538       || !validate_arg (arg2, POINTER_TYPE))
7539     return NULL_TREE;
7540
7541   type = TREE_TYPE (arg0);
7542
7543   /* Calculate the result when the argument is a constant.  */
7544   if ((res = do_mpfr_sincos (arg0, arg1, arg2)))
7545     return res;
7546
7547   /* Canonicalize sincos to cexpi.  */
7548   if (!TARGET_C99_FUNCTIONS)
7549     return NULL_TREE;
7550   fn = mathfn_built_in (type, BUILT_IN_CEXPI);
7551   if (!fn)
7552     return NULL_TREE;
7553
7554   call = build_call_expr_loc (loc, fn, 1, arg0);
7555   call = builtin_save_expr (call);
7556
7557   return build2 (COMPOUND_EXPR, void_type_node,
7558                  build2 (MODIFY_EXPR, void_type_node,
7559                          build_fold_indirect_ref_loc (loc, arg1),
7560                          build1 (IMAGPART_EXPR, type, call)),
7561                  build2 (MODIFY_EXPR, void_type_node,
7562                          build_fold_indirect_ref_loc (loc, arg2),
7563                          build1 (REALPART_EXPR, type, call)));
7564 }
7565
7566 /* Fold function call to builtin cexp, cexpf, or cexpl.  Return
7567    NULL_TREE if no simplification can be made.  */
7568
7569 static tree
7570 fold_builtin_cexp (location_t loc, tree arg0, tree type)
7571 {
7572   tree rtype;
7573   tree realp, imagp, ifn;
7574 #ifdef HAVE_mpc
7575   tree res;
7576 #endif
7577
7578   if (!validate_arg (arg0, COMPLEX_TYPE)
7579       || TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) != REAL_TYPE)
7580     return NULL_TREE;
7581
7582 #ifdef HAVE_mpc
7583   /* Calculate the result when the argument is a constant.  */
7584   if ((res = do_mpc_arg1 (arg0, type, mpc_exp)))
7585     return res;
7586 #endif
7587   
7588   rtype = TREE_TYPE (TREE_TYPE (arg0));
7589
7590   /* In case we can figure out the real part of arg0 and it is constant zero
7591      fold to cexpi.  */
7592   if (!TARGET_C99_FUNCTIONS)
7593     return NULL_TREE;
7594   ifn = mathfn_built_in (rtype, BUILT_IN_CEXPI);
7595   if (!ifn)
7596     return NULL_TREE;
7597
7598   if ((realp = fold_unary_loc (loc, REALPART_EXPR, rtype, arg0))
7599       && real_zerop (realp))
7600     {
7601       tree narg = fold_build1_loc (loc, IMAGPART_EXPR, rtype, arg0);
7602       return build_call_expr_loc (loc, ifn, 1, narg);
7603     }
7604
7605   /* In case we can easily decompose real and imaginary parts split cexp
7606      to exp (r) * cexpi (i).  */
7607   if (flag_unsafe_math_optimizations
7608       && realp)
7609     {
7610       tree rfn, rcall, icall;
7611
7612       rfn = mathfn_built_in (rtype, BUILT_IN_EXP);
7613       if (!rfn)
7614         return NULL_TREE;
7615
7616       imagp = fold_unary_loc (loc, IMAGPART_EXPR, rtype, arg0);
7617       if (!imagp)
7618         return NULL_TREE;
7619
7620       icall = build_call_expr_loc (loc, ifn, 1, imagp);
7621       icall = builtin_save_expr (icall);
7622       rcall = build_call_expr_loc (loc, rfn, 1, realp);
7623       rcall = builtin_save_expr (rcall);
7624       return fold_build2_loc (loc, COMPLEX_EXPR, type,
7625                           fold_build2_loc (loc, MULT_EXPR, rtype,
7626                                        rcall,
7627                                        fold_build1_loc (loc, REALPART_EXPR,
7628                                                     rtype, icall)),
7629                           fold_build2_loc (loc, MULT_EXPR, rtype,
7630                                        rcall,
7631                                        fold_build1_loc (loc, IMAGPART_EXPR,
7632                                                     rtype, icall)));
7633     }
7634
7635   return NULL_TREE;
7636 }
7637
7638 /* Fold function call to builtin trunc, truncf or truncl with argument ARG.
7639    Return NULL_TREE if no simplification can be made.  */
7640
7641 static tree
7642 fold_builtin_trunc (location_t loc, tree fndecl, tree arg)
7643 {
7644   if (!validate_arg (arg, REAL_TYPE))
7645     return NULL_TREE;
7646
7647   /* Optimize trunc of constant value.  */
7648   if (TREE_CODE (arg) == REAL_CST && !TREE_OVERFLOW (arg))
7649     {
7650       REAL_VALUE_TYPE r, x;
7651       tree type = TREE_TYPE (TREE_TYPE (fndecl));
7652
7653       x = TREE_REAL_CST (arg);
7654       real_trunc (&r, TYPE_MODE (type), &x);
7655       return build_real (type, r);
7656     }
7657
7658   return fold_trunc_transparent_mathfn (loc, fndecl, arg);
7659 }
7660
7661 /* Fold function call to builtin floor, floorf or floorl with argument ARG.
7662    Return NULL_TREE if no simplification can be made.  */
7663
7664 static tree
7665 fold_builtin_floor (location_t loc, tree fndecl, tree arg)
7666 {
7667   if (!validate_arg (arg, REAL_TYPE))
7668     return NULL_TREE;
7669
7670   /* Optimize floor of constant value.  */
7671   if (TREE_CODE (arg) == REAL_CST && !TREE_OVERFLOW (arg))
7672     {
7673       REAL_VALUE_TYPE x;
7674
7675       x = TREE_REAL_CST (arg);
7676       if (! REAL_VALUE_ISNAN (x) || ! flag_errno_math)
7677         {
7678           tree type = TREE_TYPE (TREE_TYPE (fndecl));
7679           REAL_VALUE_TYPE r;
7680
7681           real_floor (&r, TYPE_MODE (type), &x);
7682           return build_real (type, r);
7683         }
7684     }
7685
7686   /* Fold floor (x) where x is nonnegative to trunc (x).  */
7687   if (tree_expr_nonnegative_p (arg))
7688     {
7689       tree truncfn = mathfn_built_in (TREE_TYPE (arg), BUILT_IN_TRUNC);
7690       if (truncfn)
7691         return build_call_expr_loc (loc, truncfn, 1, arg);
7692     }
7693
7694   return fold_trunc_transparent_mathfn (loc, fndecl, arg);
7695 }
7696
7697 /* Fold function call to builtin ceil, ceilf or ceill with argument ARG.
7698    Return NULL_TREE if no simplification can be made.  */
7699
7700 static tree
7701 fold_builtin_ceil (location_t loc, tree fndecl, tree arg)
7702 {
7703   if (!validate_arg (arg, REAL_TYPE))
7704     return NULL_TREE;
7705
7706   /* Optimize ceil of constant value.  */
7707   if (TREE_CODE (arg) == REAL_CST && !TREE_OVERFLOW (arg))
7708     {
7709       REAL_VALUE_TYPE x;
7710
7711       x = TREE_REAL_CST (arg);
7712       if (! REAL_VALUE_ISNAN (x) || ! flag_errno_math)
7713         {
7714           tree type = TREE_TYPE (TREE_TYPE (fndecl));
7715           REAL_VALUE_TYPE r;
7716
7717           real_ceil (&r, TYPE_MODE (type), &x);
7718           return build_real (type, r);
7719         }
7720     }
7721
7722   return fold_trunc_transparent_mathfn (loc, fndecl, arg);
7723 }
7724
7725 /* Fold function call to builtin round, roundf or roundl with argument ARG.
7726    Return NULL_TREE if no simplification can be made.  */
7727
7728 static tree
7729 fold_builtin_round (location_t loc, tree fndecl, tree arg)
7730 {
7731   if (!validate_arg (arg, REAL_TYPE))
7732     return NULL_TREE;
7733
7734   /* Optimize round of constant value.  */
7735   if (TREE_CODE (arg) == REAL_CST && !TREE_OVERFLOW (arg))
7736     {
7737       REAL_VALUE_TYPE x;
7738
7739       x = TREE_REAL_CST (arg);
7740       if (! REAL_VALUE_ISNAN (x) || ! flag_errno_math)
7741         {
7742           tree type = TREE_TYPE (TREE_TYPE (fndecl));
7743           REAL_VALUE_TYPE r;
7744
7745           real_round (&r, TYPE_MODE (type), &x);
7746           return build_real (type, r);
7747         }
7748     }
7749
7750   return fold_trunc_transparent_mathfn (loc, fndecl, arg);
7751 }
7752
7753 /* Fold function call to builtin lround, lroundf or lroundl (or the
7754    corresponding long long versions) and other rounding functions.  ARG
7755    is the argument to the call.  Return NULL_TREE if no simplification
7756    can be made.  */
7757
7758 static tree
7759 fold_builtin_int_roundingfn (location_t loc, tree fndecl, tree arg)
7760 {
7761   if (!validate_arg (arg, REAL_TYPE))
7762     return NULL_TREE;
7763
7764   /* Optimize lround of constant value.  */
7765   if (TREE_CODE (arg) == REAL_CST && !TREE_OVERFLOW (arg))
7766     {
7767       const REAL_VALUE_TYPE x = TREE_REAL_CST (arg);
7768
7769       if (real_isfinite (&x))
7770         {
7771           tree itype = TREE_TYPE (TREE_TYPE (fndecl));
7772           tree ftype = TREE_TYPE (arg);
7773           unsigned HOST_WIDE_INT lo2;
7774           HOST_WIDE_INT hi, lo;
7775           REAL_VALUE_TYPE r;
7776
7777           switch (DECL_FUNCTION_CODE (fndecl))
7778             {
7779             CASE_FLT_FN (BUILT_IN_LFLOOR):
7780             CASE_FLT_FN (BUILT_IN_LLFLOOR):
7781               real_floor (&r, TYPE_MODE (ftype), &x);
7782               break;
7783
7784             CASE_FLT_FN (BUILT_IN_LCEIL):
7785             CASE_FLT_FN (BUILT_IN_LLCEIL):
7786               real_ceil (&r, TYPE_MODE (ftype), &x);
7787               break;
7788
7789             CASE_FLT_FN (BUILT_IN_LROUND):
7790             CASE_FLT_FN (BUILT_IN_LLROUND):
7791               real_round (&r, TYPE_MODE (ftype), &x);
7792               break;
7793
7794             default:
7795               gcc_unreachable ();
7796             }
7797
7798           REAL_VALUE_TO_INT (&lo, &hi, r);
7799           if (!fit_double_type (lo, hi, &lo2, &hi, itype))
7800             return build_int_cst_wide (itype, lo2, hi);
7801         }
7802     }
7803
7804   switch (DECL_FUNCTION_CODE (fndecl))
7805     {
7806     CASE_FLT_FN (BUILT_IN_LFLOOR):
7807     CASE_FLT_FN (BUILT_IN_LLFLOOR):
7808       /* Fold lfloor (x) where x is nonnegative to FIX_TRUNC (x).  */
7809       if (tree_expr_nonnegative_p (arg))
7810         return fold_build1_loc (loc, FIX_TRUNC_EXPR,
7811                             TREE_TYPE (TREE_TYPE (fndecl)), arg);
7812       break;
7813     default:;
7814     }
7815
7816   return fold_fixed_mathfn (loc, fndecl, arg);
7817 }
7818
7819 /* Fold function call to builtin ffs, clz, ctz, popcount and parity
7820    and their long and long long variants (i.e. ffsl and ffsll).  ARG is
7821    the argument to the call.  Return NULL_TREE if no simplification can
7822    be made.  */
7823
7824 static tree
7825 fold_builtin_bitop (tree fndecl, tree arg)
7826 {
7827   if (!validate_arg (arg, INTEGER_TYPE))
7828     return NULL_TREE;
7829
7830   /* Optimize for constant argument.  */
7831   if (TREE_CODE (arg) == INTEGER_CST && !TREE_OVERFLOW (arg))
7832     {
7833       HOST_WIDE_INT hi, width, result;
7834       unsigned HOST_WIDE_INT lo;
7835       tree type;
7836
7837       type = TREE_TYPE (arg);
7838       width = TYPE_PRECISION (type);
7839       lo = TREE_INT_CST_LOW (arg);
7840
7841       /* Clear all the bits that are beyond the type's precision.  */
7842       if (width > HOST_BITS_PER_WIDE_INT)
7843         {
7844           hi = TREE_INT_CST_HIGH (arg);
7845           if (width < 2 * HOST_BITS_PER_WIDE_INT)
7846             hi &= ~((HOST_WIDE_INT) (-1) >> (width - HOST_BITS_PER_WIDE_INT));
7847         }
7848       else
7849         {
7850           hi = 0;
7851           if (width < HOST_BITS_PER_WIDE_INT)
7852             lo &= ~((unsigned HOST_WIDE_INT) (-1) << width);
7853         }
7854
7855       switch (DECL_FUNCTION_CODE (fndecl))
7856         {
7857         CASE_INT_FN (BUILT_IN_FFS):
7858           if (lo != 0)
7859             result = exact_log2 (lo & -lo) + 1;
7860           else if (hi != 0)
7861             result = HOST_BITS_PER_WIDE_INT + exact_log2 (hi & -hi) + 1;
7862           else
7863             result = 0;
7864           break;
7865
7866         CASE_INT_FN (BUILT_IN_CLZ):
7867           if (hi != 0)
7868             result = width - floor_log2 (hi) - 1 - HOST_BITS_PER_WIDE_INT;
7869           else if (lo != 0)
7870             result = width - floor_log2 (lo) - 1;
7871           else if (! CLZ_DEFINED_VALUE_AT_ZERO (TYPE_MODE (type), result))
7872             result = width;
7873           break;
7874
7875         CASE_INT_FN (BUILT_IN_CTZ):
7876           if (lo != 0)
7877             result = exact_log2 (lo & -lo);
7878           else if (hi != 0)
7879             result = HOST_BITS_PER_WIDE_INT + exact_log2 (hi & -hi);
7880           else if (! CTZ_DEFINED_VALUE_AT_ZERO (TYPE_MODE (type), result))
7881             result = width;
7882           break;
7883
7884         CASE_INT_FN (BUILT_IN_POPCOUNT):
7885           result = 0;
7886           while (lo)
7887             result++, lo &= lo - 1;
7888           while (hi)
7889             result++, hi &= hi - 1;
7890           break;
7891
7892         CASE_INT_FN (BUILT_IN_PARITY):
7893           result = 0;
7894           while (lo)
7895             result++, lo &= lo - 1;
7896           while (hi)
7897             result++, hi &= hi - 1;
7898           result &= 1;
7899           break;
7900
7901         default:
7902           gcc_unreachable ();
7903         }
7904
7905       return build_int_cst (TREE_TYPE (TREE_TYPE (fndecl)), result);
7906     }
7907
7908   return NULL_TREE;
7909 }
7910
7911 /* Fold function call to builtin_bswap and the long and long long
7912    variants.  Return NULL_TREE if no simplification can be made.  */
7913 static tree
7914 fold_builtin_bswap (tree fndecl, tree arg)
7915 {
7916   if (! validate_arg (arg, INTEGER_TYPE))
7917     return NULL_TREE;
7918
7919   /* Optimize constant value.  */
7920   if (TREE_CODE (arg) == INTEGER_CST && !TREE_OVERFLOW (arg))
7921     {
7922       HOST_WIDE_INT hi, width, r_hi = 0;
7923       unsigned HOST_WIDE_INT lo, r_lo = 0;
7924       tree type;
7925
7926       type = TREE_TYPE (arg);
7927       width = TYPE_PRECISION (type);
7928       lo = TREE_INT_CST_LOW (arg);
7929       hi = TREE_INT_CST_HIGH (arg);
7930
7931       switch (DECL_FUNCTION_CODE (fndecl))
7932         {
7933           case BUILT_IN_BSWAP32:
7934           case BUILT_IN_BSWAP64:
7935             {
7936               int s;
7937
7938               for (s = 0; s < width; s += 8)
7939                 {
7940                   int d = width - s - 8;
7941                   unsigned HOST_WIDE_INT byte;
7942
7943                   if (s < HOST_BITS_PER_WIDE_INT)
7944                     byte = (lo >> s) & 0xff;
7945                   else
7946                     byte = (hi >> (s - HOST_BITS_PER_WIDE_INT)) & 0xff;
7947
7948                   if (d < HOST_BITS_PER_WIDE_INT)
7949                     r_lo |= byte << d;
7950                   else
7951                     r_hi |= byte << (d - HOST_BITS_PER_WIDE_INT);
7952                 }
7953             }
7954
7955             break;
7956
7957         default:
7958           gcc_unreachable ();
7959         }
7960
7961       if (width < HOST_BITS_PER_WIDE_INT)
7962         return build_int_cst (TREE_TYPE (TREE_TYPE (fndecl)), r_lo);
7963       else
7964         return build_int_cst_wide (TREE_TYPE (TREE_TYPE (fndecl)), r_lo, r_hi);
7965     }
7966
7967   return NULL_TREE;
7968 }
7969
7970 /* A subroutine of fold_builtin to fold the various logarithmic
7971    functions.  Return NULL_TREE if no simplification can me made.
7972    FUNC is the corresponding MPFR logarithm function.  */
7973
7974 static tree
7975 fold_builtin_logarithm (location_t loc, tree fndecl, tree arg,
7976                         int (*func)(mpfr_ptr, mpfr_srcptr, mp_rnd_t))
7977 {
7978   if (validate_arg (arg, REAL_TYPE))
7979     {
7980       tree type = TREE_TYPE (TREE_TYPE (fndecl));
7981       tree res;
7982       const enum built_in_function fcode = builtin_mathfn_code (arg);
7983
7984       /* Calculate the result when the argument is a constant.  */
7985       if ((res = do_mpfr_arg1 (arg, type, func, &dconst0, NULL, false)))
7986         return res;
7987
7988       /* Special case, optimize logN(expN(x)) = x.  */
7989       if (flag_unsafe_math_optimizations
7990           && ((func == mpfr_log
7991                && (fcode == BUILT_IN_EXP
7992                    || fcode == BUILT_IN_EXPF
7993                    || fcode == BUILT_IN_EXPL))
7994               || (func == mpfr_log2
7995                   && (fcode == BUILT_IN_EXP2
7996                       || fcode == BUILT_IN_EXP2F
7997                       || fcode == BUILT_IN_EXP2L))
7998               || (func == mpfr_log10 && (BUILTIN_EXP10_P (fcode)))))
7999         return fold_convert_loc (loc, type, CALL_EXPR_ARG (arg, 0));
8000
8001       /* Optimize logN(func()) for various exponential functions.  We
8002          want to determine the value "x" and the power "exponent" in
8003          order to transform logN(x**exponent) into exponent*logN(x).  */
8004       if (flag_unsafe_math_optimizations)
8005         {
8006           tree exponent = 0, x = 0;
8007
8008           switch (fcode)
8009           {
8010           CASE_FLT_FN (BUILT_IN_EXP):
8011             /* Prepare to do logN(exp(exponent) -> exponent*logN(e).  */
8012             x = build_real (type, real_value_truncate (TYPE_MODE (type), 
8013                                                        dconst_e ()));
8014             exponent = CALL_EXPR_ARG (arg, 0);
8015             break;
8016           CASE_FLT_FN (BUILT_IN_EXP2):
8017             /* Prepare to do logN(exp2(exponent) -> exponent*logN(2).  */
8018             x = build_real (type, dconst2);
8019             exponent = CALL_EXPR_ARG (arg, 0);
8020             break;
8021           CASE_FLT_FN (BUILT_IN_EXP10):
8022           CASE_FLT_FN (BUILT_IN_POW10):
8023             /* Prepare to do logN(exp10(exponent) -> exponent*logN(10).  */
8024             {
8025               REAL_VALUE_TYPE dconst10;
8026               real_from_integer (&dconst10, VOIDmode, 10, 0, 0);
8027               x = build_real (type, dconst10);
8028             }
8029             exponent = CALL_EXPR_ARG (arg, 0);
8030             break;
8031           CASE_FLT_FN (BUILT_IN_SQRT):
8032             /* Prepare to do logN(sqrt(x) -> 0.5*logN(x).  */
8033             x = CALL_EXPR_ARG (arg, 0);
8034             exponent = build_real (type, dconsthalf);
8035             break;
8036           CASE_FLT_FN (BUILT_IN_CBRT):
8037             /* Prepare to do logN(cbrt(x) -> (1/3)*logN(x).  */
8038             x = CALL_EXPR_ARG (arg, 0);
8039             exponent = build_real (type, real_value_truncate (TYPE_MODE (type),
8040                                                               dconst_third ()));
8041             break;
8042           CASE_FLT_FN (BUILT_IN_POW):
8043             /* Prepare to do logN(pow(x,exponent) -> exponent*logN(x).  */
8044             x = CALL_EXPR_ARG (arg, 0);
8045             exponent = CALL_EXPR_ARG (arg, 1);
8046             break;
8047           default:
8048             break;
8049           }
8050
8051           /* Now perform the optimization.  */
8052           if (x && exponent)
8053             {
8054               tree logfn = build_call_expr_loc (loc, fndecl, 1, x);
8055               return fold_build2_loc (loc, MULT_EXPR, type, exponent, logfn);
8056             }
8057         }
8058     }
8059
8060   return NULL_TREE;
8061 }
8062
8063 /* Fold a builtin function call to hypot, hypotf, or hypotl.  Return
8064    NULL_TREE if no simplification can be made.  */
8065
8066 static tree
8067 fold_builtin_hypot (location_t loc, tree fndecl,
8068                     tree arg0, tree arg1, tree type)
8069 {
8070   tree res, narg0, narg1;
8071
8072   if (!validate_arg (arg0, REAL_TYPE)
8073       || !validate_arg (arg1, REAL_TYPE))
8074     return NULL_TREE;
8075
8076   /* Calculate the result when the argument is a constant.  */
8077   if ((res = do_mpfr_arg2 (arg0, arg1, type, mpfr_hypot)))
8078     return res;
8079   
8080   /* If either argument to hypot has a negate or abs, strip that off.
8081      E.g. hypot(-x,fabs(y)) -> hypot(x,y).  */
8082   narg0 = fold_strip_sign_ops (arg0);
8083   narg1 = fold_strip_sign_ops (arg1);
8084   if (narg0 || narg1)
8085     {
8086       return build_call_expr_loc (loc, fndecl, 2, narg0 ? narg0 : arg0, 
8087                               narg1 ? narg1 : arg1);
8088     }
8089   
8090   /* If either argument is zero, hypot is fabs of the other.  */
8091   if (real_zerop (arg0))
8092     return fold_build1_loc (loc, ABS_EXPR, type, arg1);
8093   else if (real_zerop (arg1))
8094     return fold_build1_loc (loc, ABS_EXPR, type, arg0);
8095       
8096   /* hypot(x,x) -> fabs(x)*sqrt(2).  */
8097   if (flag_unsafe_math_optimizations
8098       && operand_equal_p (arg0, arg1, OEP_PURE_SAME))
8099     {
8100       const REAL_VALUE_TYPE sqrt2_trunc
8101         = real_value_truncate (TYPE_MODE (type), dconst_sqrt2 ());
8102       return fold_build2_loc (loc, MULT_EXPR, type,
8103                           fold_build1_loc (loc, ABS_EXPR, type, arg0),
8104                           build_real (type, sqrt2_trunc));
8105     }
8106
8107   return NULL_TREE;
8108 }
8109
8110
8111 /* Fold a builtin function call to pow, powf, or powl.  Return
8112    NULL_TREE if no simplification can be made.  */
8113 static tree
8114 fold_builtin_pow (location_t loc, tree fndecl, tree arg0, tree arg1, tree type)
8115 {
8116   tree res;
8117
8118   if (!validate_arg (arg0, REAL_TYPE)
8119        || !validate_arg (arg1, REAL_TYPE))
8120     return NULL_TREE;
8121
8122   /* Calculate the result when the argument is a constant.  */
8123   if ((res = do_mpfr_arg2 (arg0, arg1, type, mpfr_pow)))
8124     return res;
8125
8126   /* Optimize pow(1.0,y) = 1.0.  */
8127   if (real_onep (arg0))
8128     return omit_one_operand_loc (loc, type, build_real (type, dconst1), arg1);
8129
8130   if (TREE_CODE (arg1) == REAL_CST
8131       && !TREE_OVERFLOW (arg1))
8132     {
8133       REAL_VALUE_TYPE cint;
8134       REAL_VALUE_TYPE c;
8135       HOST_WIDE_INT n;
8136
8137       c = TREE_REAL_CST (arg1);
8138
8139       /* Optimize pow(x,0.0) = 1.0.  */
8140       if (REAL_VALUES_EQUAL (c, dconst0))
8141         return omit_one_operand_loc (loc, type, build_real (type, dconst1),
8142                                  arg0);
8143
8144       /* Optimize pow(x,1.0) = x.  */
8145       if (REAL_VALUES_EQUAL (c, dconst1))
8146         return arg0;
8147
8148       /* Optimize pow(x,-1.0) = 1.0/x.  */
8149       if (REAL_VALUES_EQUAL (c, dconstm1))
8150         return fold_build2_loc (loc, RDIV_EXPR, type,
8151                             build_real (type, dconst1), arg0);
8152
8153       /* Optimize pow(x,0.5) = sqrt(x).  */
8154       if (flag_unsafe_math_optimizations
8155           && REAL_VALUES_EQUAL (c, dconsthalf))
8156         {
8157           tree sqrtfn = mathfn_built_in (type, BUILT_IN_SQRT);
8158
8159           if (sqrtfn != NULL_TREE)
8160             return build_call_expr_loc (loc, sqrtfn, 1, arg0);
8161         }
8162
8163       /* Optimize pow(x,1.0/3.0) = cbrt(x).  */
8164       if (flag_unsafe_math_optimizations)
8165         {
8166           const REAL_VALUE_TYPE dconstroot
8167             = real_value_truncate (TYPE_MODE (type), dconst_third ());
8168
8169           if (REAL_VALUES_EQUAL (c, dconstroot))
8170             {
8171               tree cbrtfn = mathfn_built_in (type, BUILT_IN_CBRT);
8172               if (cbrtfn != NULL_TREE)
8173                 return build_call_expr_loc (loc, cbrtfn, 1, arg0);
8174             }
8175         }
8176
8177       /* Check for an integer exponent.  */
8178       n = real_to_integer (&c);
8179       real_from_integer (&cint, VOIDmode, n, n < 0 ? -1 : 0, 0);
8180       if (real_identical (&c, &cint))
8181         {
8182           /* Attempt to evaluate pow at compile-time, unless this should
8183              raise an exception.  */
8184           if (TREE_CODE (arg0) == REAL_CST
8185               && !TREE_OVERFLOW (arg0)
8186               && (n > 0
8187                   || (!flag_trapping_math && !flag_errno_math)
8188                   || !REAL_VALUES_EQUAL (TREE_REAL_CST (arg0), dconst0)))
8189             {
8190               REAL_VALUE_TYPE x;
8191               bool inexact;
8192
8193               x = TREE_REAL_CST (arg0);
8194               inexact = real_powi (&x, TYPE_MODE (type), &x, n);
8195               if (flag_unsafe_math_optimizations || !inexact)
8196                 return build_real (type, x);
8197             }
8198
8199           /* Strip sign ops from even integer powers.  */
8200           if ((n & 1) == 0 && flag_unsafe_math_optimizations)
8201             {
8202               tree narg0 = fold_strip_sign_ops (arg0);
8203               if (narg0)
8204                 return build_call_expr_loc (loc, fndecl, 2, narg0, arg1);
8205             }
8206         }
8207     }
8208
8209   if (flag_unsafe_math_optimizations)
8210     {
8211       const enum built_in_function fcode = builtin_mathfn_code (arg0);
8212
8213       /* Optimize pow(expN(x),y) = expN(x*y).  */
8214       if (BUILTIN_EXPONENT_P (fcode))
8215         {
8216           tree expfn = TREE_OPERAND (CALL_EXPR_FN (arg0), 0);
8217           tree arg = CALL_EXPR_ARG (arg0, 0);
8218           arg = fold_build2_loc (loc, MULT_EXPR, type, arg, arg1);
8219           return build_call_expr_loc (loc, expfn, 1, arg);
8220         }
8221
8222       /* Optimize pow(sqrt(x),y) = pow(x,y*0.5).  */
8223       if (BUILTIN_SQRT_P (fcode))
8224         {
8225           tree narg0 = CALL_EXPR_ARG (arg0, 0);
8226           tree narg1 = fold_build2_loc (loc, MULT_EXPR, type, arg1,
8227                                     build_real (type, dconsthalf));
8228           return build_call_expr_loc (loc, fndecl, 2, narg0, narg1);
8229         }
8230
8231       /* Optimize pow(cbrt(x),y) = pow(x,y/3) iff x is nonnegative.  */
8232       if (BUILTIN_CBRT_P (fcode))
8233         {
8234           tree arg = CALL_EXPR_ARG (arg0, 0);
8235           if (tree_expr_nonnegative_p (arg))
8236             {
8237               const REAL_VALUE_TYPE dconstroot
8238                 = real_value_truncate (TYPE_MODE (type), dconst_third ());
8239               tree narg1 = fold_build2_loc (loc, MULT_EXPR, type, arg1,
8240                                         build_real (type, dconstroot));
8241               return build_call_expr_loc (loc, fndecl, 2, arg, narg1);
8242             }
8243         }
8244
8245       /* Optimize pow(pow(x,y),z) = pow(x,y*z) iff x is nonnegative.  */
8246       if (fcode == BUILT_IN_POW
8247           || fcode == BUILT_IN_POWF
8248           || fcode == BUILT_IN_POWL)
8249         {
8250           tree arg00 = CALL_EXPR_ARG (arg0, 0);
8251           if (tree_expr_nonnegative_p (arg00))
8252             {
8253               tree arg01 = CALL_EXPR_ARG (arg0, 1);
8254               tree narg1 = fold_build2_loc (loc, MULT_EXPR, type, arg01, arg1);
8255               return build_call_expr_loc (loc, fndecl, 2, arg00, narg1);
8256             }
8257         }
8258     }
8259
8260   return NULL_TREE;
8261 }
8262
8263 /* Fold a builtin function call to powi, powif, or powil with argument ARG.
8264    Return NULL_TREE if no simplification can be made.  */
8265 static tree
8266 fold_builtin_powi (location_t loc, tree fndecl ATTRIBUTE_UNUSED,
8267                    tree arg0, tree arg1, tree type)
8268 {
8269   if (!validate_arg (arg0, REAL_TYPE)
8270       || !validate_arg (arg1, INTEGER_TYPE))
8271     return NULL_TREE;
8272
8273   /* Optimize pow(1.0,y) = 1.0.  */
8274   if (real_onep (arg0))
8275     return omit_one_operand_loc (loc, type, build_real (type, dconst1), arg1);
8276
8277   if (host_integerp (arg1, 0))
8278     {
8279       HOST_WIDE_INT c = TREE_INT_CST_LOW (arg1);
8280
8281       /* Evaluate powi at compile-time.  */
8282       if (TREE_CODE (arg0) == REAL_CST
8283           && !TREE_OVERFLOW (arg0))
8284         {
8285           REAL_VALUE_TYPE x;
8286           x = TREE_REAL_CST (arg0);
8287           real_powi (&x, TYPE_MODE (type), &x, c);
8288           return build_real (type, x);
8289         }
8290
8291       /* Optimize pow(x,0) = 1.0.  */
8292       if (c == 0)
8293         return omit_one_operand_loc (loc, type, build_real (type, dconst1),
8294                                  arg0);
8295
8296       /* Optimize pow(x,1) = x.  */
8297       if (c == 1)
8298         return arg0;
8299
8300       /* Optimize pow(x,-1) = 1.0/x.  */
8301       if (c == -1)
8302         return fold_build2_loc (loc, RDIV_EXPR, type,
8303                            build_real (type, dconst1), arg0);
8304     }
8305
8306   return NULL_TREE;
8307 }
8308
8309 /* A subroutine of fold_builtin to fold the various exponent
8310    functions.  Return NULL_TREE if no simplification can be made.
8311    FUNC is the corresponding MPFR exponent function.  */
8312
8313 static tree
8314 fold_builtin_exponent (location_t loc, tree fndecl, tree arg,
8315                        int (*func)(mpfr_ptr, mpfr_srcptr, mp_rnd_t))
8316 {
8317   if (validate_arg (arg, REAL_TYPE))
8318     {
8319       tree type = TREE_TYPE (TREE_TYPE (fndecl));
8320       tree res;
8321       
8322       /* Calculate the result when the argument is a constant.  */
8323       if ((res = do_mpfr_arg1 (arg, type, func, NULL, NULL, 0)))
8324         return res;
8325
8326       /* Optimize expN(logN(x)) = x.  */
8327       if (flag_unsafe_math_optimizations)
8328         {
8329           const enum built_in_function fcode = builtin_mathfn_code (arg);
8330
8331           if ((func == mpfr_exp
8332                && (fcode == BUILT_IN_LOG
8333                    || fcode == BUILT_IN_LOGF
8334                    || fcode == BUILT_IN_LOGL))
8335               || (func == mpfr_exp2
8336                   && (fcode == BUILT_IN_LOG2
8337                       || fcode == BUILT_IN_LOG2F
8338                       || fcode == BUILT_IN_LOG2L))
8339               || (func == mpfr_exp10
8340                   && (fcode == BUILT_IN_LOG10
8341                       || fcode == BUILT_IN_LOG10F
8342                       || fcode == BUILT_IN_LOG10L)))
8343             return fold_convert_loc (loc, type, CALL_EXPR_ARG (arg, 0));
8344         }
8345     }
8346
8347   return NULL_TREE;
8348 }
8349
8350 /* Return true if VAR is a VAR_DECL or a component thereof.  */
8351
8352 static bool
8353 var_decl_component_p (tree var)
8354 {
8355   tree inner = var;
8356   while (handled_component_p (inner))
8357     inner = TREE_OPERAND (inner, 0);
8358   return SSA_VAR_P (inner);
8359 }
8360
8361 /* Fold function call to builtin memset.  Return
8362    NULL_TREE if no simplification can be made.  */
8363
8364 static tree
8365 fold_builtin_memset (location_t loc, tree dest, tree c, tree len,
8366                      tree type, bool ignore)
8367 {
8368   tree var, ret, etype;
8369   unsigned HOST_WIDE_INT length, cval;
8370
8371   if (! validate_arg (dest, POINTER_TYPE)
8372       || ! validate_arg (c, INTEGER_TYPE)
8373       || ! validate_arg (len, INTEGER_TYPE))
8374     return NULL_TREE;
8375
8376   if (! host_integerp (len, 1))
8377     return NULL_TREE;
8378
8379   /* If the LEN parameter is zero, return DEST.  */
8380   if (integer_zerop (len))
8381     return omit_one_operand_loc (loc, type, dest, c);
8382
8383   if (! host_integerp (c, 1) || TREE_SIDE_EFFECTS (dest))
8384     return NULL_TREE;
8385
8386   var = dest;
8387   STRIP_NOPS (var);
8388   if (TREE_CODE (var) != ADDR_EXPR)
8389     return NULL_TREE;
8390
8391   var = TREE_OPERAND (var, 0);
8392   if (TREE_THIS_VOLATILE (var))
8393     return NULL_TREE;
8394
8395   etype = TREE_TYPE (var);
8396   if (TREE_CODE (etype) == ARRAY_TYPE)
8397     etype = TREE_TYPE (etype);
8398
8399   if (!INTEGRAL_TYPE_P (etype)
8400       && !POINTER_TYPE_P (etype))
8401     return NULL_TREE;
8402
8403   if (! var_decl_component_p (var))
8404     return NULL_TREE;
8405
8406   length = tree_low_cst (len, 1);
8407   if (GET_MODE_SIZE (TYPE_MODE (etype)) != length
8408       || get_pointer_alignment (dest, BIGGEST_ALIGNMENT) / BITS_PER_UNIT
8409          < (int) length)
8410     return NULL_TREE;
8411
8412   if (length > HOST_BITS_PER_WIDE_INT / BITS_PER_UNIT)
8413     return NULL_TREE;
8414
8415   if (integer_zerop (c))
8416     cval = 0;
8417   else
8418     {
8419       if (CHAR_BIT != 8 || BITS_PER_UNIT != 8 || HOST_BITS_PER_WIDE_INT > 64)
8420         return NULL_TREE;
8421
8422       cval = tree_low_cst (c, 1);
8423       cval &= 0xff;
8424       cval |= cval << 8;
8425       cval |= cval << 16;
8426       cval |= (cval << 31) << 1;
8427     }
8428
8429   ret = build_int_cst_type (etype, cval);
8430   var = build_fold_indirect_ref_loc (loc,
8431                                  fold_convert_loc (loc,
8432                                                    build_pointer_type (etype),
8433                                                    dest));
8434   ret = build2 (MODIFY_EXPR, etype, var, ret);
8435   if (ignore)
8436     return ret;
8437
8438   return omit_one_operand_loc (loc, type, dest, ret);
8439 }
8440
8441 /* Fold function call to builtin memset.  Return
8442    NULL_TREE if no simplification can be made.  */
8443
8444 static tree
8445 fold_builtin_bzero (location_t loc, tree dest, tree size, bool ignore)
8446 {
8447   if (! validate_arg (dest, POINTER_TYPE)
8448       || ! validate_arg (size, INTEGER_TYPE))
8449     return NULL_TREE;
8450
8451   if (!ignore)
8452     return NULL_TREE;
8453
8454   /* New argument list transforming bzero(ptr x, int y) to
8455      memset(ptr x, int 0, size_t y).   This is done this way
8456      so that if it isn't expanded inline, we fallback to
8457      calling bzero instead of memset.  */
8458
8459   return fold_builtin_memset (loc, dest, integer_zero_node,
8460                               fold_convert_loc (loc, sizetype, size),
8461                               void_type_node, ignore);
8462 }
8463
8464 /* Fold function call to builtin mem{{,p}cpy,move}.  Return
8465    NULL_TREE if no simplification can be made.
8466    If ENDP is 0, return DEST (like memcpy).
8467    If ENDP is 1, return DEST+LEN (like mempcpy).
8468    If ENDP is 2, return DEST+LEN-1 (like stpcpy).
8469    If ENDP is 3, return DEST, additionally *SRC and *DEST may overlap
8470    (memmove).   */
8471
8472 static tree
8473 fold_builtin_memory_op (location_t loc, tree dest, tree src,
8474                         tree len, tree type, bool ignore, int endp)
8475 {
8476   tree destvar, srcvar, expr;
8477
8478   if (! validate_arg (dest, POINTER_TYPE)
8479       || ! validate_arg (src, POINTER_TYPE)
8480       || ! validate_arg (len, INTEGER_TYPE))
8481     return NULL_TREE;
8482
8483   /* If the LEN parameter is zero, return DEST.  */
8484   if (integer_zerop (len))
8485     return omit_one_operand_loc (loc, type, dest, src);
8486
8487   /* If SRC and DEST are the same (and not volatile), return
8488      DEST{,+LEN,+LEN-1}.  */
8489   if (operand_equal_p (src, dest, 0))
8490     expr = len;
8491   else
8492     {
8493       tree srctype, desttype;
8494       int src_align, dest_align;
8495
8496       if (endp == 3)
8497         {
8498           src_align = get_pointer_alignment (src, BIGGEST_ALIGNMENT);
8499           dest_align = get_pointer_alignment (dest, BIGGEST_ALIGNMENT);
8500
8501           /* Both DEST and SRC must be pointer types. 
8502              ??? This is what old code did.  Is the testing for pointer types
8503              really mandatory?
8504
8505              If either SRC is readonly or length is 1, we can use memcpy.  */
8506           if (!dest_align || !src_align)
8507             return NULL_TREE;
8508           if (readonly_data_expr (src)
8509               || (host_integerp (len, 1)
8510                   && (MIN (src_align, dest_align) / BITS_PER_UNIT
8511                       >= tree_low_cst (len, 1))))
8512             {
8513               tree fn = implicit_built_in_decls[BUILT_IN_MEMCPY];
8514               if (!fn)
8515                 return NULL_TREE;
8516               return build_call_expr_loc (loc, fn, 3, dest, src, len);
8517             }
8518
8519           /* If *src and *dest can't overlap, optimize into memcpy as well.  */
8520           srcvar = build_fold_indirect_ref_loc (loc, src);
8521           destvar = build_fold_indirect_ref_loc (loc, dest);
8522           if (srcvar
8523               && !TREE_THIS_VOLATILE (srcvar)
8524               && destvar
8525               && !TREE_THIS_VOLATILE (destvar))
8526             {
8527               tree src_base, dest_base, fn;
8528               HOST_WIDE_INT src_offset = 0, dest_offset = 0;
8529               HOST_WIDE_INT size = -1;
8530               HOST_WIDE_INT maxsize = -1;
8531
8532               src_base = srcvar;
8533               if (handled_component_p (src_base))
8534                 src_base = get_ref_base_and_extent (src_base, &src_offset,
8535                                                     &size, &maxsize);
8536               dest_base = destvar;
8537               if (handled_component_p (dest_base))
8538                 dest_base = get_ref_base_and_extent (dest_base, &dest_offset,
8539                                                      &size, &maxsize);
8540               if (host_integerp (len, 1))
8541                 {
8542                   maxsize = tree_low_cst (len, 1);
8543                   if (maxsize
8544                       > INTTYPE_MAXIMUM (HOST_WIDE_INT) / BITS_PER_UNIT)
8545                     maxsize = -1;
8546                   else
8547                     maxsize *= BITS_PER_UNIT;
8548                 }
8549               else
8550                 maxsize = -1;
8551               if (SSA_VAR_P (src_base)
8552                   && SSA_VAR_P (dest_base))
8553                 {
8554                   if (operand_equal_p (src_base, dest_base, 0)
8555                       && ranges_overlap_p (src_offset, maxsize,
8556                                            dest_offset, maxsize))
8557                     return NULL_TREE;
8558                 }
8559               else if (TREE_CODE (src_base) == INDIRECT_REF
8560                        && TREE_CODE (dest_base) == INDIRECT_REF)
8561                 {
8562                   if (! operand_equal_p (TREE_OPERAND (src_base, 0),
8563                                          TREE_OPERAND (dest_base, 0), 0)
8564                       || ranges_overlap_p (src_offset, maxsize,
8565                                            dest_offset, maxsize))
8566                     return NULL_TREE;
8567                 }
8568               else
8569                 return NULL_TREE;
8570
8571               fn = implicit_built_in_decls[BUILT_IN_MEMCPY];
8572               if (!fn)
8573                 return NULL_TREE;
8574               return build_call_expr_loc (loc, fn, 3, dest, src, len);
8575             }
8576           return NULL_TREE;
8577         }
8578
8579       if (!host_integerp (len, 0))
8580         return NULL_TREE;
8581       /* FIXME:
8582          This logic lose for arguments like (type *)malloc (sizeof (type)),
8583          since we strip the casts of up to VOID return value from malloc.
8584          Perhaps we ought to inherit type from non-VOID argument here?  */
8585       STRIP_NOPS (src);
8586       STRIP_NOPS (dest);
8587       /* As we fold (void *)(p + CST) to (void *)p + CST undo this here.  */
8588       if (TREE_CODE (src) == POINTER_PLUS_EXPR)
8589         {
8590           tree tem = TREE_OPERAND (src, 0);
8591           STRIP_NOPS (tem);
8592           if (tem != TREE_OPERAND (src, 0))
8593             src = build1 (NOP_EXPR, TREE_TYPE (tem), src);
8594         }
8595       if (TREE_CODE (dest) == POINTER_PLUS_EXPR)
8596         {
8597           tree tem = TREE_OPERAND (dest, 0);
8598           STRIP_NOPS (tem);
8599           if (tem != TREE_OPERAND (dest, 0))
8600             dest = build1 (NOP_EXPR, TREE_TYPE (tem), dest);
8601         }
8602       srctype = TREE_TYPE (TREE_TYPE (src));
8603       if (srctype
8604           && TREE_CODE (srctype) == ARRAY_TYPE
8605           && !tree_int_cst_equal (TYPE_SIZE_UNIT (srctype), len))
8606         {
8607           srctype = TREE_TYPE (srctype);
8608           STRIP_NOPS (src);
8609           src = build1 (NOP_EXPR, build_pointer_type (srctype), src);
8610         }
8611       desttype = TREE_TYPE (TREE_TYPE (dest));
8612       if (desttype
8613           && TREE_CODE (desttype) == ARRAY_TYPE
8614           && !tree_int_cst_equal (TYPE_SIZE_UNIT (desttype), len))
8615         {
8616           desttype = TREE_TYPE (desttype);
8617           STRIP_NOPS (dest);
8618           dest = build1 (NOP_EXPR, build_pointer_type (desttype), dest);
8619         }
8620       if (!srctype || !desttype
8621           || !TYPE_SIZE_UNIT (srctype)
8622           || !TYPE_SIZE_UNIT (desttype)
8623           || TREE_CODE (TYPE_SIZE_UNIT (srctype)) != INTEGER_CST
8624           || TREE_CODE (TYPE_SIZE_UNIT (desttype)) != INTEGER_CST
8625           || TYPE_VOLATILE (srctype)
8626           || TYPE_VOLATILE (desttype))
8627         return NULL_TREE;
8628
8629       src_align = get_pointer_alignment (src, BIGGEST_ALIGNMENT);
8630       dest_align = get_pointer_alignment (dest, BIGGEST_ALIGNMENT);
8631       if (dest_align < (int) TYPE_ALIGN (desttype)
8632           || src_align < (int) TYPE_ALIGN (srctype))
8633         return NULL_TREE;
8634
8635       if (!ignore)
8636         dest = builtin_save_expr (dest);
8637
8638       srcvar = NULL_TREE;
8639       if (tree_int_cst_equal (TYPE_SIZE_UNIT (srctype), len))
8640         {
8641           srcvar = build_fold_indirect_ref_loc (loc, src);
8642           if (TREE_THIS_VOLATILE (srcvar))
8643             return NULL_TREE;
8644           else if (!tree_int_cst_equal (tree_expr_size (srcvar), len))
8645             srcvar = NULL_TREE;
8646           /* With memcpy, it is possible to bypass aliasing rules, so without
8647              this check i.e. execute/20060930-2.c would be misoptimized,
8648              because it use conflicting alias set to hold argument for the
8649              memcpy call.  This check is probably unnecessary with
8650              -fno-strict-aliasing.  Similarly for destvar.  See also
8651              PR29286.  */
8652           else if (!var_decl_component_p (srcvar))
8653             srcvar = NULL_TREE;
8654         }
8655
8656       destvar = NULL_TREE;
8657       if (tree_int_cst_equal (TYPE_SIZE_UNIT (desttype), len))
8658         {
8659           destvar = build_fold_indirect_ref_loc (loc, dest);
8660           if (TREE_THIS_VOLATILE (destvar))
8661             return NULL_TREE;
8662           else if (!tree_int_cst_equal (tree_expr_size (destvar), len))
8663             destvar = NULL_TREE;
8664           else if (!var_decl_component_p (destvar))
8665             destvar = NULL_TREE;
8666         }
8667
8668       if (srcvar == NULL_TREE && destvar == NULL_TREE)
8669         return NULL_TREE;
8670
8671       if (srcvar == NULL_TREE)
8672         {
8673           tree srcptype;
8674           if (TREE_ADDRESSABLE (TREE_TYPE (destvar)))
8675             return NULL_TREE;
8676
8677           srctype = build_qualified_type (desttype, 0);
8678           if (src_align < (int) TYPE_ALIGN (srctype))
8679             {
8680               if (AGGREGATE_TYPE_P (srctype)
8681                   || SLOW_UNALIGNED_ACCESS (TYPE_MODE (srctype), src_align))
8682                 return NULL_TREE;
8683
8684               srctype = build_variant_type_copy (srctype);
8685               TYPE_ALIGN (srctype) = src_align;
8686               TYPE_USER_ALIGN (srctype) = 1;
8687               TYPE_PACKED (srctype) = 1;
8688             }
8689           srcptype = build_pointer_type_for_mode (srctype, ptr_mode, true);
8690           src = fold_convert_loc (loc, srcptype, src);
8691           srcvar = build_fold_indirect_ref_loc (loc, src);
8692         }
8693       else if (destvar == NULL_TREE)
8694         {
8695           tree destptype;
8696           if (TREE_ADDRESSABLE (TREE_TYPE (srcvar)))
8697             return NULL_TREE;
8698
8699           desttype = build_qualified_type (srctype, 0);
8700           if (dest_align < (int) TYPE_ALIGN (desttype))
8701             {
8702               if (AGGREGATE_TYPE_P (desttype)
8703                   || SLOW_UNALIGNED_ACCESS (TYPE_MODE (desttype), dest_align))
8704                 return NULL_TREE;
8705
8706               desttype = build_variant_type_copy (desttype);
8707               TYPE_ALIGN (desttype) = dest_align;
8708               TYPE_USER_ALIGN (desttype) = 1;
8709               TYPE_PACKED (desttype) = 1;
8710             }
8711           destptype = build_pointer_type_for_mode (desttype, ptr_mode, true);
8712           dest = fold_convert_loc (loc, destptype, dest);
8713           destvar = build_fold_indirect_ref_loc (loc, dest);
8714         }
8715
8716       if (srctype == desttype
8717           || (gimple_in_ssa_p (cfun)
8718               && useless_type_conversion_p (desttype, srctype)))
8719         expr = srcvar;
8720       else if ((INTEGRAL_TYPE_P (TREE_TYPE (srcvar))
8721            || POINTER_TYPE_P (TREE_TYPE (srcvar)))
8722           && (INTEGRAL_TYPE_P (TREE_TYPE (destvar))
8723               || POINTER_TYPE_P (TREE_TYPE (destvar))))
8724         expr = fold_convert_loc (loc, TREE_TYPE (destvar), srcvar);
8725       else
8726         expr = fold_build1_loc (loc, VIEW_CONVERT_EXPR,
8727                             TREE_TYPE (destvar), srcvar);
8728       expr = build2 (MODIFY_EXPR, TREE_TYPE (destvar), destvar, expr);
8729     }
8730
8731   if (ignore)
8732     return expr;
8733
8734   if (endp == 0 || endp == 3)
8735     return omit_one_operand_loc (loc, type, dest, expr);
8736
8737   if (expr == len)
8738     expr = NULL_TREE;
8739
8740   if (endp == 2)
8741     len = fold_build2_loc (loc, MINUS_EXPR, TREE_TYPE (len), len,
8742                        ssize_int (1));
8743
8744   len = fold_convert_loc (loc, sizetype, len);
8745   dest = fold_build2_loc (loc, POINTER_PLUS_EXPR, TREE_TYPE (dest), dest, len);
8746   dest = fold_convert_loc (loc, type, dest);
8747   if (expr)
8748     dest = omit_one_operand_loc (loc, type, dest, expr);
8749   return dest;
8750 }
8751
8752 /* Fold function call to builtin strcpy with arguments DEST and SRC.
8753    If LEN is not NULL, it represents the length of the string to be
8754    copied.  Return NULL_TREE if no simplification can be made.  */
8755
8756 tree
8757 fold_builtin_strcpy (location_t loc, tree fndecl, tree dest, tree src, tree len)
8758 {
8759   tree fn;
8760
8761   if (!validate_arg (dest, POINTER_TYPE)
8762       || !validate_arg (src, POINTER_TYPE))
8763     return NULL_TREE;
8764
8765   /* If SRC and DEST are the same (and not volatile), return DEST.  */
8766   if (operand_equal_p (src, dest, 0))
8767     return fold_convert_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)), dest);
8768
8769   if (optimize_function_for_size_p (cfun))
8770     return NULL_TREE;
8771
8772   fn = implicit_built_in_decls[BUILT_IN_MEMCPY];
8773   if (!fn)
8774     return NULL_TREE;
8775
8776   if (!len)
8777     {
8778       len = c_strlen (src, 1);
8779       if (! len || TREE_SIDE_EFFECTS (len))
8780         return NULL_TREE;
8781     }
8782
8783   len = size_binop_loc (loc, PLUS_EXPR, len, ssize_int (1));
8784   return fold_convert_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)),
8785                            build_call_expr_loc (loc, fn, 3, dest, src, len));
8786 }
8787
8788 /* Fold function call to builtin stpcpy with arguments DEST and SRC.
8789    Return NULL_TREE if no simplification can be made.  */
8790
8791 static tree
8792 fold_builtin_stpcpy (location_t loc, tree fndecl, tree dest, tree src)
8793 {
8794   tree fn, len, lenp1, call, type;
8795
8796   if (!validate_arg (dest, POINTER_TYPE)
8797       || !validate_arg (src, POINTER_TYPE))
8798     return NULL_TREE;
8799
8800   len = c_strlen (src, 1);
8801   if (!len
8802       || TREE_CODE (len) != INTEGER_CST)
8803     return NULL_TREE;
8804
8805   if (optimize_function_for_size_p (cfun)
8806       /* If length is zero it's small enough.  */
8807       && !integer_zerop (len))
8808     return NULL_TREE;
8809
8810   fn = implicit_built_in_decls[BUILT_IN_MEMCPY];
8811   if (!fn)
8812     return NULL_TREE;
8813
8814   lenp1 = size_binop_loc (loc, PLUS_EXPR, len, ssize_int (1));
8815   /* We use dest twice in building our expression.  Save it from
8816      multiple expansions.  */
8817   dest = builtin_save_expr (dest);
8818   call = build_call_expr_loc (loc, fn, 3, dest, src, lenp1);
8819
8820   type = TREE_TYPE (TREE_TYPE (fndecl));
8821   len = fold_convert_loc (loc, sizetype, len);
8822   dest = fold_build2_loc (loc, POINTER_PLUS_EXPR, TREE_TYPE (dest), dest, len);
8823   dest = fold_convert_loc (loc, type, dest);
8824   dest = omit_one_operand_loc (loc, type, dest, call);
8825   return dest;
8826 }
8827
8828 /* Fold function call to builtin strncpy with arguments DEST, SRC, and LEN.
8829    If SLEN is not NULL, it represents the length of the source string.
8830    Return NULL_TREE if no simplification can be made.  */
8831
8832 tree
8833 fold_builtin_strncpy (location_t loc, tree fndecl, tree dest,
8834                       tree src, tree len, tree slen)
8835 {
8836   tree fn;
8837
8838   if (!validate_arg (dest, POINTER_TYPE)
8839       || !validate_arg (src, POINTER_TYPE)
8840       || !validate_arg (len, INTEGER_TYPE))
8841     return NULL_TREE;
8842
8843   /* If the LEN parameter is zero, return DEST.  */
8844   if (integer_zerop (len))
8845     return omit_one_operand_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)), dest, src);
8846
8847   /* We can't compare slen with len as constants below if len is not a
8848      constant.  */
8849   if (len == 0 || TREE_CODE (len) != INTEGER_CST)
8850     return NULL_TREE;
8851
8852   if (!slen)
8853     slen = c_strlen (src, 1);
8854
8855   /* Now, we must be passed a constant src ptr parameter.  */
8856   if (slen == 0 || TREE_CODE (slen) != INTEGER_CST)
8857     return NULL_TREE;
8858
8859   slen = size_binop_loc (loc, PLUS_EXPR, slen, ssize_int (1));
8860
8861   /* We do not support simplification of this case, though we do
8862      support it when expanding trees into RTL.  */
8863   /* FIXME: generate a call to __builtin_memset.  */
8864   if (tree_int_cst_lt (slen, len))
8865     return NULL_TREE;
8866
8867   /* OK transform into builtin memcpy.  */
8868   fn = implicit_built_in_decls[BUILT_IN_MEMCPY];
8869   if (!fn)
8870     return NULL_TREE;
8871   return fold_convert_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)),
8872                            build_call_expr_loc (loc, fn, 3, dest, src, len));
8873 }
8874
8875 /* Fold function call to builtin memchr.  ARG1, ARG2 and LEN are the
8876    arguments to the call, and TYPE is its return type.
8877    Return NULL_TREE if no simplification can be made.  */
8878
8879 static tree
8880 fold_builtin_memchr (location_t loc, tree arg1, tree arg2, tree len, tree type)
8881 {
8882   if (!validate_arg (arg1, POINTER_TYPE)
8883       || !validate_arg (arg2, INTEGER_TYPE)
8884       || !validate_arg (len, INTEGER_TYPE))
8885     return NULL_TREE;
8886   else
8887     {
8888       const char *p1;
8889
8890       if (TREE_CODE (arg2) != INTEGER_CST
8891           || !host_integerp (len, 1))
8892         return NULL_TREE;
8893
8894       p1 = c_getstr (arg1);
8895       if (p1 && compare_tree_int (len, strlen (p1) + 1) <= 0)
8896         {
8897           char c;
8898           const char *r;
8899           tree tem;
8900
8901           if (target_char_cast (arg2, &c))
8902             return NULL_TREE;
8903
8904           r = (char *) memchr (p1, c, tree_low_cst (len, 1));
8905
8906           if (r == NULL)
8907             return build_int_cst (TREE_TYPE (arg1), 0);
8908
8909           tem = fold_build2_loc (loc, POINTER_PLUS_EXPR, TREE_TYPE (arg1), arg1,
8910                              size_int (r - p1));
8911           return fold_convert_loc (loc, type, tem);
8912         }
8913       return NULL_TREE;
8914     }
8915 }
8916
8917 /* Fold function call to builtin memcmp with arguments ARG1 and ARG2.
8918    Return NULL_TREE if no simplification can be made.  */
8919
8920 static tree
8921 fold_builtin_memcmp (location_t loc, tree arg1, tree arg2, tree len)
8922 {
8923   const char *p1, *p2;
8924
8925   if (!validate_arg (arg1, POINTER_TYPE)
8926       || !validate_arg (arg2, POINTER_TYPE)
8927       || !validate_arg (len, INTEGER_TYPE))
8928     return NULL_TREE;
8929
8930   /* If the LEN parameter is zero, return zero.  */
8931   if (integer_zerop (len))
8932     return omit_two_operands_loc (loc, integer_type_node, integer_zero_node,
8933                               arg1, arg2);
8934
8935   /* If ARG1 and ARG2 are the same (and not volatile), return zero.  */
8936   if (operand_equal_p (arg1, arg2, 0))
8937     return omit_one_operand_loc (loc, integer_type_node, integer_zero_node, len);
8938
8939   p1 = c_getstr (arg1);
8940   p2 = c_getstr (arg2);
8941
8942   /* If all arguments are constant, and the value of len is not greater
8943      than the lengths of arg1 and arg2, evaluate at compile-time.  */
8944   if (host_integerp (len, 1) && p1 && p2
8945       && compare_tree_int (len, strlen (p1) + 1) <= 0
8946       && compare_tree_int (len, strlen (p2) + 1) <= 0)
8947     {
8948       const int r = memcmp (p1, p2, tree_low_cst (len, 1));
8949
8950       if (r > 0)
8951         return integer_one_node;
8952       else if (r < 0)
8953         return integer_minus_one_node;
8954       else
8955         return integer_zero_node;
8956     }
8957
8958   /* If len parameter is one, return an expression corresponding to
8959      (*(const unsigned char*)arg1 - (const unsigned char*)arg2).  */
8960   if (host_integerp (len, 1) && tree_low_cst (len, 1) == 1)
8961     {
8962       tree cst_uchar_node = build_type_variant (unsigned_char_type_node, 1, 0);
8963       tree cst_uchar_ptr_node
8964         = build_pointer_type_for_mode (cst_uchar_node, ptr_mode, true);
8965
8966       tree ind1
8967         = fold_convert_loc (loc, integer_type_node,
8968                             build1 (INDIRECT_REF, cst_uchar_node,
8969                                     fold_convert_loc (loc,
8970                                                       cst_uchar_ptr_node,
8971                                                       arg1)));
8972       tree ind2
8973         = fold_convert_loc (loc, integer_type_node,
8974                             build1 (INDIRECT_REF, cst_uchar_node,
8975                                     fold_convert_loc (loc,
8976                                                       cst_uchar_ptr_node,
8977                                                       arg2)));
8978       return fold_build2_loc (loc, MINUS_EXPR, integer_type_node, ind1, ind2);
8979     }
8980
8981   return NULL_TREE;
8982 }
8983
8984 /* Fold function call to builtin strcmp with arguments ARG1 and ARG2.
8985    Return NULL_TREE if no simplification can be made.  */
8986
8987 static tree
8988 fold_builtin_strcmp (location_t loc, tree arg1, tree arg2)
8989 {
8990   const char *p1, *p2;
8991
8992   if (!validate_arg (arg1, POINTER_TYPE)
8993       || !validate_arg (arg2, POINTER_TYPE))
8994     return NULL_TREE;
8995
8996   /* If ARG1 and ARG2 are the same (and not volatile), return zero.  */
8997   if (operand_equal_p (arg1, arg2, 0))
8998     return integer_zero_node;
8999
9000   p1 = c_getstr (arg1);
9001   p2 = c_getstr (arg2);
9002
9003   if (p1 && p2)
9004     {
9005       const int i = strcmp (p1, p2);
9006       if (i < 0)
9007         return integer_minus_one_node;
9008       else if (i > 0)
9009         return integer_one_node;
9010       else
9011         return integer_zero_node;
9012     }
9013
9014   /* If the second arg is "", return *(const unsigned char*)arg1.  */
9015   if (p2 && *p2 == '\0')
9016     {
9017       tree cst_uchar_node = build_type_variant (unsigned_char_type_node, 1, 0);
9018       tree cst_uchar_ptr_node
9019         = build_pointer_type_for_mode (cst_uchar_node, ptr_mode, true);
9020
9021       return fold_convert_loc (loc, integer_type_node,
9022                                build1 (INDIRECT_REF, cst_uchar_node,
9023                                        fold_convert_loc (loc,
9024                                                          cst_uchar_ptr_node,
9025                                                          arg1)));
9026     }
9027
9028   /* If the first arg is "", return -*(const unsigned char*)arg2.  */
9029   if (p1 && *p1 == '\0')
9030     {
9031       tree cst_uchar_node = build_type_variant (unsigned_char_type_node, 1, 0);
9032       tree cst_uchar_ptr_node
9033         = build_pointer_type_for_mode (cst_uchar_node, ptr_mode, true);
9034
9035       tree temp
9036         = fold_convert_loc (loc, integer_type_node,
9037                             build1 (INDIRECT_REF, cst_uchar_node,
9038                                     fold_convert_loc (loc,
9039                                                       cst_uchar_ptr_node,
9040                                                       arg2)));
9041       return fold_build1_loc (loc, NEGATE_EXPR, integer_type_node, temp);
9042     }
9043
9044   return NULL_TREE;
9045 }
9046
9047 /* Fold function call to builtin strncmp with arguments ARG1, ARG2, and LEN.
9048    Return NULL_TREE if no simplification can be made.  */
9049
9050 static tree
9051 fold_builtin_strncmp (location_t loc, tree arg1, tree arg2, tree len)
9052 {
9053   const char *p1, *p2;
9054
9055   if (!validate_arg (arg1, POINTER_TYPE)
9056       || !validate_arg (arg2, POINTER_TYPE)
9057       || !validate_arg (len, INTEGER_TYPE))
9058     return NULL_TREE;
9059
9060   /* If the LEN parameter is zero, return zero.  */
9061   if (integer_zerop (len))
9062     return omit_two_operands_loc (loc, integer_type_node, integer_zero_node,
9063                               arg1, arg2);
9064
9065   /* If ARG1 and ARG2 are the same (and not volatile), return zero.  */
9066   if (operand_equal_p (arg1, arg2, 0))
9067     return omit_one_operand_loc (loc, integer_type_node, integer_zero_node, len);
9068
9069   p1 = c_getstr (arg1);
9070   p2 = c_getstr (arg2);
9071
9072   if (host_integerp (len, 1) && p1 && p2)
9073     {
9074       const int i = strncmp (p1, p2, tree_low_cst (len, 1));
9075       if (i > 0)
9076         return integer_one_node;
9077       else if (i < 0)
9078         return integer_minus_one_node;
9079       else
9080         return integer_zero_node;
9081     }
9082
9083   /* If the second arg is "", and the length is greater than zero,
9084      return *(const unsigned char*)arg1.  */
9085   if (p2 && *p2 == '\0'
9086       && TREE_CODE (len) == INTEGER_CST
9087       && tree_int_cst_sgn (len) == 1)
9088     {
9089       tree cst_uchar_node = build_type_variant (unsigned_char_type_node, 1, 0);
9090       tree cst_uchar_ptr_node
9091         = build_pointer_type_for_mode (cst_uchar_node, ptr_mode, true);
9092
9093       return fold_convert_loc (loc, integer_type_node,
9094                                build1 (INDIRECT_REF, cst_uchar_node,
9095                                        fold_convert_loc (loc,
9096                                                          cst_uchar_ptr_node,
9097                                                          arg1)));
9098     }
9099
9100   /* If the first arg is "", and the length is greater than zero,
9101      return -*(const unsigned char*)arg2.  */
9102   if (p1 && *p1 == '\0'
9103       && TREE_CODE (len) == INTEGER_CST
9104       && tree_int_cst_sgn (len) == 1)
9105     {
9106       tree cst_uchar_node = build_type_variant (unsigned_char_type_node, 1, 0);
9107       tree cst_uchar_ptr_node
9108         = build_pointer_type_for_mode (cst_uchar_node, ptr_mode, true);
9109
9110       tree temp = fold_convert_loc (loc, integer_type_node,
9111                                     build1 (INDIRECT_REF, cst_uchar_node,
9112                                             fold_convert_loc (loc,
9113                                                               cst_uchar_ptr_node,
9114                                                               arg2)));
9115       return fold_build1_loc (loc, NEGATE_EXPR, integer_type_node, temp);
9116     }
9117
9118   /* If len parameter is one, return an expression corresponding to
9119      (*(const unsigned char*)arg1 - (const unsigned char*)arg2).  */
9120   if (host_integerp (len, 1) && tree_low_cst (len, 1) == 1)
9121     {
9122       tree cst_uchar_node = build_type_variant (unsigned_char_type_node, 1, 0);
9123       tree cst_uchar_ptr_node
9124         = build_pointer_type_for_mode (cst_uchar_node, ptr_mode, true);
9125
9126       tree ind1 = fold_convert_loc (loc, integer_type_node,
9127                                     build1 (INDIRECT_REF, cst_uchar_node,
9128                                             fold_convert_loc (loc,
9129                                                               cst_uchar_ptr_node,
9130                                                               arg1)));
9131       tree ind2 = fold_convert_loc (loc, integer_type_node,
9132                                     build1 (INDIRECT_REF, cst_uchar_node,
9133                                             fold_convert_loc (loc,
9134                                                               cst_uchar_ptr_node,
9135                                                               arg2)));
9136       return fold_build2_loc (loc, MINUS_EXPR, integer_type_node, ind1, ind2);
9137     }
9138
9139   return NULL_TREE;
9140 }
9141
9142 /* Fold function call to builtin signbit, signbitf or signbitl with argument
9143    ARG.  Return NULL_TREE if no simplification can be made.  */
9144
9145 static tree
9146 fold_builtin_signbit (location_t loc, tree arg, tree type)
9147 {
9148   tree temp;
9149
9150   if (!validate_arg (arg, REAL_TYPE))
9151     return NULL_TREE;
9152
9153   /* If ARG is a compile-time constant, determine the result.  */
9154   if (TREE_CODE (arg) == REAL_CST
9155       && !TREE_OVERFLOW (arg))
9156     {
9157       REAL_VALUE_TYPE c;
9158
9159       c = TREE_REAL_CST (arg);
9160       temp = REAL_VALUE_NEGATIVE (c) ? integer_one_node : integer_zero_node;
9161       return fold_convert_loc (loc, type, temp);
9162     }
9163
9164   /* If ARG is non-negative, the result is always zero.  */
9165   if (tree_expr_nonnegative_p (arg))
9166     return omit_one_operand_loc (loc, type, integer_zero_node, arg);
9167
9168   /* If ARG's format doesn't have signed zeros, return "arg < 0.0".  */
9169   if (!HONOR_SIGNED_ZEROS (TYPE_MODE (TREE_TYPE (arg))))
9170     return fold_build2_loc (loc, LT_EXPR, type, arg,
9171                         build_real (TREE_TYPE (arg), dconst0));
9172
9173   return NULL_TREE;
9174 }
9175
9176 /* Fold function call to builtin copysign, copysignf or copysignl with
9177    arguments ARG1 and ARG2.  Return NULL_TREE if no simplification can
9178    be made.  */
9179
9180 static tree
9181 fold_builtin_copysign (location_t loc, tree fndecl,
9182                        tree arg1, tree arg2, tree type)
9183 {
9184   tree tem;
9185
9186   if (!validate_arg (arg1, REAL_TYPE)
9187       || !validate_arg (arg2, REAL_TYPE))
9188     return NULL_TREE;
9189
9190   /* copysign(X,X) is X.  */
9191   if (operand_equal_p (arg1, arg2, 0))
9192     return fold_convert_loc (loc, type, arg1);
9193
9194   /* If ARG1 and ARG2 are compile-time constants, determine the result.  */
9195   if (TREE_CODE (arg1) == REAL_CST
9196       && TREE_CODE (arg2) == REAL_CST
9197       && !TREE_OVERFLOW (arg1)
9198       && !TREE_OVERFLOW (arg2))
9199     {
9200       REAL_VALUE_TYPE c1, c2;
9201
9202       c1 = TREE_REAL_CST (arg1);
9203       c2 = TREE_REAL_CST (arg2);
9204       /* c1.sign := c2.sign.  */
9205       real_copysign (&c1, &c2);
9206       return build_real (type, c1);
9207     }
9208
9209   /* copysign(X, Y) is fabs(X) when Y is always non-negative.
9210      Remember to evaluate Y for side-effects.  */
9211   if (tree_expr_nonnegative_p (arg2))
9212     return omit_one_operand_loc (loc, type,
9213                              fold_build1_loc (loc, ABS_EXPR, type, arg1),
9214                              arg2);
9215
9216   /* Strip sign changing operations for the first argument.  */
9217   tem = fold_strip_sign_ops (arg1);
9218   if (tem)
9219     return build_call_expr_loc (loc, fndecl, 2, tem, arg2);
9220
9221   return NULL_TREE;
9222 }
9223
9224 /* Fold a call to builtin isascii with argument ARG.  */
9225
9226 static tree
9227 fold_builtin_isascii (location_t loc, tree arg)
9228 {
9229   if (!validate_arg (arg, INTEGER_TYPE))
9230     return NULL_TREE;
9231   else
9232     {
9233       /* Transform isascii(c) -> ((c & ~0x7f) == 0).  */
9234       arg = fold_build2 (BIT_AND_EXPR, integer_type_node, arg,
9235                          build_int_cst (NULL_TREE,
9236                                         ~ (unsigned HOST_WIDE_INT) 0x7f));
9237       return fold_build2_loc (loc, EQ_EXPR, integer_type_node,
9238                           arg, integer_zero_node);
9239     }
9240 }
9241
9242 /* Fold a call to builtin toascii with argument ARG.  */
9243
9244 static tree
9245 fold_builtin_toascii (location_t loc, tree arg)
9246 {
9247   if (!validate_arg (arg, INTEGER_TYPE))
9248     return NULL_TREE;
9249       
9250   /* Transform toascii(c) -> (c & 0x7f).  */
9251   return fold_build2_loc (loc, BIT_AND_EXPR, integer_type_node, arg,
9252                       build_int_cst (NULL_TREE, 0x7f));
9253 }
9254
9255 /* Fold a call to builtin isdigit with argument ARG.  */
9256
9257 static tree
9258 fold_builtin_isdigit (location_t loc, tree arg)
9259 {
9260   if (!validate_arg (arg, INTEGER_TYPE))
9261     return NULL_TREE;
9262   else
9263     {
9264       /* Transform isdigit(c) -> (unsigned)(c) - '0' <= 9.  */
9265       /* According to the C standard, isdigit is unaffected by locale.
9266          However, it definitely is affected by the target character set.  */
9267       unsigned HOST_WIDE_INT target_digit0
9268         = lang_hooks.to_target_charset ('0');
9269
9270       if (target_digit0 == 0)
9271         return NULL_TREE;
9272
9273       arg = fold_convert_loc (loc, unsigned_type_node, arg);
9274       arg = fold_build2 (MINUS_EXPR, unsigned_type_node, arg,
9275                          build_int_cst (unsigned_type_node, target_digit0));
9276       return fold_build2_loc (loc, LE_EXPR, integer_type_node, arg,
9277                           build_int_cst (unsigned_type_node, 9));
9278     }
9279 }
9280
9281 /* Fold a call to fabs, fabsf or fabsl with argument ARG.  */
9282
9283 static tree
9284 fold_builtin_fabs (location_t loc, tree arg, tree type)
9285 {
9286   if (!validate_arg (arg, REAL_TYPE))
9287     return NULL_TREE;
9288
9289   arg = fold_convert_loc (loc, type, arg);
9290   if (TREE_CODE (arg) == REAL_CST)
9291     return fold_abs_const (arg, type);
9292   return fold_build1_loc (loc, ABS_EXPR, type, arg);
9293 }
9294
9295 /* Fold a call to abs, labs, llabs or imaxabs with argument ARG.  */
9296
9297 static tree
9298 fold_builtin_abs (location_t loc, tree arg, tree type)
9299 {
9300   if (!validate_arg (arg, INTEGER_TYPE))
9301     return NULL_TREE;
9302
9303   arg = fold_convert_loc (loc, type, arg);
9304   if (TREE_CODE (arg) == INTEGER_CST)
9305     return fold_abs_const (arg, type);
9306   return fold_build1_loc (loc, ABS_EXPR, type, arg);
9307 }
9308
9309 /* Fold a call to builtin fmin or fmax.  */
9310
9311 static tree
9312 fold_builtin_fmin_fmax (location_t loc, tree arg0, tree arg1,
9313                         tree type, bool max)
9314 {
9315   if (validate_arg (arg0, REAL_TYPE) && validate_arg (arg1, REAL_TYPE))
9316     {
9317       /* Calculate the result when the argument is a constant.  */
9318       tree res = do_mpfr_arg2 (arg0, arg1, type, (max ? mpfr_max : mpfr_min));
9319
9320       if (res)
9321         return res;
9322
9323       /* If either argument is NaN, return the other one.  Avoid the
9324          transformation if we get (and honor) a signalling NaN.  Using
9325          omit_one_operand() ensures we create a non-lvalue.  */
9326       if (TREE_CODE (arg0) == REAL_CST
9327           && real_isnan (&TREE_REAL_CST (arg0))
9328           && (! HONOR_SNANS (TYPE_MODE (TREE_TYPE (arg0)))
9329               || ! TREE_REAL_CST (arg0).signalling))
9330         return omit_one_operand_loc (loc, type, arg1, arg0);
9331       if (TREE_CODE (arg1) == REAL_CST
9332           && real_isnan (&TREE_REAL_CST (arg1))
9333           && (! HONOR_SNANS (TYPE_MODE (TREE_TYPE (arg1)))
9334               || ! TREE_REAL_CST (arg1).signalling))
9335         return omit_one_operand_loc (loc, type, arg0, arg1);
9336
9337       /* Transform fmin/fmax(x,x) -> x.  */
9338       if (operand_equal_p (arg0, arg1, OEP_PURE_SAME))
9339         return omit_one_operand_loc (loc, type, arg0, arg1);
9340       
9341       /* Convert fmin/fmax to MIN_EXPR/MAX_EXPR.  C99 requires these
9342          functions to return the numeric arg if the other one is NaN.
9343          These tree codes don't honor that, so only transform if
9344          -ffinite-math-only is set.  C99 doesn't require -0.0 to be
9345          handled, so we don't have to worry about it either.  */
9346       if (flag_finite_math_only)
9347         return fold_build2_loc (loc, (max ? MAX_EXPR : MIN_EXPR), type,
9348                             fold_convert_loc (loc, type, arg0),
9349                             fold_convert_loc (loc, type, arg1));
9350     }
9351   return NULL_TREE;
9352 }
9353
9354 /* Fold a call to builtin carg(a+bi) -> atan2(b,a).  */
9355
9356 static tree
9357 fold_builtin_carg (location_t loc, tree arg, tree type)
9358 {
9359   if (validate_arg (arg, COMPLEX_TYPE)
9360       && TREE_CODE (TREE_TYPE (TREE_TYPE (arg))) == REAL_TYPE)
9361     {
9362       tree atan2_fn = mathfn_built_in (type, BUILT_IN_ATAN2);
9363       
9364       if (atan2_fn)
9365         {
9366           tree new_arg = builtin_save_expr (arg);
9367           tree r_arg = fold_build1_loc (loc, REALPART_EXPR, type, new_arg);
9368           tree i_arg = fold_build1_loc (loc, IMAGPART_EXPR, type, new_arg);
9369           return build_call_expr_loc (loc, atan2_fn, 2, i_arg, r_arg);
9370         }
9371     }
9372   
9373   return NULL_TREE;
9374 }
9375
9376 /* Fold a call to builtin logb/ilogb.  */
9377
9378 static tree
9379 fold_builtin_logb (location_t loc, tree arg, tree rettype)
9380 {
9381   if (! validate_arg (arg, REAL_TYPE))
9382     return NULL_TREE;
9383   
9384   STRIP_NOPS (arg);
9385       
9386   if (TREE_CODE (arg) == REAL_CST && ! TREE_OVERFLOW (arg))
9387     {
9388       const REAL_VALUE_TYPE *const value = TREE_REAL_CST_PTR (arg);
9389           
9390       switch (value->cl)
9391       {
9392       case rvc_nan:
9393       case rvc_inf:
9394         /* If arg is Inf or NaN and we're logb, return it.  */
9395         if (TREE_CODE (rettype) == REAL_TYPE)
9396           return fold_convert_loc (loc, rettype, arg);
9397         /* Fall through... */
9398       case rvc_zero:
9399         /* Zero may set errno and/or raise an exception for logb, also
9400            for ilogb we don't know FP_ILOGB0.  */
9401         return NULL_TREE;
9402       case rvc_normal:
9403         /* For normal numbers, proceed iff radix == 2.  In GCC,
9404            normalized significands are in the range [0.5, 1.0).  We
9405            want the exponent as if they were [1.0, 2.0) so get the
9406            exponent and subtract 1.  */
9407         if (REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (arg)))->b == 2)
9408           return fold_convert_loc (loc, rettype,
9409                                    build_int_cst (NULL_TREE,
9410                                                   REAL_EXP (value)-1));
9411         break;
9412       }
9413     }
9414   
9415   return NULL_TREE;
9416 }
9417
9418 /* Fold a call to builtin significand, if radix == 2.  */
9419
9420 static tree
9421 fold_builtin_significand (location_t loc, tree arg, tree rettype)
9422 {
9423   if (! validate_arg (arg, REAL_TYPE))
9424     return NULL_TREE;
9425   
9426   STRIP_NOPS (arg);
9427       
9428   if (TREE_CODE (arg) == REAL_CST && ! TREE_OVERFLOW (arg))
9429     {
9430       const REAL_VALUE_TYPE *const value = TREE_REAL_CST_PTR (arg);
9431           
9432       switch (value->cl)
9433       {
9434       case rvc_zero:
9435       case rvc_nan:
9436       case rvc_inf:
9437         /* If arg is +-0, +-Inf or +-NaN, then return it.  */
9438         return fold_convert_loc (loc, rettype, arg);
9439       case rvc_normal:
9440         /* For normal numbers, proceed iff radix == 2.  */
9441         if (REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (arg)))->b == 2)
9442           {
9443             REAL_VALUE_TYPE result = *value;
9444             /* In GCC, normalized significands are in the range [0.5,
9445                1.0).  We want them to be [1.0, 2.0) so set the
9446                exponent to 1.  */
9447             SET_REAL_EXP (&result, 1);
9448             return build_real (rettype, result);
9449           }
9450         break;
9451       }
9452     }
9453   
9454   return NULL_TREE;
9455 }
9456
9457 /* Fold a call to builtin frexp, we can assume the base is 2.  */
9458
9459 static tree
9460 fold_builtin_frexp (location_t loc, tree arg0, tree arg1, tree rettype)
9461 {
9462   if (! validate_arg (arg0, REAL_TYPE) || ! validate_arg (arg1, POINTER_TYPE))
9463     return NULL_TREE;
9464   
9465   STRIP_NOPS (arg0);
9466       
9467   if (!(TREE_CODE (arg0) == REAL_CST && ! TREE_OVERFLOW (arg0)))
9468     return NULL_TREE;
9469   
9470   arg1 = build_fold_indirect_ref_loc (loc, arg1);
9471
9472   /* Proceed if a valid pointer type was passed in.  */
9473   if (TYPE_MAIN_VARIANT (TREE_TYPE (arg1)) == integer_type_node)
9474     {
9475       const REAL_VALUE_TYPE *const value = TREE_REAL_CST_PTR (arg0);
9476       tree frac, exp;
9477           
9478       switch (value->cl)
9479       {
9480       case rvc_zero:
9481         /* For +-0, return (*exp = 0, +-0).  */
9482         exp = integer_zero_node;
9483         frac = arg0;
9484         break;
9485       case rvc_nan:
9486       case rvc_inf:
9487         /* For +-NaN or +-Inf, *exp is unspecified, return arg0.  */
9488         return omit_one_operand_loc (loc, rettype, arg0, arg1);
9489       case rvc_normal:
9490         {
9491           /* Since the frexp function always expects base 2, and in
9492              GCC normalized significands are already in the range
9493              [0.5, 1.0), we have exactly what frexp wants.  */
9494           REAL_VALUE_TYPE frac_rvt = *value;
9495           SET_REAL_EXP (&frac_rvt, 0);
9496           frac = build_real (rettype, frac_rvt);
9497           exp = build_int_cst (NULL_TREE, REAL_EXP (value));
9498         }
9499         break;
9500       default:
9501         gcc_unreachable ();
9502       }
9503                 
9504       /* Create the COMPOUND_EXPR (*arg1 = trunc, frac). */
9505       arg1 = fold_build2_loc (loc, MODIFY_EXPR, rettype, arg1, exp);
9506       TREE_SIDE_EFFECTS (arg1) = 1;
9507       return fold_build2_loc (loc, COMPOUND_EXPR, rettype, arg1, frac);
9508     }
9509
9510   return NULL_TREE;
9511 }
9512
9513 /* Fold a call to builtin ldexp or scalbn/scalbln.  If LDEXP is true
9514    then we can assume the base is two.  If it's false, then we have to
9515    check the mode of the TYPE parameter in certain cases.  */
9516
9517 static tree
9518 fold_builtin_load_exponent (location_t loc, tree arg0, tree arg1,
9519                             tree type, bool ldexp)
9520 {
9521   if (validate_arg (arg0, REAL_TYPE) && validate_arg (arg1, INTEGER_TYPE))
9522     {
9523       STRIP_NOPS (arg0);
9524       STRIP_NOPS (arg1);
9525
9526       /* If arg0 is 0, Inf or NaN, or if arg1 is 0, then return arg0.  */
9527       if (real_zerop (arg0) || integer_zerop (arg1)
9528           || (TREE_CODE (arg0) == REAL_CST
9529               && !real_isfinite (&TREE_REAL_CST (arg0))))
9530         return omit_one_operand_loc (loc, type, arg0, arg1);
9531       
9532       /* If both arguments are constant, then try to evaluate it.  */
9533       if ((ldexp || REAL_MODE_FORMAT (TYPE_MODE (type))->b == 2)
9534           && TREE_CODE (arg0) == REAL_CST && !TREE_OVERFLOW (arg0)
9535           && host_integerp (arg1, 0))
9536         {
9537           /* Bound the maximum adjustment to twice the range of the
9538              mode's valid exponents.  Use abs to ensure the range is
9539              positive as a sanity check.  */
9540           const long max_exp_adj = 2 * 
9541             labs (REAL_MODE_FORMAT (TYPE_MODE (type))->emax
9542                  - REAL_MODE_FORMAT (TYPE_MODE (type))->emin);
9543
9544           /* Get the user-requested adjustment.  */
9545           const HOST_WIDE_INT req_exp_adj = tree_low_cst (arg1, 0);
9546           
9547           /* The requested adjustment must be inside this range.  This
9548              is a preliminary cap to avoid things like overflow, we
9549              may still fail to compute the result for other reasons.  */
9550           if (-max_exp_adj < req_exp_adj && req_exp_adj < max_exp_adj)
9551             {
9552               REAL_VALUE_TYPE initial_result;
9553               
9554               real_ldexp (&initial_result, &TREE_REAL_CST (arg0), req_exp_adj);
9555
9556               /* Ensure we didn't overflow.  */
9557               if (! real_isinf (&initial_result))
9558                 {
9559                   const REAL_VALUE_TYPE trunc_result
9560                     = real_value_truncate (TYPE_MODE (type), initial_result);
9561                   
9562                   /* Only proceed if the target mode can hold the
9563                      resulting value.  */
9564                   if (REAL_VALUES_EQUAL (initial_result, trunc_result))
9565                     return build_real (type, trunc_result);
9566                 }
9567             }
9568         }
9569     }
9570
9571   return NULL_TREE;
9572 }
9573
9574 /* Fold a call to builtin modf.  */
9575
9576 static tree
9577 fold_builtin_modf (location_t loc, tree arg0, tree arg1, tree rettype)
9578 {
9579   if (! validate_arg (arg0, REAL_TYPE) || ! validate_arg (arg1, POINTER_TYPE))
9580     return NULL_TREE;
9581   
9582   STRIP_NOPS (arg0);
9583       
9584   if (!(TREE_CODE (arg0) == REAL_CST && ! TREE_OVERFLOW (arg0)))
9585     return NULL_TREE;
9586   
9587   arg1 = build_fold_indirect_ref_loc (loc, arg1);
9588
9589   /* Proceed if a valid pointer type was passed in.  */
9590   if (TYPE_MAIN_VARIANT (TREE_TYPE (arg1)) == TYPE_MAIN_VARIANT (rettype))
9591     {
9592       const REAL_VALUE_TYPE *const value = TREE_REAL_CST_PTR (arg0);
9593       REAL_VALUE_TYPE trunc, frac;
9594
9595       switch (value->cl)
9596       {
9597       case rvc_nan:
9598       case rvc_zero:
9599         /* For +-NaN or +-0, return (*arg1 = arg0, arg0).  */
9600         trunc = frac = *value;
9601         break;
9602       case rvc_inf:
9603         /* For +-Inf, return (*arg1 = arg0, +-0).  */
9604         frac = dconst0;
9605         frac.sign = value->sign;
9606         trunc = *value;
9607         break;
9608       case rvc_normal:
9609         /* Return (*arg1 = trunc(arg0), arg0-trunc(arg0)).  */
9610         real_trunc (&trunc, VOIDmode, value);
9611         real_arithmetic (&frac, MINUS_EXPR, value, &trunc);
9612         /* If the original number was negative and already
9613            integral, then the fractional part is -0.0.  */
9614         if (value->sign && frac.cl == rvc_zero)
9615           frac.sign = value->sign;
9616         break;
9617       }
9618               
9619       /* Create the COMPOUND_EXPR (*arg1 = trunc, frac). */
9620       arg1 = fold_build2_loc (loc, MODIFY_EXPR, rettype, arg1,
9621                           build_real (rettype, trunc));
9622       TREE_SIDE_EFFECTS (arg1) = 1;
9623       return fold_build2_loc (loc, COMPOUND_EXPR, rettype, arg1,
9624                           build_real (rettype, frac));
9625     }
9626   
9627   return NULL_TREE;
9628 }
9629
9630 /* Given a location LOC, an interclass builtin function decl FNDECL
9631    and its single argument ARG, return an folded expression computing
9632    the same, or NULL_TREE if we either couldn't or didn't want to fold
9633    (the latter happen if there's an RTL instruction available).  */
9634
9635 static tree
9636 fold_builtin_interclass_mathfn (location_t loc, tree fndecl, tree arg)
9637 {
9638   enum machine_mode mode;
9639
9640   if (!validate_arg (arg, REAL_TYPE))
9641     return NULL_TREE;
9642
9643   if (interclass_mathfn_icode (arg, fndecl) != CODE_FOR_nothing)
9644     return NULL_TREE;
9645
9646   mode = TYPE_MODE (TREE_TYPE (arg));
9647
9648   /* If there is no optab, try generic code.  */
9649   switch (DECL_FUNCTION_CODE (fndecl))
9650     {
9651       tree result;
9652
9653     CASE_FLT_FN (BUILT_IN_ISINF):
9654       {
9655         /* isinf(x) -> isgreater(fabs(x),DBL_MAX).  */
9656         tree const isgr_fn = built_in_decls[BUILT_IN_ISGREATER];
9657         tree const type = TREE_TYPE (arg);
9658         REAL_VALUE_TYPE r;
9659         char buf[128];
9660
9661         get_max_float (REAL_MODE_FORMAT (mode), buf, sizeof (buf));
9662         real_from_string (&r, buf);
9663         result = build_call_expr (isgr_fn, 2,
9664                                   fold_build1_loc (loc, ABS_EXPR, type, arg),
9665                                   build_real (type, r));
9666         return result;
9667       }
9668     CASE_FLT_FN (BUILT_IN_FINITE):
9669     case BUILT_IN_ISFINITE:
9670       {
9671         /* isfinite(x) -> islessequal(fabs(x),DBL_MAX).  */
9672         tree const isle_fn = built_in_decls[BUILT_IN_ISLESSEQUAL];
9673         tree const type = TREE_TYPE (arg);
9674         REAL_VALUE_TYPE r;
9675         char buf[128];
9676
9677         get_max_float (REAL_MODE_FORMAT (mode), buf, sizeof (buf));
9678         real_from_string (&r, buf);
9679         result = build_call_expr (isle_fn, 2,
9680                                   fold_build1_loc (loc, ABS_EXPR, type, arg),
9681                                   build_real (type, r));
9682         /*result = fold_build2_loc (loc, UNGT_EXPR,
9683                                   TREE_TYPE (TREE_TYPE (fndecl)),
9684                                   fold_build1_loc (loc, ABS_EXPR, type, arg),
9685                                   build_real (type, r));
9686         result = fold_build1_loc (loc, TRUTH_NOT_EXPR,
9687                                   TREE_TYPE (TREE_TYPE (fndecl)),
9688                                   result);*/
9689         return result;
9690       }
9691     case BUILT_IN_ISNORMAL:
9692       {
9693         /* isnormal(x) -> isgreaterequal(fabs(x),DBL_MIN) &
9694            islessequal(fabs(x),DBL_MAX).  */
9695         tree const isle_fn = built_in_decls[BUILT_IN_ISLESSEQUAL];
9696         tree const isge_fn = built_in_decls[BUILT_IN_ISGREATEREQUAL];
9697         tree const type = TREE_TYPE (arg);
9698         REAL_VALUE_TYPE rmax, rmin;
9699         char buf[128];
9700
9701         get_max_float (REAL_MODE_FORMAT (mode), buf, sizeof (buf));
9702         real_from_string (&rmax, buf);
9703         sprintf (buf, "0x1p%d", REAL_MODE_FORMAT (mode)->emin - 1);
9704         real_from_string (&rmin, buf);
9705         arg = builtin_save_expr (fold_build1_loc (loc, ABS_EXPR, type, arg));
9706         result = build_call_expr (isle_fn, 2, arg,
9707                                   build_real (type, rmax));
9708         result = fold_build2 (BIT_AND_EXPR, integer_type_node, result,
9709                               build_call_expr (isge_fn, 2, arg,
9710                                                build_real (type, rmin)));
9711         return result;
9712       }
9713     default:
9714       break;
9715     }
9716
9717   return NULL_TREE;
9718 }
9719
9720 /* Fold a call to __builtin_isnan(), __builtin_isinf, __builtin_finite.
9721    ARG is the argument for the call.  */
9722
9723 static tree
9724 fold_builtin_classify (location_t loc, tree fndecl, tree arg, int builtin_index)
9725 {
9726   tree type = TREE_TYPE (TREE_TYPE (fndecl));
9727   REAL_VALUE_TYPE r;
9728
9729   if (!validate_arg (arg, REAL_TYPE))
9730     return NULL_TREE;
9731
9732   switch (builtin_index)
9733     {
9734     case BUILT_IN_ISINF:
9735       if (!HONOR_INFINITIES (TYPE_MODE (TREE_TYPE (arg))))
9736         return omit_one_operand_loc (loc, type, integer_zero_node, arg);
9737
9738       if (TREE_CODE (arg) == REAL_CST)
9739         {
9740           r = TREE_REAL_CST (arg);
9741           if (real_isinf (&r))
9742             return real_compare (GT_EXPR, &r, &dconst0)
9743                    ? integer_one_node : integer_minus_one_node;
9744           else
9745             return integer_zero_node;
9746         }
9747
9748       return NULL_TREE;
9749
9750     case BUILT_IN_ISINF_SIGN:
9751       {
9752         /* isinf_sign(x) -> isinf(x) ? (signbit(x) ? -1 : 1) : 0 */
9753         /* In a boolean context, GCC will fold the inner COND_EXPR to
9754            1.  So e.g. "if (isinf_sign(x))" would be folded to just
9755            "if (isinf(x) ? 1 : 0)" which becomes "if (isinf(x))". */
9756         tree signbit_fn = mathfn_built_in_1 (TREE_TYPE (arg), BUILT_IN_SIGNBIT, 0);
9757         tree isinf_fn = built_in_decls[BUILT_IN_ISINF];
9758         tree tmp = NULL_TREE;
9759
9760         arg = builtin_save_expr (arg);
9761
9762         if (signbit_fn && isinf_fn)
9763           {
9764             tree signbit_call = build_call_expr_loc (loc, signbit_fn, 1, arg);
9765             tree isinf_call = build_call_expr_loc (loc, isinf_fn, 1, arg);
9766
9767             signbit_call = fold_build2_loc (loc, NE_EXPR, integer_type_node,
9768                                         signbit_call, integer_zero_node);
9769             isinf_call = fold_build2_loc (loc, NE_EXPR, integer_type_node,
9770                                       isinf_call, integer_zero_node);
9771             
9772             tmp = fold_build3_loc (loc, COND_EXPR, integer_type_node, signbit_call,
9773                                integer_minus_one_node, integer_one_node);
9774             tmp = fold_build3_loc (loc, COND_EXPR, integer_type_node,
9775                                isinf_call, tmp,
9776                                integer_zero_node);
9777           }
9778
9779         return tmp;
9780       }
9781
9782     case BUILT_IN_ISFINITE:
9783       if (!HONOR_NANS (TYPE_MODE (TREE_TYPE (arg)))
9784           && !HONOR_INFINITIES (TYPE_MODE (TREE_TYPE (arg))))
9785         return omit_one_operand_loc (loc, type, integer_one_node, arg);
9786
9787       if (TREE_CODE (arg) == REAL_CST)
9788         {
9789           r = TREE_REAL_CST (arg);
9790           return real_isfinite (&r) ? integer_one_node : integer_zero_node;
9791         }
9792
9793       return NULL_TREE;
9794
9795     case BUILT_IN_ISNAN:
9796       if (!HONOR_NANS (TYPE_MODE (TREE_TYPE (arg))))
9797         return omit_one_operand_loc (loc, type, integer_zero_node, arg);
9798
9799       if (TREE_CODE (arg) == REAL_CST)
9800         {
9801           r = TREE_REAL_CST (arg);
9802           return real_isnan (&r) ? integer_one_node : integer_zero_node;
9803         }
9804
9805       arg = builtin_save_expr (arg);
9806       return fold_build2_loc (loc, UNORDERED_EXPR, type, arg, arg);
9807
9808     default:
9809       gcc_unreachable ();
9810     }
9811 }
9812
9813 /* Fold a call to __builtin_fpclassify(int, int, int, int, int, ...).
9814    This builtin will generate code to return the appropriate floating
9815    point classification depending on the value of the floating point
9816    number passed in.  The possible return values must be supplied as
9817    int arguments to the call in the following order: FP_NAN, FP_INFINITE,
9818    FP_NORMAL, FP_SUBNORMAL and FP_ZERO.  The ellipses is for exactly
9819    one floating point argument which is "type generic".  */
9820
9821 static tree
9822 fold_builtin_fpclassify (location_t loc, tree exp)
9823 {
9824   tree fp_nan, fp_infinite, fp_normal, fp_subnormal, fp_zero,
9825     arg, type, res, tmp;
9826   enum machine_mode mode;
9827   REAL_VALUE_TYPE r;
9828   char buf[128];
9829   
9830   /* Verify the required arguments in the original call.  */
9831   if (!validate_arglist (exp, INTEGER_TYPE, INTEGER_TYPE,
9832                          INTEGER_TYPE, INTEGER_TYPE,
9833                          INTEGER_TYPE, REAL_TYPE, VOID_TYPE))
9834     return NULL_TREE;
9835   
9836   fp_nan = CALL_EXPR_ARG (exp, 0);
9837   fp_infinite = CALL_EXPR_ARG (exp, 1);
9838   fp_normal = CALL_EXPR_ARG (exp, 2);
9839   fp_subnormal = CALL_EXPR_ARG (exp, 3);
9840   fp_zero = CALL_EXPR_ARG (exp, 4);
9841   arg = CALL_EXPR_ARG (exp, 5);
9842   type = TREE_TYPE (arg);
9843   mode = TYPE_MODE (type);
9844   arg = builtin_save_expr (fold_build1_loc (loc, ABS_EXPR, type, arg));
9845
9846   /* fpclassify(x) -> 
9847        isnan(x) ? FP_NAN :
9848          (fabs(x) == Inf ? FP_INFINITE :
9849            (fabs(x) >= DBL_MIN ? FP_NORMAL :
9850              (x == 0 ? FP_ZERO : FP_SUBNORMAL))).  */
9851   
9852   tmp = fold_build2_loc (loc, EQ_EXPR, integer_type_node, arg,
9853                      build_real (type, dconst0));
9854   res = fold_build3_loc (loc, COND_EXPR, integer_type_node,
9855                      tmp, fp_zero, fp_subnormal);
9856
9857   sprintf (buf, "0x1p%d", REAL_MODE_FORMAT (mode)->emin - 1);
9858   real_from_string (&r, buf);
9859   tmp = fold_build2_loc (loc, GE_EXPR, integer_type_node,
9860                      arg, build_real (type, r));
9861   res = fold_build3_loc (loc, COND_EXPR, integer_type_node, tmp, fp_normal, res);
9862   
9863   if (HONOR_INFINITIES (mode))
9864     {
9865       real_inf (&r);
9866       tmp = fold_build2_loc (loc, EQ_EXPR, integer_type_node, arg,
9867                          build_real (type, r));
9868       res = fold_build3_loc (loc, COND_EXPR, integer_type_node, tmp,
9869                          fp_infinite, res);
9870     }
9871
9872   if (HONOR_NANS (mode))
9873     {
9874       tmp = fold_build2_loc (loc, ORDERED_EXPR, integer_type_node, arg, arg);
9875       res = fold_build3_loc (loc, COND_EXPR, integer_type_node, tmp, res, fp_nan);
9876     }
9877   
9878   return res;
9879 }
9880
9881 /* Fold a call to an unordered comparison function such as
9882    __builtin_isgreater().  FNDECL is the FUNCTION_DECL for the function
9883    being called and ARG0 and ARG1 are the arguments for the call.
9884    UNORDERED_CODE and ORDERED_CODE are comparison codes that give
9885    the opposite of the desired result.  UNORDERED_CODE is used
9886    for modes that can hold NaNs and ORDERED_CODE is used for
9887    the rest.  */
9888
9889 static tree
9890 fold_builtin_unordered_cmp (location_t loc, tree fndecl, tree arg0, tree arg1,
9891                             enum tree_code unordered_code,
9892                             enum tree_code ordered_code)
9893 {
9894   tree type = TREE_TYPE (TREE_TYPE (fndecl));
9895   enum tree_code code;
9896   tree type0, type1;
9897   enum tree_code code0, code1;
9898   tree cmp_type = NULL_TREE;
9899
9900   type0 = TREE_TYPE (arg0);
9901   type1 = TREE_TYPE (arg1);
9902
9903   code0 = TREE_CODE (type0);
9904   code1 = TREE_CODE (type1);
9905
9906   if (code0 == REAL_TYPE && code1 == REAL_TYPE)
9907     /* Choose the wider of two real types.  */
9908     cmp_type = TYPE_PRECISION (type0) >= TYPE_PRECISION (type1)
9909       ? type0 : type1;
9910   else if (code0 == REAL_TYPE && code1 == INTEGER_TYPE)
9911     cmp_type = type0;
9912   else if (code0 == INTEGER_TYPE && code1 == REAL_TYPE)
9913     cmp_type = type1;
9914
9915   arg0 = fold_convert_loc (loc, cmp_type, arg0);
9916   arg1 = fold_convert_loc (loc, cmp_type, arg1);
9917
9918   if (unordered_code == UNORDERED_EXPR)
9919     {
9920       if (!HONOR_NANS (TYPE_MODE (TREE_TYPE (arg0))))
9921         return omit_two_operands_loc (loc, type, integer_zero_node, arg0, arg1);
9922       return fold_build2_loc (loc, UNORDERED_EXPR, type, arg0, arg1);
9923     }
9924
9925   code = HONOR_NANS (TYPE_MODE (TREE_TYPE (arg0))) ? unordered_code
9926                                                    : ordered_code;
9927   return fold_build1_loc (loc, TRUTH_NOT_EXPR, type,
9928                       fold_build2_loc (loc, code, type, arg0, arg1));
9929 }
9930
9931 /* Fold a call to built-in function FNDECL with 0 arguments.
9932    IGNORE is true if the result of the function call is ignored.  This
9933    function returns NULL_TREE if no simplification was possible.  */
9934
9935 static tree
9936 fold_builtin_0 (location_t loc, tree fndecl, bool ignore ATTRIBUTE_UNUSED)
9937 {
9938   tree type = TREE_TYPE (TREE_TYPE (fndecl));
9939   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
9940   switch (fcode)
9941     {
9942     CASE_FLT_FN (BUILT_IN_INF):
9943     case BUILT_IN_INFD32:
9944     case BUILT_IN_INFD64:
9945     case BUILT_IN_INFD128:
9946       return fold_builtin_inf (loc, type, true);
9947
9948     CASE_FLT_FN (BUILT_IN_HUGE_VAL):
9949       return fold_builtin_inf (loc, type, false);
9950
9951     case BUILT_IN_CLASSIFY_TYPE:
9952       return fold_builtin_classify_type (NULL_TREE);
9953
9954     default:
9955       break;
9956     }
9957   return NULL_TREE;
9958 }
9959
9960 /* Fold a call to built-in function FNDECL with 1 argument, ARG0.
9961    IGNORE is true if the result of the function call is ignored.  This
9962    function returns NULL_TREE if no simplification was possible.  */
9963
9964 static tree
9965 fold_builtin_1 (location_t loc, tree fndecl, tree arg0, bool ignore)
9966 {
9967   tree type = TREE_TYPE (TREE_TYPE (fndecl));
9968   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
9969   switch (fcode)
9970     {
9971
9972     case BUILT_IN_CONSTANT_P:
9973       {
9974         tree val = fold_builtin_constant_p (arg0);
9975
9976         /* Gimplification will pull the CALL_EXPR for the builtin out of
9977            an if condition.  When not optimizing, we'll not CSE it back.
9978            To avoid link error types of regressions, return false now.  */
9979         if (!val && !optimize)
9980           val = integer_zero_node;
9981
9982         return val;
9983       }
9984
9985     case BUILT_IN_CLASSIFY_TYPE:
9986       return fold_builtin_classify_type (arg0);
9987
9988     case BUILT_IN_STRLEN:
9989       return fold_builtin_strlen (loc, arg0);
9990
9991     CASE_FLT_FN (BUILT_IN_FABS):
9992       return fold_builtin_fabs (loc, arg0, type);
9993
9994     case BUILT_IN_ABS:
9995     case BUILT_IN_LABS:
9996     case BUILT_IN_LLABS:
9997     case BUILT_IN_IMAXABS:
9998       return fold_builtin_abs (loc, arg0, type);
9999
10000     CASE_FLT_FN (BUILT_IN_CONJ):
10001       if (validate_arg (arg0, COMPLEX_TYPE)
10002         && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE) 
10003         return fold_build1_loc (loc, CONJ_EXPR, type, arg0);
10004     break;
10005
10006     CASE_FLT_FN (BUILT_IN_CREAL):
10007       if (validate_arg (arg0, COMPLEX_TYPE)
10008         && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE) 
10009         return non_lvalue_loc (loc, fold_build1_loc (loc, REALPART_EXPR, type, arg0));;
10010     break;
10011
10012     CASE_FLT_FN (BUILT_IN_CIMAG):
10013       if (validate_arg (arg0, COMPLEX_TYPE)
10014           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
10015         return non_lvalue_loc (loc, fold_build1_loc (loc, IMAGPART_EXPR, type, arg0));
10016     break;
10017
10018     CASE_FLT_FN (BUILT_IN_CCOS):
10019       return fold_builtin_ccos(loc, arg0, type, fndecl, /*hyper=*/ false);
10020     
10021     CASE_FLT_FN (BUILT_IN_CCOSH):
10022       return fold_builtin_ccos(loc, arg0, type, fndecl, /*hyper=*/ true);
10023     
10024 #ifdef HAVE_mpc
10025     CASE_FLT_FN (BUILT_IN_CSIN):
10026       if (validate_arg (arg0, COMPLEX_TYPE)
10027           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE) 
10028         return do_mpc_arg1 (arg0, type, mpc_sin);
10029     break;
10030     
10031     CASE_FLT_FN (BUILT_IN_CSINH):
10032       if (validate_arg (arg0, COMPLEX_TYPE)
10033           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE) 
10034         return do_mpc_arg1 (arg0, type, mpc_sinh);
10035     break;
10036     
10037     CASE_FLT_FN (BUILT_IN_CTAN):
10038       if (validate_arg (arg0, COMPLEX_TYPE)
10039           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE) 
10040         return do_mpc_arg1 (arg0, type, mpc_tan);
10041     break;
10042     
10043     CASE_FLT_FN (BUILT_IN_CTANH):
10044       if (validate_arg (arg0, COMPLEX_TYPE)
10045           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE) 
10046         return do_mpc_arg1 (arg0, type, mpc_tanh);
10047     break;
10048     
10049     CASE_FLT_FN (BUILT_IN_CLOG):
10050       if (validate_arg (arg0, COMPLEX_TYPE)
10051           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE) 
10052         return do_mpc_arg1 (arg0, type, mpc_log);
10053     break;
10054     
10055     CASE_FLT_FN (BUILT_IN_CSQRT):
10056       if (validate_arg (arg0, COMPLEX_TYPE)
10057           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE) 
10058         return do_mpc_arg1 (arg0, type, mpc_sqrt);
10059     break;
10060     
10061 #ifdef HAVE_mpc_arc
10062     CASE_FLT_FN (BUILT_IN_CASIN):
10063       if (validate_arg (arg0, COMPLEX_TYPE)
10064           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE) 
10065         return do_mpc_arg1 (arg0, type, mpc_asin);
10066     break;
10067     
10068     CASE_FLT_FN (BUILT_IN_CACOS):
10069       if (validate_arg (arg0, COMPLEX_TYPE)
10070           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE) 
10071         return do_mpc_arg1 (arg0, type, mpc_acos);
10072     break;
10073     
10074     CASE_FLT_FN (BUILT_IN_CATAN):
10075       if (validate_arg (arg0, COMPLEX_TYPE)
10076           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE) 
10077         return do_mpc_arg1 (arg0, type, mpc_atan);
10078     break;
10079     
10080     CASE_FLT_FN (BUILT_IN_CASINH):
10081       if (validate_arg (arg0, COMPLEX_TYPE)
10082           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE) 
10083         return do_mpc_arg1 (arg0, type, mpc_asinh);
10084     break;
10085     
10086     CASE_FLT_FN (BUILT_IN_CACOSH):
10087       if (validate_arg (arg0, COMPLEX_TYPE)
10088           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE) 
10089         return do_mpc_arg1 (arg0, type, mpc_acosh);
10090     break;
10091     
10092     CASE_FLT_FN (BUILT_IN_CATANH):
10093       if (validate_arg (arg0, COMPLEX_TYPE)
10094           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE) 
10095         return do_mpc_arg1 (arg0, type, mpc_atanh);
10096     break;
10097 #endif /* HAVE_mpc_arc */
10098 #endif /* HAVE_mpc */
10099     
10100     CASE_FLT_FN (BUILT_IN_CABS):
10101       return fold_builtin_cabs (loc, arg0, type, fndecl);
10102
10103     CASE_FLT_FN (BUILT_IN_CARG):
10104       return fold_builtin_carg (loc, arg0, type);
10105
10106     CASE_FLT_FN (BUILT_IN_SQRT):
10107       return fold_builtin_sqrt (loc, arg0, type);
10108
10109     CASE_FLT_FN (BUILT_IN_CBRT):
10110       return fold_builtin_cbrt (loc, arg0, type);
10111
10112     CASE_FLT_FN (BUILT_IN_ASIN):
10113       if (validate_arg (arg0, REAL_TYPE))
10114         return do_mpfr_arg1 (arg0, type, mpfr_asin,
10115                              &dconstm1, &dconst1, true);
10116     break;
10117
10118     CASE_FLT_FN (BUILT_IN_ACOS):
10119       if (validate_arg (arg0, REAL_TYPE))
10120         return do_mpfr_arg1 (arg0, type, mpfr_acos,
10121                              &dconstm1, &dconst1, true);
10122     break;
10123
10124     CASE_FLT_FN (BUILT_IN_ATAN):
10125       if (validate_arg (arg0, REAL_TYPE))
10126         return do_mpfr_arg1 (arg0, type, mpfr_atan, NULL, NULL, 0);
10127     break;
10128
10129     CASE_FLT_FN (BUILT_IN_ASINH):
10130       if (validate_arg (arg0, REAL_TYPE))
10131         return do_mpfr_arg1 (arg0, type, mpfr_asinh, NULL, NULL, 0);
10132     break;
10133
10134     CASE_FLT_FN (BUILT_IN_ACOSH):
10135       if (validate_arg (arg0, REAL_TYPE))
10136         return do_mpfr_arg1 (arg0, type, mpfr_acosh,
10137                              &dconst1, NULL, true);
10138     break;
10139
10140     CASE_FLT_FN (BUILT_IN_ATANH):
10141       if (validate_arg (arg0, REAL_TYPE))
10142         return do_mpfr_arg1 (arg0, type, mpfr_atanh,
10143                              &dconstm1, &dconst1, false);
10144     break;
10145
10146     CASE_FLT_FN (BUILT_IN_SIN):
10147       if (validate_arg (arg0, REAL_TYPE))
10148         return do_mpfr_arg1 (arg0, type, mpfr_sin, NULL, NULL, 0);
10149     break;
10150
10151     CASE_FLT_FN (BUILT_IN_COS):
10152       return fold_builtin_cos (loc, arg0, type, fndecl);
10153
10154     CASE_FLT_FN (BUILT_IN_TAN):
10155       return fold_builtin_tan (arg0, type);
10156
10157     CASE_FLT_FN (BUILT_IN_CEXP):
10158       return fold_builtin_cexp (loc, arg0, type);
10159
10160     CASE_FLT_FN (BUILT_IN_CEXPI):
10161       if (validate_arg (arg0, REAL_TYPE))
10162         return do_mpfr_sincos (arg0, NULL_TREE, NULL_TREE);
10163     break;
10164
10165     CASE_FLT_FN (BUILT_IN_SINH):
10166       if (validate_arg (arg0, REAL_TYPE))
10167         return do_mpfr_arg1 (arg0, type, mpfr_sinh, NULL, NULL, 0);
10168     break;
10169
10170     CASE_FLT_FN (BUILT_IN_COSH):
10171       return fold_builtin_cosh (loc, arg0, type, fndecl);
10172
10173     CASE_FLT_FN (BUILT_IN_TANH):
10174       if (validate_arg (arg0, REAL_TYPE))
10175         return do_mpfr_arg1 (arg0, type, mpfr_tanh, NULL, NULL, 0);
10176     break;
10177
10178     CASE_FLT_FN (BUILT_IN_ERF):
10179       if (validate_arg (arg0, REAL_TYPE))
10180         return do_mpfr_arg1 (arg0, type, mpfr_erf, NULL, NULL, 0);
10181     break;
10182
10183     CASE_FLT_FN (BUILT_IN_ERFC):
10184       if (validate_arg (arg0, REAL_TYPE))
10185         return do_mpfr_arg1 (arg0, type, mpfr_erfc, NULL, NULL, 0);
10186     break;
10187
10188     CASE_FLT_FN (BUILT_IN_TGAMMA):
10189       if (validate_arg (arg0, REAL_TYPE))
10190         return do_mpfr_arg1 (arg0, type, mpfr_gamma, NULL, NULL, 0);
10191     break;
10192  
10193     CASE_FLT_FN (BUILT_IN_EXP):
10194       return fold_builtin_exponent (loc, fndecl, arg0, mpfr_exp);
10195
10196     CASE_FLT_FN (BUILT_IN_EXP2):
10197       return fold_builtin_exponent (loc, fndecl, arg0, mpfr_exp2);
10198
10199     CASE_FLT_FN (BUILT_IN_EXP10):
10200     CASE_FLT_FN (BUILT_IN_POW10):
10201       return fold_builtin_exponent (loc, fndecl, arg0, mpfr_exp10);
10202
10203     CASE_FLT_FN (BUILT_IN_EXPM1):
10204       if (validate_arg (arg0, REAL_TYPE))
10205         return do_mpfr_arg1 (arg0, type, mpfr_expm1, NULL, NULL, 0);
10206     break;
10207  
10208     CASE_FLT_FN (BUILT_IN_LOG):
10209     return fold_builtin_logarithm (loc, fndecl, arg0, mpfr_log);
10210
10211     CASE_FLT_FN (BUILT_IN_LOG2):
10212       return fold_builtin_logarithm (loc, fndecl, arg0, mpfr_log2);
10213
10214     CASE_FLT_FN (BUILT_IN_LOG10):
10215       return fold_builtin_logarithm (loc, fndecl, arg0, mpfr_log10);
10216
10217     CASE_FLT_FN (BUILT_IN_LOG1P):
10218       if (validate_arg (arg0, REAL_TYPE))
10219         return do_mpfr_arg1 (arg0, type, mpfr_log1p,
10220                              &dconstm1, NULL, false);
10221     break;
10222
10223     CASE_FLT_FN (BUILT_IN_J0):
10224       if (validate_arg (arg0, REAL_TYPE))
10225         return do_mpfr_arg1 (arg0, type, mpfr_j0,
10226                              NULL, NULL, 0);
10227     break;
10228
10229     CASE_FLT_FN (BUILT_IN_J1):
10230       if (validate_arg (arg0, REAL_TYPE))
10231         return do_mpfr_arg1 (arg0, type, mpfr_j1,
10232                              NULL, NULL, 0);
10233     break;
10234
10235     CASE_FLT_FN (BUILT_IN_Y0):
10236       if (validate_arg (arg0, REAL_TYPE))
10237         return do_mpfr_arg1 (arg0, type, mpfr_y0,
10238                              &dconst0, NULL, false);
10239     break;
10240
10241     CASE_FLT_FN (BUILT_IN_Y1):
10242       if (validate_arg (arg0, REAL_TYPE))
10243         return do_mpfr_arg1 (arg0, type, mpfr_y1,
10244                              &dconst0, NULL, false);
10245     break;
10246
10247     CASE_FLT_FN (BUILT_IN_NAN):
10248     case BUILT_IN_NAND32:
10249     case BUILT_IN_NAND64:
10250     case BUILT_IN_NAND128:
10251       return fold_builtin_nan (arg0, type, true);
10252
10253     CASE_FLT_FN (BUILT_IN_NANS):
10254       return fold_builtin_nan (arg0, type, false);
10255
10256     CASE_FLT_FN (BUILT_IN_FLOOR):
10257       return fold_builtin_floor (loc, fndecl, arg0);
10258
10259     CASE_FLT_FN (BUILT_IN_CEIL):
10260       return fold_builtin_ceil (loc, fndecl, arg0);
10261
10262     CASE_FLT_FN (BUILT_IN_TRUNC):
10263       return fold_builtin_trunc (loc, fndecl, arg0);
10264
10265     CASE_FLT_FN (BUILT_IN_ROUND):
10266       return fold_builtin_round (loc, fndecl, arg0);
10267
10268     CASE_FLT_FN (BUILT_IN_NEARBYINT):
10269     CASE_FLT_FN (BUILT_IN_RINT):
10270       return fold_trunc_transparent_mathfn (loc, fndecl, arg0);
10271
10272     CASE_FLT_FN (BUILT_IN_LCEIL):
10273     CASE_FLT_FN (BUILT_IN_LLCEIL):
10274     CASE_FLT_FN (BUILT_IN_LFLOOR):
10275     CASE_FLT_FN (BUILT_IN_LLFLOOR):
10276     CASE_FLT_FN (BUILT_IN_LROUND):
10277     CASE_FLT_FN (BUILT_IN_LLROUND):
10278       return fold_builtin_int_roundingfn (loc, fndecl, arg0);
10279
10280     CASE_FLT_FN (BUILT_IN_LRINT):
10281     CASE_FLT_FN (BUILT_IN_LLRINT):
10282       return fold_fixed_mathfn (loc, fndecl, arg0);
10283
10284     case BUILT_IN_BSWAP32:
10285     case BUILT_IN_BSWAP64:
10286       return fold_builtin_bswap (fndecl, arg0);
10287
10288     CASE_INT_FN (BUILT_IN_FFS):
10289     CASE_INT_FN (BUILT_IN_CLZ):
10290     CASE_INT_FN (BUILT_IN_CTZ):
10291     CASE_INT_FN (BUILT_IN_POPCOUNT):
10292     CASE_INT_FN (BUILT_IN_PARITY):
10293       return fold_builtin_bitop (fndecl, arg0);
10294
10295     CASE_FLT_FN (BUILT_IN_SIGNBIT):
10296       return fold_builtin_signbit (loc, arg0, type);
10297
10298     CASE_FLT_FN (BUILT_IN_SIGNIFICAND):
10299       return fold_builtin_significand (loc, arg0, type);
10300
10301     CASE_FLT_FN (BUILT_IN_ILOGB):
10302     CASE_FLT_FN (BUILT_IN_LOGB):
10303       return fold_builtin_logb (loc, arg0, type);
10304
10305     case BUILT_IN_ISASCII:
10306       return fold_builtin_isascii (loc, arg0);
10307
10308     case BUILT_IN_TOASCII:
10309       return fold_builtin_toascii (loc, arg0);
10310
10311     case BUILT_IN_ISDIGIT:
10312       return fold_builtin_isdigit (loc, arg0);
10313
10314     CASE_FLT_FN (BUILT_IN_FINITE):
10315     case BUILT_IN_FINITED32:
10316     case BUILT_IN_FINITED64:
10317     case BUILT_IN_FINITED128:
10318     case BUILT_IN_ISFINITE:
10319       {
10320         tree ret = fold_builtin_classify (loc, fndecl, arg0, BUILT_IN_ISFINITE);
10321         if (ret)
10322           return ret;
10323         return fold_builtin_interclass_mathfn (loc, fndecl, arg0);
10324       }
10325
10326     CASE_FLT_FN (BUILT_IN_ISINF):
10327     case BUILT_IN_ISINFD32:
10328     case BUILT_IN_ISINFD64:
10329     case BUILT_IN_ISINFD128:
10330       {
10331         tree ret = fold_builtin_classify (loc, fndecl, arg0, BUILT_IN_ISINF);
10332         if (ret)
10333           return ret;
10334         return fold_builtin_interclass_mathfn (loc, fndecl, arg0);
10335       }
10336
10337     case BUILT_IN_ISNORMAL:
10338       return fold_builtin_interclass_mathfn (loc, fndecl, arg0);
10339
10340     case BUILT_IN_ISINF_SIGN:
10341       return fold_builtin_classify (loc, fndecl, arg0, BUILT_IN_ISINF_SIGN);
10342
10343     CASE_FLT_FN (BUILT_IN_ISNAN):
10344     case BUILT_IN_ISNAND32:
10345     case BUILT_IN_ISNAND64:
10346     case BUILT_IN_ISNAND128:
10347       return fold_builtin_classify (loc, fndecl, arg0, BUILT_IN_ISNAN);
10348
10349     case BUILT_IN_PRINTF:
10350     case BUILT_IN_PRINTF_UNLOCKED:
10351     case BUILT_IN_VPRINTF:
10352       return fold_builtin_printf (loc, fndecl, arg0, NULL_TREE, ignore, fcode);
10353
10354     default:
10355       break;
10356     }
10357
10358   return NULL_TREE;
10359
10360 }
10361
10362 /* Fold a call to built-in function FNDECL with 2 arguments, ARG0 and ARG1.
10363    IGNORE is true if the result of the function call is ignored.  This
10364    function returns NULL_TREE if no simplification was possible.  */
10365
10366 static tree
10367 fold_builtin_2 (location_t loc, tree fndecl, tree arg0, tree arg1, bool ignore)
10368 {
10369   tree type = TREE_TYPE (TREE_TYPE (fndecl));
10370   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
10371
10372   switch (fcode)
10373     {
10374     CASE_FLT_FN (BUILT_IN_JN):
10375       if (validate_arg (arg0, INTEGER_TYPE)
10376           && validate_arg (arg1, REAL_TYPE))
10377         return do_mpfr_bessel_n (arg0, arg1, type, mpfr_jn, NULL, 0);
10378     break;
10379
10380     CASE_FLT_FN (BUILT_IN_YN):
10381       if (validate_arg (arg0, INTEGER_TYPE)
10382           && validate_arg (arg1, REAL_TYPE))
10383         return do_mpfr_bessel_n (arg0, arg1, type, mpfr_yn,
10384                                  &dconst0, false);
10385     break;
10386
10387     CASE_FLT_FN (BUILT_IN_DREM):
10388     CASE_FLT_FN (BUILT_IN_REMAINDER):
10389       if (validate_arg (arg0, REAL_TYPE)
10390           && validate_arg(arg1, REAL_TYPE))
10391         return do_mpfr_arg2 (arg0, arg1, type, mpfr_remainder);
10392     break;
10393
10394     CASE_FLT_FN_REENT (BUILT_IN_GAMMA): /* GAMMA_R */
10395     CASE_FLT_FN_REENT (BUILT_IN_LGAMMA): /* LGAMMA_R */
10396       if (validate_arg (arg0, REAL_TYPE)
10397           && validate_arg(arg1, POINTER_TYPE))
10398         return do_mpfr_lgamma_r (arg0, arg1, type);
10399     break;
10400
10401     CASE_FLT_FN (BUILT_IN_ATAN2):
10402       if (validate_arg (arg0, REAL_TYPE)
10403           && validate_arg(arg1, REAL_TYPE))
10404         return do_mpfr_arg2 (arg0, arg1, type, mpfr_atan2);
10405     break;
10406
10407     CASE_FLT_FN (BUILT_IN_FDIM):
10408       if (validate_arg (arg0, REAL_TYPE)
10409           && validate_arg(arg1, REAL_TYPE))
10410         return do_mpfr_arg2 (arg0, arg1, type, mpfr_dim);
10411     break;
10412
10413     CASE_FLT_FN (BUILT_IN_HYPOT):
10414       return fold_builtin_hypot (loc, fndecl, arg0, arg1, type);
10415
10416 #ifdef HAVE_mpc_pow
10417     CASE_FLT_FN (BUILT_IN_CPOW):
10418       if (validate_arg (arg0, COMPLEX_TYPE)
10419           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE
10420           && validate_arg (arg1, COMPLEX_TYPE)
10421           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg1))) == REAL_TYPE) 
10422         return do_mpc_arg2 (arg0, arg1, type, /*do_nonfinite=*/ 0, mpc_pow);
10423     break;
10424 #endif
10425
10426     CASE_FLT_FN (BUILT_IN_LDEXP):
10427       return fold_builtin_load_exponent (loc, arg0, arg1, type, /*ldexp=*/true);
10428     CASE_FLT_FN (BUILT_IN_SCALBN):
10429     CASE_FLT_FN (BUILT_IN_SCALBLN):
10430       return fold_builtin_load_exponent (loc, arg0, arg1,
10431                                          type, /*ldexp=*/false);
10432
10433     CASE_FLT_FN (BUILT_IN_FREXP):
10434       return fold_builtin_frexp (loc, arg0, arg1, type);
10435
10436     CASE_FLT_FN (BUILT_IN_MODF):
10437       return fold_builtin_modf (loc, arg0, arg1, type);
10438
10439     case BUILT_IN_BZERO:
10440       return fold_builtin_bzero (loc, arg0, arg1, ignore);
10441
10442     case BUILT_IN_FPUTS:
10443       return fold_builtin_fputs (loc, arg0, arg1, ignore, false, NULL_TREE);
10444
10445     case BUILT_IN_FPUTS_UNLOCKED:
10446       return fold_builtin_fputs (loc, arg0, arg1, ignore, true, NULL_TREE);
10447
10448     case BUILT_IN_STRSTR:
10449       return fold_builtin_strstr (loc, arg0, arg1, type);
10450
10451     case BUILT_IN_STRCAT:
10452       return fold_builtin_strcat (loc, arg0, arg1);
10453
10454     case BUILT_IN_STRSPN:
10455       return fold_builtin_strspn (loc, arg0, arg1);
10456
10457     case BUILT_IN_STRCSPN:
10458       return fold_builtin_strcspn (loc, arg0, arg1);
10459
10460     case BUILT_IN_STRCHR:
10461     case BUILT_IN_INDEX:
10462       return fold_builtin_strchr (loc, arg0, arg1, type);
10463
10464     case BUILT_IN_STRRCHR:
10465     case BUILT_IN_RINDEX:
10466       return fold_builtin_strrchr (loc, arg0, arg1, type);
10467
10468     case BUILT_IN_STRCPY:
10469       return fold_builtin_strcpy (loc, fndecl, arg0, arg1, NULL_TREE);
10470
10471     case BUILT_IN_STPCPY:
10472       if (ignore)
10473         {
10474           tree fn = implicit_built_in_decls[BUILT_IN_STRCPY];
10475           if (!fn)
10476             break;
10477
10478           return build_call_expr_loc (loc, fn, 2, arg0, arg1);
10479         }
10480       else
10481         return fold_builtin_stpcpy (loc, fndecl, arg0, arg1);
10482       break;
10483
10484     case BUILT_IN_STRCMP:
10485       return fold_builtin_strcmp (loc, arg0, arg1);
10486
10487     case BUILT_IN_STRPBRK:
10488       return fold_builtin_strpbrk (loc, arg0, arg1, type);
10489
10490     case BUILT_IN_EXPECT:
10491       return fold_builtin_expect (loc, arg0, arg1);
10492
10493     CASE_FLT_FN (BUILT_IN_POW):
10494       return fold_builtin_pow (loc, fndecl, arg0, arg1, type);
10495
10496     CASE_FLT_FN (BUILT_IN_POWI):
10497       return fold_builtin_powi (loc, fndecl, arg0, arg1, type);
10498
10499     CASE_FLT_FN (BUILT_IN_COPYSIGN):
10500       return fold_builtin_copysign (loc, fndecl, arg0, arg1, type);
10501
10502     CASE_FLT_FN (BUILT_IN_FMIN):
10503       return fold_builtin_fmin_fmax (loc, arg0, arg1, type, /*max=*/false);
10504
10505     CASE_FLT_FN (BUILT_IN_FMAX):
10506       return fold_builtin_fmin_fmax (loc, arg0, arg1, type, /*max=*/true);
10507
10508     case BUILT_IN_ISGREATER:
10509       return fold_builtin_unordered_cmp (loc, fndecl,
10510                                          arg0, arg1, UNLE_EXPR, LE_EXPR);
10511     case BUILT_IN_ISGREATEREQUAL:
10512       return fold_builtin_unordered_cmp (loc, fndecl,
10513                                          arg0, arg1, UNLT_EXPR, LT_EXPR);
10514     case BUILT_IN_ISLESS:
10515       return fold_builtin_unordered_cmp (loc, fndecl,
10516                                          arg0, arg1, UNGE_EXPR, GE_EXPR);
10517     case BUILT_IN_ISLESSEQUAL:
10518       return fold_builtin_unordered_cmp (loc, fndecl,
10519                                          arg0, arg1, UNGT_EXPR, GT_EXPR);
10520     case BUILT_IN_ISLESSGREATER:
10521       return fold_builtin_unordered_cmp (loc, fndecl,
10522                                          arg0, arg1, UNEQ_EXPR, EQ_EXPR);
10523     case BUILT_IN_ISUNORDERED:
10524       return fold_builtin_unordered_cmp (loc, fndecl,
10525                                          arg0, arg1, UNORDERED_EXPR,
10526                                          NOP_EXPR);
10527
10528       /* We do the folding for va_start in the expander.  */
10529     case BUILT_IN_VA_START:
10530       break;
10531
10532     case BUILT_IN_SPRINTF:
10533       return fold_builtin_sprintf (loc, arg0, arg1, NULL_TREE, ignore);
10534
10535     case BUILT_IN_OBJECT_SIZE:
10536       return fold_builtin_object_size (arg0, arg1);
10537
10538     case BUILT_IN_PRINTF:
10539     case BUILT_IN_PRINTF_UNLOCKED:
10540     case BUILT_IN_VPRINTF:
10541       return fold_builtin_printf (loc, fndecl, arg0, arg1, ignore, fcode);
10542
10543     case BUILT_IN_PRINTF_CHK:
10544     case BUILT_IN_VPRINTF_CHK:
10545       if (!validate_arg (arg0, INTEGER_TYPE)
10546           || TREE_SIDE_EFFECTS (arg0))
10547         return NULL_TREE;
10548       else
10549         return fold_builtin_printf (loc, fndecl,
10550                                     arg1, NULL_TREE, ignore, fcode);
10551     break;
10552
10553     case BUILT_IN_FPRINTF:
10554     case BUILT_IN_FPRINTF_UNLOCKED:
10555     case BUILT_IN_VFPRINTF:
10556       return fold_builtin_fprintf (loc, fndecl, arg0, arg1, NULL_TREE,
10557                                    ignore, fcode);
10558
10559     default:
10560       break;
10561     }
10562   return NULL_TREE;
10563 }
10564
10565 /* Fold a call to built-in function FNDECL with 3 arguments, ARG0, ARG1,
10566    and ARG2.  IGNORE is true if the result of the function call is ignored.
10567    This function returns NULL_TREE if no simplification was possible.  */
10568
10569 static tree
10570 fold_builtin_3 (location_t loc, tree fndecl,
10571                 tree arg0, tree arg1, tree arg2, bool ignore)
10572 {
10573   tree type = TREE_TYPE (TREE_TYPE (fndecl));
10574   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
10575   switch (fcode)
10576     {
10577
10578     CASE_FLT_FN (BUILT_IN_SINCOS):
10579       return fold_builtin_sincos (loc, arg0, arg1, arg2);
10580
10581     CASE_FLT_FN (BUILT_IN_FMA):
10582       if (validate_arg (arg0, REAL_TYPE)
10583           && validate_arg(arg1, REAL_TYPE)
10584           && validate_arg(arg2, REAL_TYPE))
10585         return do_mpfr_arg3 (arg0, arg1, arg2, type, mpfr_fma);
10586     break;
10587
10588     CASE_FLT_FN (BUILT_IN_REMQUO):
10589       if (validate_arg (arg0, REAL_TYPE)
10590           && validate_arg(arg1, REAL_TYPE)
10591           && validate_arg(arg2, POINTER_TYPE))
10592         return do_mpfr_remquo (arg0, arg1, arg2);
10593     break;
10594
10595     case BUILT_IN_MEMSET:
10596       return fold_builtin_memset (loc, arg0, arg1, arg2, type, ignore);
10597
10598     case BUILT_IN_BCOPY:
10599       return fold_builtin_memory_op (loc, arg1, arg0, arg2,
10600                                      void_type_node, true, /*endp=*/3);
10601
10602     case BUILT_IN_MEMCPY:
10603       return fold_builtin_memory_op (loc, arg0, arg1, arg2,
10604                                      type, ignore, /*endp=*/0);
10605
10606     case BUILT_IN_MEMPCPY:
10607       return fold_builtin_memory_op (loc, arg0, arg1, arg2,
10608                                      type, ignore, /*endp=*/1);
10609
10610     case BUILT_IN_MEMMOVE:
10611       return fold_builtin_memory_op (loc, arg0, arg1, arg2,
10612                                      type, ignore, /*endp=*/3);
10613
10614     case BUILT_IN_STRNCAT:
10615       return fold_builtin_strncat (loc, arg0, arg1, arg2);
10616
10617     case BUILT_IN_STRNCPY:
10618       return fold_builtin_strncpy (loc, fndecl, arg0, arg1, arg2, NULL_TREE);
10619
10620     case BUILT_IN_STRNCMP:
10621       return fold_builtin_strncmp (loc, arg0, arg1, arg2);
10622
10623     case BUILT_IN_MEMCHR:
10624       return fold_builtin_memchr (loc, arg0, arg1, arg2, type);
10625
10626     case BUILT_IN_BCMP:
10627     case BUILT_IN_MEMCMP:
10628       return fold_builtin_memcmp (loc, arg0, arg1, arg2);;
10629
10630     case BUILT_IN_SPRINTF:
10631       return fold_builtin_sprintf (loc, arg0, arg1, arg2, ignore);
10632
10633     case BUILT_IN_STRCPY_CHK:
10634     case BUILT_IN_STPCPY_CHK:
10635       return fold_builtin_stxcpy_chk (loc, fndecl, arg0, arg1, arg2, NULL_TREE,
10636                                       ignore, fcode);
10637
10638     case BUILT_IN_STRCAT_CHK:
10639       return fold_builtin_strcat_chk (loc, fndecl, arg0, arg1, arg2);
10640
10641     case BUILT_IN_PRINTF_CHK:
10642     case BUILT_IN_VPRINTF_CHK:
10643       if (!validate_arg (arg0, INTEGER_TYPE)
10644           || TREE_SIDE_EFFECTS (arg0))
10645         return NULL_TREE;
10646       else
10647         return fold_builtin_printf (loc, fndecl, arg1, arg2, ignore, fcode);
10648     break;
10649
10650     case BUILT_IN_FPRINTF:
10651     case BUILT_IN_FPRINTF_UNLOCKED:
10652     case BUILT_IN_VFPRINTF:
10653       return fold_builtin_fprintf (loc, fndecl, arg0, arg1, arg2,
10654                                    ignore, fcode);
10655
10656     case BUILT_IN_FPRINTF_CHK:
10657     case BUILT_IN_VFPRINTF_CHK:
10658       if (!validate_arg (arg1, INTEGER_TYPE)
10659           || TREE_SIDE_EFFECTS (arg1))
10660         return NULL_TREE;
10661       else
10662         return fold_builtin_fprintf (loc, fndecl, arg0, arg2, NULL_TREE,
10663                                      ignore, fcode);
10664
10665     default:
10666       break;
10667     }
10668   return NULL_TREE;
10669 }
10670
10671 /* Fold a call to built-in function FNDECL with 4 arguments, ARG0, ARG1,
10672    ARG2, and ARG3.  IGNORE is true if the result of the function call is
10673    ignored.  This function returns NULL_TREE if no simplification was
10674    possible.  */
10675  
10676 static tree
10677 fold_builtin_4 (location_t loc, tree fndecl,
10678                 tree arg0, tree arg1, tree arg2, tree arg3, bool ignore)
10679 {
10680   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
10681
10682   switch (fcode)
10683     {
10684     case BUILT_IN_MEMCPY_CHK:
10685     case BUILT_IN_MEMPCPY_CHK:
10686     case BUILT_IN_MEMMOVE_CHK:
10687     case BUILT_IN_MEMSET_CHK:
10688       return fold_builtin_memory_chk (loc, fndecl, arg0, arg1, arg2, arg3,
10689                                       NULL_TREE, ignore,
10690                                       DECL_FUNCTION_CODE (fndecl));
10691
10692     case BUILT_IN_STRNCPY_CHK:
10693       return fold_builtin_strncpy_chk (loc, arg0, arg1, arg2, arg3, NULL_TREE);
10694
10695     case BUILT_IN_STRNCAT_CHK:
10696       return fold_builtin_strncat_chk (loc, fndecl, arg0, arg1, arg2, arg3);
10697
10698     case BUILT_IN_FPRINTF_CHK:
10699     case BUILT_IN_VFPRINTF_CHK:
10700       if (!validate_arg (arg1, INTEGER_TYPE)
10701           || TREE_SIDE_EFFECTS (arg1))
10702         return NULL_TREE;
10703       else
10704         return fold_builtin_fprintf (loc, fndecl, arg0, arg2, arg3,
10705                                      ignore, fcode);
10706     break;
10707
10708     default:
10709       break;
10710     }
10711   return NULL_TREE;
10712 }
10713
10714 /* Fold a call to built-in function FNDECL.  ARGS is an array of NARGS
10715     arguments, where NARGS <= 4.  IGNORE is true if the result of the
10716     function call is ignored.  This function returns NULL_TREE if no
10717     simplification was possible.  Note that this only folds builtins with
10718     fixed argument patterns.  Foldings that do varargs-to-varargs
10719     transformations, or that match calls with more than 4 arguments,
10720     need to be handled with fold_builtin_varargs instead.  */
10721  
10722 #define MAX_ARGS_TO_FOLD_BUILTIN 4
10723  
10724 static tree
10725 fold_builtin_n (location_t loc, tree fndecl, tree *args, int nargs, bool ignore)
10726 {
10727   tree ret = NULL_TREE;
10728
10729   switch (nargs)
10730     {
10731     case 0:
10732       ret = fold_builtin_0 (loc, fndecl, ignore);
10733       break;
10734     case 1:
10735       ret = fold_builtin_1 (loc, fndecl, args[0], ignore);
10736       break;
10737     case 2:
10738       ret = fold_builtin_2 (loc, fndecl, args[0], args[1], ignore);
10739       break;
10740     case 3:
10741       ret = fold_builtin_3 (loc, fndecl, args[0], args[1], args[2], ignore);
10742       break;
10743     case 4:
10744       ret = fold_builtin_4 (loc, fndecl, args[0], args[1], args[2], args[3],
10745                             ignore);
10746       break;
10747     default:
10748       break;
10749     }
10750   if (ret)
10751     {
10752       ret = build1 (NOP_EXPR, TREE_TYPE (ret), ret);
10753       SET_EXPR_LOCATION (ret, loc);
10754       TREE_NO_WARNING (ret) = 1;
10755       return ret;
10756     }
10757   return NULL_TREE;
10758 }
10759
10760 /* Builtins with folding operations that operate on "..." arguments
10761    need special handling; we need to store the arguments in a convenient
10762    data structure before attempting any folding.  Fortunately there are
10763    only a few builtins that fall into this category.  FNDECL is the
10764    function, EXP is the CALL_EXPR for the call, and IGNORE is true if the
10765    result of the function call is ignored.  */
10766
10767 static tree
10768 fold_builtin_varargs (location_t loc, tree fndecl, tree exp,
10769                       bool ignore ATTRIBUTE_UNUSED)
10770 {
10771   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
10772   tree ret = NULL_TREE;
10773
10774   switch (fcode)
10775     {
10776     case BUILT_IN_SPRINTF_CHK:
10777     case BUILT_IN_VSPRINTF_CHK:
10778       ret = fold_builtin_sprintf_chk (loc, exp, fcode);
10779       break;
10780
10781     case BUILT_IN_SNPRINTF_CHK:
10782     case BUILT_IN_VSNPRINTF_CHK:
10783       ret = fold_builtin_snprintf_chk (loc, exp, NULL_TREE, fcode);
10784       break;
10785
10786     case BUILT_IN_FPCLASSIFY:
10787       ret = fold_builtin_fpclassify (loc, exp);
10788       break;
10789
10790     default:
10791       break;
10792     }
10793   if (ret)
10794     {
10795       ret = build1 (NOP_EXPR, TREE_TYPE (ret), ret);
10796       SET_EXPR_LOCATION (ret, loc);
10797       TREE_NO_WARNING (ret) = 1;
10798       return ret;
10799     }
10800   return NULL_TREE;
10801 }
10802
10803 /* Return true if FNDECL shouldn't be folded right now.
10804    If a built-in function has an inline attribute always_inline
10805    wrapper, defer folding it after always_inline functions have
10806    been inlined, otherwise e.g. -D_FORTIFY_SOURCE checking
10807    might not be performed.  */
10808
10809 static bool
10810 avoid_folding_inline_builtin (tree fndecl)
10811 {
10812   return (DECL_DECLARED_INLINE_P (fndecl)
10813           && DECL_DISREGARD_INLINE_LIMITS (fndecl)
10814           && cfun
10815           && !cfun->always_inline_functions_inlined
10816           && lookup_attribute ("always_inline", DECL_ATTRIBUTES (fndecl)));
10817 }
10818
10819 /* A wrapper function for builtin folding that prevents warnings for
10820    "statement without effect" and the like, caused by removing the
10821    call node earlier than the warning is generated.  */
10822
10823 tree
10824 fold_call_expr (location_t loc, tree exp, bool ignore)
10825 {
10826   tree ret = NULL_TREE;
10827   tree fndecl = get_callee_fndecl (exp);
10828   if (fndecl
10829       && TREE_CODE (fndecl) == FUNCTION_DECL
10830       && DECL_BUILT_IN (fndecl)
10831       /* If CALL_EXPR_VA_ARG_PACK is set, the arguments aren't finalized
10832          yet.  Defer folding until we see all the arguments
10833          (after inlining).  */
10834       && !CALL_EXPR_VA_ARG_PACK (exp))
10835     {
10836       int nargs = call_expr_nargs (exp);
10837
10838       /* Before gimplification CALL_EXPR_VA_ARG_PACK is not set, but
10839          instead last argument is __builtin_va_arg_pack ().  Defer folding
10840          even in that case, until arguments are finalized.  */
10841       if (nargs && TREE_CODE (CALL_EXPR_ARG (exp, nargs - 1)) == CALL_EXPR)
10842         {
10843           tree fndecl2 = get_callee_fndecl (CALL_EXPR_ARG (exp, nargs - 1));
10844           if (fndecl2
10845               && TREE_CODE (fndecl2) == FUNCTION_DECL
10846               && DECL_BUILT_IN_CLASS (fndecl2) == BUILT_IN_NORMAL
10847               && DECL_FUNCTION_CODE (fndecl2) == BUILT_IN_VA_ARG_PACK)
10848             return NULL_TREE;
10849         }
10850
10851       if (avoid_folding_inline_builtin (fndecl))
10852         return NULL_TREE;
10853
10854       /* FIXME: Don't use a list in this interface.  */
10855       if (DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_MD)
10856           return targetm.fold_builtin (fndecl, CALL_EXPR_ARGS (exp), ignore);
10857       else
10858         {
10859           if (nargs <= MAX_ARGS_TO_FOLD_BUILTIN)
10860             {
10861               tree *args = CALL_EXPR_ARGP (exp);
10862               ret = fold_builtin_n (loc, fndecl, args, nargs, ignore);
10863             }
10864           if (!ret)
10865             ret = fold_builtin_varargs (loc, fndecl, exp, ignore);
10866           if (ret)
10867             return ret;
10868         }
10869     }
10870   return NULL_TREE;
10871 }
10872  
10873 /* Conveniently construct a function call expression.  FNDECL names the
10874     function to be called and ARGLIST is a TREE_LIST of arguments.  */
10875  
10876 tree
10877 build_function_call_expr (location_t loc, tree fndecl, tree arglist)
10878 {
10879   tree fntype = TREE_TYPE (fndecl);
10880   tree fn = build1 (ADDR_EXPR, build_pointer_type (fntype), fndecl);
10881   int n = list_length (arglist);
10882   tree *argarray = (tree *) alloca (n * sizeof (tree));
10883   int i;
10884
10885   for (i = 0; i < n; i++, arglist = TREE_CHAIN (arglist))
10886     argarray[i] = TREE_VALUE (arglist);
10887   return fold_builtin_call_array (loc, TREE_TYPE (fntype), fn, n, argarray);
10888 }
10889
10890 /* Conveniently construct a function call expression.  FNDECL names the
10891    function to be called, N is the number of arguments, and the "..."
10892    parameters are the argument expressions.  */
10893  
10894 tree
10895 build_call_expr_loc (location_t loc, tree fndecl, int n, ...)
10896 {
10897   va_list ap;
10898   tree fntype = TREE_TYPE (fndecl);
10899   tree fn = build1 (ADDR_EXPR, build_pointer_type (fntype), fndecl);
10900   tree *argarray = (tree *) alloca (n * sizeof (tree));
10901   int i;
10902
10903   va_start (ap, n);
10904   for (i = 0; i < n; i++)
10905     argarray[i] = va_arg (ap, tree);
10906   va_end (ap);
10907   return fold_builtin_call_array (loc, TREE_TYPE (fntype), fn, n, argarray);
10908 }
10909
10910 /* Construct a CALL_EXPR with type TYPE with FN as the function expression.
10911    N arguments are passed in the array ARGARRAY.  */
10912
10913 tree
10914 fold_builtin_call_array (location_t loc, tree type,
10915                          tree fn,
10916                          int n,
10917                          tree *argarray)
10918 {
10919   tree ret = NULL_TREE;
10920   int i;
10921    tree exp;
10922
10923   if (TREE_CODE (fn) == ADDR_EXPR)
10924   {
10925     tree fndecl = TREE_OPERAND (fn, 0);
10926     if (TREE_CODE (fndecl) == FUNCTION_DECL
10927         && DECL_BUILT_IN (fndecl))
10928       {
10929         /* If last argument is __builtin_va_arg_pack (), arguments to this
10930            function are not finalized yet.  Defer folding until they are.  */
10931         if (n && TREE_CODE (argarray[n - 1]) == CALL_EXPR)
10932           {
10933             tree fndecl2 = get_callee_fndecl (argarray[n - 1]);
10934             if (fndecl2
10935                 && TREE_CODE (fndecl2) == FUNCTION_DECL
10936                 && DECL_BUILT_IN_CLASS (fndecl2) == BUILT_IN_NORMAL
10937                 && DECL_FUNCTION_CODE (fndecl2) == BUILT_IN_VA_ARG_PACK)
10938               return build_call_array_loc (loc, type, fn, n, argarray);
10939           }
10940         if (avoid_folding_inline_builtin (fndecl))
10941           return build_call_array_loc (loc, type, fn, n, argarray);
10942         if (DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_MD)
10943           {
10944             tree arglist = NULL_TREE;
10945             for (i = n - 1; i >= 0; i--)
10946               arglist = tree_cons (NULL_TREE, argarray[i], arglist);
10947             ret = targetm.fold_builtin (fndecl, arglist, false);
10948             if (ret)
10949               return ret;
10950             return build_call_array_loc (loc, type, fn, n, argarray);
10951           }
10952         else if (n <= MAX_ARGS_TO_FOLD_BUILTIN)
10953           {
10954             /* First try the transformations that don't require consing up
10955                an exp.  */
10956             ret = fold_builtin_n (loc, fndecl, argarray, n, false);
10957             if (ret)
10958               return ret;
10959           }
10960
10961         /* If we got this far, we need to build an exp.  */
10962         exp = build_call_array_loc (loc, type, fn, n, argarray);
10963         ret = fold_builtin_varargs (loc, fndecl, exp, false);
10964         return ret ? ret : exp;
10965       }
10966   }
10967
10968   return build_call_array_loc (loc, type, fn, n, argarray);
10969 }
10970
10971 /* Construct a new CALL_EXPR using the tail of the argument list of EXP
10972    along with N new arguments specified as the "..." parameters.  SKIP
10973    is the number of arguments in EXP to be omitted.  This function is used
10974    to do varargs-to-varargs transformations.  */
10975
10976 static tree
10977 rewrite_call_expr (location_t loc, tree exp, int skip, tree fndecl, int n, ...)
10978 {
10979   int oldnargs = call_expr_nargs (exp);
10980   int nargs = oldnargs - skip + n;
10981   tree fntype = TREE_TYPE (fndecl);
10982   tree fn = build1 (ADDR_EXPR, build_pointer_type (fntype), fndecl);
10983   tree *buffer;
10984
10985   if (n > 0)
10986     {
10987       int i, j;
10988       va_list ap;
10989
10990       buffer = XALLOCAVEC (tree, nargs);
10991       va_start (ap, n);
10992       for (i = 0; i < n; i++)
10993         buffer[i] = va_arg (ap, tree);
10994       va_end (ap);
10995       for (j = skip; j < oldnargs; j++, i++)
10996         buffer[i] = CALL_EXPR_ARG (exp, j);
10997     }
10998   else 
10999     buffer = CALL_EXPR_ARGP (exp) + skip;
11000
11001   return fold (build_call_array_loc (loc, TREE_TYPE (exp), fn, nargs, buffer));
11002 }
11003
11004 /* Validate a single argument ARG against a tree code CODE representing
11005    a type.  */
11006   
11007 static bool
11008 validate_arg (const_tree arg, enum tree_code code)
11009 {
11010   if (!arg)
11011     return false;
11012   else if (code == POINTER_TYPE)
11013     return POINTER_TYPE_P (TREE_TYPE (arg));
11014   else if (code == INTEGER_TYPE)
11015     return INTEGRAL_TYPE_P (TREE_TYPE (arg));
11016   return code == TREE_CODE (TREE_TYPE (arg));
11017 }
11018
11019 /* This function validates the types of a function call argument list
11020    against a specified list of tree_codes.  If the last specifier is a 0,
11021    that represents an ellipses, otherwise the last specifier must be a
11022    VOID_TYPE.
11023
11024    This is the GIMPLE version of validate_arglist.  Eventually we want to
11025    completely convert builtins.c to work from GIMPLEs and the tree based
11026    validate_arglist will then be removed.  */
11027
11028 bool
11029 validate_gimple_arglist (const_gimple call, ...)
11030 {
11031   enum tree_code code;
11032   bool res = 0;
11033   va_list ap;
11034   const_tree arg;
11035   size_t i;
11036
11037   va_start (ap, call);
11038   i = 0;
11039
11040   do
11041     {
11042       code = (enum tree_code) va_arg (ap, int);
11043       switch (code)
11044         {
11045         case 0:
11046           /* This signifies an ellipses, any further arguments are all ok.  */
11047           res = true;
11048           goto end;
11049         case VOID_TYPE:
11050           /* This signifies an endlink, if no arguments remain, return
11051              true, otherwise return false.  */
11052           res = (i == gimple_call_num_args (call));
11053           goto end;
11054         default:
11055           /* If no parameters remain or the parameter's code does not
11056              match the specified code, return false.  Otherwise continue
11057              checking any remaining arguments.  */
11058           arg = gimple_call_arg (call, i++);
11059           if (!validate_arg (arg, code))
11060             goto end;
11061           break;
11062         }
11063     }
11064   while (1);
11065
11066   /* We need gotos here since we can only have one VA_CLOSE in a
11067      function.  */
11068  end: ;
11069   va_end (ap);
11070
11071   return res;
11072 }
11073
11074 /* This function validates the types of a function call argument list
11075    against a specified list of tree_codes.  If the last specifier is a 0,
11076    that represents an ellipses, otherwise the last specifier must be a
11077    VOID_TYPE.  */
11078
11079 bool
11080 validate_arglist (const_tree callexpr, ...)
11081 {
11082   enum tree_code code;
11083   bool res = 0;
11084   va_list ap;
11085   const_call_expr_arg_iterator iter;
11086   const_tree arg;
11087
11088   va_start (ap, callexpr);
11089   init_const_call_expr_arg_iterator (callexpr, &iter);
11090
11091   do
11092     {
11093       code = (enum tree_code) va_arg (ap, int);
11094       switch (code)
11095         {
11096         case 0:
11097           /* This signifies an ellipses, any further arguments are all ok.  */
11098           res = true;
11099           goto end;
11100         case VOID_TYPE:
11101           /* This signifies an endlink, if no arguments remain, return
11102              true, otherwise return false.  */
11103           res = !more_const_call_expr_args_p (&iter);
11104           goto end;
11105         default:
11106           /* If no parameters remain or the parameter's code does not
11107              match the specified code, return false.  Otherwise continue
11108              checking any remaining arguments.  */
11109           arg = next_const_call_expr_arg (&iter);
11110           if (!validate_arg (arg, code))
11111             goto end;
11112           break;
11113         }
11114     }
11115   while (1);
11116
11117   /* We need gotos here since we can only have one VA_CLOSE in a
11118      function.  */
11119  end: ;
11120   va_end (ap);
11121
11122   return res;
11123 }
11124
11125 /* Default target-specific builtin expander that does nothing.  */
11126
11127 rtx
11128 default_expand_builtin (tree exp ATTRIBUTE_UNUSED,
11129                         rtx target ATTRIBUTE_UNUSED,
11130                         rtx subtarget ATTRIBUTE_UNUSED,
11131                         enum machine_mode mode ATTRIBUTE_UNUSED,
11132                         int ignore ATTRIBUTE_UNUSED)
11133 {
11134   return NULL_RTX;
11135 }
11136
11137 /* Returns true is EXP represents data that would potentially reside
11138    in a readonly section.  */
11139
11140 static bool
11141 readonly_data_expr (tree exp)
11142 {
11143   STRIP_NOPS (exp);
11144
11145   if (TREE_CODE (exp) != ADDR_EXPR)
11146     return false;
11147
11148   exp = get_base_address (TREE_OPERAND (exp, 0));
11149   if (!exp)
11150     return false;
11151
11152   /* Make sure we call decl_readonly_section only for trees it
11153      can handle (since it returns true for everything it doesn't
11154      understand).  */
11155   if (TREE_CODE (exp) == STRING_CST
11156       || TREE_CODE (exp) == CONSTRUCTOR
11157       || (TREE_CODE (exp) == VAR_DECL && TREE_STATIC (exp)))
11158     return decl_readonly_section (exp, 0);
11159   else
11160     return false;
11161 }
11162
11163 /* Simplify a call to the strstr builtin.  S1 and S2 are the arguments
11164    to the call, and TYPE is its return type.
11165
11166    Return NULL_TREE if no simplification was possible, otherwise return the
11167    simplified form of the call as a tree.
11168
11169    The simplified form may be a constant or other expression which
11170    computes the same value, but in a more efficient manner (including
11171    calls to other builtin functions).
11172
11173    The call may contain arguments which need to be evaluated, but
11174    which are not useful to determine the result of the call.  In
11175    this case we return a chain of COMPOUND_EXPRs.  The LHS of each
11176    COMPOUND_EXPR will be an argument which must be evaluated.
11177    COMPOUND_EXPRs are chained through their RHS.  The RHS of the last
11178    COMPOUND_EXPR in the chain will contain the tree for the simplified
11179    form of the builtin function call.  */
11180
11181 static tree
11182 fold_builtin_strstr (location_t loc, tree s1, tree s2, tree type)
11183 {
11184   if (!validate_arg (s1, POINTER_TYPE)
11185       || !validate_arg (s2, POINTER_TYPE))
11186     return NULL_TREE;
11187   else
11188     {
11189       tree fn;
11190       const char *p1, *p2;
11191
11192       p2 = c_getstr (s2);
11193       if (p2 == NULL)
11194         return NULL_TREE;
11195
11196       p1 = c_getstr (s1);
11197       if (p1 != NULL)
11198         {
11199           const char *r = strstr (p1, p2);
11200           tree tem;
11201
11202           if (r == NULL)
11203             return build_int_cst (TREE_TYPE (s1), 0);
11204
11205           /* Return an offset into the constant string argument.  */
11206           tem = fold_build2_loc (loc, POINTER_PLUS_EXPR, TREE_TYPE (s1),
11207                              s1, size_int (r - p1));
11208           return fold_convert_loc (loc, type, tem);
11209         }
11210
11211       /* The argument is const char *, and the result is char *, so we need
11212          a type conversion here to avoid a warning.  */
11213       if (p2[0] == '\0')
11214         return fold_convert_loc (loc, type, s1);
11215
11216       if (p2[1] != '\0')
11217         return NULL_TREE;
11218
11219       fn = implicit_built_in_decls[BUILT_IN_STRCHR];
11220       if (!fn)
11221         return NULL_TREE;
11222
11223       /* New argument list transforming strstr(s1, s2) to
11224          strchr(s1, s2[0]).  */
11225       return build_call_expr_loc (loc, fn, 2, s1, build_int_cst (NULL_TREE, p2[0]));
11226     }
11227 }
11228
11229 /* Simplify a call to the strchr builtin.  S1 and S2 are the arguments to
11230    the call, and TYPE is its return type.
11231
11232    Return NULL_TREE if no simplification was possible, otherwise return the
11233    simplified form of the call as a tree.
11234
11235    The simplified form may be a constant or other expression which
11236    computes the same value, but in a more efficient manner (including
11237    calls to other builtin functions).
11238
11239    The call may contain arguments which need to be evaluated, but
11240    which are not useful to determine the result of the call.  In
11241    this case we return a chain of COMPOUND_EXPRs.  The LHS of each
11242    COMPOUND_EXPR will be an argument which must be evaluated.
11243    COMPOUND_EXPRs are chained through their RHS.  The RHS of the last
11244    COMPOUND_EXPR in the chain will contain the tree for the simplified
11245    form of the builtin function call.  */
11246
11247 static tree
11248 fold_builtin_strchr (location_t loc, tree s1, tree s2, tree type)
11249 {
11250   if (!validate_arg (s1, POINTER_TYPE)
11251       || !validate_arg (s2, INTEGER_TYPE))
11252     return NULL_TREE;
11253   else
11254     {
11255       const char *p1;
11256
11257       if (TREE_CODE (s2) != INTEGER_CST)
11258         return NULL_TREE;
11259
11260       p1 = c_getstr (s1);
11261       if (p1 != NULL)
11262         {
11263           char c;
11264           const char *r;
11265           tree tem;
11266
11267           if (target_char_cast (s2, &c))
11268             return NULL_TREE;
11269
11270           r = strchr (p1, c);
11271
11272           if (r == NULL)
11273             return build_int_cst (TREE_TYPE (s1), 0);
11274
11275           /* Return an offset into the constant string argument.  */
11276           tem = fold_build2_loc (loc, POINTER_PLUS_EXPR, TREE_TYPE (s1),
11277                              s1, size_int (r - p1));
11278           return fold_convert_loc (loc, type, tem);
11279         }
11280       return NULL_TREE;
11281     }
11282 }
11283
11284 /* Simplify a call to the strrchr builtin.  S1 and S2 are the arguments to
11285    the call, and TYPE is its return type.
11286
11287    Return NULL_TREE if no simplification was possible, otherwise return the
11288    simplified form of the call as a tree.
11289
11290    The simplified form may be a constant or other expression which
11291    computes the same value, but in a more efficient manner (including
11292    calls to other builtin functions).
11293
11294    The call may contain arguments which need to be evaluated, but
11295    which are not useful to determine the result of the call.  In
11296    this case we return a chain of COMPOUND_EXPRs.  The LHS of each
11297    COMPOUND_EXPR will be an argument which must be evaluated.
11298    COMPOUND_EXPRs are chained through their RHS.  The RHS of the last
11299    COMPOUND_EXPR in the chain will contain the tree for the simplified
11300    form of the builtin function call.  */
11301
11302 static tree
11303 fold_builtin_strrchr (location_t loc, tree s1, tree s2, tree type)
11304 {
11305   if (!validate_arg (s1, POINTER_TYPE)
11306       || !validate_arg (s2, INTEGER_TYPE))
11307     return NULL_TREE;
11308   else
11309     {
11310       tree fn;
11311       const char *p1;
11312
11313       if (TREE_CODE (s2) != INTEGER_CST)
11314         return NULL_TREE;
11315
11316       p1 = c_getstr (s1);
11317       if (p1 != NULL)
11318         {
11319           char c;
11320           const char *r;
11321           tree tem;
11322
11323           if (target_char_cast (s2, &c))
11324             return NULL_TREE;
11325
11326           r = strrchr (p1, c);
11327
11328           if (r == NULL)
11329             return build_int_cst (TREE_TYPE (s1), 0);
11330
11331           /* Return an offset into the constant string argument.  */
11332           tem = fold_build2_loc (loc, POINTER_PLUS_EXPR, TREE_TYPE (s1),
11333                              s1, size_int (r - p1));
11334           return fold_convert_loc (loc, type, tem);
11335         }
11336
11337       if (! integer_zerop (s2))
11338         return NULL_TREE;
11339
11340       fn = implicit_built_in_decls[BUILT_IN_STRCHR];
11341       if (!fn)
11342         return NULL_TREE;
11343
11344       /* Transform strrchr(s1, '\0') to strchr(s1, '\0').  */
11345       return build_call_expr_loc (loc, fn, 2, s1, s2);
11346     }
11347 }
11348
11349 /* Simplify a call to the strpbrk builtin.  S1 and S2 are the arguments
11350    to the call, and TYPE is its return type.
11351
11352    Return NULL_TREE if no simplification was possible, otherwise return the
11353    simplified form of the call as a tree.
11354
11355    The simplified form may be a constant or other expression which
11356    computes the same value, but in a more efficient manner (including
11357    calls to other builtin functions).
11358
11359    The call may contain arguments which need to be evaluated, but
11360    which are not useful to determine the result of the call.  In
11361    this case we return a chain of COMPOUND_EXPRs.  The LHS of each
11362    COMPOUND_EXPR will be an argument which must be evaluated.
11363    COMPOUND_EXPRs are chained through their RHS.  The RHS of the last
11364    COMPOUND_EXPR in the chain will contain the tree for the simplified
11365    form of the builtin function call.  */
11366
11367 static tree
11368 fold_builtin_strpbrk (location_t loc, tree s1, tree s2, tree type)
11369 {
11370   if (!validate_arg (s1, POINTER_TYPE)
11371       || !validate_arg (s2, POINTER_TYPE))
11372     return NULL_TREE;
11373   else
11374     {
11375       tree fn;
11376       const char *p1, *p2;
11377
11378       p2 = c_getstr (s2);
11379       if (p2 == NULL)
11380         return NULL_TREE;
11381
11382       p1 = c_getstr (s1);
11383       if (p1 != NULL)
11384         {
11385           const char *r = strpbrk (p1, p2);
11386           tree tem;
11387
11388           if (r == NULL)
11389             return build_int_cst (TREE_TYPE (s1), 0);
11390
11391           /* Return an offset into the constant string argument.  */
11392           tem = fold_build2_loc (loc, POINTER_PLUS_EXPR, TREE_TYPE (s1),
11393                              s1, size_int (r - p1));
11394           return fold_convert_loc (loc, type, tem);
11395         }
11396
11397       if (p2[0] == '\0')
11398         /* strpbrk(x, "") == NULL.
11399            Evaluate and ignore s1 in case it had side-effects.  */
11400         return omit_one_operand_loc (loc, TREE_TYPE (s1), integer_zero_node, s1);
11401
11402       if (p2[1] != '\0')
11403         return NULL_TREE;  /* Really call strpbrk.  */
11404
11405       fn = implicit_built_in_decls[BUILT_IN_STRCHR];
11406       if (!fn)
11407         return NULL_TREE;
11408
11409       /* New argument list transforming strpbrk(s1, s2) to
11410          strchr(s1, s2[0]).  */
11411       return build_call_expr_loc (loc, fn, 2, s1, build_int_cst (NULL_TREE, p2[0]));
11412     }
11413 }
11414
11415 /* Simplify a call to the strcat builtin.  DST and SRC are the arguments
11416    to the call.
11417
11418    Return NULL_TREE if no simplification was possible, otherwise return the
11419    simplified form of the call as a tree.
11420
11421    The simplified form may be a constant or other expression which
11422    computes the same value, but in a more efficient manner (including
11423    calls to other builtin functions).
11424
11425    The call may contain arguments which need to be evaluated, but
11426    which are not useful to determine the result of the call.  In
11427    this case we return a chain of COMPOUND_EXPRs.  The LHS of each
11428    COMPOUND_EXPR will be an argument which must be evaluated.
11429    COMPOUND_EXPRs are chained through their RHS.  The RHS of the last
11430    COMPOUND_EXPR in the chain will contain the tree for the simplified
11431    form of the builtin function call.  */
11432
11433 static tree
11434 fold_builtin_strcat (location_t loc ATTRIBUTE_UNUSED, tree dst, tree src)
11435 {
11436   if (!validate_arg (dst, POINTER_TYPE)
11437       || !validate_arg (src, POINTER_TYPE))
11438     return NULL_TREE;
11439   else
11440     {
11441       const char *p = c_getstr (src);
11442
11443       /* If the string length is zero, return the dst parameter.  */
11444       if (p && *p == '\0')
11445         return dst;
11446
11447       if (optimize_insn_for_speed_p ())
11448         {
11449           /* See if we can store by pieces into (dst + strlen(dst)).  */
11450           tree newdst, call;
11451           tree strlen_fn = implicit_built_in_decls[BUILT_IN_STRLEN];
11452           tree strcpy_fn = implicit_built_in_decls[BUILT_IN_STRCPY];
11453
11454           if (!strlen_fn || !strcpy_fn)
11455             return NULL_TREE;
11456
11457           /* If we don't have a movstr we don't want to emit an strcpy
11458              call.  We have to do that if the length of the source string
11459              isn't computable (in that case we can use memcpy probably
11460              later expanding to a sequence of mov instructions).  If we 
11461              have movstr instructions we can emit strcpy calls.  */
11462           if (!HAVE_movstr)
11463             {
11464               tree len = c_strlen (src, 1);
11465               if (! len || TREE_SIDE_EFFECTS (len))
11466                 return NULL_TREE;
11467             }
11468
11469           /* Stabilize the argument list.  */
11470           dst = builtin_save_expr (dst);
11471
11472           /* Create strlen (dst).  */
11473           newdst = build_call_expr_loc (loc, strlen_fn, 1, dst);
11474           /* Create (dst p+ strlen (dst)).  */
11475
11476           newdst = fold_build2_loc (loc, POINTER_PLUS_EXPR,
11477                                 TREE_TYPE (dst), dst, newdst);
11478           newdst = builtin_save_expr (newdst);
11479
11480           call = build_call_expr_loc (loc, strcpy_fn, 2, newdst, src);
11481           return build2 (COMPOUND_EXPR, TREE_TYPE (dst), call, dst);
11482         }
11483       return NULL_TREE;
11484     }
11485 }
11486
11487 /* Simplify a call to the strncat builtin.  DST, SRC, and LEN are the
11488    arguments to the call.
11489
11490    Return NULL_TREE if no simplification was possible, otherwise return the
11491    simplified form of the call as a tree.
11492
11493    The simplified form may be a constant or other expression which
11494    computes the same value, but in a more efficient manner (including
11495    calls to other builtin functions).
11496
11497    The call may contain arguments which need to be evaluated, but
11498    which are not useful to determine the result of the call.  In
11499    this case we return a chain of COMPOUND_EXPRs.  The LHS of each
11500    COMPOUND_EXPR will be an argument which must be evaluated.
11501    COMPOUND_EXPRs are chained through their RHS.  The RHS of the last
11502    COMPOUND_EXPR in the chain will contain the tree for the simplified
11503    form of the builtin function call.  */
11504
11505 static tree
11506 fold_builtin_strncat (location_t loc, tree dst, tree src, tree len)
11507 {
11508   if (!validate_arg (dst, POINTER_TYPE)
11509       || !validate_arg (src, POINTER_TYPE)
11510       || !validate_arg (len, INTEGER_TYPE))
11511     return NULL_TREE;
11512   else
11513     {
11514       const char *p = c_getstr (src);
11515
11516       /* If the requested length is zero, or the src parameter string
11517          length is zero, return the dst parameter.  */
11518       if (integer_zerop (len) || (p && *p == '\0'))
11519         return omit_two_operands_loc (loc, TREE_TYPE (dst), dst, src, len);
11520
11521       /* If the requested len is greater than or equal to the string
11522          length, call strcat.  */
11523       if (TREE_CODE (len) == INTEGER_CST && p
11524           && compare_tree_int (len, strlen (p)) >= 0)
11525         {
11526           tree fn = implicit_built_in_decls[BUILT_IN_STRCAT];
11527
11528           /* If the replacement _DECL isn't initialized, don't do the
11529              transformation.  */
11530           if (!fn)
11531             return NULL_TREE;
11532
11533           return build_call_expr_loc (loc, fn, 2, dst, src);
11534         }
11535       return NULL_TREE;
11536     }
11537 }
11538
11539 /* Simplify a call to the strspn builtin.  S1 and S2 are the arguments
11540    to the call.
11541
11542    Return NULL_TREE if no simplification was possible, otherwise return the
11543    simplified form of the call as a tree.
11544
11545    The simplified form may be a constant or other expression which
11546    computes the same value, but in a more efficient manner (including
11547    calls to other builtin functions).
11548
11549    The call may contain arguments which need to be evaluated, but
11550    which are not useful to determine the result of the call.  In
11551    this case we return a chain of COMPOUND_EXPRs.  The LHS of each
11552    COMPOUND_EXPR will be an argument which must be evaluated.
11553    COMPOUND_EXPRs are chained through their RHS.  The RHS of the last
11554    COMPOUND_EXPR in the chain will contain the tree for the simplified
11555    form of the builtin function call.  */
11556
11557 static tree
11558 fold_builtin_strspn (location_t loc, tree s1, tree s2)
11559 {
11560   if (!validate_arg (s1, POINTER_TYPE)
11561       || !validate_arg (s2, POINTER_TYPE))
11562     return NULL_TREE;
11563   else
11564     {
11565       const char *p1 = c_getstr (s1), *p2 = c_getstr (s2);
11566
11567       /* If both arguments are constants, evaluate at compile-time.  */
11568       if (p1 && p2)
11569         {
11570           const size_t r = strspn (p1, p2);
11571           return size_int (r);
11572         }
11573
11574       /* If either argument is "", return NULL_TREE.  */
11575       if ((p1 && *p1 == '\0') || (p2 && *p2 == '\0'))
11576         /* Evaluate and ignore both arguments in case either one has
11577            side-effects.  */
11578         return omit_two_operands_loc (loc, size_type_node, size_zero_node,
11579                                   s1, s2);
11580       return NULL_TREE;
11581     }
11582 }
11583
11584 /* Simplify a call to the strcspn builtin.  S1 and S2 are the arguments
11585    to the call.
11586
11587    Return NULL_TREE if no simplification was possible, otherwise return the
11588    simplified form of the call as a tree.
11589
11590    The simplified form may be a constant or other expression which
11591    computes the same value, but in a more efficient manner (including
11592    calls to other builtin functions).
11593
11594    The call may contain arguments which need to be evaluated, but
11595    which are not useful to determine the result of the call.  In
11596    this case we return a chain of COMPOUND_EXPRs.  The LHS of each
11597    COMPOUND_EXPR will be an argument which must be evaluated.
11598    COMPOUND_EXPRs are chained through their RHS.  The RHS of the last
11599    COMPOUND_EXPR in the chain will contain the tree for the simplified
11600    form of the builtin function call.  */
11601
11602 static tree
11603 fold_builtin_strcspn (location_t loc, tree s1, tree s2)
11604 {
11605   if (!validate_arg (s1, POINTER_TYPE)
11606       || !validate_arg (s2, POINTER_TYPE))
11607     return NULL_TREE;
11608   else
11609     {
11610       const char *p1 = c_getstr (s1), *p2 = c_getstr (s2);
11611
11612       /* If both arguments are constants, evaluate at compile-time.  */
11613       if (p1 && p2)
11614         {
11615           const size_t r = strcspn (p1, p2);
11616           return size_int (r);
11617         }
11618
11619       /* If the first argument is "", return NULL_TREE.  */
11620       if (p1 && *p1 == '\0')
11621         {
11622           /* Evaluate and ignore argument s2 in case it has
11623              side-effects.  */
11624           return omit_one_operand_loc (loc, size_type_node,
11625                                    size_zero_node, s2);
11626         }
11627
11628       /* If the second argument is "", return __builtin_strlen(s1).  */
11629       if (p2 && *p2 == '\0')
11630         {
11631           tree fn = implicit_built_in_decls[BUILT_IN_STRLEN];
11632
11633           /* If the replacement _DECL isn't initialized, don't do the
11634              transformation.  */
11635           if (!fn)
11636             return NULL_TREE;
11637
11638           return build_call_expr_loc (loc, fn, 1, s1);
11639         }
11640       return NULL_TREE;
11641     }
11642 }
11643
11644 /* Fold a call to the fputs builtin.  ARG0 and ARG1 are the arguments
11645    to the call.  IGNORE is true if the value returned
11646    by the builtin will be ignored.  UNLOCKED is true is true if this
11647    actually a call to fputs_unlocked.  If LEN in non-NULL, it represents
11648    the known length of the string.  Return NULL_TREE if no simplification
11649    was possible.  */
11650
11651 tree
11652 fold_builtin_fputs (location_t loc, tree arg0, tree arg1,
11653                     bool ignore, bool unlocked, tree len)
11654 {
11655   /* If we're using an unlocked function, assume the other unlocked
11656      functions exist explicitly.  */
11657   tree const fn_fputc = unlocked ? built_in_decls[BUILT_IN_FPUTC_UNLOCKED]
11658     : implicit_built_in_decls[BUILT_IN_FPUTC];
11659   tree const fn_fwrite = unlocked ? built_in_decls[BUILT_IN_FWRITE_UNLOCKED]
11660     : implicit_built_in_decls[BUILT_IN_FWRITE];
11661
11662   /* If the return value is used, don't do the transformation.  */
11663   if (!ignore)
11664     return NULL_TREE;
11665
11666   /* Verify the arguments in the original call.  */
11667   if (!validate_arg (arg0, POINTER_TYPE)
11668       || !validate_arg (arg1, POINTER_TYPE))
11669     return NULL_TREE;
11670
11671   if (! len)
11672     len = c_strlen (arg0, 0);
11673
11674   /* Get the length of the string passed to fputs.  If the length
11675      can't be determined, punt.  */
11676   if (!len
11677       || TREE_CODE (len) != INTEGER_CST)
11678     return NULL_TREE;
11679
11680   switch (compare_tree_int (len, 1))
11681     {
11682     case -1: /* length is 0, delete the call entirely .  */
11683       return omit_one_operand_loc (loc, integer_type_node,
11684                                integer_zero_node, arg1);;
11685
11686     case 0: /* length is 1, call fputc.  */
11687       {
11688         const char *p = c_getstr (arg0);
11689
11690         if (p != NULL)
11691           {
11692             if (fn_fputc)
11693               return build_call_expr_loc (loc, fn_fputc, 2,
11694                                       build_int_cst (NULL_TREE, p[0]), arg1);
11695             else
11696               return NULL_TREE;
11697           }
11698       }
11699       /* FALLTHROUGH */
11700     case 1: /* length is greater than 1, call fwrite.  */
11701       {
11702         /* If optimizing for size keep fputs.  */
11703         if (optimize_function_for_size_p (cfun))
11704           return NULL_TREE;
11705         /* New argument list transforming fputs(string, stream) to
11706            fwrite(string, 1, len, stream).  */
11707         if (fn_fwrite)
11708           return build_call_expr_loc (loc, fn_fwrite, 4, arg0,
11709                                   size_one_node, len, arg1);
11710         else
11711           return NULL_TREE;
11712       }
11713     default:
11714       gcc_unreachable ();
11715     }
11716   return NULL_TREE;
11717 }
11718
11719 /* Fold the next_arg or va_start call EXP. Returns true if there was an error
11720    produced.  False otherwise.  This is done so that we don't output the error
11721    or warning twice or three times.  */
11722
11723 bool
11724 fold_builtin_next_arg (tree exp, bool va_start_p)
11725 {
11726   tree fntype = TREE_TYPE (current_function_decl);
11727   int nargs = call_expr_nargs (exp);
11728   tree arg;
11729
11730   if (TYPE_ARG_TYPES (fntype) == 0
11731       || (TREE_VALUE (tree_last (TYPE_ARG_TYPES (fntype)))
11732           == void_type_node))
11733     {
11734       error ("%<va_start%> used in function with fixed args");
11735       return true;
11736     }
11737
11738   if (va_start_p)
11739     {
11740       if (va_start_p && (nargs != 2))
11741         {
11742           error ("wrong number of arguments to function %<va_start%>");
11743           return true;
11744         }
11745       arg = CALL_EXPR_ARG (exp, 1);
11746     }
11747   /* We use __builtin_va_start (ap, 0, 0) or __builtin_next_arg (0, 0)
11748      when we checked the arguments and if needed issued a warning.  */
11749   else
11750     {
11751       if (nargs == 0)
11752         {
11753           /* Evidently an out of date version of <stdarg.h>; can't validate
11754              va_start's second argument, but can still work as intended.  */
11755           warning (0, "%<__builtin_next_arg%> called without an argument");
11756           return true;
11757         }
11758       else if (nargs > 1)
11759         {
11760           error ("wrong number of arguments to function %<__builtin_next_arg%>");
11761           return true;
11762         }
11763       arg = CALL_EXPR_ARG (exp, 0);
11764     }
11765
11766   if (TREE_CODE (arg) == SSA_NAME)
11767     arg = SSA_NAME_VAR (arg);
11768
11769   /* We destructively modify the call to be __builtin_va_start (ap, 0)
11770      or __builtin_next_arg (0) the first time we see it, after checking 
11771      the arguments and if needed issuing a warning.  */
11772   if (!integer_zerop (arg))
11773     {
11774       tree last_parm = tree_last (DECL_ARGUMENTS (current_function_decl));
11775
11776       /* Strip off all nops for the sake of the comparison.  This
11777          is not quite the same as STRIP_NOPS.  It does more.
11778          We must also strip off INDIRECT_EXPR for C++ reference
11779          parameters.  */
11780       while (CONVERT_EXPR_P (arg)
11781              || TREE_CODE (arg) == INDIRECT_REF)
11782         arg = TREE_OPERAND (arg, 0);
11783       if (arg != last_parm)
11784         {
11785           /* FIXME: Sometimes with the tree optimizers we can get the
11786              not the last argument even though the user used the last
11787              argument.  We just warn and set the arg to be the last
11788              argument so that we will get wrong-code because of
11789              it.  */
11790           warning (0, "second parameter of %<va_start%> not last named argument");
11791         }
11792
11793       /* Undefined by C99 7.15.1.4p4 (va_start):
11794          "If the parameter parmN is declared with the register storage
11795          class, with a function or array type, or with a type that is
11796          not compatible with the type that results after application of
11797          the default argument promotions, the behavior is undefined."
11798       */
11799       else if (DECL_REGISTER (arg))
11800         warning (0, "undefined behaviour when second parameter of "
11801                  "%<va_start%> is declared with %<register%> storage");
11802
11803       /* We want to verify the second parameter just once before the tree
11804          optimizers are run and then avoid keeping it in the tree,
11805          as otherwise we could warn even for correct code like:
11806          void foo (int i, ...)
11807          { va_list ap; i++; va_start (ap, i); va_end (ap); }  */
11808       if (va_start_p)
11809         CALL_EXPR_ARG (exp, 1) = integer_zero_node;
11810       else
11811         CALL_EXPR_ARG (exp, 0) = integer_zero_node;
11812     }
11813   return false;
11814 }
11815
11816
11817 /* Simplify a call to the sprintf builtin with arguments DEST, FMT, and ORIG.
11818    ORIG may be null if this is a 2-argument call.  We don't attempt to
11819    simplify calls with more than 3 arguments.
11820
11821    Return NULL_TREE if no simplification was possible, otherwise return the
11822    simplified form of the call as a tree.  If IGNORED is true, it means that
11823    the caller does not use the returned value of the function.  */
11824
11825 static tree
11826 fold_builtin_sprintf (location_t loc, tree dest, tree fmt,
11827                       tree orig, int ignored)
11828 {
11829   tree call, retval;
11830   const char *fmt_str = NULL;
11831
11832   /* Verify the required arguments in the original call.  We deal with two
11833      types of sprintf() calls: 'sprintf (str, fmt)' and
11834      'sprintf (dest, "%s", orig)'.  */
11835   if (!validate_arg (dest, POINTER_TYPE)
11836       || !validate_arg (fmt, POINTER_TYPE))
11837     return NULL_TREE;
11838   if (orig && !validate_arg (orig, POINTER_TYPE))
11839     return NULL_TREE;
11840
11841   /* Check whether the format is a literal string constant.  */
11842   fmt_str = c_getstr (fmt);
11843   if (fmt_str == NULL)
11844     return NULL_TREE;
11845
11846   call = NULL_TREE;
11847   retval = NULL_TREE;
11848
11849   if (!init_target_chars ())
11850     return NULL_TREE;
11851
11852   /* If the format doesn't contain % args or %%, use strcpy.  */
11853   if (strchr (fmt_str, target_percent) == NULL)
11854     {
11855       tree fn = implicit_built_in_decls[BUILT_IN_STRCPY];
11856
11857       if (!fn)
11858         return NULL_TREE;
11859
11860       /* Don't optimize sprintf (buf, "abc", ptr++).  */
11861       if (orig)
11862         return NULL_TREE;
11863
11864       /* Convert sprintf (str, fmt) into strcpy (str, fmt) when
11865          'format' is known to contain no % formats.  */
11866       call = build_call_expr_loc (loc, fn, 2, dest, fmt);
11867       if (!ignored)
11868         retval = build_int_cst (NULL_TREE, strlen (fmt_str));
11869     }
11870
11871   /* If the format is "%s", use strcpy if the result isn't used.  */
11872   else if (fmt_str && strcmp (fmt_str, target_percent_s) == 0)
11873     {
11874       tree fn;
11875       fn = implicit_built_in_decls[BUILT_IN_STRCPY];
11876
11877       if (!fn)
11878         return NULL_TREE;
11879
11880       /* Don't crash on sprintf (str1, "%s").  */
11881       if (!orig)
11882         return NULL_TREE;
11883
11884       /* Convert sprintf (str1, "%s", str2) into strcpy (str1, str2).  */
11885       if (!ignored)
11886         {
11887           retval = c_strlen (orig, 1);
11888           if (!retval || TREE_CODE (retval) != INTEGER_CST)
11889             return NULL_TREE;
11890         }
11891       call = build_call_expr_loc (loc, fn, 2, dest, orig);
11892     }
11893
11894   if (call && retval)
11895     {
11896       retval = fold_convert_loc
11897         (loc, TREE_TYPE (TREE_TYPE (implicit_built_in_decls[BUILT_IN_SPRINTF])),
11898          retval);
11899       return build2 (COMPOUND_EXPR, TREE_TYPE (retval), call, retval);
11900     }
11901   else
11902     return call;
11903 }
11904
11905 /* Expand a call EXP to __builtin_object_size.  */
11906
11907 rtx
11908 expand_builtin_object_size (tree exp)
11909 {
11910   tree ost;
11911   int object_size_type;
11912   tree fndecl = get_callee_fndecl (exp);
11913
11914   if (!validate_arglist (exp, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
11915     {
11916       error ("%Kfirst argument of %D must be a pointer, second integer constant",
11917              exp, fndecl);
11918       expand_builtin_trap ();
11919       return const0_rtx;
11920     }
11921
11922   ost = CALL_EXPR_ARG (exp, 1);
11923   STRIP_NOPS (ost);
11924
11925   if (TREE_CODE (ost) != INTEGER_CST
11926       || tree_int_cst_sgn (ost) < 0
11927       || compare_tree_int (ost, 3) > 0)
11928     {
11929       error ("%Klast argument of %D is not integer constant between 0 and 3",
11930              exp, fndecl);
11931       expand_builtin_trap ();
11932       return const0_rtx;
11933     }
11934
11935   object_size_type = tree_low_cst (ost, 0);
11936
11937   return object_size_type < 2 ? constm1_rtx : const0_rtx;
11938 }
11939
11940 /* Expand EXP, a call to the __mem{cpy,pcpy,move,set}_chk builtin.
11941    FCODE is the BUILT_IN_* to use.
11942    Return NULL_RTX if we failed; the caller should emit a normal call,
11943    otherwise try to get the result in TARGET, if convenient (and in
11944    mode MODE if that's convenient).  */
11945
11946 static rtx
11947 expand_builtin_memory_chk (tree exp, rtx target, enum machine_mode mode,
11948                            enum built_in_function fcode)
11949 {
11950   tree dest, src, len, size;
11951
11952   if (!validate_arglist (exp,
11953                          POINTER_TYPE,
11954                          fcode == BUILT_IN_MEMSET_CHK
11955                          ? INTEGER_TYPE : POINTER_TYPE,
11956                          INTEGER_TYPE, INTEGER_TYPE, VOID_TYPE))
11957     return NULL_RTX;
11958
11959   dest = CALL_EXPR_ARG (exp, 0);
11960   src = CALL_EXPR_ARG (exp, 1);
11961   len = CALL_EXPR_ARG (exp, 2);
11962   size = CALL_EXPR_ARG (exp, 3);
11963
11964   if (! host_integerp (size, 1))
11965     return NULL_RTX;
11966
11967   if (host_integerp (len, 1) || integer_all_onesp (size))
11968     {
11969       tree fn;
11970
11971       if (! integer_all_onesp (size) && tree_int_cst_lt (size, len))
11972         {
11973           warning_at (tree_nonartificial_location (exp),
11974                       0, "%Kcall to %D will always overflow destination buffer",
11975                       exp, get_callee_fndecl (exp));
11976           return NULL_RTX;
11977         }
11978
11979       fn = NULL_TREE;
11980       /* If __builtin_mem{cpy,pcpy,move,set}_chk is used, assume
11981          mem{cpy,pcpy,move,set} is available.  */
11982       switch (fcode)
11983         {
11984         case BUILT_IN_MEMCPY_CHK:
11985           fn = built_in_decls[BUILT_IN_MEMCPY];
11986           break;
11987         case BUILT_IN_MEMPCPY_CHK:
11988           fn = built_in_decls[BUILT_IN_MEMPCPY];
11989           break;
11990         case BUILT_IN_MEMMOVE_CHK:
11991           fn = built_in_decls[BUILT_IN_MEMMOVE];
11992           break;
11993         case BUILT_IN_MEMSET_CHK:
11994           fn = built_in_decls[BUILT_IN_MEMSET];
11995           break;
11996         default:
11997           break;
11998         }
11999
12000       if (! fn)
12001         return NULL_RTX;
12002
12003       fn = build_call_nofold (fn, 3, dest, src, len);
12004       gcc_assert (TREE_CODE (fn) == CALL_EXPR);
12005       CALL_EXPR_TAILCALL (fn) = CALL_EXPR_TAILCALL (exp);
12006       return expand_expr (fn, target, mode, EXPAND_NORMAL);
12007     }
12008   else if (fcode == BUILT_IN_MEMSET_CHK)
12009     return NULL_RTX;
12010   else
12011     {
12012       unsigned int dest_align
12013         = get_pointer_alignment (dest, BIGGEST_ALIGNMENT);
12014
12015       /* If DEST is not a pointer type, call the normal function.  */
12016       if (dest_align == 0)
12017         return NULL_RTX;
12018
12019       /* If SRC and DEST are the same (and not volatile), do nothing.  */
12020       if (operand_equal_p (src, dest, 0))
12021         {
12022           tree expr;
12023
12024           if (fcode != BUILT_IN_MEMPCPY_CHK)
12025             {
12026               /* Evaluate and ignore LEN in case it has side-effects.  */
12027               expand_expr (len, const0_rtx, VOIDmode, EXPAND_NORMAL);
12028               return expand_expr (dest, target, mode, EXPAND_NORMAL);
12029             }
12030
12031           expr = fold_build2 (POINTER_PLUS_EXPR, TREE_TYPE (dest), dest, len);
12032           return expand_expr (expr, target, mode, EXPAND_NORMAL);
12033         }
12034
12035       /* __memmove_chk special case.  */
12036       if (fcode == BUILT_IN_MEMMOVE_CHK)
12037         {
12038           unsigned int src_align
12039             = get_pointer_alignment (src, BIGGEST_ALIGNMENT);
12040
12041           if (src_align == 0)
12042             return NULL_RTX;
12043
12044           /* If src is categorized for a readonly section we can use
12045              normal __memcpy_chk.  */
12046           if (readonly_data_expr (src))
12047             {
12048               tree fn = built_in_decls[BUILT_IN_MEMCPY_CHK];
12049               if (!fn)
12050                 return NULL_RTX;
12051               fn = build_call_nofold (fn, 4, dest, src, len, size);
12052               gcc_assert (TREE_CODE (fn) == CALL_EXPR);
12053               CALL_EXPR_TAILCALL (fn) = CALL_EXPR_TAILCALL (exp);
12054               return expand_expr (fn, target, mode, EXPAND_NORMAL);
12055             }
12056         }
12057       return NULL_RTX;
12058     }
12059 }
12060
12061 /* Emit warning if a buffer overflow is detected at compile time.  */
12062
12063 static void
12064 maybe_emit_chk_warning (tree exp, enum built_in_function fcode)
12065 {
12066   int is_strlen = 0;
12067   tree len, size;
12068   location_t loc = tree_nonartificial_location (exp);
12069
12070   switch (fcode)
12071     {
12072     case BUILT_IN_STRCPY_CHK:
12073     case BUILT_IN_STPCPY_CHK:
12074     /* For __strcat_chk the warning will be emitted only if overflowing
12075        by at least strlen (dest) + 1 bytes.  */
12076     case BUILT_IN_STRCAT_CHK:
12077       len = CALL_EXPR_ARG (exp, 1);
12078       size = CALL_EXPR_ARG (exp, 2);
12079       is_strlen = 1;
12080       break;
12081     case BUILT_IN_STRNCAT_CHK:
12082     case BUILT_IN_STRNCPY_CHK:
12083       len = CALL_EXPR_ARG (exp, 2);
12084       size = CALL_EXPR_ARG (exp, 3);
12085       break;
12086     case BUILT_IN_SNPRINTF_CHK:
12087     case BUILT_IN_VSNPRINTF_CHK:
12088       len = CALL_EXPR_ARG (exp, 1);
12089       size = CALL_EXPR_ARG (exp, 3);
12090       break;
12091     default:
12092       gcc_unreachable ();
12093     }
12094
12095   if (!len || !size)
12096     return;
12097
12098   if (! host_integerp (size, 1) || integer_all_onesp (size))
12099     return;
12100
12101   if (is_strlen)
12102     {
12103       len = c_strlen (len, 1);
12104       if (! len || ! host_integerp (len, 1) || tree_int_cst_lt (len, size))
12105         return;
12106     }
12107   else if (fcode == BUILT_IN_STRNCAT_CHK)
12108     {
12109       tree src = CALL_EXPR_ARG (exp, 1);
12110       if (! src || ! host_integerp (len, 1) || tree_int_cst_lt (len, size))
12111         return;
12112       src = c_strlen (src, 1);
12113       if (! src || ! host_integerp (src, 1))
12114         {
12115           warning_at (loc, 0, "%Kcall to %D might overflow destination buffer",
12116                       exp, get_callee_fndecl (exp));
12117           return;
12118         }
12119       else if (tree_int_cst_lt (src, size))
12120         return;
12121     }
12122   else if (! host_integerp (len, 1) || ! tree_int_cst_lt (size, len))
12123     return;
12124
12125   warning_at (loc, 0, "%Kcall to %D will always overflow destination buffer",
12126               exp, get_callee_fndecl (exp));
12127 }
12128
12129 /* Emit warning if a buffer overflow is detected at compile time
12130    in __sprintf_chk/__vsprintf_chk calls.  */
12131
12132 static void
12133 maybe_emit_sprintf_chk_warning (tree exp, enum built_in_function fcode)
12134 {
12135   tree size, len, fmt;
12136   const char *fmt_str;
12137   int nargs = call_expr_nargs (exp);
12138
12139   /* Verify the required arguments in the original call.  */
12140   
12141   if (nargs < 4)
12142     return;
12143   size = CALL_EXPR_ARG (exp, 2);
12144   fmt = CALL_EXPR_ARG (exp, 3);
12145
12146   if (! host_integerp (size, 1) || integer_all_onesp (size))
12147     return;
12148
12149   /* Check whether the format is a literal string constant.  */
12150   fmt_str = c_getstr (fmt);
12151   if (fmt_str == NULL)
12152     return;
12153
12154   if (!init_target_chars ())
12155     return;
12156
12157   /* If the format doesn't contain % args or %%, we know its size.  */
12158   if (strchr (fmt_str, target_percent) == 0)
12159     len = build_int_cstu (size_type_node, strlen (fmt_str));
12160   /* If the format is "%s" and first ... argument is a string literal,
12161      we know it too.  */
12162   else if (fcode == BUILT_IN_SPRINTF_CHK
12163            && strcmp (fmt_str, target_percent_s) == 0)
12164     {
12165       tree arg;
12166
12167       if (nargs < 5)
12168         return;
12169       arg = CALL_EXPR_ARG (exp, 4);
12170       if (! POINTER_TYPE_P (TREE_TYPE (arg)))
12171         return;
12172
12173       len = c_strlen (arg, 1);
12174       if (!len || ! host_integerp (len, 1))
12175         return;
12176     }
12177   else
12178     return;
12179
12180   if (! tree_int_cst_lt (len, size))
12181     warning_at (tree_nonartificial_location (exp),
12182                 0, "%Kcall to %D will always overflow destination buffer",
12183                 exp, get_callee_fndecl (exp));
12184 }
12185
12186 /* Emit warning if a free is called with address of a variable.  */
12187
12188 static void
12189 maybe_emit_free_warning (tree exp)
12190 {
12191   tree arg = CALL_EXPR_ARG (exp, 0);
12192
12193   STRIP_NOPS (arg);
12194   if (TREE_CODE (arg) != ADDR_EXPR)
12195     return;
12196
12197   arg = get_base_address (TREE_OPERAND (arg, 0));
12198   if (arg == NULL || INDIRECT_REF_P (arg))
12199     return;
12200
12201   if (SSA_VAR_P (arg))
12202     warning_at (tree_nonartificial_location (exp),
12203                 0, "%Kattempt to free a non-heap object %qD", exp, arg);
12204   else
12205     warning_at (tree_nonartificial_location (exp),
12206                 0, "%Kattempt to free a non-heap object", exp);
12207 }
12208
12209 /* Fold a call to __builtin_object_size with arguments PTR and OST,
12210    if possible.  */
12211
12212 tree
12213 fold_builtin_object_size (tree ptr, tree ost)
12214 {
12215   tree ret = NULL_TREE;
12216   int object_size_type;
12217
12218   if (!validate_arg (ptr, POINTER_TYPE)
12219       || !validate_arg (ost, INTEGER_TYPE))
12220     return NULL_TREE;
12221
12222   STRIP_NOPS (ost);
12223
12224   if (TREE_CODE (ost) != INTEGER_CST
12225       || tree_int_cst_sgn (ost) < 0
12226       || compare_tree_int (ost, 3) > 0)
12227     return NULL_TREE;
12228
12229   object_size_type = tree_low_cst (ost, 0);
12230
12231   /* __builtin_object_size doesn't evaluate side-effects in its arguments;
12232      if there are any side-effects, it returns (size_t) -1 for types 0 and 1
12233      and (size_t) 0 for types 2 and 3.  */
12234   if (TREE_SIDE_EFFECTS (ptr))
12235     return build_int_cst_type (size_type_node, object_size_type < 2 ? -1 : 0);
12236
12237   if (TREE_CODE (ptr) == ADDR_EXPR)
12238     ret = build_int_cstu (size_type_node,
12239                           compute_builtin_object_size (ptr, object_size_type));
12240
12241   else if (TREE_CODE (ptr) == SSA_NAME)
12242     {
12243       unsigned HOST_WIDE_INT bytes;
12244
12245       /* If object size is not known yet, delay folding until
12246        later.  Maybe subsequent passes will help determining
12247        it.  */
12248       bytes = compute_builtin_object_size (ptr, object_size_type);
12249       if (bytes != (unsigned HOST_WIDE_INT) (object_size_type < 2
12250                                              ? -1 : 0))
12251         ret = build_int_cstu (size_type_node, bytes);
12252     }
12253
12254   if (ret)
12255     {
12256       unsigned HOST_WIDE_INT low = TREE_INT_CST_LOW (ret);
12257       HOST_WIDE_INT high = TREE_INT_CST_HIGH (ret);
12258       if (fit_double_type (low, high, &low, &high, TREE_TYPE (ret)))
12259         ret = NULL_TREE;
12260     }
12261
12262   return ret;
12263 }
12264
12265 /* Fold a call to the __mem{cpy,pcpy,move,set}_chk builtin.
12266    DEST, SRC, LEN, and SIZE are the arguments to the call.
12267    IGNORE is true, if return value can be ignored.  FCODE is the BUILT_IN_*
12268    code of the builtin.  If MAXLEN is not NULL, it is maximum length
12269    passed as third argument.  */
12270
12271 tree
12272 fold_builtin_memory_chk (location_t loc, tree fndecl,
12273                          tree dest, tree src, tree len, tree size,
12274                          tree maxlen, bool ignore,
12275                          enum built_in_function fcode)
12276 {
12277   tree fn;
12278
12279   if (!validate_arg (dest, POINTER_TYPE)
12280       || !validate_arg (src,
12281                         (fcode == BUILT_IN_MEMSET_CHK
12282                          ? INTEGER_TYPE : POINTER_TYPE))
12283       || !validate_arg (len, INTEGER_TYPE)
12284       || !validate_arg (size, INTEGER_TYPE))
12285     return NULL_TREE;
12286
12287   /* If SRC and DEST are the same (and not volatile), return DEST
12288      (resp. DEST+LEN for __mempcpy_chk).  */
12289   if (fcode != BUILT_IN_MEMSET_CHK && operand_equal_p (src, dest, 0))
12290     {
12291       if (fcode != BUILT_IN_MEMPCPY_CHK)
12292         return omit_one_operand_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)),
12293                                  dest, len);
12294       else
12295         {
12296           tree temp = fold_build2_loc (loc, POINTER_PLUS_EXPR, TREE_TYPE (dest),
12297                                    dest, len);
12298           return fold_convert_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)), temp);
12299         }
12300     }
12301
12302   if (! host_integerp (size, 1))
12303     return NULL_TREE;
12304
12305   if (! integer_all_onesp (size))
12306     {
12307       if (! host_integerp (len, 1))
12308         {
12309           /* If LEN is not constant, try MAXLEN too.
12310              For MAXLEN only allow optimizing into non-_ocs function
12311              if SIZE is >= MAXLEN, never convert to __ocs_fail ().  */
12312           if (maxlen == NULL_TREE || ! host_integerp (maxlen, 1))
12313             {
12314               if (fcode == BUILT_IN_MEMPCPY_CHK && ignore)
12315                 {
12316                   /* (void) __mempcpy_chk () can be optimized into
12317                      (void) __memcpy_chk ().  */
12318                   fn = built_in_decls[BUILT_IN_MEMCPY_CHK];
12319                   if (!fn)
12320                     return NULL_TREE;
12321
12322                   return build_call_expr_loc (loc, fn, 4, dest, src, len, size);
12323                 }
12324               return NULL_TREE;
12325             }
12326         }
12327       else
12328         maxlen = len;
12329
12330       if (tree_int_cst_lt (size, maxlen))
12331         return NULL_TREE;
12332     }
12333
12334   fn = NULL_TREE;
12335   /* If __builtin_mem{cpy,pcpy,move,set}_chk is used, assume
12336      mem{cpy,pcpy,move,set} is available.  */
12337   switch (fcode)
12338     {
12339     case BUILT_IN_MEMCPY_CHK:
12340       fn = built_in_decls[BUILT_IN_MEMCPY];
12341       break;
12342     case BUILT_IN_MEMPCPY_CHK:
12343       fn = built_in_decls[BUILT_IN_MEMPCPY];
12344       break;
12345     case BUILT_IN_MEMMOVE_CHK:
12346       fn = built_in_decls[BUILT_IN_MEMMOVE];
12347       break;
12348     case BUILT_IN_MEMSET_CHK:
12349       fn = built_in_decls[BUILT_IN_MEMSET];
12350       break;
12351     default:
12352       break;
12353     }
12354
12355   if (!fn)
12356     return NULL_TREE;
12357
12358   return build_call_expr_loc (loc, fn, 3, dest, src, len);
12359 }
12360
12361 /* Fold a call to the __st[rp]cpy_chk builtin.
12362    DEST, SRC, and SIZE are the arguments to the call.
12363    IGNORE is true if return value can be ignored.  FCODE is the BUILT_IN_*
12364    code of the builtin.  If MAXLEN is not NULL, it is maximum length of
12365    strings passed as second argument.  */
12366
12367 tree
12368 fold_builtin_stxcpy_chk (location_t loc, tree fndecl, tree dest,
12369                          tree src, tree size,
12370                          tree maxlen, bool ignore,
12371                          enum built_in_function fcode)
12372 {
12373   tree len, fn;
12374
12375   if (!validate_arg (dest, POINTER_TYPE)
12376       || !validate_arg (src, POINTER_TYPE)
12377       || !validate_arg (size, INTEGER_TYPE))
12378     return NULL_TREE;
12379
12380   /* If SRC and DEST are the same (and not volatile), return DEST.  */
12381   if (fcode == BUILT_IN_STRCPY_CHK && operand_equal_p (src, dest, 0))
12382     return fold_convert_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)), dest);
12383
12384   if (! host_integerp (size, 1))
12385     return NULL_TREE;
12386
12387   if (! integer_all_onesp (size))
12388     {
12389       len = c_strlen (src, 1);
12390       if (! len || ! host_integerp (len, 1))
12391         {
12392           /* If LEN is not constant, try MAXLEN too.
12393              For MAXLEN only allow optimizing into non-_ocs function
12394              if SIZE is >= MAXLEN, never convert to __ocs_fail ().  */
12395           if (maxlen == NULL_TREE || ! host_integerp (maxlen, 1))
12396             {
12397               if (fcode == BUILT_IN_STPCPY_CHK)
12398                 {
12399                   if (! ignore)
12400                     return NULL_TREE;
12401
12402                   /* If return value of __stpcpy_chk is ignored,
12403                      optimize into __strcpy_chk.  */
12404                   fn = built_in_decls[BUILT_IN_STRCPY_CHK];
12405                   if (!fn)
12406                     return NULL_TREE;
12407
12408                   return build_call_expr_loc (loc, fn, 3, dest, src, size);
12409                 }
12410
12411               if (! len || TREE_SIDE_EFFECTS (len))
12412                 return NULL_TREE;
12413
12414               /* If c_strlen returned something, but not a constant,
12415                  transform __strcpy_chk into __memcpy_chk.  */
12416               fn = built_in_decls[BUILT_IN_MEMCPY_CHK];
12417               if (!fn)
12418                 return NULL_TREE;
12419
12420               len = size_binop_loc (loc, PLUS_EXPR, len, ssize_int (1));
12421               return fold_convert_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)),
12422                                        build_call_expr_loc (loc, fn, 4,
12423                                                         dest, src, len, size));
12424             }
12425         }
12426       else
12427         maxlen = len;
12428
12429       if (! tree_int_cst_lt (maxlen, size))
12430         return NULL_TREE;
12431     }
12432
12433   /* If __builtin_st{r,p}cpy_chk is used, assume st{r,p}cpy is available.  */
12434   fn = built_in_decls[fcode == BUILT_IN_STPCPY_CHK
12435                       ? BUILT_IN_STPCPY : BUILT_IN_STRCPY];
12436   if (!fn)
12437     return NULL_TREE;
12438
12439   return build_call_expr_loc (loc, fn, 2, dest, src);
12440 }
12441
12442 /* Fold a call to the __strncpy_chk builtin.  DEST, SRC, LEN, and SIZE
12443    are the arguments to the call.  If MAXLEN is not NULL, it is maximum
12444    length passed as third argument.  */
12445
12446 tree
12447 fold_builtin_strncpy_chk (location_t loc, tree dest, tree src,
12448                           tree len, tree size, tree maxlen)
12449 {
12450   tree fn;
12451
12452   if (!validate_arg (dest, POINTER_TYPE)
12453       || !validate_arg (src, POINTER_TYPE)
12454       || !validate_arg (len, INTEGER_TYPE)
12455       || !validate_arg (size, INTEGER_TYPE))
12456     return NULL_TREE;
12457
12458   if (! host_integerp (size, 1))
12459     return NULL_TREE;
12460
12461   if (! integer_all_onesp (size))
12462     {
12463       if (! host_integerp (len, 1))
12464         {
12465           /* If LEN is not constant, try MAXLEN too.
12466              For MAXLEN only allow optimizing into non-_ocs function
12467              if SIZE is >= MAXLEN, never convert to __ocs_fail ().  */
12468           if (maxlen == NULL_TREE || ! host_integerp (maxlen, 1))
12469             return NULL_TREE;
12470         }
12471       else
12472         maxlen = len;
12473
12474       if (tree_int_cst_lt (size, maxlen))
12475         return NULL_TREE;
12476     }
12477
12478   /* If __builtin_strncpy_chk is used, assume strncpy is available.  */
12479   fn = built_in_decls[BUILT_IN_STRNCPY];
12480   if (!fn)
12481     return NULL_TREE;
12482
12483   return build_call_expr_loc (loc, fn, 3, dest, src, len);
12484 }
12485
12486 /* Fold a call to the __strcat_chk builtin FNDECL.  DEST, SRC, and SIZE
12487    are the arguments to the call.  */
12488
12489 static tree
12490 fold_builtin_strcat_chk (location_t loc, tree fndecl, tree dest,
12491                          tree src, tree size)
12492 {
12493   tree fn;
12494   const char *p;
12495
12496   if (!validate_arg (dest, POINTER_TYPE)
12497       || !validate_arg (src, POINTER_TYPE)
12498       || !validate_arg (size, INTEGER_TYPE))
12499     return NULL_TREE;
12500
12501   p = c_getstr (src);
12502   /* If the SRC parameter is "", return DEST.  */
12503   if (p && *p == '\0')
12504     return omit_one_operand_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)), dest, src);
12505
12506   if (! host_integerp (size, 1) || ! integer_all_onesp (size))
12507     return NULL_TREE;
12508
12509   /* If __builtin_strcat_chk is used, assume strcat is available.  */
12510   fn = built_in_decls[BUILT_IN_STRCAT];
12511   if (!fn)
12512     return NULL_TREE;
12513
12514   return build_call_expr_loc (loc, fn, 2, dest, src);
12515 }
12516
12517 /* Fold a call to the __strncat_chk builtin with arguments DEST, SRC,
12518    LEN, and SIZE.  */
12519
12520 static tree
12521 fold_builtin_strncat_chk (location_t loc, tree fndecl,
12522                           tree dest, tree src, tree len, tree size)
12523 {
12524   tree fn;
12525   const char *p;
12526
12527   if (!validate_arg (dest, POINTER_TYPE)
12528       || !validate_arg (src, POINTER_TYPE)
12529       || !validate_arg (size, INTEGER_TYPE)
12530       || !validate_arg (size, INTEGER_TYPE))
12531     return NULL_TREE;
12532
12533   p = c_getstr (src);
12534   /* If the SRC parameter is "" or if LEN is 0, return DEST.  */
12535   if (p && *p == '\0')
12536     return omit_one_operand_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)), dest, len);
12537   else if (integer_zerop (len))
12538     return omit_one_operand_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)), dest, src);
12539
12540   if (! host_integerp (size, 1))
12541     return NULL_TREE;
12542
12543   if (! integer_all_onesp (size))
12544     {
12545       tree src_len = c_strlen (src, 1);
12546       if (src_len
12547           && host_integerp (src_len, 1)
12548           && host_integerp (len, 1)
12549           && ! tree_int_cst_lt (len, src_len))
12550         {
12551           /* If LEN >= strlen (SRC), optimize into __strcat_chk.  */
12552           fn = built_in_decls[BUILT_IN_STRCAT_CHK];
12553           if (!fn)
12554             return NULL_TREE;
12555
12556           return build_call_expr_loc (loc, fn, 3, dest, src, size);
12557         }
12558       return NULL_TREE;
12559     }
12560
12561   /* If __builtin_strncat_chk is used, assume strncat is available.  */
12562   fn = built_in_decls[BUILT_IN_STRNCAT];
12563   if (!fn)
12564     return NULL_TREE;
12565
12566   return build_call_expr_loc (loc, fn, 3, dest, src, len);
12567 }
12568
12569 /* Fold a call EXP to __{,v}sprintf_chk.  Return NULL_TREE if
12570    a normal call should be emitted rather than expanding the function
12571    inline.  FCODE is either BUILT_IN_SPRINTF_CHK or BUILT_IN_VSPRINTF_CHK.  */
12572
12573 static tree
12574 fold_builtin_sprintf_chk (location_t loc, tree exp,
12575                           enum built_in_function fcode)
12576 {
12577   tree dest, size, len, fn, fmt, flag;
12578   const char *fmt_str;
12579   int nargs = call_expr_nargs (exp);
12580
12581   /* Verify the required arguments in the original call.  */
12582   if (nargs < 4)
12583     return NULL_TREE;
12584   dest = CALL_EXPR_ARG (exp, 0);
12585   if (!validate_arg (dest, POINTER_TYPE))
12586     return NULL_TREE;
12587   flag = CALL_EXPR_ARG (exp, 1);
12588   if (!validate_arg (flag, INTEGER_TYPE))
12589     return NULL_TREE;
12590   size = CALL_EXPR_ARG (exp, 2);
12591   if (!validate_arg (size, INTEGER_TYPE))
12592     return NULL_TREE;
12593   fmt = CALL_EXPR_ARG (exp, 3);
12594   if (!validate_arg (fmt, POINTER_TYPE))
12595     return NULL_TREE;
12596
12597   if (! host_integerp (size, 1))
12598     return NULL_TREE;
12599
12600   len = NULL_TREE;
12601
12602   if (!init_target_chars ())
12603     return NULL_TREE;
12604
12605   /* Check whether the format is a literal string constant.  */
12606   fmt_str = c_getstr (fmt);
12607   if (fmt_str != NULL)
12608     {
12609       /* If the format doesn't contain % args or %%, we know the size.  */
12610       if (strchr (fmt_str, target_percent) == 0)
12611         {
12612           if (fcode != BUILT_IN_SPRINTF_CHK || nargs == 4)
12613             len = build_int_cstu (size_type_node, strlen (fmt_str));
12614         }
12615       /* If the format is "%s" and first ... argument is a string literal,
12616          we know the size too.  */
12617       else if (fcode == BUILT_IN_SPRINTF_CHK
12618                && strcmp (fmt_str, target_percent_s) == 0)
12619         {
12620           tree arg;
12621
12622           if (nargs == 5)
12623             {
12624               arg = CALL_EXPR_ARG (exp, 4);
12625               if (validate_arg (arg, POINTER_TYPE))
12626                 {
12627                   len = c_strlen (arg, 1);
12628                   if (! len || ! host_integerp (len, 1))
12629                     len = NULL_TREE;
12630                 }
12631             }
12632         }
12633     }
12634
12635   if (! integer_all_onesp (size))
12636     {
12637       if (! len || ! tree_int_cst_lt (len, size))
12638         return NULL_TREE;
12639     }
12640
12641   /* Only convert __{,v}sprintf_chk to {,v}sprintf if flag is 0
12642      or if format doesn't contain % chars or is "%s".  */
12643   if (! integer_zerop (flag))
12644     {
12645       if (fmt_str == NULL)
12646         return NULL_TREE;
12647       if (strchr (fmt_str, target_percent) != NULL
12648           && strcmp (fmt_str, target_percent_s))
12649         return NULL_TREE;
12650     }
12651
12652   /* If __builtin_{,v}sprintf_chk is used, assume {,v}sprintf is available.  */
12653   fn = built_in_decls[fcode == BUILT_IN_VSPRINTF_CHK
12654                       ? BUILT_IN_VSPRINTF : BUILT_IN_SPRINTF];
12655   if (!fn)
12656     return NULL_TREE;
12657
12658   return rewrite_call_expr (loc, exp, 4, fn, 2, dest, fmt);
12659 }
12660
12661 /* Fold a call EXP to {,v}snprintf.  Return NULL_TREE if
12662    a normal call should be emitted rather than expanding the function
12663    inline.  FCODE is either BUILT_IN_SNPRINTF_CHK or
12664    BUILT_IN_VSNPRINTF_CHK.  If MAXLEN is not NULL, it is maximum length
12665    passed as second argument.  */
12666
12667 tree
12668 fold_builtin_snprintf_chk (location_t loc, tree exp, tree maxlen,
12669                            enum built_in_function fcode)
12670 {
12671   tree dest, size, len, fn, fmt, flag;
12672   const char *fmt_str;
12673
12674   /* Verify the required arguments in the original call.  */
12675   if (call_expr_nargs (exp) < 5)
12676     return NULL_TREE;
12677   dest = CALL_EXPR_ARG (exp, 0);
12678   if (!validate_arg (dest, POINTER_TYPE))
12679     return NULL_TREE;
12680   len = CALL_EXPR_ARG (exp, 1);
12681   if (!validate_arg (len, INTEGER_TYPE))
12682     return NULL_TREE;
12683   flag = CALL_EXPR_ARG (exp, 2);
12684   if (!validate_arg (flag, INTEGER_TYPE))
12685     return NULL_TREE;
12686   size = CALL_EXPR_ARG (exp, 3);
12687   if (!validate_arg (size, INTEGER_TYPE))
12688     return NULL_TREE;
12689   fmt = CALL_EXPR_ARG (exp, 4);
12690   if (!validate_arg (fmt, POINTER_TYPE))
12691     return NULL_TREE;
12692
12693   if (! host_integerp (size, 1))
12694     return NULL_TREE;
12695
12696   if (! integer_all_onesp (size))
12697     {
12698       if (! host_integerp (len, 1))
12699         {
12700           /* If LEN is not constant, try MAXLEN too.
12701              For MAXLEN only allow optimizing into non-_ocs function
12702              if SIZE is >= MAXLEN, never convert to __ocs_fail ().  */
12703           if (maxlen == NULL_TREE || ! host_integerp (maxlen, 1))
12704             return NULL_TREE;
12705         }
12706       else
12707         maxlen = len;
12708
12709       if (tree_int_cst_lt (size, maxlen))
12710         return NULL_TREE;
12711     }
12712
12713   if (!init_target_chars ())
12714     return NULL_TREE;
12715
12716   /* Only convert __{,v}snprintf_chk to {,v}snprintf if flag is 0
12717      or if format doesn't contain % chars or is "%s".  */
12718   if (! integer_zerop (flag))
12719     {
12720       fmt_str = c_getstr (fmt);
12721       if (fmt_str == NULL)
12722         return NULL_TREE;
12723       if (strchr (fmt_str, target_percent) != NULL
12724           && strcmp (fmt_str, target_percent_s))
12725         return NULL_TREE;
12726     }
12727
12728   /* If __builtin_{,v}snprintf_chk is used, assume {,v}snprintf is
12729      available.  */
12730   fn = built_in_decls[fcode == BUILT_IN_VSNPRINTF_CHK
12731                       ? BUILT_IN_VSNPRINTF : BUILT_IN_SNPRINTF];
12732   if (!fn)
12733     return NULL_TREE;
12734
12735   return rewrite_call_expr (loc, exp, 5, fn, 3, dest, len, fmt);
12736 }
12737
12738 /* Fold a call to the {,v}printf{,_unlocked} and __{,v}printf_chk builtins.
12739    FMT and ARG are the arguments to the call; we don't fold cases with
12740    more than 2 arguments, and ARG may be null if this is a 1-argument case.
12741
12742    Return NULL_TREE if no simplification was possible, otherwise return the
12743    simplified form of the call as a tree.  FCODE is the BUILT_IN_*
12744    code of the function to be simplified.  */
12745
12746 static tree
12747 fold_builtin_printf (location_t loc, tree fndecl, tree fmt,
12748                      tree arg, bool ignore,
12749                      enum built_in_function fcode)
12750 {
12751   tree fn_putchar, fn_puts, newarg, call = NULL_TREE;
12752   const char *fmt_str = NULL;
12753
12754   /* If the return value is used, don't do the transformation.  */
12755   if (! ignore)
12756     return NULL_TREE;
12757
12758   /* Verify the required arguments in the original call.  */
12759   if (!validate_arg (fmt, POINTER_TYPE))
12760     return NULL_TREE;
12761
12762   /* Check whether the format is a literal string constant.  */
12763   fmt_str = c_getstr (fmt);
12764   if (fmt_str == NULL)
12765     return NULL_TREE;
12766
12767   if (fcode == BUILT_IN_PRINTF_UNLOCKED)
12768     {
12769       /* If we're using an unlocked function, assume the other
12770          unlocked functions exist explicitly.  */
12771       fn_putchar = built_in_decls[BUILT_IN_PUTCHAR_UNLOCKED];
12772       fn_puts = built_in_decls[BUILT_IN_PUTS_UNLOCKED];
12773     }
12774   else
12775     {
12776       fn_putchar = implicit_built_in_decls[BUILT_IN_PUTCHAR];
12777       fn_puts = implicit_built_in_decls[BUILT_IN_PUTS];
12778     }
12779
12780   if (!init_target_chars ())
12781     return NULL_TREE;
12782
12783   if (strcmp (fmt_str, target_percent_s) == 0
12784       || strchr (fmt_str, target_percent) == NULL)
12785     {
12786       const char *str;
12787
12788       if (strcmp (fmt_str, target_percent_s) == 0)
12789         {
12790           if (fcode == BUILT_IN_VPRINTF || fcode == BUILT_IN_VPRINTF_CHK)
12791             return NULL_TREE;
12792
12793           if (!arg || !validate_arg (arg, POINTER_TYPE))
12794             return NULL_TREE;
12795
12796           str = c_getstr (arg);
12797           if (str == NULL)
12798             return NULL_TREE;
12799         }
12800       else
12801         {
12802           /* The format specifier doesn't contain any '%' characters.  */
12803           if (fcode != BUILT_IN_VPRINTF && fcode != BUILT_IN_VPRINTF_CHK
12804               && arg)
12805             return NULL_TREE;
12806           str = fmt_str;
12807         }
12808
12809       /* If the string was "", printf does nothing.  */
12810       if (str[0] == '\0')
12811         return build_int_cst (TREE_TYPE (TREE_TYPE (fndecl)), 0);
12812
12813       /* If the string has length of 1, call putchar.  */
12814       if (str[1] == '\0')
12815         {
12816           /* Given printf("c"), (where c is any one character,)
12817              convert "c"[0] to an int and pass that to the replacement
12818              function.  */
12819           newarg = build_int_cst (NULL_TREE, str[0]);
12820           if (fn_putchar)
12821             call = build_call_expr_loc (loc, fn_putchar, 1, newarg);
12822         }
12823       else
12824         {
12825           /* If the string was "string\n", call puts("string").  */
12826           size_t len = strlen (str);
12827           if ((unsigned char)str[len - 1] == target_newline)
12828             {
12829               /* Create a NUL-terminated string that's one char shorter
12830                  than the original, stripping off the trailing '\n'.  */
12831               char *newstr = XALLOCAVEC (char, len);
12832               memcpy (newstr, str, len - 1);
12833               newstr[len - 1] = 0;
12834
12835               newarg = build_string_literal (len, newstr);
12836               if (fn_puts)
12837                 call = build_call_expr_loc (loc, fn_puts, 1, newarg);
12838             }
12839           else
12840             /* We'd like to arrange to call fputs(string,stdout) here,
12841                but we need stdout and don't have a way to get it yet.  */
12842             return NULL_TREE;
12843         }
12844     }
12845
12846   /* The other optimizations can be done only on the non-va_list variants.  */
12847   else if (fcode == BUILT_IN_VPRINTF || fcode == BUILT_IN_VPRINTF_CHK)
12848     return NULL_TREE;
12849
12850   /* If the format specifier was "%s\n", call __builtin_puts(arg).  */
12851   else if (strcmp (fmt_str, target_percent_s_newline) == 0)
12852     {
12853       if (!arg || !validate_arg (arg, POINTER_TYPE))
12854         return NULL_TREE;
12855       if (fn_puts)
12856         call = build_call_expr_loc (loc, fn_puts, 1, arg);
12857     }
12858
12859   /* If the format specifier was "%c", call __builtin_putchar(arg).  */
12860   else if (strcmp (fmt_str, target_percent_c) == 0)
12861     {
12862       if (!arg || !validate_arg (arg, INTEGER_TYPE))
12863         return NULL_TREE;
12864       if (fn_putchar)
12865         call = build_call_expr_loc (loc, fn_putchar, 1, arg);
12866     }
12867
12868   if (!call)
12869     return NULL_TREE;
12870
12871   return fold_convert_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)), call);
12872 }
12873
12874 /* Fold a call to the {,v}fprintf{,_unlocked} and __{,v}printf_chk builtins.
12875    FP, FMT, and ARG are the arguments to the call.  We don't fold calls with
12876    more than 3 arguments, and ARG may be null in the 2-argument case.
12877
12878    Return NULL_TREE if no simplification was possible, otherwise return the
12879    simplified form of the call as a tree.  FCODE is the BUILT_IN_*
12880    code of the function to be simplified.  */
12881
12882 static tree
12883 fold_builtin_fprintf (location_t loc, tree fndecl, tree fp,
12884                       tree fmt, tree arg, bool ignore,
12885                       enum built_in_function fcode)
12886 {
12887   tree fn_fputc, fn_fputs, call = NULL_TREE;
12888   const char *fmt_str = NULL;
12889
12890   /* If the return value is used, don't do the transformation.  */
12891   if (! ignore)
12892     return NULL_TREE;
12893
12894   /* Verify the required arguments in the original call.  */
12895   if (!validate_arg (fp, POINTER_TYPE))
12896     return NULL_TREE;
12897   if (!validate_arg (fmt, POINTER_TYPE))
12898     return NULL_TREE;
12899
12900   /* Check whether the format is a literal string constant.  */
12901   fmt_str = c_getstr (fmt);
12902   if (fmt_str == NULL)
12903     return NULL_TREE;
12904
12905   if (fcode == BUILT_IN_FPRINTF_UNLOCKED)
12906     {
12907       /* If we're using an unlocked function, assume the other
12908          unlocked functions exist explicitly.  */
12909       fn_fputc = built_in_decls[BUILT_IN_FPUTC_UNLOCKED];
12910       fn_fputs = built_in_decls[BUILT_IN_FPUTS_UNLOCKED];
12911     }
12912   else
12913     {
12914       fn_fputc = implicit_built_in_decls[BUILT_IN_FPUTC];
12915       fn_fputs = implicit_built_in_decls[BUILT_IN_FPUTS];
12916     }
12917
12918   if (!init_target_chars ())
12919     return NULL_TREE;
12920
12921   /* If the format doesn't contain % args or %%, use strcpy.  */
12922   if (strchr (fmt_str, target_percent) == NULL)
12923     {
12924       if (fcode != BUILT_IN_VFPRINTF && fcode != BUILT_IN_VFPRINTF_CHK
12925           && arg)
12926         return NULL_TREE;
12927
12928       /* If the format specifier was "", fprintf does nothing.  */
12929       if (fmt_str[0] == '\0')
12930         {
12931           /* If FP has side-effects, just wait until gimplification is
12932              done.  */
12933           if (TREE_SIDE_EFFECTS (fp))
12934             return NULL_TREE;
12935
12936           return build_int_cst (TREE_TYPE (TREE_TYPE (fndecl)), 0);
12937         }
12938
12939       /* When "string" doesn't contain %, replace all cases of
12940          fprintf (fp, string) with fputs (string, fp).  The fputs
12941          builtin will take care of special cases like length == 1.  */
12942       if (fn_fputs)
12943         call = build_call_expr_loc (loc, fn_fputs, 2, fmt, fp);
12944     }
12945
12946   /* The other optimizations can be done only on the non-va_list variants.  */
12947   else if (fcode == BUILT_IN_VFPRINTF || fcode == BUILT_IN_VFPRINTF_CHK)
12948     return NULL_TREE;
12949
12950   /* If the format specifier was "%s", call __builtin_fputs (arg, fp).  */
12951   else if (strcmp (fmt_str, target_percent_s) == 0)
12952     {
12953       if (!arg || !validate_arg (arg, POINTER_TYPE))
12954         return NULL_TREE;
12955       if (fn_fputs)
12956         call = build_call_expr_loc (loc, fn_fputs, 2, arg, fp);
12957     }
12958
12959   /* If the format specifier was "%c", call __builtin_fputc (arg, fp).  */
12960   else if (strcmp (fmt_str, target_percent_c) == 0)
12961     {
12962       if (!arg || !validate_arg (arg, INTEGER_TYPE))
12963         return NULL_TREE;
12964       if (fn_fputc)
12965         call = build_call_expr_loc (loc, fn_fputc, 2, arg, fp);
12966     }
12967
12968   if (!call)
12969     return NULL_TREE;
12970   return fold_convert_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)), call);
12971 }
12972
12973 /* Initialize format string characters in the target charset.  */
12974
12975 static bool
12976 init_target_chars (void)
12977 {
12978   static bool init;
12979   if (!init)
12980     {
12981       target_newline = lang_hooks.to_target_charset ('\n');
12982       target_percent = lang_hooks.to_target_charset ('%');
12983       target_c = lang_hooks.to_target_charset ('c');
12984       target_s = lang_hooks.to_target_charset ('s');
12985       if (target_newline == 0 || target_percent == 0 || target_c == 0
12986           || target_s == 0)
12987         return false;
12988
12989       target_percent_c[0] = target_percent;
12990       target_percent_c[1] = target_c;
12991       target_percent_c[2] = '\0';
12992
12993       target_percent_s[0] = target_percent;
12994       target_percent_s[1] = target_s;
12995       target_percent_s[2] = '\0';
12996
12997       target_percent_s_newline[0] = target_percent;
12998       target_percent_s_newline[1] = target_s;
12999       target_percent_s_newline[2] = target_newline;
13000       target_percent_s_newline[3] = '\0';
13001
13002       init = true;
13003     }
13004   return true;
13005 }
13006
13007 /* Helper function for do_mpfr_arg*().  Ensure M is a normal number
13008    and no overflow/underflow occurred.  INEXACT is true if M was not
13009    exactly calculated.  TYPE is the tree type for the result.  This
13010    function assumes that you cleared the MPFR flags and then
13011    calculated M to see if anything subsequently set a flag prior to
13012    entering this function.  Return NULL_TREE if any checks fail.  */
13013
13014 static tree
13015 do_mpfr_ckconv (mpfr_srcptr m, tree type, int inexact)
13016 {
13017   /* Proceed iff we get a normal number, i.e. not NaN or Inf and no
13018      overflow/underflow occurred.  If -frounding-math, proceed iff the
13019      result of calling FUNC was exact.  */
13020   if (mpfr_number_p (m) && !mpfr_overflow_p () && !mpfr_underflow_p ()
13021       && (!flag_rounding_math || !inexact))
13022     {
13023       REAL_VALUE_TYPE rr;
13024
13025       real_from_mpfr (&rr, m, type, GMP_RNDN);
13026       /* Proceed iff GCC's REAL_VALUE_TYPE can hold the MPFR value,
13027          check for overflow/underflow.  If the REAL_VALUE_TYPE is zero
13028          but the mpft_t is not, then we underflowed in the
13029          conversion.  */
13030       if (real_isfinite (&rr)
13031           && (rr.cl == rvc_zero) == (mpfr_zero_p (m) != 0))
13032         {
13033           REAL_VALUE_TYPE rmode;
13034
13035           real_convert (&rmode, TYPE_MODE (type), &rr);
13036           /* Proceed iff the specified mode can hold the value.  */
13037           if (real_identical (&rmode, &rr))
13038             return build_real (type, rmode);
13039         }
13040     }
13041   return NULL_TREE;
13042 }
13043
13044 #ifdef HAVE_mpc
13045 /* Helper function for do_mpc_arg*().  Ensure M is a normal complex
13046    number and no overflow/underflow occurred.  INEXACT is true if M
13047    was not exactly calculated.  TYPE is the tree type for the result.
13048    This function assumes that you cleared the MPFR flags and then
13049    calculated M to see if anything subsequently set a flag prior to
13050    entering this function.  Return NULL_TREE if any checks fail, if
13051    FORCE_CONVERT is true, then bypass the checks.  */
13052
13053 static tree
13054 do_mpc_ckconv (mpc_srcptr m, tree type, int inexact, int force_convert)
13055 {
13056   /* Proceed iff we get a normal number, i.e. not NaN or Inf and no
13057      overflow/underflow occurred.  If -frounding-math, proceed iff the
13058      result of calling FUNC was exact.  */
13059   if (force_convert
13060       || (mpfr_number_p (mpc_realref (m)) && mpfr_number_p (mpc_imagref (m))
13061           && !mpfr_overflow_p () && !mpfr_underflow_p ()
13062           && (!flag_rounding_math || !inexact)))
13063     {
13064       REAL_VALUE_TYPE re, im;
13065
13066       real_from_mpfr (&re, mpc_realref (m), type, GMP_RNDN);
13067       real_from_mpfr (&im, mpc_imagref (m), type, GMP_RNDN);
13068       /* Proceed iff GCC's REAL_VALUE_TYPE can hold the MPFR values,
13069          check for overflow/underflow.  If the REAL_VALUE_TYPE is zero
13070          but the mpft_t is not, then we underflowed in the
13071          conversion.  */
13072       if (force_convert
13073           || (real_isfinite (&re) && real_isfinite (&im)
13074               && (re.cl == rvc_zero) == (mpfr_zero_p (mpc_realref (m)) != 0)
13075               && (im.cl == rvc_zero) == (mpfr_zero_p (mpc_imagref (m)) != 0)))
13076         {
13077           REAL_VALUE_TYPE re_mode, im_mode;
13078
13079           real_convert (&re_mode, TYPE_MODE (TREE_TYPE (type)), &re);
13080           real_convert (&im_mode, TYPE_MODE (TREE_TYPE (type)), &im);
13081           /* Proceed iff the specified mode can hold the value.  */
13082           if (force_convert
13083               || (real_identical (&re_mode, &re)
13084                   && real_identical (&im_mode, &im)))
13085             return build_complex (type, build_real (TREE_TYPE (type), re_mode),
13086                                   build_real (TREE_TYPE (type), im_mode));
13087         }
13088     }
13089   return NULL_TREE;
13090 }
13091 #endif /* HAVE_mpc */
13092
13093 /* If argument ARG is a REAL_CST, call the one-argument mpfr function
13094    FUNC on it and return the resulting value as a tree with type TYPE.
13095    If MIN and/or MAX are not NULL, then the supplied ARG must be
13096    within those bounds.  If INCLUSIVE is true, then MIN/MAX are
13097    acceptable values, otherwise they are not.  The mpfr precision is
13098    set to the precision of TYPE.  We assume that function FUNC returns
13099    zero if the result could be calculated exactly within the requested
13100    precision.  */
13101
13102 static tree
13103 do_mpfr_arg1 (tree arg, tree type, int (*func)(mpfr_ptr, mpfr_srcptr, mp_rnd_t),
13104               const REAL_VALUE_TYPE *min, const REAL_VALUE_TYPE *max,
13105               bool inclusive)
13106 {
13107   tree result = NULL_TREE;
13108   
13109   STRIP_NOPS (arg);
13110
13111   /* To proceed, MPFR must exactly represent the target floating point
13112      format, which only happens when the target base equals two.  */
13113   if (REAL_MODE_FORMAT (TYPE_MODE (type))->b == 2
13114       && TREE_CODE (arg) == REAL_CST && !TREE_OVERFLOW (arg))
13115     {
13116       const REAL_VALUE_TYPE *const ra = &TREE_REAL_CST (arg);
13117
13118       if (real_isfinite (ra)
13119           && (!min || real_compare (inclusive ? GE_EXPR: GT_EXPR , ra, min))
13120           && (!max || real_compare (inclusive ? LE_EXPR: LT_EXPR , ra, max)))
13121         {
13122           const struct real_format *fmt = REAL_MODE_FORMAT (TYPE_MODE (type));
13123           const int prec = fmt->p;
13124           const mp_rnd_t rnd = fmt->round_towards_zero? GMP_RNDZ : GMP_RNDN;
13125           int inexact;
13126           mpfr_t m;
13127
13128           mpfr_init2 (m, prec);
13129           mpfr_from_real (m, ra, GMP_RNDN);
13130           mpfr_clear_flags ();
13131           inexact = func (m, m, rnd);
13132           result = do_mpfr_ckconv (m, type, inexact);
13133           mpfr_clear (m);
13134         }
13135     }
13136   
13137   return result;
13138 }
13139
13140 /* If argument ARG is a REAL_CST, call the two-argument mpfr function
13141    FUNC on it and return the resulting value as a tree with type TYPE.
13142    The mpfr precision is set to the precision of TYPE.  We assume that
13143    function FUNC returns zero if the result could be calculated
13144    exactly within the requested precision.  */
13145
13146 static tree
13147 do_mpfr_arg2 (tree arg1, tree arg2, tree type,
13148               int (*func)(mpfr_ptr, mpfr_srcptr, mpfr_srcptr, mp_rnd_t))
13149 {
13150   tree result = NULL_TREE;
13151   
13152   STRIP_NOPS (arg1);
13153   STRIP_NOPS (arg2);
13154
13155   /* To proceed, MPFR must exactly represent the target floating point
13156      format, which only happens when the target base equals two.  */
13157   if (REAL_MODE_FORMAT (TYPE_MODE (type))->b == 2
13158       && TREE_CODE (arg1) == REAL_CST && !TREE_OVERFLOW (arg1)
13159       && TREE_CODE (arg2) == REAL_CST && !TREE_OVERFLOW (arg2))
13160     {
13161       const REAL_VALUE_TYPE *const ra1 = &TREE_REAL_CST (arg1);
13162       const REAL_VALUE_TYPE *const ra2 = &TREE_REAL_CST (arg2);
13163
13164       if (real_isfinite (ra1) && real_isfinite (ra2))
13165         {
13166           const struct real_format *fmt = REAL_MODE_FORMAT (TYPE_MODE (type));
13167           const int prec = fmt->p;
13168           const mp_rnd_t rnd = fmt->round_towards_zero? GMP_RNDZ : GMP_RNDN;
13169           int inexact;
13170           mpfr_t m1, m2;
13171
13172           mpfr_inits2 (prec, m1, m2, NULL);
13173           mpfr_from_real (m1, ra1, GMP_RNDN);
13174           mpfr_from_real (m2, ra2, GMP_RNDN);
13175           mpfr_clear_flags ();
13176           inexact = func (m1, m1, m2, rnd);
13177           result = do_mpfr_ckconv (m1, type, inexact);
13178           mpfr_clears (m1, m2, NULL);
13179         }
13180     }
13181   
13182   return result;
13183 }
13184
13185 /* If argument ARG is a REAL_CST, call the three-argument mpfr function
13186    FUNC on it and return the resulting value as a tree with type TYPE.
13187    The mpfr precision is set to the precision of TYPE.  We assume that
13188    function FUNC returns zero if the result could be calculated
13189    exactly within the requested precision.  */
13190
13191 static tree
13192 do_mpfr_arg3 (tree arg1, tree arg2, tree arg3, tree type,
13193               int (*func)(mpfr_ptr, mpfr_srcptr, mpfr_srcptr, mpfr_srcptr, mp_rnd_t))
13194 {
13195   tree result = NULL_TREE;
13196   
13197   STRIP_NOPS (arg1);
13198   STRIP_NOPS (arg2);
13199   STRIP_NOPS (arg3);
13200
13201   /* To proceed, MPFR must exactly represent the target floating point
13202      format, which only happens when the target base equals two.  */
13203   if (REAL_MODE_FORMAT (TYPE_MODE (type))->b == 2
13204       && TREE_CODE (arg1) == REAL_CST && !TREE_OVERFLOW (arg1)
13205       && TREE_CODE (arg2) == REAL_CST && !TREE_OVERFLOW (arg2)
13206       && TREE_CODE (arg3) == REAL_CST && !TREE_OVERFLOW (arg3))
13207     {
13208       const REAL_VALUE_TYPE *const ra1 = &TREE_REAL_CST (arg1);
13209       const REAL_VALUE_TYPE *const ra2 = &TREE_REAL_CST (arg2);
13210       const REAL_VALUE_TYPE *const ra3 = &TREE_REAL_CST (arg3);
13211
13212       if (real_isfinite (ra1) && real_isfinite (ra2) && real_isfinite (ra3))
13213         {
13214           const struct real_format *fmt = REAL_MODE_FORMAT (TYPE_MODE (type));
13215           const int prec = fmt->p;
13216           const mp_rnd_t rnd = fmt->round_towards_zero? GMP_RNDZ : GMP_RNDN;
13217           int inexact;
13218           mpfr_t m1, m2, m3;
13219
13220           mpfr_inits2 (prec, m1, m2, m3, NULL);
13221           mpfr_from_real (m1, ra1, GMP_RNDN);
13222           mpfr_from_real (m2, ra2, GMP_RNDN);
13223           mpfr_from_real (m3, ra3, GMP_RNDN);
13224           mpfr_clear_flags ();
13225           inexact = func (m1, m1, m2, m3, rnd);
13226           result = do_mpfr_ckconv (m1, type, inexact);
13227           mpfr_clears (m1, m2, m3, NULL);
13228         }
13229     }
13230   
13231   return result;
13232 }
13233
13234 /* If argument ARG is a REAL_CST, call mpfr_sin_cos() on it and set
13235    the pointers *(ARG_SINP) and *(ARG_COSP) to the resulting values.
13236    If ARG_SINP and ARG_COSP are NULL then the result is returned
13237    as a complex value.
13238    The type is taken from the type of ARG and is used for setting the
13239    precision of the calculation and results.  */
13240
13241 static tree
13242 do_mpfr_sincos (tree arg, tree arg_sinp, tree arg_cosp)
13243 {
13244   tree const type = TREE_TYPE (arg);
13245   tree result = NULL_TREE;
13246   
13247   STRIP_NOPS (arg);
13248   
13249   /* To proceed, MPFR must exactly represent the target floating point
13250      format, which only happens when the target base equals two.  */
13251   if (REAL_MODE_FORMAT (TYPE_MODE (type))->b == 2
13252       && TREE_CODE (arg) == REAL_CST
13253       && !TREE_OVERFLOW (arg))
13254     {
13255       const REAL_VALUE_TYPE *const ra = &TREE_REAL_CST (arg);
13256
13257       if (real_isfinite (ra))
13258         {
13259           const struct real_format *fmt = REAL_MODE_FORMAT (TYPE_MODE (type));
13260           const int prec = fmt->p;
13261           const mp_rnd_t rnd = fmt->round_towards_zero? GMP_RNDZ : GMP_RNDN;
13262           tree result_s, result_c;
13263           int inexact;
13264           mpfr_t m, ms, mc;
13265
13266           mpfr_inits2 (prec, m, ms, mc, NULL);
13267           mpfr_from_real (m, ra, GMP_RNDN);
13268           mpfr_clear_flags ();
13269           inexact = mpfr_sin_cos (ms, mc, m, rnd);
13270           result_s = do_mpfr_ckconv (ms, type, inexact);
13271           result_c = do_mpfr_ckconv (mc, type, inexact);
13272           mpfr_clears (m, ms, mc, NULL);
13273           if (result_s && result_c)
13274             {
13275               /* If we are to return in a complex value do so.  */
13276               if (!arg_sinp && !arg_cosp)
13277                 return build_complex (build_complex_type (type),
13278                                       result_c, result_s);
13279
13280               /* Dereference the sin/cos pointer arguments.  */
13281               arg_sinp = build_fold_indirect_ref (arg_sinp);
13282               arg_cosp = build_fold_indirect_ref (arg_cosp);
13283               /* Proceed if valid pointer type were passed in.  */
13284               if (TYPE_MAIN_VARIANT (TREE_TYPE (arg_sinp)) == TYPE_MAIN_VARIANT (type)
13285                   && TYPE_MAIN_VARIANT (TREE_TYPE (arg_cosp)) == TYPE_MAIN_VARIANT (type))
13286                 {
13287                   /* Set the values. */
13288                   result_s = fold_build2 (MODIFY_EXPR, type, arg_sinp,
13289                                           result_s);
13290                   TREE_SIDE_EFFECTS (result_s) = 1;
13291                   result_c = fold_build2 (MODIFY_EXPR, type, arg_cosp,
13292                                           result_c);
13293                   TREE_SIDE_EFFECTS (result_c) = 1;
13294                   /* Combine the assignments into a compound expr.  */
13295                   result = non_lvalue (fold_build2 (COMPOUND_EXPR, type,
13296                                                     result_s, result_c));
13297                 }
13298             }
13299         }
13300     }
13301   return result;
13302 }
13303
13304 /* If argument ARG1 is an INTEGER_CST and ARG2 is a REAL_CST, call the
13305    two-argument mpfr order N Bessel function FUNC on them and return
13306    the resulting value as a tree with type TYPE.  The mpfr precision
13307    is set to the precision of TYPE.  We assume that function FUNC
13308    returns zero if the result could be calculated exactly within the
13309    requested precision.  */
13310 static tree
13311 do_mpfr_bessel_n (tree arg1, tree arg2, tree type,
13312                   int (*func)(mpfr_ptr, long, mpfr_srcptr, mp_rnd_t),
13313                   const REAL_VALUE_TYPE *min, bool inclusive)
13314 {
13315   tree result = NULL_TREE;
13316
13317   STRIP_NOPS (arg1);
13318   STRIP_NOPS (arg2);
13319
13320   /* To proceed, MPFR must exactly represent the target floating point
13321      format, which only happens when the target base equals two.  */
13322   if (REAL_MODE_FORMAT (TYPE_MODE (type))->b == 2
13323       && host_integerp (arg1, 0)
13324       && TREE_CODE (arg2) == REAL_CST && !TREE_OVERFLOW (arg2))
13325     {
13326       const HOST_WIDE_INT n = tree_low_cst(arg1, 0);
13327       const REAL_VALUE_TYPE *const ra = &TREE_REAL_CST (arg2);
13328
13329       if (n == (long)n
13330           && real_isfinite (ra)
13331           && (!min || real_compare (inclusive ? GE_EXPR: GT_EXPR , ra, min)))
13332         {
13333           const struct real_format *fmt = REAL_MODE_FORMAT (TYPE_MODE (type));
13334           const int prec = fmt->p;
13335           const mp_rnd_t rnd = fmt->round_towards_zero? GMP_RNDZ : GMP_RNDN;
13336           int inexact;
13337           mpfr_t m;
13338
13339           mpfr_init2 (m, prec);
13340           mpfr_from_real (m, ra, GMP_RNDN);
13341           mpfr_clear_flags ();
13342           inexact = func (m, n, m, rnd);
13343           result = do_mpfr_ckconv (m, type, inexact);
13344           mpfr_clear (m);
13345         }
13346     }
13347   
13348   return result;
13349 }
13350
13351 /* If arguments ARG0 and ARG1 are REAL_CSTs, call mpfr_remquo() to set
13352    the pointer *(ARG_QUO) and return the result.  The type is taken
13353    from the type of ARG0 and is used for setting the precision of the
13354    calculation and results.  */
13355
13356 static tree
13357 do_mpfr_remquo (tree arg0, tree arg1, tree arg_quo)
13358 {
13359   tree const type = TREE_TYPE (arg0);
13360   tree result = NULL_TREE;
13361   
13362   STRIP_NOPS (arg0);
13363   STRIP_NOPS (arg1);
13364   
13365   /* To proceed, MPFR must exactly represent the target floating point
13366      format, which only happens when the target base equals two.  */
13367   if (REAL_MODE_FORMAT (TYPE_MODE (type))->b == 2
13368       && TREE_CODE (arg0) == REAL_CST && !TREE_OVERFLOW (arg0)
13369       && TREE_CODE (arg1) == REAL_CST && !TREE_OVERFLOW (arg1))
13370     {
13371       const REAL_VALUE_TYPE *const ra0 = TREE_REAL_CST_PTR (arg0);
13372       const REAL_VALUE_TYPE *const ra1 = TREE_REAL_CST_PTR (arg1);
13373
13374       if (real_isfinite (ra0) && real_isfinite (ra1))
13375         {
13376           const struct real_format *fmt = REAL_MODE_FORMAT (TYPE_MODE (type));
13377           const int prec = fmt->p;
13378           const mp_rnd_t rnd = fmt->round_towards_zero? GMP_RNDZ : GMP_RNDN;
13379           tree result_rem;
13380           long integer_quo;
13381           mpfr_t m0, m1;
13382
13383           mpfr_inits2 (prec, m0, m1, NULL);
13384           mpfr_from_real (m0, ra0, GMP_RNDN);
13385           mpfr_from_real (m1, ra1, GMP_RNDN);
13386           mpfr_clear_flags ();
13387           mpfr_remquo (m0, &integer_quo, m0, m1, rnd);
13388           /* Remquo is independent of the rounding mode, so pass
13389              inexact=0 to do_mpfr_ckconv().  */
13390           result_rem = do_mpfr_ckconv (m0, type, /*inexact=*/ 0);
13391           mpfr_clears (m0, m1, NULL);
13392           if (result_rem)
13393             {
13394               /* MPFR calculates quo in the host's long so it may
13395                  return more bits in quo than the target int can hold
13396                  if sizeof(host long) > sizeof(target int).  This can
13397                  happen even for native compilers in LP64 mode.  In
13398                  these cases, modulo the quo value with the largest
13399                  number that the target int can hold while leaving one
13400                  bit for the sign.  */
13401               if (sizeof (integer_quo) * CHAR_BIT > INT_TYPE_SIZE)
13402                 integer_quo %= (long)(1UL << (INT_TYPE_SIZE - 1));
13403
13404               /* Dereference the quo pointer argument.  */
13405               arg_quo = build_fold_indirect_ref (arg_quo);
13406               /* Proceed iff a valid pointer type was passed in.  */
13407               if (TYPE_MAIN_VARIANT (TREE_TYPE (arg_quo)) == integer_type_node)
13408                 {
13409                   /* Set the value. */
13410                   tree result_quo = fold_build2 (MODIFY_EXPR,
13411                                                  TREE_TYPE (arg_quo), arg_quo,
13412                                                  build_int_cst (NULL, integer_quo));
13413                   TREE_SIDE_EFFECTS (result_quo) = 1;
13414                   /* Combine the quo assignment with the rem.  */
13415                   result = non_lvalue (fold_build2 (COMPOUND_EXPR, type,
13416                                                     result_quo, result_rem));
13417                 }
13418             }
13419         }
13420     }
13421   return result;
13422 }
13423
13424 /* If ARG is a REAL_CST, call mpfr_lgamma() on it and return the
13425    resulting value as a tree with type TYPE.  The mpfr precision is
13426    set to the precision of TYPE.  We assume that this mpfr function
13427    returns zero if the result could be calculated exactly within the
13428    requested precision.  In addition, the integer pointer represented
13429    by ARG_SG will be dereferenced and set to the appropriate signgam
13430    (-1,1) value.  */
13431
13432 static tree
13433 do_mpfr_lgamma_r (tree arg, tree arg_sg, tree type)
13434 {
13435   tree result = NULL_TREE;
13436
13437   STRIP_NOPS (arg);
13438   
13439   /* To proceed, MPFR must exactly represent the target floating point
13440      format, which only happens when the target base equals two.  Also
13441      verify ARG is a constant and that ARG_SG is an int pointer.  */
13442   if (REAL_MODE_FORMAT (TYPE_MODE (type))->b == 2
13443       && TREE_CODE (arg) == REAL_CST && !TREE_OVERFLOW (arg)
13444       && TREE_CODE (TREE_TYPE (arg_sg)) == POINTER_TYPE
13445       && TYPE_MAIN_VARIANT (TREE_TYPE (TREE_TYPE (arg_sg))) == integer_type_node)
13446     {
13447       const REAL_VALUE_TYPE *const ra = TREE_REAL_CST_PTR (arg);
13448
13449       /* In addition to NaN and Inf, the argument cannot be zero or a
13450          negative integer.  */
13451       if (real_isfinite (ra)
13452           && ra->cl != rvc_zero
13453           && !(real_isneg(ra) && real_isinteger(ra, TYPE_MODE (type))))
13454         {
13455           const struct real_format *fmt = REAL_MODE_FORMAT (TYPE_MODE (type));
13456           const int prec = fmt->p;
13457           const mp_rnd_t rnd = fmt->round_towards_zero? GMP_RNDZ : GMP_RNDN;
13458           int inexact, sg;
13459           mpfr_t m;
13460           tree result_lg;
13461
13462           mpfr_init2 (m, prec);
13463           mpfr_from_real (m, ra, GMP_RNDN);
13464           mpfr_clear_flags ();
13465           inexact = mpfr_lgamma (m, &sg, m, rnd);
13466           result_lg = do_mpfr_ckconv (m, type, inexact);
13467           mpfr_clear (m);
13468           if (result_lg)
13469             {
13470               tree result_sg;
13471
13472               /* Dereference the arg_sg pointer argument.  */
13473               arg_sg = build_fold_indirect_ref (arg_sg);
13474               /* Assign the signgam value into *arg_sg. */
13475               result_sg = fold_build2 (MODIFY_EXPR,
13476                                        TREE_TYPE (arg_sg), arg_sg,
13477                                        build_int_cst (NULL, sg));
13478               TREE_SIDE_EFFECTS (result_sg) = 1;
13479               /* Combine the signgam assignment with the lgamma result.  */
13480               result = non_lvalue (fold_build2 (COMPOUND_EXPR, type,
13481                                                 result_sg, result_lg));
13482             }
13483         }
13484     }
13485
13486   return result;
13487 }
13488
13489 #ifdef HAVE_mpc
13490 /* If argument ARG is a COMPLEX_CST, call the one-argument mpc
13491    function FUNC on it and return the resulting value as a tree with
13492    type TYPE.  The mpfr precision is set to the precision of TYPE.  We
13493    assume that function FUNC returns zero if the result could be
13494    calculated exactly within the requested precision.  */
13495
13496 static tree
13497 do_mpc_arg1 (tree arg, tree type, int (*func)(mpc_ptr, mpc_srcptr, mpc_rnd_t))
13498 {
13499   tree result = NULL_TREE;
13500   
13501   STRIP_NOPS (arg);
13502
13503   /* To proceed, MPFR must exactly represent the target floating point
13504      format, which only happens when the target base equals two.  */
13505   if (TREE_CODE (arg) == COMPLEX_CST && !TREE_OVERFLOW (arg)
13506       && TREE_CODE (TREE_TYPE (TREE_TYPE (arg))) == REAL_TYPE
13507       && REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (TREE_TYPE (arg))))->b == 2)
13508     {
13509       const REAL_VALUE_TYPE *const re = TREE_REAL_CST_PTR (TREE_REALPART (arg));
13510       const REAL_VALUE_TYPE *const im = TREE_REAL_CST_PTR (TREE_IMAGPART (arg));
13511
13512       if (real_isfinite (re) && real_isfinite (im))
13513         {
13514           const struct real_format *const fmt =
13515             REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (type)));
13516           const int prec = fmt->p;
13517           const mp_rnd_t rnd = fmt->round_towards_zero ? GMP_RNDZ : GMP_RNDN;
13518           const mpc_rnd_t crnd = fmt->round_towards_zero ? MPC_RNDZZ : MPC_RNDNN;
13519           int inexact;
13520           mpc_t m;
13521           
13522           mpc_init2 (m, prec);
13523           mpfr_from_real (mpc_realref(m), re, rnd);
13524           mpfr_from_real (mpc_imagref(m), im, rnd);
13525           mpfr_clear_flags ();
13526           inexact = func (m, m, crnd);
13527           result = do_mpc_ckconv (m, type, inexact, /*force_convert=*/ 0);
13528           mpc_clear (m);
13529         }
13530     }
13531
13532   return result;
13533 }
13534
13535 /* If arguments ARG0 and ARG1 are a COMPLEX_CST, call the two-argument
13536    mpc function FUNC on it and return the resulting value as a tree
13537    with type TYPE.  The mpfr precision is set to the precision of
13538    TYPE.  We assume that function FUNC returns zero if the result
13539    could be calculated exactly within the requested precision.  If
13540    DO_NONFINITE is true, then fold expressions containing Inf or NaN
13541    in the arguments and/or results.  */
13542
13543 #ifdef HAVE_mpc
13544 tree
13545 do_mpc_arg2 (tree arg0, tree arg1, tree type, int do_nonfinite,
13546              int (*func)(mpc_ptr, mpc_srcptr, mpc_srcptr, mpc_rnd_t))
13547 {
13548   tree result = NULL_TREE;
13549   
13550   STRIP_NOPS (arg0);
13551   STRIP_NOPS (arg1);
13552
13553   /* To proceed, MPFR must exactly represent the target floating point
13554      format, which only happens when the target base equals two.  */
13555   if (TREE_CODE (arg0) == COMPLEX_CST && !TREE_OVERFLOW (arg0)
13556       && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE
13557       && TREE_CODE (arg1) == COMPLEX_CST && !TREE_OVERFLOW (arg1)
13558       && TREE_CODE (TREE_TYPE (TREE_TYPE (arg1))) == REAL_TYPE
13559       && REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (TREE_TYPE (arg0))))->b == 2)
13560     {
13561       const REAL_VALUE_TYPE *const re0 = TREE_REAL_CST_PTR (TREE_REALPART (arg0));
13562       const REAL_VALUE_TYPE *const im0 = TREE_REAL_CST_PTR (TREE_IMAGPART (arg0));
13563       const REAL_VALUE_TYPE *const re1 = TREE_REAL_CST_PTR (TREE_REALPART (arg1));
13564       const REAL_VALUE_TYPE *const im1 = TREE_REAL_CST_PTR (TREE_IMAGPART (arg1));
13565
13566       if (do_nonfinite
13567           || (real_isfinite (re0) && real_isfinite (im0)
13568               && real_isfinite (re1) && real_isfinite (im1)))
13569         {
13570           const struct real_format *const fmt =
13571             REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (type)));
13572           const int prec = fmt->p;
13573           const mp_rnd_t rnd = fmt->round_towards_zero ? GMP_RNDZ : GMP_RNDN;
13574           const mpc_rnd_t crnd = fmt->round_towards_zero ? MPC_RNDZZ : MPC_RNDNN;
13575           int inexact;
13576           mpc_t m0, m1;
13577           
13578           mpc_init2 (m0, prec);
13579           mpc_init2 (m1, prec);
13580           mpfr_from_real (mpc_realref(m0), re0, rnd);
13581           mpfr_from_real (mpc_imagref(m0), im0, rnd);
13582           mpfr_from_real (mpc_realref(m1), re1, rnd);
13583           mpfr_from_real (mpc_imagref(m1), im1, rnd);
13584           mpfr_clear_flags ();
13585           inexact = func (m0, m0, m1, crnd);
13586           result = do_mpc_ckconv (m0, type, inexact, do_nonfinite);
13587           mpc_clear (m0);
13588           mpc_clear (m1);
13589         }
13590     }
13591
13592   return result;
13593 }
13594 # endif
13595 #endif /* HAVE_mpc */
13596
13597 /* FIXME tuples.
13598    The functions below provide an alternate interface for folding
13599    builtin function calls presented as GIMPLE_CALL statements rather
13600    than as CALL_EXPRs.  The folded result is still expressed as a
13601    tree.  There is too much code duplication in the handling of
13602    varargs functions, and a more intrusive re-factoring would permit
13603    better sharing of code between the tree and statement-based
13604    versions of these functions.  */
13605
13606 /* Construct a new CALL_EXPR using the tail of the argument list of STMT
13607    along with N new arguments specified as the "..." parameters.  SKIP
13608    is the number of arguments in STMT to be omitted.  This function is used
13609    to do varargs-to-varargs transformations.  */
13610
13611 static tree
13612 gimple_rewrite_call_expr (gimple stmt, int skip, tree fndecl, int n, ...)
13613 {
13614   int oldnargs = gimple_call_num_args (stmt);
13615   int nargs = oldnargs - skip + n;
13616   tree fntype = TREE_TYPE (fndecl);
13617   tree fn = build1 (ADDR_EXPR, build_pointer_type (fntype), fndecl);
13618   tree *buffer;
13619   int i, j;
13620   va_list ap;
13621   location_t loc = gimple_location (stmt);
13622
13623   buffer = XALLOCAVEC (tree, nargs);
13624   va_start (ap, n);
13625   for (i = 0; i < n; i++)
13626     buffer[i] = va_arg (ap, tree);
13627   va_end (ap);
13628   for (j = skip; j < oldnargs; j++, i++)
13629     buffer[i] = gimple_call_arg (stmt, j);
13630
13631   return fold (build_call_array_loc (loc, TREE_TYPE (fntype), fn, nargs, buffer));
13632 }
13633
13634 /* Fold a call STMT to __{,v}sprintf_chk.  Return NULL_TREE if
13635    a normal call should be emitted rather than expanding the function
13636    inline.  FCODE is either BUILT_IN_SPRINTF_CHK or BUILT_IN_VSPRINTF_CHK.  */
13637
13638 static tree
13639 gimple_fold_builtin_sprintf_chk (gimple stmt, enum built_in_function fcode)
13640 {
13641   tree dest, size, len, fn, fmt, flag;
13642   const char *fmt_str;
13643   int nargs = gimple_call_num_args (stmt);
13644
13645   /* Verify the required arguments in the original call.  */
13646   if (nargs < 4)
13647     return NULL_TREE;
13648   dest = gimple_call_arg (stmt, 0);
13649   if (!validate_arg (dest, POINTER_TYPE))
13650     return NULL_TREE;
13651   flag = gimple_call_arg (stmt, 1);
13652   if (!validate_arg (flag, INTEGER_TYPE))
13653     return NULL_TREE;
13654   size = gimple_call_arg (stmt, 2);
13655   if (!validate_arg (size, INTEGER_TYPE))
13656     return NULL_TREE;
13657   fmt = gimple_call_arg (stmt, 3);
13658   if (!validate_arg (fmt, POINTER_TYPE))
13659     return NULL_TREE;
13660
13661   if (! host_integerp (size, 1))
13662     return NULL_TREE;
13663
13664   len = NULL_TREE;
13665
13666   if (!init_target_chars ())
13667     return NULL_TREE;
13668
13669   /* Check whether the format is a literal string constant.  */
13670   fmt_str = c_getstr (fmt);
13671   if (fmt_str != NULL)
13672     {
13673       /* If the format doesn't contain % args or %%, we know the size.  */
13674       if (strchr (fmt_str, target_percent) == 0)
13675         {
13676           if (fcode != BUILT_IN_SPRINTF_CHK || nargs == 4)
13677             len = build_int_cstu (size_type_node, strlen (fmt_str));
13678         }
13679       /* If the format is "%s" and first ... argument is a string literal,
13680          we know the size too.  */
13681       else if (fcode == BUILT_IN_SPRINTF_CHK
13682                && strcmp (fmt_str, target_percent_s) == 0)
13683         {
13684           tree arg;
13685
13686           if (nargs == 5)
13687             {
13688               arg = gimple_call_arg (stmt, 4);
13689               if (validate_arg (arg, POINTER_TYPE))
13690                 {
13691                   len = c_strlen (arg, 1);
13692                   if (! len || ! host_integerp (len, 1))
13693                     len = NULL_TREE;
13694                 }
13695             }
13696         }
13697     }
13698
13699   if (! integer_all_onesp (size))
13700     {
13701       if (! len || ! tree_int_cst_lt (len, size))
13702         return NULL_TREE;
13703     }
13704
13705   /* Only convert __{,v}sprintf_chk to {,v}sprintf if flag is 0
13706      or if format doesn't contain % chars or is "%s".  */
13707   if (! integer_zerop (flag))
13708     {
13709       if (fmt_str == NULL)
13710         return NULL_TREE;
13711       if (strchr (fmt_str, target_percent) != NULL
13712           && strcmp (fmt_str, target_percent_s))
13713         return NULL_TREE;
13714     }
13715
13716   /* If __builtin_{,v}sprintf_chk is used, assume {,v}sprintf is available.  */
13717   fn = built_in_decls[fcode == BUILT_IN_VSPRINTF_CHK
13718                       ? BUILT_IN_VSPRINTF : BUILT_IN_SPRINTF];
13719   if (!fn)
13720     return NULL_TREE;
13721
13722   return gimple_rewrite_call_expr (stmt, 4, fn, 2, dest, fmt);
13723 }
13724
13725 /* Fold a call STMT to {,v}snprintf.  Return NULL_TREE if
13726    a normal call should be emitted rather than expanding the function
13727    inline.  FCODE is either BUILT_IN_SNPRINTF_CHK or
13728    BUILT_IN_VSNPRINTF_CHK.  If MAXLEN is not NULL, it is maximum length
13729    passed as second argument.  */
13730
13731 tree
13732 gimple_fold_builtin_snprintf_chk (gimple stmt, tree maxlen,
13733                                   enum built_in_function fcode)
13734 {
13735   tree dest, size, len, fn, fmt, flag;
13736   const char *fmt_str;
13737
13738   /* Verify the required arguments in the original call.  */
13739   if (gimple_call_num_args (stmt) < 5)
13740     return NULL_TREE;
13741   dest = gimple_call_arg (stmt, 0);
13742   if (!validate_arg (dest, POINTER_TYPE))
13743     return NULL_TREE;
13744   len = gimple_call_arg (stmt, 1);
13745   if (!validate_arg (len, INTEGER_TYPE))
13746     return NULL_TREE;
13747   flag = gimple_call_arg (stmt, 2);
13748   if (!validate_arg (flag, INTEGER_TYPE))
13749     return NULL_TREE;
13750   size = gimple_call_arg (stmt, 3);
13751   if (!validate_arg (size, INTEGER_TYPE))
13752     return NULL_TREE;
13753   fmt = gimple_call_arg (stmt, 4);
13754   if (!validate_arg (fmt, POINTER_TYPE))
13755     return NULL_TREE;
13756
13757   if (! host_integerp (size, 1))
13758     return NULL_TREE;
13759
13760   if (! integer_all_onesp (size))
13761     {
13762       if (! host_integerp (len, 1))
13763         {
13764           /* If LEN is not constant, try MAXLEN too.
13765              For MAXLEN only allow optimizing into non-_ocs function
13766              if SIZE is >= MAXLEN, never convert to __ocs_fail ().  */
13767           if (maxlen == NULL_TREE || ! host_integerp (maxlen, 1))
13768             return NULL_TREE;
13769         }
13770       else
13771         maxlen = len;
13772
13773       if (tree_int_cst_lt (size, maxlen))
13774         return NULL_TREE;
13775     }
13776
13777   if (!init_target_chars ())
13778     return NULL_TREE;
13779
13780   /* Only convert __{,v}snprintf_chk to {,v}snprintf if flag is 0
13781      or if format doesn't contain % chars or is "%s".  */
13782   if (! integer_zerop (flag))
13783     {
13784       fmt_str = c_getstr (fmt);
13785       if (fmt_str == NULL)
13786         return NULL_TREE;
13787       if (strchr (fmt_str, target_percent) != NULL
13788           && strcmp (fmt_str, target_percent_s))
13789         return NULL_TREE;
13790     }
13791
13792   /* If __builtin_{,v}snprintf_chk is used, assume {,v}snprintf is
13793      available.  */
13794   fn = built_in_decls[fcode == BUILT_IN_VSNPRINTF_CHK
13795                       ? BUILT_IN_VSNPRINTF : BUILT_IN_SNPRINTF];
13796   if (!fn)
13797     return NULL_TREE;
13798
13799   return gimple_rewrite_call_expr (stmt, 5, fn, 3, dest, len, fmt);
13800 }
13801
13802 /* Builtins with folding operations that operate on "..." arguments
13803    need special handling; we need to store the arguments in a convenient
13804    data structure before attempting any folding.  Fortunately there are
13805    only a few builtins that fall into this category.  FNDECL is the
13806    function, EXP is the CALL_EXPR for the call, and IGNORE is true if the
13807    result of the function call is ignored.  */
13808
13809 static tree
13810 gimple_fold_builtin_varargs (tree fndecl, gimple stmt,
13811                              bool ignore ATTRIBUTE_UNUSED)
13812 {
13813   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
13814   tree ret = NULL_TREE;
13815
13816   switch (fcode)
13817     {
13818     case BUILT_IN_SPRINTF_CHK:
13819     case BUILT_IN_VSPRINTF_CHK:
13820       ret = gimple_fold_builtin_sprintf_chk (stmt, fcode);
13821       break;
13822
13823     case BUILT_IN_SNPRINTF_CHK:
13824     case BUILT_IN_VSNPRINTF_CHK:
13825       ret = gimple_fold_builtin_snprintf_chk (stmt, NULL_TREE, fcode);
13826
13827     default:
13828       break;
13829     }
13830   if (ret)
13831     {
13832       ret = build1 (NOP_EXPR, TREE_TYPE (ret), ret);
13833       TREE_NO_WARNING (ret) = 1;
13834       return ret;
13835     }
13836   return NULL_TREE;
13837 }
13838
13839 /* A wrapper function for builtin folding that prevents warnings for
13840    "statement without effect" and the like, caused by removing the
13841    call node earlier than the warning is generated.  */
13842
13843 tree
13844 fold_call_stmt (gimple stmt, bool ignore)
13845 {
13846   tree ret = NULL_TREE;
13847   tree fndecl = gimple_call_fndecl (stmt);
13848   location_t loc = gimple_location (stmt);
13849   if (fndecl
13850       && TREE_CODE (fndecl) == FUNCTION_DECL
13851       && DECL_BUILT_IN (fndecl)
13852       && !gimple_call_va_arg_pack_p (stmt))
13853     {
13854       int nargs = gimple_call_num_args (stmt);
13855
13856       if (avoid_folding_inline_builtin (fndecl))
13857         return NULL_TREE;
13858       /* FIXME: Don't use a list in this interface.  */
13859       if (DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_MD)
13860         {
13861           tree arglist = NULL_TREE;
13862           int i;
13863           for (i = nargs - 1; i >= 0; i--)
13864             arglist = tree_cons (NULL_TREE, gimple_call_arg (stmt, i), arglist);
13865           return targetm.fold_builtin (fndecl, arglist, ignore);
13866         }
13867       else
13868         {
13869           if (nargs <= MAX_ARGS_TO_FOLD_BUILTIN)
13870             {
13871               tree args[MAX_ARGS_TO_FOLD_BUILTIN];
13872               int i;
13873               for (i = 0; i < nargs; i++)
13874                 args[i] = gimple_call_arg (stmt, i);
13875               ret = fold_builtin_n (loc, fndecl, args, nargs, ignore);
13876             }
13877           if (!ret)
13878             ret = gimple_fold_builtin_varargs (fndecl, stmt, ignore);
13879           if (ret)
13880             {
13881               /* Propagate location information from original call to
13882                  expansion of builtin.  Otherwise things like
13883                  maybe_emit_chk_warning, that operate on the expansion
13884                  of a builtin, will use the wrong location information.  */
13885               if (gimple_has_location (stmt))
13886                 {
13887                   tree realret = ret;
13888                   if (TREE_CODE (ret) == NOP_EXPR)
13889                     realret = TREE_OPERAND (ret, 0);
13890                   if (CAN_HAVE_LOCATION_P (realret)
13891                       && !EXPR_HAS_LOCATION (realret))
13892                     SET_EXPR_LOCATION (realret, loc);
13893                   return realret;
13894                 }
13895               return ret;
13896             }
13897         }
13898     }
13899   return NULL_TREE;
13900 }
13901
13902 /* Look up the function in built_in_decls that corresponds to DECL
13903    and set ASMSPEC as its user assembler name.  DECL must be a
13904    function decl that declares a builtin.  */
13905
13906 void
13907 set_builtin_user_assembler_name (tree decl, const char *asmspec)
13908 {
13909   tree builtin;
13910   gcc_assert (TREE_CODE (decl) == FUNCTION_DECL
13911               && DECL_BUILT_IN_CLASS (decl) == BUILT_IN_NORMAL
13912               && asmspec != 0);
13913
13914   builtin = built_in_decls [DECL_FUNCTION_CODE (decl)];
13915   set_user_assembler_name (builtin, asmspec);
13916   switch (DECL_FUNCTION_CODE (decl))
13917     {
13918     case BUILT_IN_MEMCPY:
13919       init_block_move_fn (asmspec);
13920       memcpy_libfunc = set_user_assembler_libfunc ("memcpy", asmspec);
13921       break;
13922     case BUILT_IN_MEMSET:
13923       init_block_clear_fn (asmspec);
13924       memset_libfunc = set_user_assembler_libfunc ("memset", asmspec);
13925       break;
13926     case BUILT_IN_MEMMOVE:
13927       memmove_libfunc = set_user_assembler_libfunc ("memmove", asmspec);
13928       break;
13929     case BUILT_IN_MEMCMP:
13930       memcmp_libfunc = set_user_assembler_libfunc ("memcmp", asmspec);
13931       break;
13932     case BUILT_IN_ABORT:
13933       abort_libfunc = set_user_assembler_libfunc ("abort", asmspec);
13934       break;
13935     default:
13936       break;
13937     }
13938 }