OSDN Git Service

2010-08-04 Tobias Burnus <burnus@net-b.de>
[pf3gnuchains/gcc-fork.git] / gcc / builtins.c
1 /* Expand builtin functions.
2    Copyright (C) 1988, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
3    2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010
4    Free Software Foundation, Inc.
5
6 This file is part of GCC.
7
8 GCC is free software; you can redistribute it and/or modify it under
9 the terms of the GNU General Public License as published by the Free
10 Software Foundation; either version 3, or (at your option) any later
11 version.
12
13 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
14 WARRANTY; without even the implied warranty of MERCHANTABILITY or
15 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
16 for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with GCC; see the file COPYING3.  If not see
20 <http://www.gnu.org/licenses/>.  */
21
22 #include "config.h"
23 #include "system.h"
24 #include "coretypes.h"
25 #include "tm.h"
26 #include "machmode.h"
27 #include "rtl.h"
28 #include "tree.h"
29 #include "realmpfr.h"
30 #include "gimple.h"
31 #include "flags.h"
32 #include "regs.h"
33 #include "hard-reg-set.h"
34 #include "except.h"
35 #include "function.h"
36 #include "insn-config.h"
37 #include "expr.h"
38 #include "optabs.h"
39 #include "libfuncs.h"
40 #include "recog.h"
41 #include "output.h"
42 #include "typeclass.h"
43 #include "toplev.h"
44 #include "predict.h"
45 #include "tm_p.h"
46 #include "target.h"
47 #include "langhooks.h"
48 #include "basic-block.h"
49 #include "tree-mudflap.h"
50 #include "tree-flow.h"
51 #include "value-prof.h"
52 #include "diagnostic-core.h"
53 #include "builtins.h"
54
55 #ifndef SLOW_UNALIGNED_ACCESS
56 #define SLOW_UNALIGNED_ACCESS(MODE, ALIGN) STRICT_ALIGNMENT
57 #endif
58
59 #ifndef PAD_VARARGS_DOWN
60 #define PAD_VARARGS_DOWN BYTES_BIG_ENDIAN
61 #endif
62 static tree do_mpc_arg1 (tree, tree, int (*)(mpc_ptr, mpc_srcptr, mpc_rnd_t));
63
64 struct target_builtins default_target_builtins;
65 #if SWITCHABLE_TARGET
66 struct target_builtins *this_target_builtins = &default_target_builtins;
67 #endif
68
69 /* Define the names of the builtin function types and codes.  */
70 const char *const built_in_class_names[4]
71   = {"NOT_BUILT_IN", "BUILT_IN_FRONTEND", "BUILT_IN_MD", "BUILT_IN_NORMAL"};
72
73 #define DEF_BUILTIN(X, N, C, T, LT, B, F, NA, AT, IM, COND) #X,
74 const char * built_in_names[(int) END_BUILTINS] =
75 {
76 #include "builtins.def"
77 };
78 #undef DEF_BUILTIN
79
80 /* Setup an array of _DECL trees, make sure each element is
81    initialized to NULL_TREE.  */
82 tree built_in_decls[(int) END_BUILTINS];
83 /* Declarations used when constructing the builtin implicitly in the compiler.
84    It may be NULL_TREE when this is invalid (for instance runtime is not
85    required to implement the function call in all cases).  */
86 tree implicit_built_in_decls[(int) END_BUILTINS];
87
88 static const char *c_getstr (tree);
89 static rtx c_readstr (const char *, enum machine_mode);
90 static int target_char_cast (tree, char *);
91 static rtx get_memory_rtx (tree, tree);
92 static int apply_args_size (void);
93 static int apply_result_size (void);
94 #if defined (HAVE_untyped_call) || defined (HAVE_untyped_return)
95 static rtx result_vector (int, rtx);
96 #endif
97 static void expand_builtin_update_setjmp_buf (rtx);
98 static void expand_builtin_prefetch (tree);
99 static rtx expand_builtin_apply_args (void);
100 static rtx expand_builtin_apply_args_1 (void);
101 static rtx expand_builtin_apply (rtx, rtx, rtx);
102 static void expand_builtin_return (rtx);
103 static enum type_class type_to_class (tree);
104 static rtx expand_builtin_classify_type (tree);
105 static void expand_errno_check (tree, rtx);
106 static rtx expand_builtin_mathfn (tree, rtx, rtx);
107 static rtx expand_builtin_mathfn_2 (tree, rtx, rtx);
108 static rtx expand_builtin_mathfn_3 (tree, rtx, rtx);
109 static rtx expand_builtin_interclass_mathfn (tree, rtx, rtx);
110 static rtx expand_builtin_sincos (tree);
111 static rtx expand_builtin_cexpi (tree, rtx, rtx);
112 static rtx expand_builtin_int_roundingfn (tree, rtx);
113 static rtx expand_builtin_int_roundingfn_2 (tree, rtx);
114 static rtx expand_builtin_next_arg (void);
115 static rtx expand_builtin_va_start (tree);
116 static rtx expand_builtin_va_end (tree);
117 static rtx expand_builtin_va_copy (tree);
118 static rtx expand_builtin_memcmp (tree, rtx, enum machine_mode);
119 static rtx expand_builtin_strcmp (tree, rtx);
120 static rtx expand_builtin_strncmp (tree, rtx, enum machine_mode);
121 static rtx builtin_memcpy_read_str (void *, HOST_WIDE_INT, enum machine_mode);
122 static rtx expand_builtin_memcpy (tree, rtx);
123 static rtx expand_builtin_mempcpy (tree, rtx, enum machine_mode);
124 static rtx expand_builtin_mempcpy_args (tree, tree, tree, rtx,
125                                         enum machine_mode, int);
126 static rtx expand_builtin_strcpy (tree, rtx);
127 static rtx expand_builtin_strcpy_args (tree, tree, rtx);
128 static rtx expand_builtin_stpcpy (tree, rtx, enum machine_mode);
129 static rtx expand_builtin_strncpy (tree, rtx);
130 static rtx builtin_memset_gen_str (void *, HOST_WIDE_INT, enum machine_mode);
131 static rtx expand_builtin_memset (tree, rtx, enum machine_mode);
132 static rtx expand_builtin_memset_args (tree, tree, tree, rtx, enum machine_mode, tree);
133 static rtx expand_builtin_bzero (tree);
134 static rtx expand_builtin_strlen (tree, rtx, enum machine_mode);
135 static rtx expand_builtin_alloca (tree, rtx);
136 static rtx expand_builtin_unop (enum machine_mode, tree, rtx, rtx, optab);
137 static rtx expand_builtin_frame_address (tree, tree);
138 static tree stabilize_va_list_loc (location_t, tree, int);
139 static rtx expand_builtin_expect (tree, rtx);
140 static tree fold_builtin_constant_p (tree);
141 static tree fold_builtin_expect (location_t, tree, tree);
142 static tree fold_builtin_classify_type (tree);
143 static tree fold_builtin_strlen (location_t, tree, tree);
144 static tree fold_builtin_inf (location_t, tree, int);
145 static tree fold_builtin_nan (tree, tree, int);
146 static tree rewrite_call_expr (location_t, tree, int, tree, int, ...);
147 static bool validate_arg (const_tree, enum tree_code code);
148 static bool integer_valued_real_p (tree);
149 static tree fold_trunc_transparent_mathfn (location_t, tree, tree);
150 static bool readonly_data_expr (tree);
151 static rtx expand_builtin_fabs (tree, rtx, rtx);
152 static rtx expand_builtin_signbit (tree, rtx);
153 static tree fold_builtin_sqrt (location_t, tree, tree);
154 static tree fold_builtin_cbrt (location_t, tree, tree);
155 static tree fold_builtin_pow (location_t, tree, tree, tree, tree);
156 static tree fold_builtin_powi (location_t, tree, tree, tree, tree);
157 static tree fold_builtin_cos (location_t, tree, tree, tree);
158 static tree fold_builtin_cosh (location_t, tree, tree, tree);
159 static tree fold_builtin_tan (tree, tree);
160 static tree fold_builtin_trunc (location_t, tree, tree);
161 static tree fold_builtin_floor (location_t, tree, tree);
162 static tree fold_builtin_ceil (location_t, tree, tree);
163 static tree fold_builtin_round (location_t, tree, tree);
164 static tree fold_builtin_int_roundingfn (location_t, tree, tree);
165 static tree fold_builtin_bitop (tree, tree);
166 static tree fold_builtin_memory_op (location_t, tree, tree, tree, tree, bool, int);
167 static tree fold_builtin_strchr (location_t, tree, tree, tree);
168 static tree fold_builtin_memchr (location_t, tree, tree, tree, tree);
169 static tree fold_builtin_memcmp (location_t, tree, tree, tree);
170 static tree fold_builtin_strcmp (location_t, tree, tree);
171 static tree fold_builtin_strncmp (location_t, tree, tree, tree);
172 static tree fold_builtin_signbit (location_t, tree, tree);
173 static tree fold_builtin_copysign (location_t, tree, tree, tree, tree);
174 static tree fold_builtin_isascii (location_t, tree);
175 static tree fold_builtin_toascii (location_t, tree);
176 static tree fold_builtin_isdigit (location_t, tree);
177 static tree fold_builtin_fabs (location_t, tree, tree);
178 static tree fold_builtin_abs (location_t, tree, tree);
179 static tree fold_builtin_unordered_cmp (location_t, tree, tree, tree, enum tree_code,
180                                         enum tree_code);
181 static tree fold_builtin_n (location_t, tree, tree *, int, bool);
182 static tree fold_builtin_0 (location_t, tree, bool);
183 static tree fold_builtin_1 (location_t, tree, tree, bool);
184 static tree fold_builtin_2 (location_t, tree, tree, tree, bool);
185 static tree fold_builtin_3 (location_t, tree, tree, tree, tree, bool);
186 static tree fold_builtin_4 (location_t, tree, tree, tree, tree, tree, bool);
187 static tree fold_builtin_varargs (location_t, tree, tree, bool);
188
189 static tree fold_builtin_strpbrk (location_t, tree, tree, tree);
190 static tree fold_builtin_strstr (location_t, tree, tree, tree);
191 static tree fold_builtin_strrchr (location_t, tree, tree, tree);
192 static tree fold_builtin_strcat (location_t, tree, tree);
193 static tree fold_builtin_strncat (location_t, tree, tree, tree);
194 static tree fold_builtin_strspn (location_t, tree, tree);
195 static tree fold_builtin_strcspn (location_t, tree, tree);
196 static tree fold_builtin_sprintf (location_t, tree, tree, tree, int);
197
198 static rtx expand_builtin_object_size (tree);
199 static rtx expand_builtin_memory_chk (tree, rtx, enum machine_mode,
200                                       enum built_in_function);
201 static void maybe_emit_chk_warning (tree, enum built_in_function);
202 static void maybe_emit_sprintf_chk_warning (tree, enum built_in_function);
203 static void maybe_emit_free_warning (tree);
204 static tree fold_builtin_object_size (tree, tree);
205 static tree fold_builtin_strcat_chk (location_t, tree, tree, tree, tree);
206 static tree fold_builtin_strncat_chk (location_t, tree, tree, tree, tree, tree);
207 static tree fold_builtin_sprintf_chk (location_t, tree, enum built_in_function);
208 static tree fold_builtin_printf (location_t, tree, tree, tree, bool, enum built_in_function);
209 static tree fold_builtin_fprintf (location_t, tree, tree, tree, tree, bool,
210                                   enum built_in_function);
211 static bool init_target_chars (void);
212
213 static unsigned HOST_WIDE_INT target_newline;
214 static unsigned HOST_WIDE_INT target_percent;
215 static unsigned HOST_WIDE_INT target_c;
216 static unsigned HOST_WIDE_INT target_s;
217 static char target_percent_c[3];
218 static char target_percent_s[3];
219 static char target_percent_s_newline[4];
220 static tree do_mpfr_arg1 (tree, tree, int (*)(mpfr_ptr, mpfr_srcptr, mp_rnd_t),
221                           const REAL_VALUE_TYPE *, const REAL_VALUE_TYPE *, bool);
222 static tree do_mpfr_arg2 (tree, tree, tree,
223                           int (*)(mpfr_ptr, mpfr_srcptr, mpfr_srcptr, mp_rnd_t));
224 static tree do_mpfr_arg3 (tree, tree, tree, tree,
225                           int (*)(mpfr_ptr, mpfr_srcptr, mpfr_srcptr, mpfr_srcptr, mp_rnd_t));
226 static tree do_mpfr_sincos (tree, tree, tree);
227 static tree do_mpfr_bessel_n (tree, tree, tree,
228                               int (*)(mpfr_ptr, long, mpfr_srcptr, mp_rnd_t),
229                               const REAL_VALUE_TYPE *, bool);
230 static tree do_mpfr_remquo (tree, tree, tree);
231 static tree do_mpfr_lgamma_r (tree, tree, tree);
232
233 /* Return true if NAME starts with __builtin_ or __sync_.  */
234
235 bool
236 is_builtin_name (const char *name)
237 {
238   if (strncmp (name, "__builtin_", 10) == 0)
239     return true;
240   if (strncmp (name, "__sync_", 7) == 0)
241     return true;
242   return false;
243 }
244
245
246 /* Return true if DECL is a function symbol representing a built-in.  */
247
248 bool
249 is_builtin_fn (tree decl)
250 {
251   return TREE_CODE (decl) == FUNCTION_DECL && DECL_BUILT_IN (decl);
252 }
253
254
255 /* Return true if NODE should be considered for inline expansion regardless
256    of the optimization level.  This means whenever a function is invoked with
257    its "internal" name, which normally contains the prefix "__builtin".  */
258
259 static bool
260 called_as_built_in (tree node)
261 {
262   /* Note that we must use DECL_NAME, not DECL_ASSEMBLER_NAME_SET_P since
263      we want the name used to call the function, not the name it
264      will have. */
265   const char *name = IDENTIFIER_POINTER (DECL_NAME (node));
266   return is_builtin_name (name);
267 }
268
269 /* Return the alignment in bits of EXP, an object.
270    Don't return more than MAX_ALIGN no matter what, 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 (TREE_CODE (exp) == CONST_DECL)
332     exp = DECL_INITIAL (exp);
333   if (DECL_P (exp)
334       && TREE_CODE (exp) != LABEL_DECL)
335     align = MIN (inner, DECL_ALIGN (exp));
336 #ifdef CONSTANT_ALIGNMENT
337   else if (CONSTANT_CLASS_P (exp))
338     align = MIN (inner, (unsigned)CONSTANT_ALIGNMENT (exp, align));
339 #endif
340   else if (TREE_CODE (exp) == VIEW_CONVERT_EXPR
341            || TREE_CODE (exp) == INDIRECT_REF)
342     align = MIN (TYPE_ALIGN (TREE_TYPE (exp)), inner);
343   else
344     align = MIN (align, inner);
345   return MIN (align, max_align);
346 }
347
348 /* Returns true iff we can trust that alignment information has been
349    calculated properly.  */
350
351 bool
352 can_trust_pointer_alignment (void)
353 {
354   /* We rely on TER to compute accurate alignment information.  */
355   return (optimize && flag_tree_ter);
356 }
357
358 /* Return the alignment in bits of EXP, a pointer valued expression.
359    But don't return more than MAX_ALIGN no matter what.
360    The alignment returned is, by default, the alignment of the thing that
361    EXP points to.  If it is not a POINTER_TYPE, 0 is returned.
362
363    Otherwise, look at the expression to see if we can do better, i.e., if the
364    expression is actually pointing at an object whose alignment is tighter.  */
365
366 int
367 get_pointer_alignment (tree exp, unsigned int max_align)
368 {
369   unsigned int align, inner;
370
371   if (!can_trust_pointer_alignment ())
372     return 0;
373
374   if (!POINTER_TYPE_P (TREE_TYPE (exp)))
375     return 0;
376
377   align = TYPE_ALIGN (TREE_TYPE (TREE_TYPE (exp)));
378   align = MIN (align, max_align);
379
380   while (1)
381     {
382       switch (TREE_CODE (exp))
383         {
384         CASE_CONVERT:
385           exp = TREE_OPERAND (exp, 0);
386           if (! POINTER_TYPE_P (TREE_TYPE (exp)))
387             return align;
388
389           inner = TYPE_ALIGN (TREE_TYPE (TREE_TYPE (exp)));
390           align = MIN (inner, max_align);
391           break;
392
393         case POINTER_PLUS_EXPR:
394           /* If sum of pointer + int, restrict our maximum alignment to that
395              imposed by the integer.  If not, we can't do any better than
396              ALIGN.  */
397           if (! host_integerp (TREE_OPERAND (exp, 1), 1))
398             return align;
399
400           while (((tree_low_cst (TREE_OPERAND (exp, 1), 1))
401                   & (max_align / BITS_PER_UNIT - 1))
402                  != 0)
403             max_align >>= 1;
404
405           exp = TREE_OPERAND (exp, 0);
406           break;
407
408         case ADDR_EXPR:
409           /* See what we are pointing at and look at its alignment.  */
410           return get_object_alignment (TREE_OPERAND (exp, 0), align, max_align);
411
412         default:
413           return align;
414         }
415     }
416 }
417
418 /* Compute the length of a C string.  TREE_STRING_LENGTH is not the right
419    way, because it could contain a zero byte in the middle.
420    TREE_STRING_LENGTH is the size of the character array, not the string.
421
422    ONLY_VALUE should be nonzero if the result is not going to be emitted
423    into the instruction stream and zero if it is going to be expanded.
424    E.g. with i++ ? "foo" : "bar", if ONLY_VALUE is nonzero, constant 3
425    is returned, otherwise NULL, since
426    len = c_strlen (src, 1); if (len) expand_expr (len, ...); would not
427    evaluate the side-effects.
428
429    The value returned is of type `ssizetype'.
430
431    Unfortunately, string_constant can't access the values of const char
432    arrays with initializers, so neither can we do so here.  */
433
434 tree
435 c_strlen (tree src, int only_value)
436 {
437   tree offset_node;
438   HOST_WIDE_INT offset;
439   int max;
440   const char *ptr;
441   location_t loc;
442
443   STRIP_NOPS (src);
444   if (TREE_CODE (src) == COND_EXPR
445       && (only_value || !TREE_SIDE_EFFECTS (TREE_OPERAND (src, 0))))
446     {
447       tree len1, len2;
448
449       len1 = c_strlen (TREE_OPERAND (src, 1), only_value);
450       len2 = c_strlen (TREE_OPERAND (src, 2), only_value);
451       if (tree_int_cst_equal (len1, len2))
452         return len1;
453     }
454
455   if (TREE_CODE (src) == COMPOUND_EXPR
456       && (only_value || !TREE_SIDE_EFFECTS (TREE_OPERAND (src, 0))))
457     return c_strlen (TREE_OPERAND (src, 1), only_value);
458
459   if (EXPR_HAS_LOCATION (src))
460     loc = EXPR_LOCATION (src);
461   else
462     loc = input_location;
463
464   src = string_constant (src, &offset_node);
465   if (src == 0)
466     return NULL_TREE;
467
468   max = TREE_STRING_LENGTH (src) - 1;
469   ptr = TREE_STRING_POINTER (src);
470
471   if (offset_node && TREE_CODE (offset_node) != INTEGER_CST)
472     {
473       /* If the string has an internal zero byte (e.g., "foo\0bar"), we can't
474          compute the offset to the following null if we don't know where to
475          start searching for it.  */
476       int i;
477
478       for (i = 0; i < max; i++)
479         if (ptr[i] == 0)
480           return NULL_TREE;
481
482       /* We don't know the starting offset, but we do know that the string
483          has no internal zero bytes.  We can assume that the offset falls
484          within the bounds of the string; otherwise, the programmer deserves
485          what he gets.  Subtract the offset from the length of the string,
486          and return that.  This would perhaps not be valid if we were dealing
487          with named arrays in addition to literal string constants.  */
488
489       return size_diffop_loc (loc, size_int (max), offset_node);
490     }
491
492   /* We have a known offset into the string.  Start searching there for
493      a null character if we can represent it as a single HOST_WIDE_INT.  */
494   if (offset_node == 0)
495     offset = 0;
496   else if (! host_integerp (offset_node, 0))
497     offset = -1;
498   else
499     offset = tree_low_cst (offset_node, 0);
500
501   /* If the offset is known to be out of bounds, warn, and call strlen at
502      runtime.  */
503   if (offset < 0 || offset > max)
504     {
505      /* Suppress multiple warnings for propagated constant strings.  */
506       if (! TREE_NO_WARNING (src))
507         {
508           warning_at (loc, 0, "offset outside bounds of constant string");
509           TREE_NO_WARNING (src) = 1;
510         }
511       return NULL_TREE;
512     }
513
514   /* Use strlen to search for the first zero byte.  Since any strings
515      constructed with build_string will have nulls appended, we win even
516      if we get handed something like (char[4])"abcd".
517
518      Since OFFSET is our starting index into the string, no further
519      calculation is needed.  */
520   return ssize_int (strlen (ptr + offset));
521 }
522
523 /* Return a char pointer for a C string if it is a string constant
524    or sum of string constant and integer constant.  */
525
526 static const char *
527 c_getstr (tree src)
528 {
529   tree offset_node;
530
531   src = string_constant (src, &offset_node);
532   if (src == 0)
533     return 0;
534
535   if (offset_node == 0)
536     return TREE_STRING_POINTER (src);
537   else if (!host_integerp (offset_node, 1)
538            || compare_tree_int (offset_node, TREE_STRING_LENGTH (src) - 1) > 0)
539     return 0;
540
541   return TREE_STRING_POINTER (src) + tree_low_cst (offset_node, 1);
542 }
543
544 /* Return a CONST_INT or CONST_DOUBLE corresponding to target reading
545    GET_MODE_BITSIZE (MODE) bits from string constant STR.  */
546
547 static rtx
548 c_readstr (const char *str, enum machine_mode mode)
549 {
550   HOST_WIDE_INT c[2];
551   HOST_WIDE_INT ch;
552   unsigned int i, j;
553
554   gcc_assert (GET_MODE_CLASS (mode) == MODE_INT);
555
556   c[0] = 0;
557   c[1] = 0;
558   ch = 1;
559   for (i = 0; i < GET_MODE_SIZE (mode); i++)
560     {
561       j = i;
562       if (WORDS_BIG_ENDIAN)
563         j = GET_MODE_SIZE (mode) - i - 1;
564       if (BYTES_BIG_ENDIAN != WORDS_BIG_ENDIAN
565           && GET_MODE_SIZE (mode) > UNITS_PER_WORD)
566         j = j + UNITS_PER_WORD - 2 * (j % UNITS_PER_WORD) - 1;
567       j *= BITS_PER_UNIT;
568       gcc_assert (j < 2 * HOST_BITS_PER_WIDE_INT);
569
570       if (ch)
571         ch = (unsigned char) str[i];
572       c[j / HOST_BITS_PER_WIDE_INT] |= ch << (j % HOST_BITS_PER_WIDE_INT);
573     }
574   return immed_double_const (c[0], c[1], mode);
575 }
576
577 /* Cast a target constant CST to target CHAR and if that value fits into
578    host char type, return zero and put that value into variable pointed to by
579    P.  */
580
581 static int
582 target_char_cast (tree cst, char *p)
583 {
584   unsigned HOST_WIDE_INT val, hostval;
585
586   if (!host_integerp (cst, 1)
587       || CHAR_TYPE_SIZE > HOST_BITS_PER_WIDE_INT)
588     return 1;
589
590   val = tree_low_cst (cst, 1);
591   if (CHAR_TYPE_SIZE < HOST_BITS_PER_WIDE_INT)
592     val &= (((unsigned HOST_WIDE_INT) 1) << CHAR_TYPE_SIZE) - 1;
593
594   hostval = val;
595   if (HOST_BITS_PER_CHAR < HOST_BITS_PER_WIDE_INT)
596     hostval &= (((unsigned HOST_WIDE_INT) 1) << HOST_BITS_PER_CHAR) - 1;
597
598   if (val != hostval)
599     return 1;
600
601   *p = hostval;
602   return 0;
603 }
604
605 /* Similar to save_expr, but assumes that arbitrary code is not executed
606    in between the multiple evaluations.  In particular, we assume that a
607    non-addressable local variable will not be modified.  */
608
609 static tree
610 builtin_save_expr (tree exp)
611 {
612   if (TREE_ADDRESSABLE (exp) == 0
613       && (TREE_CODE (exp) == PARM_DECL
614           || (TREE_CODE (exp) == VAR_DECL && !TREE_STATIC (exp))))
615     return exp;
616
617   return save_expr (exp);
618 }
619
620 /* Given TEM, a pointer to a stack frame, follow the dynamic chain COUNT
621    times to get the address of either a higher stack frame, or a return
622    address located within it (depending on FNDECL_CODE).  */
623
624 static rtx
625 expand_builtin_return_addr (enum built_in_function fndecl_code, int count)
626 {
627   int i;
628
629 #ifdef INITIAL_FRAME_ADDRESS_RTX
630   rtx tem = INITIAL_FRAME_ADDRESS_RTX;
631 #else
632   rtx tem;
633
634   /* For a zero count with __builtin_return_address, we don't care what
635      frame address we return, because target-specific definitions will
636      override us.  Therefore frame pointer elimination is OK, and using
637      the soft frame pointer is OK.
638
639      For a nonzero count, or a zero count with __builtin_frame_address,
640      we require a stable offset from the current frame pointer to the
641      previous one, so we must use the hard frame pointer, and
642      we must disable frame pointer elimination.  */
643   if (count == 0 && fndecl_code == BUILT_IN_RETURN_ADDRESS)
644     tem = frame_pointer_rtx;
645   else
646     {
647       tem = hard_frame_pointer_rtx;
648
649       /* Tell reload not to eliminate the frame pointer.  */
650       crtl->accesses_prior_frames = 1;
651     }
652 #endif
653
654   /* Some machines need special handling before we can access
655      arbitrary frames.  For example, on the SPARC, we must first flush
656      all register windows to the stack.  */
657 #ifdef SETUP_FRAME_ADDRESSES
658   if (count > 0)
659     SETUP_FRAME_ADDRESSES ();
660 #endif
661
662   /* On the SPARC, the return address is not in the frame, it is in a
663      register.  There is no way to access it off of the current frame
664      pointer, but it can be accessed off the previous frame pointer by
665      reading the value from the register window save area.  */
666 #ifdef RETURN_ADDR_IN_PREVIOUS_FRAME
667   if (fndecl_code == BUILT_IN_RETURN_ADDRESS)
668     count--;
669 #endif
670
671   /* Scan back COUNT frames to the specified frame.  */
672   for (i = 0; i < count; i++)
673     {
674       /* Assume the dynamic chain pointer is in the word that the
675          frame address points to, unless otherwise specified.  */
676 #ifdef DYNAMIC_CHAIN_ADDRESS
677       tem = DYNAMIC_CHAIN_ADDRESS (tem);
678 #endif
679       tem = memory_address (Pmode, tem);
680       tem = gen_frame_mem (Pmode, tem);
681       tem = copy_to_reg (tem);
682     }
683
684   /* For __builtin_frame_address, return what we've got.  But, on
685      the SPARC for example, we may have to add a bias.  */
686   if (fndecl_code == BUILT_IN_FRAME_ADDRESS)
687 #ifdef FRAME_ADDR_RTX
688     return FRAME_ADDR_RTX (tem);
689 #else
690     return tem;
691 #endif
692
693   /* For __builtin_return_address, get the return address from that frame.  */
694 #ifdef RETURN_ADDR_RTX
695   tem = RETURN_ADDR_RTX (count, tem);
696 #else
697   tem = memory_address (Pmode,
698                         plus_constant (tem, GET_MODE_SIZE (Pmode)));
699   tem = gen_frame_mem (Pmode, tem);
700 #endif
701   return tem;
702 }
703
704 /* Alias set used for setjmp buffer.  */
705 static alias_set_type setjmp_alias_set = -1;
706
707 /* Construct the leading half of a __builtin_setjmp call.  Control will
708    return to RECEIVER_LABEL.  This is also called directly by the SJLJ
709    exception handling code.  */
710
711 void
712 expand_builtin_setjmp_setup (rtx buf_addr, rtx receiver_label)
713 {
714   enum machine_mode sa_mode = STACK_SAVEAREA_MODE (SAVE_NONLOCAL);
715   rtx stack_save;
716   rtx mem;
717
718   if (setjmp_alias_set == -1)
719     setjmp_alias_set = new_alias_set ();
720
721   buf_addr = convert_memory_address (Pmode, buf_addr);
722
723   buf_addr = force_reg (Pmode, force_operand (buf_addr, NULL_RTX));
724
725   /* We store the frame pointer and the address of receiver_label in
726      the buffer and use the rest of it for the stack save area, which
727      is machine-dependent.  */
728
729   mem = gen_rtx_MEM (Pmode, buf_addr);
730   set_mem_alias_set (mem, setjmp_alias_set);
731   emit_move_insn (mem, targetm.builtin_setjmp_frame_value ());
732
733   mem = gen_rtx_MEM (Pmode, plus_constant (buf_addr, GET_MODE_SIZE (Pmode))),
734   set_mem_alias_set (mem, setjmp_alias_set);
735
736   emit_move_insn (validize_mem (mem),
737                   force_reg (Pmode, gen_rtx_LABEL_REF (Pmode, receiver_label)));
738
739   stack_save = gen_rtx_MEM (sa_mode,
740                             plus_constant (buf_addr,
741                                            2 * GET_MODE_SIZE (Pmode)));
742   set_mem_alias_set (stack_save, setjmp_alias_set);
743   emit_stack_save (SAVE_NONLOCAL, &stack_save, NULL_RTX);
744
745   /* If there is further processing to do, do it.  */
746 #ifdef HAVE_builtin_setjmp_setup
747   if (HAVE_builtin_setjmp_setup)
748     emit_insn (gen_builtin_setjmp_setup (buf_addr));
749 #endif
750
751   /* Tell optimize_save_area_alloca that extra work is going to
752      need to go on during alloca.  */
753   cfun->calls_setjmp = 1;
754
755   /* We have a nonlocal label.   */
756   cfun->has_nonlocal_label = 1;
757 }
758
759 /* Construct the trailing part of a __builtin_setjmp call.  This is
760    also called directly by the SJLJ exception handling code.  */
761
762 void
763 expand_builtin_setjmp_receiver (rtx receiver_label ATTRIBUTE_UNUSED)
764 {
765   rtx chain;
766
767   /* Clobber the FP when we get here, so we have to make sure it's
768      marked as used by this function.  */
769   emit_use (hard_frame_pointer_rtx);
770
771   /* Mark the static chain as clobbered here so life information
772      doesn't get messed up for it.  */
773   chain = targetm.calls.static_chain (current_function_decl, true);
774   if (chain && REG_P (chain))
775     emit_clobber (chain);
776
777   /* Now put in the code to restore the frame pointer, and argument
778      pointer, if needed.  */
779 #ifdef HAVE_nonlocal_goto
780   if (! HAVE_nonlocal_goto)
781 #endif
782     {
783       emit_move_insn (virtual_stack_vars_rtx, hard_frame_pointer_rtx);
784       /* This might change the hard frame pointer in ways that aren't
785          apparent to early optimization passes, so force a clobber.  */
786       emit_clobber (hard_frame_pointer_rtx);
787     }
788
789 #if ARG_POINTER_REGNUM != HARD_FRAME_POINTER_REGNUM
790   if (fixed_regs[ARG_POINTER_REGNUM])
791     {
792 #ifdef ELIMINABLE_REGS
793       size_t i;
794       static const struct elims {const int from, to;} elim_regs[] = ELIMINABLE_REGS;
795
796       for (i = 0; i < ARRAY_SIZE (elim_regs); i++)
797         if (elim_regs[i].from == ARG_POINTER_REGNUM
798             && elim_regs[i].to == HARD_FRAME_POINTER_REGNUM)
799           break;
800
801       if (i == ARRAY_SIZE (elim_regs))
802 #endif
803         {
804           /* Now restore our arg pointer from the address at which it
805              was saved in our stack frame.  */
806           emit_move_insn (crtl->args.internal_arg_pointer,
807                           copy_to_reg (get_arg_pointer_save_area ()));
808         }
809     }
810 #endif
811
812 #ifdef HAVE_builtin_setjmp_receiver
813   if (HAVE_builtin_setjmp_receiver)
814     emit_insn (gen_builtin_setjmp_receiver (receiver_label));
815   else
816 #endif
817 #ifdef HAVE_nonlocal_goto_receiver
818     if (HAVE_nonlocal_goto_receiver)
819       emit_insn (gen_nonlocal_goto_receiver ());
820     else
821 #endif
822       { /* Nothing */ }
823
824   /* We must not allow the code we just generated to be reordered by
825      scheduling.  Specifically, the update of the frame pointer must
826      happen immediately, not later.  */
827   emit_insn (gen_blockage ());
828 }
829
830 /* __builtin_longjmp is passed a pointer to an array of five words (not
831    all will be used on all machines).  It operates similarly to the C
832    library function of the same name, but is more efficient.  Much of
833    the code below is copied from the handling of non-local gotos.  */
834
835 static void
836 expand_builtin_longjmp (rtx buf_addr, rtx value)
837 {
838   rtx fp, lab, stack, insn, last;
839   enum machine_mode sa_mode = STACK_SAVEAREA_MODE (SAVE_NONLOCAL);
840
841   /* DRAP is needed for stack realign if longjmp is expanded to current
842      function  */
843   if (SUPPORTS_STACK_ALIGNMENT)
844     crtl->need_drap = true;
845
846   if (setjmp_alias_set == -1)
847     setjmp_alias_set = new_alias_set ();
848
849   buf_addr = convert_memory_address (Pmode, buf_addr);
850
851   buf_addr = force_reg (Pmode, buf_addr);
852
853   /* We require that the user must pass a second argument of 1, because
854      that is what builtin_setjmp will return.  */
855   gcc_assert (value == const1_rtx);
856
857   last = get_last_insn ();
858 #ifdef HAVE_builtin_longjmp
859   if (HAVE_builtin_longjmp)
860     emit_insn (gen_builtin_longjmp (buf_addr));
861   else
862 #endif
863     {
864       fp = gen_rtx_MEM (Pmode, buf_addr);
865       lab = gen_rtx_MEM (Pmode, plus_constant (buf_addr,
866                                                GET_MODE_SIZE (Pmode)));
867
868       stack = gen_rtx_MEM (sa_mode, plus_constant (buf_addr,
869                                                    2 * GET_MODE_SIZE (Pmode)));
870       set_mem_alias_set (fp, setjmp_alias_set);
871       set_mem_alias_set (lab, setjmp_alias_set);
872       set_mem_alias_set (stack, setjmp_alias_set);
873
874       /* Pick up FP, label, and SP from the block and jump.  This code is
875          from expand_goto in stmt.c; see there for detailed comments.  */
876 #ifdef HAVE_nonlocal_goto
877       if (HAVE_nonlocal_goto)
878         /* We have to pass a value to the nonlocal_goto pattern that will
879            get copied into the static_chain pointer, but it does not matter
880            what that value is, because builtin_setjmp does not use it.  */
881         emit_insn (gen_nonlocal_goto (value, lab, stack, fp));
882       else
883 #endif
884         {
885           lab = copy_to_reg (lab);
886
887           emit_clobber (gen_rtx_MEM (BLKmode, gen_rtx_SCRATCH (VOIDmode)));
888           emit_clobber (gen_rtx_MEM (BLKmode, hard_frame_pointer_rtx));
889
890           emit_move_insn (hard_frame_pointer_rtx, fp);
891           emit_stack_restore (SAVE_NONLOCAL, stack, NULL_RTX);
892
893           emit_use (hard_frame_pointer_rtx);
894           emit_use (stack_pointer_rtx);
895           emit_indirect_jump (lab);
896         }
897     }
898
899   /* Search backwards and mark the jump insn as a non-local goto.
900      Note that this precludes the use of __builtin_longjmp to a
901      __builtin_setjmp target in the same function.  However, we've
902      already cautioned the user that these functions are for
903      internal exception handling use only.  */
904   for (insn = get_last_insn (); insn; insn = PREV_INSN (insn))
905     {
906       gcc_assert (insn != last);
907
908       if (JUMP_P (insn))
909         {
910           add_reg_note (insn, REG_NON_LOCAL_GOTO, const0_rtx);
911           break;
912         }
913       else if (CALL_P (insn))
914         break;
915     }
916 }
917
918 /* Expand a call to __builtin_nonlocal_goto.  We're passed the target label
919    and the address of the save area.  */
920
921 static rtx
922 expand_builtin_nonlocal_goto (tree exp)
923 {
924   tree t_label, t_save_area;
925   rtx r_label, r_save_area, r_fp, r_sp, insn;
926
927   if (!validate_arglist (exp, POINTER_TYPE, POINTER_TYPE, VOID_TYPE))
928     return NULL_RTX;
929
930   t_label = CALL_EXPR_ARG (exp, 0);
931   t_save_area = CALL_EXPR_ARG (exp, 1);
932
933   r_label = expand_normal (t_label);
934   r_label = convert_memory_address (Pmode, r_label);
935   r_save_area = expand_normal (t_save_area);
936   r_save_area = convert_memory_address (Pmode, r_save_area);
937   /* Copy the address of the save location to a register just in case it was based
938     on the frame pointer.   */
939   r_save_area = copy_to_reg (r_save_area);
940   r_fp = gen_rtx_MEM (Pmode, r_save_area);
941   r_sp = gen_rtx_MEM (STACK_SAVEAREA_MODE (SAVE_NONLOCAL),
942                       plus_constant (r_save_area, GET_MODE_SIZE (Pmode)));
943
944   crtl->has_nonlocal_goto = 1;
945
946 #ifdef HAVE_nonlocal_goto
947   /* ??? We no longer need to pass the static chain value, afaik.  */
948   if (HAVE_nonlocal_goto)
949     emit_insn (gen_nonlocal_goto (const0_rtx, r_label, r_sp, r_fp));
950   else
951 #endif
952     {
953       r_label = copy_to_reg (r_label);
954
955       emit_clobber (gen_rtx_MEM (BLKmode, gen_rtx_SCRATCH (VOIDmode)));
956       emit_clobber (gen_rtx_MEM (BLKmode, hard_frame_pointer_rtx));
957
958       /* Restore frame pointer for containing function.
959          This sets the actual hard register used for the frame pointer
960          to the location of the function's incoming static chain info.
961          The non-local goto handler will then adjust it to contain the
962          proper value and reload the argument pointer, if needed.  */
963       emit_move_insn (hard_frame_pointer_rtx, r_fp);
964       emit_stack_restore (SAVE_NONLOCAL, r_sp, NULL_RTX);
965
966       /* USE of hard_frame_pointer_rtx added for consistency;
967          not clear if really needed.  */
968       emit_use (hard_frame_pointer_rtx);
969       emit_use (stack_pointer_rtx);
970
971       /* If the architecture is using a GP register, we must
972          conservatively assume that the target function makes use of it.
973          The prologue of functions with nonlocal gotos must therefore
974          initialize the GP register to the appropriate value, and we
975          must then make sure that this value is live at the point
976          of the jump.  (Note that this doesn't necessarily apply
977          to targets with a nonlocal_goto pattern; they are free
978          to implement it in their own way.  Note also that this is
979          a no-op if the GP register is a global invariant.)  */
980       if ((unsigned) PIC_OFFSET_TABLE_REGNUM != INVALID_REGNUM
981           && fixed_regs[PIC_OFFSET_TABLE_REGNUM])
982         emit_use (pic_offset_table_rtx);
983
984       emit_indirect_jump (r_label);
985     }
986
987   /* Search backwards to the jump insn and mark it as a
988      non-local goto.  */
989   for (insn = get_last_insn (); insn; insn = PREV_INSN (insn))
990     {
991       if (JUMP_P (insn))
992         {
993           add_reg_note (insn, REG_NON_LOCAL_GOTO, const0_rtx);
994           break;
995         }
996       else if (CALL_P (insn))
997         break;
998     }
999
1000   return const0_rtx;
1001 }
1002
1003 /* __builtin_update_setjmp_buf is passed a pointer to an array of five words
1004    (not all will be used on all machines) that was passed to __builtin_setjmp.
1005    It updates the stack pointer in that block to correspond to the current
1006    stack pointer.  */
1007
1008 static void
1009 expand_builtin_update_setjmp_buf (rtx buf_addr)
1010 {
1011   enum machine_mode sa_mode = Pmode;
1012   rtx stack_save;
1013
1014
1015 #ifdef HAVE_save_stack_nonlocal
1016   if (HAVE_save_stack_nonlocal)
1017     sa_mode = insn_data[(int) CODE_FOR_save_stack_nonlocal].operand[0].mode;
1018 #endif
1019 #ifdef STACK_SAVEAREA_MODE
1020   sa_mode = STACK_SAVEAREA_MODE (SAVE_NONLOCAL);
1021 #endif
1022
1023   stack_save
1024     = gen_rtx_MEM (sa_mode,
1025                    memory_address
1026                    (sa_mode,
1027                     plus_constant (buf_addr, 2 * GET_MODE_SIZE (Pmode))));
1028
1029 #ifdef HAVE_setjmp
1030   if (HAVE_setjmp)
1031     emit_insn (gen_setjmp ());
1032 #endif
1033
1034   emit_stack_save (SAVE_NONLOCAL, &stack_save, NULL_RTX);
1035 }
1036
1037 /* Expand a call to __builtin_prefetch.  For a target that does not support
1038    data prefetch, evaluate the memory address argument in case it has side
1039    effects.  */
1040
1041 static void
1042 expand_builtin_prefetch (tree exp)
1043 {
1044   tree arg0, arg1, arg2;
1045   int nargs;
1046   rtx op0, op1, op2;
1047
1048   if (!validate_arglist (exp, POINTER_TYPE, 0))
1049     return;
1050
1051   arg0 = CALL_EXPR_ARG (exp, 0);
1052
1053   /* Arguments 1 and 2 are optional; argument 1 (read/write) defaults to
1054      zero (read) and argument 2 (locality) defaults to 3 (high degree of
1055      locality).  */
1056   nargs = call_expr_nargs (exp);
1057   if (nargs > 1)
1058     arg1 = CALL_EXPR_ARG (exp, 1);
1059   else
1060     arg1 = integer_zero_node;
1061   if (nargs > 2)
1062     arg2 = CALL_EXPR_ARG (exp, 2);
1063   else
1064     arg2 = integer_three_node;
1065
1066   /* Argument 0 is an address.  */
1067   op0 = expand_expr (arg0, NULL_RTX, Pmode, EXPAND_NORMAL);
1068
1069   /* Argument 1 (read/write flag) must be a compile-time constant int.  */
1070   if (TREE_CODE (arg1) != INTEGER_CST)
1071     {
1072       error ("second argument to %<__builtin_prefetch%> must be a constant");
1073       arg1 = integer_zero_node;
1074     }
1075   op1 = expand_normal (arg1);
1076   /* Argument 1 must be either zero or one.  */
1077   if (INTVAL (op1) != 0 && INTVAL (op1) != 1)
1078     {
1079       warning (0, "invalid second argument to %<__builtin_prefetch%>;"
1080                " using zero");
1081       op1 = const0_rtx;
1082     }
1083
1084   /* Argument 2 (locality) must be a compile-time constant int.  */
1085   if (TREE_CODE (arg2) != INTEGER_CST)
1086     {
1087       error ("third argument to %<__builtin_prefetch%> must be a constant");
1088       arg2 = integer_zero_node;
1089     }
1090   op2 = expand_normal (arg2);
1091   /* Argument 2 must be 0, 1, 2, or 3.  */
1092   if (INTVAL (op2) < 0 || INTVAL (op2) > 3)
1093     {
1094       warning (0, "invalid third argument to %<__builtin_prefetch%>; using zero");
1095       op2 = const0_rtx;
1096     }
1097
1098 #ifdef HAVE_prefetch
1099   if (HAVE_prefetch)
1100     {
1101       if ((! (*insn_data[(int) CODE_FOR_prefetch].operand[0].predicate)
1102              (op0,
1103               insn_data[(int) CODE_FOR_prefetch].operand[0].mode))
1104           || (GET_MODE (op0) != Pmode))
1105         {
1106           op0 = convert_memory_address (Pmode, op0);
1107           op0 = force_reg (Pmode, op0);
1108         }
1109       emit_insn (gen_prefetch (op0, op1, op2));
1110     }
1111 #endif
1112
1113   /* Don't do anything with direct references to volatile memory, but
1114      generate code to handle other side effects.  */
1115   if (!MEM_P (op0) && side_effects_p (op0))
1116     emit_insn (op0);
1117 }
1118
1119 /* Get a MEM rtx for expression EXP which is the address of an operand
1120    to be used in a string instruction (cmpstrsi, movmemsi, ..).  LEN is
1121    the maximum length of the block of memory that might be accessed or
1122    NULL if unknown.  */
1123
1124 static rtx
1125 get_memory_rtx (tree exp, tree len)
1126 {
1127   tree orig_exp = exp;
1128   rtx addr, mem;
1129   HOST_WIDE_INT off;
1130
1131   /* When EXP is not resolved SAVE_EXPR, MEM_ATTRS can be still derived
1132      from its expression, for expr->a.b only <variable>.a.b is recorded.  */
1133   if (TREE_CODE (exp) == SAVE_EXPR && !SAVE_EXPR_RESOLVED_P (exp))
1134     exp = TREE_OPERAND (exp, 0);
1135
1136   addr = expand_expr (orig_exp, NULL_RTX, ptr_mode, EXPAND_NORMAL);
1137   mem = gen_rtx_MEM (BLKmode, memory_address (BLKmode, addr));
1138
1139   /* Get an expression we can use to find the attributes to assign to MEM.
1140      If it is an ADDR_EXPR, use the operand.  Otherwise, dereference it if
1141      we can.  First remove any nops.  */
1142   while (CONVERT_EXPR_P (exp)
1143          && POINTER_TYPE_P (TREE_TYPE (TREE_OPERAND (exp, 0))))
1144     exp = TREE_OPERAND (exp, 0);
1145
1146   off = 0;
1147   if (TREE_CODE (exp) == POINTER_PLUS_EXPR
1148       && TREE_CODE (TREE_OPERAND (exp, 0)) == ADDR_EXPR
1149       && host_integerp (TREE_OPERAND (exp, 1), 0)
1150       && (off = tree_low_cst (TREE_OPERAND (exp, 1), 0)) > 0)
1151     exp = TREE_OPERAND (TREE_OPERAND (exp, 0), 0);
1152   else if (TREE_CODE (exp) == ADDR_EXPR)
1153     exp = TREE_OPERAND (exp, 0);
1154   else if (POINTER_TYPE_P (TREE_TYPE (exp)))
1155     exp = build1 (INDIRECT_REF, TREE_TYPE (TREE_TYPE (exp)), exp);
1156   else
1157     exp = NULL;
1158
1159   /* Honor attributes derived from exp, except for the alias set
1160      (as builtin stringops may alias with anything) and the size
1161      (as stringops may access multiple array elements).  */
1162   if (exp)
1163     {
1164       set_mem_attributes (mem, exp, 0);
1165
1166       if (off)
1167         mem = adjust_automodify_address_nv (mem, BLKmode, NULL, off);
1168
1169       /* Allow the string and memory builtins to overflow from one
1170          field into another, see http://gcc.gnu.org/PR23561.
1171          Thus avoid COMPONENT_REFs in MEM_EXPR unless we know the whole
1172          memory accessed by the string or memory builtin will fit
1173          within the field.  */
1174       if (MEM_EXPR (mem) && TREE_CODE (MEM_EXPR (mem)) == COMPONENT_REF)
1175         {
1176           tree mem_expr = MEM_EXPR (mem);
1177           HOST_WIDE_INT offset = -1, length = -1;
1178           tree inner = exp;
1179
1180           while (TREE_CODE (inner) == ARRAY_REF
1181                  || CONVERT_EXPR_P (inner)
1182                  || TREE_CODE (inner) == VIEW_CONVERT_EXPR
1183                  || TREE_CODE (inner) == SAVE_EXPR)
1184             inner = TREE_OPERAND (inner, 0);
1185
1186           gcc_assert (TREE_CODE (inner) == COMPONENT_REF);
1187
1188           if (MEM_OFFSET (mem)
1189               && CONST_INT_P (MEM_OFFSET (mem)))
1190             offset = INTVAL (MEM_OFFSET (mem));
1191
1192           if (offset >= 0 && len && host_integerp (len, 0))
1193             length = tree_low_cst (len, 0);
1194
1195           while (TREE_CODE (inner) == COMPONENT_REF)
1196             {
1197               tree field = TREE_OPERAND (inner, 1);
1198               gcc_assert (TREE_CODE (mem_expr) == COMPONENT_REF);
1199               gcc_assert (field == TREE_OPERAND (mem_expr, 1));
1200
1201               /* Bitfields are generally not byte-addressable.  */
1202               gcc_assert (!DECL_BIT_FIELD (field)
1203                           || ((tree_low_cst (DECL_FIELD_BIT_OFFSET (field), 1)
1204                                % BITS_PER_UNIT) == 0
1205                               && host_integerp (DECL_SIZE (field), 0)
1206                               && (TREE_INT_CST_LOW (DECL_SIZE (field))
1207                                   % BITS_PER_UNIT) == 0));
1208
1209               /* If we can prove that the memory starting at XEXP (mem, 0) and
1210                  ending at XEXP (mem, 0) + LENGTH will fit into this field, we
1211                  can keep the COMPONENT_REF in MEM_EXPR.  But be careful with
1212                  fields without DECL_SIZE_UNIT like flexible array members.  */
1213               if (length >= 0
1214                   && DECL_SIZE_UNIT (field)
1215                   && host_integerp (DECL_SIZE_UNIT (field), 0))
1216                 {
1217                   HOST_WIDE_INT size
1218                     = TREE_INT_CST_LOW (DECL_SIZE_UNIT (field));
1219                   if (offset <= size
1220                       && length <= size
1221                       && offset + length <= size)
1222                     break;
1223                 }
1224
1225               if (offset >= 0
1226                   && host_integerp (DECL_FIELD_OFFSET (field), 0))
1227                 offset += TREE_INT_CST_LOW (DECL_FIELD_OFFSET (field))
1228                           + tree_low_cst (DECL_FIELD_BIT_OFFSET (field), 1)
1229                             / BITS_PER_UNIT;
1230               else
1231                 {
1232                   offset = -1;
1233                   length = -1;
1234                 }
1235
1236               mem_expr = TREE_OPERAND (mem_expr, 0);
1237               inner = TREE_OPERAND (inner, 0);
1238             }
1239
1240           if (mem_expr == NULL)
1241             offset = -1;
1242           if (mem_expr != MEM_EXPR (mem))
1243             {
1244               set_mem_expr (mem, mem_expr);
1245               set_mem_offset (mem, offset >= 0 ? GEN_INT (offset) : NULL_RTX);
1246             }
1247         }
1248       set_mem_alias_set (mem, 0);
1249       set_mem_size (mem, NULL_RTX);
1250     }
1251
1252   return mem;
1253 }
1254 \f
1255 /* Built-in functions to perform an untyped call and return.  */
1256
1257 #define apply_args_mode \
1258   (this_target_builtins->x_apply_args_mode)
1259 #define apply_result_mode \
1260   (this_target_builtins->x_apply_result_mode)
1261
1262 /* Return the size required for the block returned by __builtin_apply_args,
1263    and initialize apply_args_mode.  */
1264
1265 static int
1266 apply_args_size (void)
1267 {
1268   static int size = -1;
1269   int align;
1270   unsigned int regno;
1271   enum machine_mode mode;
1272
1273   /* The values computed by this function never change.  */
1274   if (size < 0)
1275     {
1276       /* The first value is the incoming arg-pointer.  */
1277       size = GET_MODE_SIZE (Pmode);
1278
1279       /* The second value is the structure value address unless this is
1280          passed as an "invisible" first argument.  */
1281       if (targetm.calls.struct_value_rtx (cfun ? TREE_TYPE (cfun->decl) : 0, 0))
1282         size += GET_MODE_SIZE (Pmode);
1283
1284       for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
1285         if (FUNCTION_ARG_REGNO_P (regno))
1286           {
1287             mode = reg_raw_mode[regno];
1288
1289             gcc_assert (mode != VOIDmode);
1290
1291             align = GET_MODE_ALIGNMENT (mode) / BITS_PER_UNIT;
1292             if (size % align != 0)
1293               size = CEIL (size, align) * align;
1294             size += GET_MODE_SIZE (mode);
1295             apply_args_mode[regno] = mode;
1296           }
1297         else
1298           {
1299             apply_args_mode[regno] = VOIDmode;
1300           }
1301     }
1302   return size;
1303 }
1304
1305 /* Return the size required for the block returned by __builtin_apply,
1306    and initialize apply_result_mode.  */
1307
1308 static int
1309 apply_result_size (void)
1310 {
1311   static int size = -1;
1312   int align, regno;
1313   enum machine_mode mode;
1314
1315   /* The values computed by this function never change.  */
1316   if (size < 0)
1317     {
1318       size = 0;
1319
1320       for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
1321         if (targetm.calls.function_value_regno_p (regno))
1322           {
1323             mode = reg_raw_mode[regno];
1324
1325             gcc_assert (mode != VOIDmode);
1326
1327             align = GET_MODE_ALIGNMENT (mode) / BITS_PER_UNIT;
1328             if (size % align != 0)
1329               size = CEIL (size, align) * align;
1330             size += GET_MODE_SIZE (mode);
1331             apply_result_mode[regno] = mode;
1332           }
1333         else
1334           apply_result_mode[regno] = VOIDmode;
1335
1336       /* Allow targets that use untyped_call and untyped_return to override
1337          the size so that machine-specific information can be stored here.  */
1338 #ifdef APPLY_RESULT_SIZE
1339       size = APPLY_RESULT_SIZE;
1340 #endif
1341     }
1342   return size;
1343 }
1344
1345 #if defined (HAVE_untyped_call) || defined (HAVE_untyped_return)
1346 /* Create a vector describing the result block RESULT.  If SAVEP is true,
1347    the result block is used to save the values; otherwise it is used to
1348    restore the values.  */
1349
1350 static rtx
1351 result_vector (int savep, rtx result)
1352 {
1353   int regno, size, align, nelts;
1354   enum machine_mode mode;
1355   rtx reg, mem;
1356   rtx *savevec = XALLOCAVEC (rtx, FIRST_PSEUDO_REGISTER);
1357
1358   size = nelts = 0;
1359   for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
1360     if ((mode = apply_result_mode[regno]) != VOIDmode)
1361       {
1362         align = GET_MODE_ALIGNMENT (mode) / BITS_PER_UNIT;
1363         if (size % align != 0)
1364           size = CEIL (size, align) * align;
1365         reg = gen_rtx_REG (mode, savep ? regno : INCOMING_REGNO (regno));
1366         mem = adjust_address (result, mode, size);
1367         savevec[nelts++] = (savep
1368                             ? gen_rtx_SET (VOIDmode, mem, reg)
1369                             : gen_rtx_SET (VOIDmode, reg, mem));
1370         size += GET_MODE_SIZE (mode);
1371       }
1372   return gen_rtx_PARALLEL (VOIDmode, gen_rtvec_v (nelts, savevec));
1373 }
1374 #endif /* HAVE_untyped_call or HAVE_untyped_return */
1375
1376 /* Save the state required to perform an untyped call with the same
1377    arguments as were passed to the current function.  */
1378
1379 static rtx
1380 expand_builtin_apply_args_1 (void)
1381 {
1382   rtx registers, tem;
1383   int size, align, regno;
1384   enum machine_mode mode;
1385   rtx struct_incoming_value = targetm.calls.struct_value_rtx (cfun ? TREE_TYPE (cfun->decl) : 0, 1);
1386
1387   /* Create a block where the arg-pointer, structure value address,
1388      and argument registers can be saved.  */
1389   registers = assign_stack_local (BLKmode, apply_args_size (), -1);
1390
1391   /* Walk past the arg-pointer and structure value address.  */
1392   size = GET_MODE_SIZE (Pmode);
1393   if (targetm.calls.struct_value_rtx (cfun ? TREE_TYPE (cfun->decl) : 0, 0))
1394     size += GET_MODE_SIZE (Pmode);
1395
1396   /* Save each register used in calling a function to the block.  */
1397   for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
1398     if ((mode = apply_args_mode[regno]) != VOIDmode)
1399       {
1400         align = GET_MODE_ALIGNMENT (mode) / BITS_PER_UNIT;
1401         if (size % align != 0)
1402           size = CEIL (size, align) * align;
1403
1404         tem = gen_rtx_REG (mode, INCOMING_REGNO (regno));
1405
1406         emit_move_insn (adjust_address (registers, mode, size), tem);
1407         size += GET_MODE_SIZE (mode);
1408       }
1409
1410   /* Save the arg pointer to the block.  */
1411   tem = copy_to_reg (crtl->args.internal_arg_pointer);
1412 #ifdef STACK_GROWS_DOWNWARD
1413   /* We need the pointer as the caller actually passed them to us, not
1414      as we might have pretended they were passed.  Make sure it's a valid
1415      operand, as emit_move_insn isn't expected to handle a PLUS.  */
1416   tem
1417     = force_operand (plus_constant (tem, crtl->args.pretend_args_size),
1418                      NULL_RTX);
1419 #endif
1420   emit_move_insn (adjust_address (registers, Pmode, 0), tem);
1421
1422   size = GET_MODE_SIZE (Pmode);
1423
1424   /* Save the structure value address unless this is passed as an
1425      "invisible" first argument.  */
1426   if (struct_incoming_value)
1427     {
1428       emit_move_insn (adjust_address (registers, Pmode, size),
1429                       copy_to_reg (struct_incoming_value));
1430       size += GET_MODE_SIZE (Pmode);
1431     }
1432
1433   /* Return the address of the block.  */
1434   return copy_addr_to_reg (XEXP (registers, 0));
1435 }
1436
1437 /* __builtin_apply_args returns block of memory allocated on
1438    the stack into which is stored the arg pointer, structure
1439    value address, static chain, and all the registers that might
1440    possibly be used in performing a function call.  The code is
1441    moved to the start of the function so the incoming values are
1442    saved.  */
1443
1444 static rtx
1445 expand_builtin_apply_args (void)
1446 {
1447   /* Don't do __builtin_apply_args more than once in a function.
1448      Save the result of the first call and reuse it.  */
1449   if (apply_args_value != 0)
1450     return apply_args_value;
1451   {
1452     /* When this function is called, it means that registers must be
1453        saved on entry to this function.  So we migrate the
1454        call to the first insn of this function.  */
1455     rtx temp;
1456     rtx seq;
1457
1458     start_sequence ();
1459     temp = expand_builtin_apply_args_1 ();
1460     seq = get_insns ();
1461     end_sequence ();
1462
1463     apply_args_value = temp;
1464
1465     /* Put the insns after the NOTE that starts the function.
1466        If this is inside a start_sequence, make the outer-level insn
1467        chain current, so the code is placed at the start of the
1468        function.  If internal_arg_pointer is a non-virtual pseudo,
1469        it needs to be placed after the function that initializes
1470        that pseudo.  */
1471     push_topmost_sequence ();
1472     if (REG_P (crtl->args.internal_arg_pointer)
1473         && REGNO (crtl->args.internal_arg_pointer) > LAST_VIRTUAL_REGISTER)
1474       emit_insn_before (seq, parm_birth_insn);
1475     else
1476       emit_insn_before (seq, NEXT_INSN (entry_of_function ()));
1477     pop_topmost_sequence ();
1478     return temp;
1479   }
1480 }
1481
1482 /* Perform an untyped call and save the state required to perform an
1483    untyped return of whatever value was returned by the given function.  */
1484
1485 static rtx
1486 expand_builtin_apply (rtx function, rtx arguments, rtx argsize)
1487 {
1488   int size, align, regno;
1489   enum machine_mode mode;
1490   rtx incoming_args, result, reg, dest, src, call_insn;
1491   rtx old_stack_level = 0;
1492   rtx call_fusage = 0;
1493   rtx struct_value = targetm.calls.struct_value_rtx (cfun ? TREE_TYPE (cfun->decl) : 0, 0);
1494
1495   arguments = convert_memory_address (Pmode, arguments);
1496
1497   /* Create a block where the return registers can be saved.  */
1498   result = assign_stack_local (BLKmode, apply_result_size (), -1);
1499
1500   /* Fetch the arg pointer from the ARGUMENTS block.  */
1501   incoming_args = gen_reg_rtx (Pmode);
1502   emit_move_insn (incoming_args, gen_rtx_MEM (Pmode, arguments));
1503 #ifndef STACK_GROWS_DOWNWARD
1504   incoming_args = expand_simple_binop (Pmode, MINUS, incoming_args, argsize,
1505                                        incoming_args, 0, OPTAB_LIB_WIDEN);
1506 #endif
1507
1508   /* Push a new argument block and copy the arguments.  Do not allow
1509      the (potential) memcpy call below to interfere with our stack
1510      manipulations.  */
1511   do_pending_stack_adjust ();
1512   NO_DEFER_POP;
1513
1514   /* Save the stack with nonlocal if available.  */
1515 #ifdef HAVE_save_stack_nonlocal
1516   if (HAVE_save_stack_nonlocal)
1517     emit_stack_save (SAVE_NONLOCAL, &old_stack_level, NULL_RTX);
1518   else
1519 #endif
1520     emit_stack_save (SAVE_BLOCK, &old_stack_level, NULL_RTX);
1521
1522   /* Allocate a block of memory onto the stack and copy the memory
1523      arguments to the outgoing arguments address.  */
1524   allocate_dynamic_stack_space (argsize, 0, BITS_PER_UNIT);
1525
1526   /* Set DRAP flag to true, even though allocate_dynamic_stack_space
1527      may have already set current_function_calls_alloca to true.
1528      current_function_calls_alloca won't be set if argsize is zero,
1529      so we have to guarantee need_drap is true here.  */
1530   if (SUPPORTS_STACK_ALIGNMENT)
1531     crtl->need_drap = true;
1532
1533   dest = virtual_outgoing_args_rtx;
1534 #ifndef STACK_GROWS_DOWNWARD
1535   if (CONST_INT_P (argsize))
1536     dest = plus_constant (dest, -INTVAL (argsize));
1537   else
1538     dest = gen_rtx_PLUS (Pmode, dest, negate_rtx (Pmode, argsize));
1539 #endif
1540   dest = gen_rtx_MEM (BLKmode, dest);
1541   set_mem_align (dest, PARM_BOUNDARY);
1542   src = gen_rtx_MEM (BLKmode, incoming_args);
1543   set_mem_align (src, PARM_BOUNDARY);
1544   emit_block_move (dest, src, argsize, BLOCK_OP_NORMAL);
1545
1546   /* Refer to the argument block.  */
1547   apply_args_size ();
1548   arguments = gen_rtx_MEM (BLKmode, arguments);
1549   set_mem_align (arguments, PARM_BOUNDARY);
1550
1551   /* Walk past the arg-pointer and structure value address.  */
1552   size = GET_MODE_SIZE (Pmode);
1553   if (struct_value)
1554     size += GET_MODE_SIZE (Pmode);
1555
1556   /* Restore each of the registers previously saved.  Make USE insns
1557      for each of these registers for use in making the call.  */
1558   for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
1559     if ((mode = apply_args_mode[regno]) != VOIDmode)
1560       {
1561         align = GET_MODE_ALIGNMENT (mode) / BITS_PER_UNIT;
1562         if (size % align != 0)
1563           size = CEIL (size, align) * align;
1564         reg = gen_rtx_REG (mode, regno);
1565         emit_move_insn (reg, adjust_address (arguments, mode, size));
1566         use_reg (&call_fusage, reg);
1567         size += GET_MODE_SIZE (mode);
1568       }
1569
1570   /* Restore the structure value address unless this is passed as an
1571      "invisible" first argument.  */
1572   size = GET_MODE_SIZE (Pmode);
1573   if (struct_value)
1574     {
1575       rtx value = gen_reg_rtx (Pmode);
1576       emit_move_insn (value, adjust_address (arguments, Pmode, size));
1577       emit_move_insn (struct_value, value);
1578       if (REG_P (struct_value))
1579         use_reg (&call_fusage, struct_value);
1580       size += GET_MODE_SIZE (Pmode);
1581     }
1582
1583   /* All arguments and registers used for the call are set up by now!  */
1584   function = prepare_call_address (NULL, function, NULL, &call_fusage, 0, 0);
1585
1586   /* Ensure address is valid.  SYMBOL_REF is already valid, so no need,
1587      and we don't want to load it into a register as an optimization,
1588      because prepare_call_address already did it if it should be done.  */
1589   if (GET_CODE (function) != SYMBOL_REF)
1590     function = memory_address (FUNCTION_MODE, function);
1591
1592   /* Generate the actual call instruction and save the return value.  */
1593 #ifdef HAVE_untyped_call
1594   if (HAVE_untyped_call)
1595     emit_call_insn (gen_untyped_call (gen_rtx_MEM (FUNCTION_MODE, function),
1596                                       result, result_vector (1, result)));
1597   else
1598 #endif
1599 #ifdef HAVE_call_value
1600   if (HAVE_call_value)
1601     {
1602       rtx valreg = 0;
1603
1604       /* Locate the unique return register.  It is not possible to
1605          express a call that sets more than one return register using
1606          call_value; use untyped_call for that.  In fact, untyped_call
1607          only needs to save the return registers in the given block.  */
1608       for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
1609         if ((mode = apply_result_mode[regno]) != VOIDmode)
1610           {
1611             gcc_assert (!valreg); /* HAVE_untyped_call required.  */
1612
1613             valreg = gen_rtx_REG (mode, regno);
1614           }
1615
1616       emit_call_insn (GEN_CALL_VALUE (valreg,
1617                                       gen_rtx_MEM (FUNCTION_MODE, function),
1618                                       const0_rtx, NULL_RTX, const0_rtx));
1619
1620       emit_move_insn (adjust_address (result, GET_MODE (valreg), 0), valreg);
1621     }
1622   else
1623 #endif
1624     gcc_unreachable ();
1625
1626   /* Find the CALL insn we just emitted, and attach the register usage
1627      information.  */
1628   call_insn = last_call_insn ();
1629   add_function_usage_to (call_insn, call_fusage);
1630
1631   /* Restore the stack.  */
1632 #ifdef HAVE_save_stack_nonlocal
1633   if (HAVE_save_stack_nonlocal)
1634     emit_stack_restore (SAVE_NONLOCAL, old_stack_level, NULL_RTX);
1635   else
1636 #endif
1637     emit_stack_restore (SAVE_BLOCK, old_stack_level, NULL_RTX);
1638
1639   OK_DEFER_POP;
1640
1641   /* Return the address of the result block.  */
1642   result = copy_addr_to_reg (XEXP (result, 0));
1643   return convert_memory_address (ptr_mode, result);
1644 }
1645
1646 /* Perform an untyped return.  */
1647
1648 static void
1649 expand_builtin_return (rtx result)
1650 {
1651   int size, align, regno;
1652   enum machine_mode mode;
1653   rtx reg;
1654   rtx call_fusage = 0;
1655
1656   result = convert_memory_address (Pmode, result);
1657
1658   apply_result_size ();
1659   result = gen_rtx_MEM (BLKmode, result);
1660
1661 #ifdef HAVE_untyped_return
1662   if (HAVE_untyped_return)
1663     {
1664       emit_jump_insn (gen_untyped_return (result, result_vector (0, result)));
1665       emit_barrier ();
1666       return;
1667     }
1668 #endif
1669
1670   /* Restore the return value and note that each value is used.  */
1671   size = 0;
1672   for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
1673     if ((mode = apply_result_mode[regno]) != VOIDmode)
1674       {
1675         align = GET_MODE_ALIGNMENT (mode) / BITS_PER_UNIT;
1676         if (size % align != 0)
1677           size = CEIL (size, align) * align;
1678         reg = gen_rtx_REG (mode, INCOMING_REGNO (regno));
1679         emit_move_insn (reg, adjust_address (result, mode, size));
1680
1681         push_to_sequence (call_fusage);
1682         emit_use (reg);
1683         call_fusage = get_insns ();
1684         end_sequence ();
1685         size += GET_MODE_SIZE (mode);
1686       }
1687
1688   /* Put the USE insns before the return.  */
1689   emit_insn (call_fusage);
1690
1691   /* Return whatever values was restored by jumping directly to the end
1692      of the function.  */
1693   expand_naked_return ();
1694 }
1695
1696 /* Used by expand_builtin_classify_type and fold_builtin_classify_type.  */
1697
1698 static enum type_class
1699 type_to_class (tree type)
1700 {
1701   switch (TREE_CODE (type))
1702     {
1703     case VOID_TYPE:        return void_type_class;
1704     case INTEGER_TYPE:     return integer_type_class;
1705     case ENUMERAL_TYPE:    return enumeral_type_class;
1706     case BOOLEAN_TYPE:     return boolean_type_class;
1707     case POINTER_TYPE:     return pointer_type_class;
1708     case REFERENCE_TYPE:   return reference_type_class;
1709     case OFFSET_TYPE:      return offset_type_class;
1710     case REAL_TYPE:        return real_type_class;
1711     case COMPLEX_TYPE:     return complex_type_class;
1712     case FUNCTION_TYPE:    return function_type_class;
1713     case METHOD_TYPE:      return method_type_class;
1714     case RECORD_TYPE:      return record_type_class;
1715     case UNION_TYPE:
1716     case QUAL_UNION_TYPE:  return union_type_class;
1717     case ARRAY_TYPE:       return (TYPE_STRING_FLAG (type)
1718                                    ? string_type_class : array_type_class);
1719     case LANG_TYPE:        return lang_type_class;
1720     default:               return no_type_class;
1721     }
1722 }
1723
1724 /* Expand a call EXP to __builtin_classify_type.  */
1725
1726 static rtx
1727 expand_builtin_classify_type (tree exp)
1728 {
1729   if (call_expr_nargs (exp))
1730     return GEN_INT (type_to_class (TREE_TYPE (CALL_EXPR_ARG (exp, 0))));
1731   return GEN_INT (no_type_class);
1732 }
1733
1734 /* This helper macro, meant to be used in mathfn_built_in below,
1735    determines which among a set of three builtin math functions is
1736    appropriate for a given type mode.  The `F' and `L' cases are
1737    automatically generated from the `double' case.  */
1738 #define CASE_MATHFN(BUILT_IN_MATHFN) \
1739   case BUILT_IN_MATHFN: case BUILT_IN_MATHFN##F: case BUILT_IN_MATHFN##L: \
1740   fcode = BUILT_IN_MATHFN; fcodef = BUILT_IN_MATHFN##F ; \
1741   fcodel = BUILT_IN_MATHFN##L ; break;
1742 /* Similar to above, but appends _R after any F/L suffix.  */
1743 #define CASE_MATHFN_REENT(BUILT_IN_MATHFN) \
1744   case BUILT_IN_MATHFN##_R: case BUILT_IN_MATHFN##F_R: case BUILT_IN_MATHFN##L_R: \
1745   fcode = BUILT_IN_MATHFN##_R; fcodef = BUILT_IN_MATHFN##F_R ; \
1746   fcodel = BUILT_IN_MATHFN##L_R ; break;
1747
1748 /* Return mathematic function equivalent to FN but operating directly
1749    on TYPE, if available.  If IMPLICIT is true find the function in
1750    implicit_built_in_decls[], otherwise use built_in_decls[].  If we
1751    can't do the conversion, return zero.  */
1752
1753 static tree
1754 mathfn_built_in_1 (tree type, enum built_in_function fn, bool implicit)
1755 {
1756   tree const *const fn_arr
1757     = implicit ? implicit_built_in_decls : built_in_decls;
1758   enum built_in_function fcode, fcodef, fcodel;
1759
1760   switch (fn)
1761     {
1762       CASE_MATHFN (BUILT_IN_ACOS)
1763       CASE_MATHFN (BUILT_IN_ACOSH)
1764       CASE_MATHFN (BUILT_IN_ASIN)
1765       CASE_MATHFN (BUILT_IN_ASINH)
1766       CASE_MATHFN (BUILT_IN_ATAN)
1767       CASE_MATHFN (BUILT_IN_ATAN2)
1768       CASE_MATHFN (BUILT_IN_ATANH)
1769       CASE_MATHFN (BUILT_IN_CBRT)
1770       CASE_MATHFN (BUILT_IN_CEIL)
1771       CASE_MATHFN (BUILT_IN_CEXPI)
1772       CASE_MATHFN (BUILT_IN_COPYSIGN)
1773       CASE_MATHFN (BUILT_IN_COS)
1774       CASE_MATHFN (BUILT_IN_COSH)
1775       CASE_MATHFN (BUILT_IN_DREM)
1776       CASE_MATHFN (BUILT_IN_ERF)
1777       CASE_MATHFN (BUILT_IN_ERFC)
1778       CASE_MATHFN (BUILT_IN_EXP)
1779       CASE_MATHFN (BUILT_IN_EXP10)
1780       CASE_MATHFN (BUILT_IN_EXP2)
1781       CASE_MATHFN (BUILT_IN_EXPM1)
1782       CASE_MATHFN (BUILT_IN_FABS)
1783       CASE_MATHFN (BUILT_IN_FDIM)
1784       CASE_MATHFN (BUILT_IN_FLOOR)
1785       CASE_MATHFN (BUILT_IN_FMA)
1786       CASE_MATHFN (BUILT_IN_FMAX)
1787       CASE_MATHFN (BUILT_IN_FMIN)
1788       CASE_MATHFN (BUILT_IN_FMOD)
1789       CASE_MATHFN (BUILT_IN_FREXP)
1790       CASE_MATHFN (BUILT_IN_GAMMA)
1791       CASE_MATHFN_REENT (BUILT_IN_GAMMA) /* GAMMA_R */
1792       CASE_MATHFN (BUILT_IN_HUGE_VAL)
1793       CASE_MATHFN (BUILT_IN_HYPOT)
1794       CASE_MATHFN (BUILT_IN_ILOGB)
1795       CASE_MATHFN (BUILT_IN_INF)
1796       CASE_MATHFN (BUILT_IN_ISINF)
1797       CASE_MATHFN (BUILT_IN_J0)
1798       CASE_MATHFN (BUILT_IN_J1)
1799       CASE_MATHFN (BUILT_IN_JN)
1800       CASE_MATHFN (BUILT_IN_LCEIL)
1801       CASE_MATHFN (BUILT_IN_LDEXP)
1802       CASE_MATHFN (BUILT_IN_LFLOOR)
1803       CASE_MATHFN (BUILT_IN_LGAMMA)
1804       CASE_MATHFN_REENT (BUILT_IN_LGAMMA) /* LGAMMA_R */
1805       CASE_MATHFN (BUILT_IN_LLCEIL)
1806       CASE_MATHFN (BUILT_IN_LLFLOOR)
1807       CASE_MATHFN (BUILT_IN_LLRINT)
1808       CASE_MATHFN (BUILT_IN_LLROUND)
1809       CASE_MATHFN (BUILT_IN_LOG)
1810       CASE_MATHFN (BUILT_IN_LOG10)
1811       CASE_MATHFN (BUILT_IN_LOG1P)
1812       CASE_MATHFN (BUILT_IN_LOG2)
1813       CASE_MATHFN (BUILT_IN_LOGB)
1814       CASE_MATHFN (BUILT_IN_LRINT)
1815       CASE_MATHFN (BUILT_IN_LROUND)
1816       CASE_MATHFN (BUILT_IN_MODF)
1817       CASE_MATHFN (BUILT_IN_NAN)
1818       CASE_MATHFN (BUILT_IN_NANS)
1819       CASE_MATHFN (BUILT_IN_NEARBYINT)
1820       CASE_MATHFN (BUILT_IN_NEXTAFTER)
1821       CASE_MATHFN (BUILT_IN_NEXTTOWARD)
1822       CASE_MATHFN (BUILT_IN_POW)
1823       CASE_MATHFN (BUILT_IN_POWI)
1824       CASE_MATHFN (BUILT_IN_POW10)
1825       CASE_MATHFN (BUILT_IN_REMAINDER)
1826       CASE_MATHFN (BUILT_IN_REMQUO)
1827       CASE_MATHFN (BUILT_IN_RINT)
1828       CASE_MATHFN (BUILT_IN_ROUND)
1829       CASE_MATHFN (BUILT_IN_SCALB)
1830       CASE_MATHFN (BUILT_IN_SCALBLN)
1831       CASE_MATHFN (BUILT_IN_SCALBN)
1832       CASE_MATHFN (BUILT_IN_SIGNBIT)
1833       CASE_MATHFN (BUILT_IN_SIGNIFICAND)
1834       CASE_MATHFN (BUILT_IN_SIN)
1835       CASE_MATHFN (BUILT_IN_SINCOS)
1836       CASE_MATHFN (BUILT_IN_SINH)
1837       CASE_MATHFN (BUILT_IN_SQRT)
1838       CASE_MATHFN (BUILT_IN_TAN)
1839       CASE_MATHFN (BUILT_IN_TANH)
1840       CASE_MATHFN (BUILT_IN_TGAMMA)
1841       CASE_MATHFN (BUILT_IN_TRUNC)
1842       CASE_MATHFN (BUILT_IN_Y0)
1843       CASE_MATHFN (BUILT_IN_Y1)
1844       CASE_MATHFN (BUILT_IN_YN)
1845
1846       default:
1847         return NULL_TREE;
1848       }
1849
1850   if (TYPE_MAIN_VARIANT (type) == double_type_node)
1851     return fn_arr[fcode];
1852   else if (TYPE_MAIN_VARIANT (type) == float_type_node)
1853     return fn_arr[fcodef];
1854   else if (TYPE_MAIN_VARIANT (type) == long_double_type_node)
1855     return fn_arr[fcodel];
1856   else
1857     return NULL_TREE;
1858 }
1859
1860 /* Like mathfn_built_in_1(), but always use the implicit array.  */
1861
1862 tree
1863 mathfn_built_in (tree type, enum built_in_function fn)
1864 {
1865   return mathfn_built_in_1 (type, fn, /*implicit=*/ 1);
1866 }
1867
1868 /* If errno must be maintained, expand the RTL to check if the result,
1869    TARGET, of a built-in function call, EXP, is NaN, and if so set
1870    errno to EDOM.  */
1871
1872 static void
1873 expand_errno_check (tree exp, rtx target)
1874 {
1875   rtx lab = gen_label_rtx ();
1876
1877   /* Test the result; if it is NaN, set errno=EDOM because
1878      the argument was not in the domain.  */
1879   do_compare_rtx_and_jump (target, target, EQ, 0, GET_MODE (target),
1880                            NULL_RTX, NULL_RTX, lab,
1881                            /* The jump is very likely.  */
1882                            REG_BR_PROB_BASE - (REG_BR_PROB_BASE / 2000 - 1));
1883
1884 #ifdef TARGET_EDOM
1885   /* If this built-in doesn't throw an exception, set errno directly.  */
1886   if (TREE_NOTHROW (TREE_OPERAND (CALL_EXPR_FN (exp), 0)))
1887     {
1888 #ifdef GEN_ERRNO_RTX
1889       rtx errno_rtx = GEN_ERRNO_RTX;
1890 #else
1891       rtx errno_rtx
1892           = gen_rtx_MEM (word_mode, gen_rtx_SYMBOL_REF (Pmode, "errno"));
1893 #endif
1894       emit_move_insn (errno_rtx, GEN_INT (TARGET_EDOM));
1895       emit_label (lab);
1896       return;
1897     }
1898 #endif
1899
1900   /* Make sure the library call isn't expanded as a tail call.  */
1901   CALL_EXPR_TAILCALL (exp) = 0;
1902
1903   /* We can't set errno=EDOM directly; let the library call do it.
1904      Pop the arguments right away in case the call gets deleted.  */
1905   NO_DEFER_POP;
1906   expand_call (exp, target, 0);
1907   OK_DEFER_POP;
1908   emit_label (lab);
1909 }
1910
1911 /* Expand a call to one of the builtin math functions (sqrt, exp, or log).
1912    Return NULL_RTX if a normal call should be emitted rather than expanding
1913    the function in-line.  EXP is the expression that is a call to the builtin
1914    function; if convenient, the result should be placed in TARGET.
1915    SUBTARGET may be used as the target for computing one of EXP's operands.  */
1916
1917 static rtx
1918 expand_builtin_mathfn (tree exp, rtx target, rtx subtarget)
1919 {
1920   optab builtin_optab;
1921   rtx op0, insns;
1922   tree fndecl = get_callee_fndecl (exp);
1923   enum machine_mode mode;
1924   bool errno_set = false;
1925   tree arg;
1926
1927   if (!validate_arglist (exp, REAL_TYPE, VOID_TYPE))
1928     return NULL_RTX;
1929
1930   arg = CALL_EXPR_ARG (exp, 0);
1931
1932   switch (DECL_FUNCTION_CODE (fndecl))
1933     {
1934     CASE_FLT_FN (BUILT_IN_SQRT):
1935       errno_set = ! tree_expr_nonnegative_p (arg);
1936       builtin_optab = sqrt_optab;
1937       break;
1938     CASE_FLT_FN (BUILT_IN_EXP):
1939       errno_set = true; builtin_optab = exp_optab; break;
1940     CASE_FLT_FN (BUILT_IN_EXP10):
1941     CASE_FLT_FN (BUILT_IN_POW10):
1942       errno_set = true; builtin_optab = exp10_optab; break;
1943     CASE_FLT_FN (BUILT_IN_EXP2):
1944       errno_set = true; builtin_optab = exp2_optab; break;
1945     CASE_FLT_FN (BUILT_IN_EXPM1):
1946       errno_set = true; builtin_optab = expm1_optab; break;
1947     CASE_FLT_FN (BUILT_IN_LOGB):
1948       errno_set = true; builtin_optab = logb_optab; break;
1949     CASE_FLT_FN (BUILT_IN_LOG):
1950       errno_set = true; builtin_optab = log_optab; break;
1951     CASE_FLT_FN (BUILT_IN_LOG10):
1952       errno_set = true; builtin_optab = log10_optab; break;
1953     CASE_FLT_FN (BUILT_IN_LOG2):
1954       errno_set = true; builtin_optab = log2_optab; break;
1955     CASE_FLT_FN (BUILT_IN_LOG1P):
1956       errno_set = true; builtin_optab = log1p_optab; break;
1957     CASE_FLT_FN (BUILT_IN_ASIN):
1958       builtin_optab = asin_optab; break;
1959     CASE_FLT_FN (BUILT_IN_ACOS):
1960       builtin_optab = acos_optab; break;
1961     CASE_FLT_FN (BUILT_IN_TAN):
1962       builtin_optab = tan_optab; break;
1963     CASE_FLT_FN (BUILT_IN_ATAN):
1964       builtin_optab = atan_optab; break;
1965     CASE_FLT_FN (BUILT_IN_FLOOR):
1966       builtin_optab = floor_optab; break;
1967     CASE_FLT_FN (BUILT_IN_CEIL):
1968       builtin_optab = ceil_optab; break;
1969     CASE_FLT_FN (BUILT_IN_TRUNC):
1970       builtin_optab = btrunc_optab; break;
1971     CASE_FLT_FN (BUILT_IN_ROUND):
1972       builtin_optab = round_optab; break;
1973     CASE_FLT_FN (BUILT_IN_NEARBYINT):
1974       builtin_optab = nearbyint_optab;
1975       if (flag_trapping_math)
1976         break;
1977       /* Else fallthrough and expand as rint.  */
1978     CASE_FLT_FN (BUILT_IN_RINT):
1979       builtin_optab = rint_optab; break;
1980     CASE_FLT_FN (BUILT_IN_SIGNIFICAND):
1981       builtin_optab = significand_optab; break;
1982     default:
1983       gcc_unreachable ();
1984     }
1985
1986   /* Make a suitable register to place result in.  */
1987   mode = TYPE_MODE (TREE_TYPE (exp));
1988
1989   if (! flag_errno_math || ! HONOR_NANS (mode))
1990     errno_set = false;
1991
1992   /* Before working hard, check whether the instruction is available.  */
1993   if (optab_handler (builtin_optab, mode) != CODE_FOR_nothing)
1994     {
1995       target = gen_reg_rtx (mode);
1996
1997       /* Wrap the computation of the argument in a SAVE_EXPR, as we may
1998          need to expand the argument again.  This way, we will not perform
1999          side-effects more the once.  */
2000       CALL_EXPR_ARG (exp, 0) = arg = builtin_save_expr (arg);
2001
2002       op0 = expand_expr (arg, subtarget, VOIDmode, EXPAND_NORMAL);
2003
2004       start_sequence ();
2005
2006       /* Compute into TARGET.
2007          Set TARGET to wherever the result comes back.  */
2008       target = expand_unop (mode, builtin_optab, op0, target, 0);
2009
2010       if (target != 0)
2011         {
2012           if (errno_set)
2013             expand_errno_check (exp, target);
2014
2015           /* Output the entire sequence.  */
2016           insns = get_insns ();
2017           end_sequence ();
2018           emit_insn (insns);
2019           return target;
2020         }
2021
2022       /* If we were unable to expand via the builtin, stop the sequence
2023          (without outputting the insns) and call to the library function
2024          with the stabilized argument list.  */
2025       end_sequence ();
2026     }
2027
2028   return expand_call (exp, target, target == const0_rtx);
2029 }
2030
2031 /* Expand a call to the builtin binary math functions (pow and atan2).
2032    Return NULL_RTX if a normal call should be emitted rather than expanding the
2033    function in-line.  EXP is the expression that is a call to the builtin
2034    function; if convenient, the result should be placed in TARGET.
2035    SUBTARGET may be used as the target for computing one of EXP's
2036    operands.  */
2037
2038 static rtx
2039 expand_builtin_mathfn_2 (tree exp, rtx target, rtx subtarget)
2040 {
2041   optab builtin_optab;
2042   rtx op0, op1, insns;
2043   int op1_type = REAL_TYPE;
2044   tree fndecl = get_callee_fndecl (exp);
2045   tree arg0, arg1;
2046   enum machine_mode mode;
2047   bool errno_set = true;
2048
2049   switch (DECL_FUNCTION_CODE (fndecl))
2050     {
2051     CASE_FLT_FN (BUILT_IN_SCALBN):
2052     CASE_FLT_FN (BUILT_IN_SCALBLN):
2053     CASE_FLT_FN (BUILT_IN_LDEXP):
2054       op1_type = INTEGER_TYPE;
2055     default:
2056       break;
2057     }
2058
2059   if (!validate_arglist (exp, REAL_TYPE, op1_type, VOID_TYPE))
2060     return NULL_RTX;
2061
2062   arg0 = CALL_EXPR_ARG (exp, 0);
2063   arg1 = CALL_EXPR_ARG (exp, 1);
2064
2065   switch (DECL_FUNCTION_CODE (fndecl))
2066     {
2067     CASE_FLT_FN (BUILT_IN_POW):
2068       builtin_optab = pow_optab; break;
2069     CASE_FLT_FN (BUILT_IN_ATAN2):
2070       builtin_optab = atan2_optab; break;
2071     CASE_FLT_FN (BUILT_IN_SCALB):
2072       if (REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (exp)))->b != 2)
2073         return 0;
2074       builtin_optab = scalb_optab; break;
2075     CASE_FLT_FN (BUILT_IN_SCALBN):
2076     CASE_FLT_FN (BUILT_IN_SCALBLN):
2077       if (REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (exp)))->b != 2)
2078         return 0;
2079     /* Fall through... */
2080     CASE_FLT_FN (BUILT_IN_LDEXP):
2081       builtin_optab = ldexp_optab; break;
2082     CASE_FLT_FN (BUILT_IN_FMOD):
2083       builtin_optab = fmod_optab; break;
2084     CASE_FLT_FN (BUILT_IN_REMAINDER):
2085     CASE_FLT_FN (BUILT_IN_DREM):
2086       builtin_optab = remainder_optab; break;
2087     default:
2088       gcc_unreachable ();
2089     }
2090
2091   /* Make a suitable register to place result in.  */
2092   mode = TYPE_MODE (TREE_TYPE (exp));
2093
2094   /* Before working hard, check whether the instruction is available.  */
2095   if (optab_handler (builtin_optab, mode) == CODE_FOR_nothing)
2096     return NULL_RTX;
2097
2098   target = gen_reg_rtx (mode);
2099
2100   if (! flag_errno_math || ! HONOR_NANS (mode))
2101     errno_set = false;
2102
2103   /* Always stabilize the argument list.  */
2104   CALL_EXPR_ARG (exp, 0) = arg0 = builtin_save_expr (arg0);
2105   CALL_EXPR_ARG (exp, 1) = arg1 = builtin_save_expr (arg1);
2106
2107   op0 = expand_expr (arg0, subtarget, VOIDmode, EXPAND_NORMAL);
2108   op1 = expand_normal (arg1);
2109
2110   start_sequence ();
2111
2112   /* Compute into TARGET.
2113      Set TARGET to wherever the result comes back.  */
2114   target = expand_binop (mode, builtin_optab, op0, op1,
2115                          target, 0, OPTAB_DIRECT);
2116
2117   /* If we were unable to expand via the builtin, stop the sequence
2118      (without outputting the insns) and call to the library function
2119      with the stabilized argument list.  */
2120   if (target == 0)
2121     {
2122       end_sequence ();
2123       return expand_call (exp, target, target == const0_rtx);
2124     }
2125
2126   if (errno_set)
2127     expand_errno_check (exp, target);
2128
2129   /* Output the entire sequence.  */
2130   insns = get_insns ();
2131   end_sequence ();
2132   emit_insn (insns);
2133
2134   return target;
2135 }
2136
2137 /* Expand a call to the builtin sin and cos math functions.
2138    Return NULL_RTX if a normal call should be emitted rather than expanding the
2139    function in-line.  EXP is the expression that is a call to the builtin
2140    function; if convenient, the result should be placed in TARGET.
2141    SUBTARGET may be used as the target for computing one of EXP's
2142    operands.  */
2143
2144 static rtx
2145 expand_builtin_mathfn_3 (tree exp, rtx target, rtx subtarget)
2146 {
2147   optab builtin_optab;
2148   rtx op0, insns;
2149   tree fndecl = get_callee_fndecl (exp);
2150   enum machine_mode mode;
2151   tree arg;
2152
2153   if (!validate_arglist (exp, REAL_TYPE, VOID_TYPE))
2154     return NULL_RTX;
2155
2156   arg = CALL_EXPR_ARG (exp, 0);
2157
2158   switch (DECL_FUNCTION_CODE (fndecl))
2159     {
2160     CASE_FLT_FN (BUILT_IN_SIN):
2161     CASE_FLT_FN (BUILT_IN_COS):
2162       builtin_optab = sincos_optab; break;
2163     default:
2164       gcc_unreachable ();
2165     }
2166
2167   /* Make a suitable register to place result in.  */
2168   mode = TYPE_MODE (TREE_TYPE (exp));
2169
2170   /* Check if sincos insn is available, otherwise fallback
2171      to sin or cos insn.  */
2172   if (optab_handler (builtin_optab, mode) == CODE_FOR_nothing)
2173     switch (DECL_FUNCTION_CODE (fndecl))
2174       {
2175       CASE_FLT_FN (BUILT_IN_SIN):
2176         builtin_optab = sin_optab; break;
2177       CASE_FLT_FN (BUILT_IN_COS):
2178         builtin_optab = cos_optab; break;
2179       default:
2180         gcc_unreachable ();
2181       }
2182
2183   /* Before working hard, check whether the instruction is available.  */
2184   if (optab_handler (builtin_optab, mode) != CODE_FOR_nothing)
2185     {
2186       target = gen_reg_rtx (mode);
2187
2188       /* Wrap the computation of the argument in a SAVE_EXPR, as we may
2189          need to expand the argument again.  This way, we will not perform
2190          side-effects more the once.  */
2191       CALL_EXPR_ARG (exp, 0) = arg = builtin_save_expr (arg);
2192
2193       op0 = expand_expr (arg, subtarget, VOIDmode, EXPAND_NORMAL);
2194
2195       start_sequence ();
2196
2197       /* Compute into TARGET.
2198          Set TARGET to wherever the result comes back.  */
2199       if (builtin_optab == sincos_optab)
2200         {
2201           int result;
2202
2203           switch (DECL_FUNCTION_CODE (fndecl))
2204             {
2205             CASE_FLT_FN (BUILT_IN_SIN):
2206               result = expand_twoval_unop (builtin_optab, op0, 0, target, 0);
2207               break;
2208             CASE_FLT_FN (BUILT_IN_COS):
2209               result = expand_twoval_unop (builtin_optab, op0, target, 0, 0);
2210               break;
2211             default:
2212               gcc_unreachable ();
2213             }
2214           gcc_assert (result);
2215         }
2216       else
2217         {
2218           target = expand_unop (mode, builtin_optab, op0, target, 0);
2219         }
2220
2221       if (target != 0)
2222         {
2223           /* Output the entire sequence.  */
2224           insns = get_insns ();
2225           end_sequence ();
2226           emit_insn (insns);
2227           return target;
2228         }
2229
2230       /* If we were unable to expand via the builtin, stop the sequence
2231          (without outputting the insns) and call to the library function
2232          with the stabilized argument list.  */
2233       end_sequence ();
2234     }
2235
2236   target = expand_call (exp, target, target == const0_rtx);
2237
2238   return target;
2239 }
2240
2241 /* Given an interclass math builtin decl FNDECL and it's argument ARG
2242    return an RTL instruction code that implements the functionality.
2243    If that isn't possible or available return CODE_FOR_nothing.  */
2244
2245 static enum insn_code
2246 interclass_mathfn_icode (tree arg, tree fndecl)
2247 {
2248   bool errno_set = false;
2249   optab builtin_optab = 0;
2250   enum machine_mode mode;
2251
2252   switch (DECL_FUNCTION_CODE (fndecl))
2253     {
2254     CASE_FLT_FN (BUILT_IN_ILOGB):
2255       errno_set = true; builtin_optab = ilogb_optab; break;
2256     CASE_FLT_FN (BUILT_IN_ISINF):
2257       builtin_optab = isinf_optab; break;
2258     case BUILT_IN_ISNORMAL:
2259     case BUILT_IN_ISFINITE:
2260     CASE_FLT_FN (BUILT_IN_FINITE):
2261     case BUILT_IN_FINITED32:
2262     case BUILT_IN_FINITED64:
2263     case BUILT_IN_FINITED128:
2264     case BUILT_IN_ISINFD32:
2265     case BUILT_IN_ISINFD64:
2266     case BUILT_IN_ISINFD128:
2267       /* These builtins have no optabs (yet).  */
2268       break;
2269     default:
2270       gcc_unreachable ();
2271     }
2272
2273   /* There's no easy way to detect the case we need to set EDOM.  */
2274   if (flag_errno_math && errno_set)
2275     return CODE_FOR_nothing;
2276
2277   /* Optab mode depends on the mode of the input argument.  */
2278   mode = TYPE_MODE (TREE_TYPE (arg));
2279
2280   if (builtin_optab)
2281     return optab_handler (builtin_optab, mode);
2282   return CODE_FOR_nothing;
2283 }
2284
2285 /* Expand a call to one of the builtin math functions that operate on
2286    floating point argument and output an integer result (ilogb, isinf,
2287    isnan, etc).
2288    Return 0 if a normal call should be emitted rather than expanding the
2289    function in-line.  EXP is the expression that is a call to the builtin
2290    function; if convenient, the result should be placed in TARGET.
2291    SUBTARGET may be used as the target for computing one of EXP's operands.  */
2292
2293 static rtx
2294 expand_builtin_interclass_mathfn (tree exp, rtx target, rtx subtarget)
2295 {
2296   enum insn_code icode = CODE_FOR_nothing;
2297   rtx op0;
2298   tree fndecl = get_callee_fndecl (exp);
2299   enum machine_mode mode;
2300   tree arg;
2301
2302   if (!validate_arglist (exp, REAL_TYPE, VOID_TYPE))
2303     return NULL_RTX;
2304
2305   arg = CALL_EXPR_ARG (exp, 0);
2306   icode = interclass_mathfn_icode (arg, fndecl);
2307   mode = TYPE_MODE (TREE_TYPE (arg));
2308
2309   if (icode != CODE_FOR_nothing)
2310     {
2311       rtx last = get_last_insn ();
2312       tree orig_arg = arg;
2313       /* Make a suitable register to place result in.  */
2314       if (!target
2315           || GET_MODE (target) != TYPE_MODE (TREE_TYPE (exp))
2316           || !insn_data[icode].operand[0].predicate (target, GET_MODE (target)))
2317          target = gen_reg_rtx (TYPE_MODE (TREE_TYPE (exp)));
2318
2319       gcc_assert (insn_data[icode].operand[0].predicate
2320                   (target, GET_MODE (target)));
2321
2322       /* Wrap the computation of the argument in a SAVE_EXPR, as we may
2323          need to expand the argument again.  This way, we will not perform
2324          side-effects more the once.  */
2325       CALL_EXPR_ARG (exp, 0) = arg = builtin_save_expr (arg);
2326
2327       op0 = expand_expr (arg, subtarget, VOIDmode, EXPAND_NORMAL);
2328
2329       if (mode != GET_MODE (op0))
2330         op0 = convert_to_mode (mode, op0, 0);
2331
2332       /* Compute into TARGET.
2333          Set TARGET to wherever the result comes back.  */
2334       if (maybe_emit_unop_insn (icode, target, op0, UNKNOWN))
2335         return target;
2336       delete_insns_since (last);
2337       CALL_EXPR_ARG (exp, 0) = orig_arg;
2338     }
2339
2340   return NULL_RTX;
2341 }
2342
2343 /* Expand a call to the builtin sincos math function.
2344    Return NULL_RTX if a normal call should be emitted rather than expanding the
2345    function in-line.  EXP is the expression that is a call to the builtin
2346    function.  */
2347
2348 static rtx
2349 expand_builtin_sincos (tree exp)
2350 {
2351   rtx op0, op1, op2, target1, target2;
2352   enum machine_mode mode;
2353   tree arg, sinp, cosp;
2354   int result;
2355   location_t loc = EXPR_LOCATION (exp);
2356
2357   if (!validate_arglist (exp, REAL_TYPE,
2358                          POINTER_TYPE, POINTER_TYPE, VOID_TYPE))
2359     return NULL_RTX;
2360
2361   arg = CALL_EXPR_ARG (exp, 0);
2362   sinp = CALL_EXPR_ARG (exp, 1);
2363   cosp = CALL_EXPR_ARG (exp, 2);
2364
2365   /* Make a suitable register to place result in.  */
2366   mode = TYPE_MODE (TREE_TYPE (arg));
2367
2368   /* Check if sincos insn is available, otherwise emit the call.  */
2369   if (optab_handler (sincos_optab, mode) == CODE_FOR_nothing)
2370     return NULL_RTX;
2371
2372   target1 = gen_reg_rtx (mode);
2373   target2 = gen_reg_rtx (mode);
2374
2375   op0 = expand_normal (arg);
2376   op1 = expand_normal (build_fold_indirect_ref_loc (loc, sinp));
2377   op2 = expand_normal (build_fold_indirect_ref_loc (loc, cosp));
2378
2379   /* Compute into target1 and target2.
2380      Set TARGET to wherever the result comes back.  */
2381   result = expand_twoval_unop (sincos_optab, op0, target2, target1, 0);
2382   gcc_assert (result);
2383
2384   /* Move target1 and target2 to the memory locations indicated
2385      by op1 and op2.  */
2386   emit_move_insn (op1, target1);
2387   emit_move_insn (op2, target2);
2388
2389   return const0_rtx;
2390 }
2391
2392 /* Expand a call to the internal cexpi builtin to the sincos math function.
2393    EXP is the expression that is a call to the builtin function; if convenient,
2394    the result should be placed in TARGET.  SUBTARGET may be used as the target
2395    for computing one of EXP's operands.  */
2396
2397 static rtx
2398 expand_builtin_cexpi (tree exp, rtx target, rtx subtarget)
2399 {
2400   tree fndecl = get_callee_fndecl (exp);
2401   tree arg, type;
2402   enum machine_mode mode;
2403   rtx op0, op1, op2;
2404   location_t loc = EXPR_LOCATION (exp);
2405
2406   if (!validate_arglist (exp, REAL_TYPE, VOID_TYPE))
2407     return NULL_RTX;
2408
2409   arg = CALL_EXPR_ARG (exp, 0);
2410   type = TREE_TYPE (arg);
2411   mode = TYPE_MODE (TREE_TYPE (arg));
2412
2413   /* Try expanding via a sincos optab, fall back to emitting a libcall
2414      to sincos or cexp.  We are sure we have sincos or cexp because cexpi
2415      is only generated from sincos, cexp or if we have either of them.  */
2416   if (optab_handler (sincos_optab, mode) != CODE_FOR_nothing)
2417     {
2418       op1 = gen_reg_rtx (mode);
2419       op2 = gen_reg_rtx (mode);
2420
2421       op0 = expand_expr (arg, subtarget, VOIDmode, EXPAND_NORMAL);
2422
2423       /* Compute into op1 and op2.  */
2424       expand_twoval_unop (sincos_optab, op0, op2, op1, 0);
2425     }
2426   else if (TARGET_HAS_SINCOS)
2427     {
2428       tree call, fn = NULL_TREE;
2429       tree top1, top2;
2430       rtx op1a, op2a;
2431
2432       if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPIF)
2433         fn = built_in_decls[BUILT_IN_SINCOSF];
2434       else if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPI)
2435         fn = built_in_decls[BUILT_IN_SINCOS];
2436       else if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPIL)
2437         fn = built_in_decls[BUILT_IN_SINCOSL];
2438       else
2439         gcc_unreachable ();
2440
2441       op1 = assign_temp (TREE_TYPE (arg), 0, 1, 1);
2442       op2 = assign_temp (TREE_TYPE (arg), 0, 1, 1);
2443       op1a = copy_to_mode_reg (Pmode, XEXP (op1, 0));
2444       op2a = copy_to_mode_reg (Pmode, XEXP (op2, 0));
2445       top1 = make_tree (build_pointer_type (TREE_TYPE (arg)), op1a);
2446       top2 = make_tree (build_pointer_type (TREE_TYPE (arg)), op2a);
2447
2448       /* Make sure not to fold the sincos call again.  */
2449       call = build1 (ADDR_EXPR, build_pointer_type (TREE_TYPE (fn)), fn);
2450       expand_normal (build_call_nary (TREE_TYPE (TREE_TYPE (fn)),
2451                                       call, 3, arg, top1, top2));
2452     }
2453   else
2454     {
2455       tree call, fn = NULL_TREE, narg;
2456       tree ctype = build_complex_type (type);
2457
2458       if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPIF)
2459         fn = built_in_decls[BUILT_IN_CEXPF];
2460       else if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPI)
2461         fn = built_in_decls[BUILT_IN_CEXP];
2462       else if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPIL)
2463         fn = built_in_decls[BUILT_IN_CEXPL];
2464       else
2465         gcc_unreachable ();
2466
2467       /* If we don't have a decl for cexp create one.  This is the
2468          friendliest fallback if the user calls __builtin_cexpi
2469          without full target C99 function support.  */
2470       if (fn == NULL_TREE)
2471         {
2472           tree fntype;
2473           const char *name = NULL;
2474
2475           if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPIF)
2476             name = "cexpf";
2477           else if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPI)
2478             name = "cexp";
2479           else if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CEXPIL)
2480             name = "cexpl";
2481
2482           fntype = build_function_type_list (ctype, ctype, NULL_TREE);
2483           fn = build_fn_decl (name, fntype);
2484         }
2485
2486       narg = fold_build2_loc (loc, COMPLEX_EXPR, ctype,
2487                           build_real (type, dconst0), arg);
2488
2489       /* Make sure not to fold the cexp call again.  */
2490       call = build1 (ADDR_EXPR, build_pointer_type (TREE_TYPE (fn)), fn);
2491       return expand_expr (build_call_nary (ctype, call, 1, narg),
2492                           target, VOIDmode, EXPAND_NORMAL);
2493     }
2494
2495   /* Now build the proper return type.  */
2496   return expand_expr (build2 (COMPLEX_EXPR, build_complex_type (type),
2497                               make_tree (TREE_TYPE (arg), op2),
2498                               make_tree (TREE_TYPE (arg), op1)),
2499                       target, VOIDmode, EXPAND_NORMAL);
2500 }
2501
2502 /* Conveniently construct a function call expression.  FNDECL names the
2503    function to be called, N is the number of arguments, and the "..."
2504    parameters are the argument expressions.  Unlike build_call_exr
2505    this doesn't fold the call, hence it will always return a CALL_EXPR.  */
2506
2507 static tree
2508 build_call_nofold_loc (location_t loc, tree fndecl, int n, ...)
2509 {
2510   va_list ap;
2511   tree fntype = TREE_TYPE (fndecl);
2512   tree fn = build1 (ADDR_EXPR, build_pointer_type (fntype), fndecl);
2513
2514   va_start (ap, n);
2515   fn = build_call_valist (TREE_TYPE (fntype), fn, n, ap);
2516   va_end (ap);
2517   SET_EXPR_LOCATION (fn, loc);
2518   return fn;
2519 }
2520
2521 /* Expand a call to one of the builtin rounding functions gcc defines
2522    as an extension (lfloor and lceil).  As these are gcc extensions we
2523    do not need to worry about setting errno to EDOM.
2524    If expanding via optab fails, lower expression to (int)(floor(x)).
2525    EXP is the expression that is a call to the builtin function;
2526    if convenient, the result should be placed in TARGET.  */
2527
2528 static rtx
2529 expand_builtin_int_roundingfn (tree exp, rtx target)
2530 {
2531   convert_optab builtin_optab;
2532   rtx op0, insns, tmp;
2533   tree fndecl = get_callee_fndecl (exp);
2534   enum built_in_function fallback_fn;
2535   tree fallback_fndecl;
2536   enum machine_mode mode;
2537   tree arg;
2538
2539   if (!validate_arglist (exp, REAL_TYPE, VOID_TYPE))
2540     gcc_unreachable ();
2541
2542   arg = CALL_EXPR_ARG (exp, 0);
2543
2544   switch (DECL_FUNCTION_CODE (fndecl))
2545     {
2546     CASE_FLT_FN (BUILT_IN_LCEIL):
2547     CASE_FLT_FN (BUILT_IN_LLCEIL):
2548       builtin_optab = lceil_optab;
2549       fallback_fn = BUILT_IN_CEIL;
2550       break;
2551
2552     CASE_FLT_FN (BUILT_IN_LFLOOR):
2553     CASE_FLT_FN (BUILT_IN_LLFLOOR):
2554       builtin_optab = lfloor_optab;
2555       fallback_fn = BUILT_IN_FLOOR;
2556       break;
2557
2558     default:
2559       gcc_unreachable ();
2560     }
2561
2562   /* Make a suitable register to place result in.  */
2563   mode = TYPE_MODE (TREE_TYPE (exp));
2564
2565   target = gen_reg_rtx (mode);
2566
2567   /* Wrap the computation of the argument in a SAVE_EXPR, as we may
2568      need to expand the argument again.  This way, we will not perform
2569      side-effects more the once.  */
2570   CALL_EXPR_ARG (exp, 0) = arg = builtin_save_expr (arg);
2571
2572   op0 = expand_expr (arg, NULL, VOIDmode, EXPAND_NORMAL);
2573
2574   start_sequence ();
2575
2576   /* Compute into TARGET.  */
2577   if (expand_sfix_optab (target, op0, builtin_optab))
2578     {
2579       /* Output the entire sequence.  */
2580       insns = get_insns ();
2581       end_sequence ();
2582       emit_insn (insns);
2583       return target;
2584     }
2585
2586   /* If we were unable to expand via the builtin, stop the sequence
2587      (without outputting the insns).  */
2588   end_sequence ();
2589
2590   /* Fall back to floating point rounding optab.  */
2591   fallback_fndecl = mathfn_built_in (TREE_TYPE (arg), fallback_fn);
2592
2593   /* For non-C99 targets we may end up without a fallback fndecl here
2594      if the user called __builtin_lfloor directly.  In this case emit
2595      a call to the floor/ceil variants nevertheless.  This should result
2596      in the best user experience for not full C99 targets.  */
2597   if (fallback_fndecl == NULL_TREE)
2598     {
2599       tree fntype;
2600       const char *name = NULL;
2601
2602       switch (DECL_FUNCTION_CODE (fndecl))
2603         {
2604         case BUILT_IN_LCEIL:
2605         case BUILT_IN_LLCEIL:
2606           name = "ceil";
2607           break;
2608         case BUILT_IN_LCEILF:
2609         case BUILT_IN_LLCEILF:
2610           name = "ceilf";
2611           break;
2612         case BUILT_IN_LCEILL:
2613         case BUILT_IN_LLCEILL:
2614           name = "ceill";
2615           break;
2616         case BUILT_IN_LFLOOR:
2617         case BUILT_IN_LLFLOOR:
2618           name = "floor";
2619           break;
2620         case BUILT_IN_LFLOORF:
2621         case BUILT_IN_LLFLOORF:
2622           name = "floorf";
2623           break;
2624         case BUILT_IN_LFLOORL:
2625         case BUILT_IN_LLFLOORL:
2626           name = "floorl";
2627           break;
2628         default:
2629           gcc_unreachable ();
2630         }
2631
2632       fntype = build_function_type_list (TREE_TYPE (arg),
2633                                          TREE_TYPE (arg), NULL_TREE);
2634       fallback_fndecl = build_fn_decl (name, fntype);
2635     }
2636
2637   exp = build_call_nofold_loc (EXPR_LOCATION (exp), fallback_fndecl, 1, arg);
2638
2639   tmp = expand_normal (exp);
2640
2641   /* Truncate the result of floating point optab to integer
2642      via expand_fix ().  */
2643   target = gen_reg_rtx (mode);
2644   expand_fix (target, tmp, 0);
2645
2646   return target;
2647 }
2648
2649 /* Expand a call to one of the builtin math functions doing integer
2650    conversion (lrint).
2651    Return 0 if a normal call should be emitted rather than expanding the
2652    function in-line.  EXP is the expression that is a call to the builtin
2653    function; if convenient, the result should be placed in TARGET.  */
2654
2655 static rtx
2656 expand_builtin_int_roundingfn_2 (tree exp, rtx target)
2657 {
2658   convert_optab builtin_optab;
2659   rtx op0, insns;
2660   tree fndecl = get_callee_fndecl (exp);
2661   tree arg;
2662   enum machine_mode mode;
2663
2664   /* There's no easy way to detect the case we need to set EDOM.  */
2665   if (flag_errno_math)
2666     return NULL_RTX;
2667
2668   if (!validate_arglist (exp, REAL_TYPE, VOID_TYPE))
2669      gcc_unreachable ();
2670
2671   arg = CALL_EXPR_ARG (exp, 0);
2672
2673   switch (DECL_FUNCTION_CODE (fndecl))
2674     {
2675     CASE_FLT_FN (BUILT_IN_LRINT):
2676     CASE_FLT_FN (BUILT_IN_LLRINT):
2677       builtin_optab = lrint_optab; break;
2678     CASE_FLT_FN (BUILT_IN_LROUND):
2679     CASE_FLT_FN (BUILT_IN_LLROUND):
2680       builtin_optab = lround_optab; break;
2681     default:
2682       gcc_unreachable ();
2683     }
2684
2685   /* Make a suitable register to place result in.  */
2686   mode = TYPE_MODE (TREE_TYPE (exp));
2687
2688   target = gen_reg_rtx (mode);
2689
2690   /* Wrap the computation of the argument in a SAVE_EXPR, as we may
2691      need to expand the argument again.  This way, we will not perform
2692      side-effects more the once.  */
2693   CALL_EXPR_ARG (exp, 0) = arg = builtin_save_expr (arg);
2694
2695   op0 = expand_expr (arg, NULL, VOIDmode, EXPAND_NORMAL);
2696
2697   start_sequence ();
2698
2699   if (expand_sfix_optab (target, op0, builtin_optab))
2700     {
2701       /* Output the entire sequence.  */
2702       insns = get_insns ();
2703       end_sequence ();
2704       emit_insn (insns);
2705       return target;
2706     }
2707
2708   /* If we were unable to expand via the builtin, stop the sequence
2709      (without outputting the insns) and call to the library function
2710      with the stabilized argument list.  */
2711   end_sequence ();
2712
2713   target = expand_call (exp, target, target == const0_rtx);
2714
2715   return target;
2716 }
2717
2718 /* To evaluate powi(x,n), the floating point value x raised to the
2719    constant integer exponent n, we use a hybrid algorithm that
2720    combines the "window method" with look-up tables.  For an
2721    introduction to exponentiation algorithms and "addition chains",
2722    see section 4.6.3, "Evaluation of Powers" of Donald E. Knuth,
2723    "Seminumerical Algorithms", Vol. 2, "The Art of Computer Programming",
2724    3rd Edition, 1998, and Daniel M. Gordon, "A Survey of Fast Exponentiation
2725    Methods", Journal of Algorithms, Vol. 27, pp. 129-146, 1998.  */
2726
2727 /* Provide a default value for POWI_MAX_MULTS, the maximum number of
2728    multiplications to inline before calling the system library's pow
2729    function.  powi(x,n) requires at worst 2*bits(n)-2 multiplications,
2730    so this default never requires calling pow, powf or powl.  */
2731
2732 #ifndef POWI_MAX_MULTS
2733 #define POWI_MAX_MULTS  (2*HOST_BITS_PER_WIDE_INT-2)
2734 #endif
2735
2736 /* The size of the "optimal power tree" lookup table.  All
2737    exponents less than this value are simply looked up in the
2738    powi_table below.  This threshold is also used to size the
2739    cache of pseudo registers that hold intermediate results.  */
2740 #define POWI_TABLE_SIZE 256
2741
2742 /* The size, in bits of the window, used in the "window method"
2743    exponentiation algorithm.  This is equivalent to a radix of
2744    (1<<POWI_WINDOW_SIZE) in the corresponding "m-ary method".  */
2745 #define POWI_WINDOW_SIZE 3
2746
2747 /* The following table is an efficient representation of an
2748    "optimal power tree".  For each value, i, the corresponding
2749    value, j, in the table states than an optimal evaluation
2750    sequence for calculating pow(x,i) can be found by evaluating
2751    pow(x,j)*pow(x,i-j).  An optimal power tree for the first
2752    100 integers is given in Knuth's "Seminumerical algorithms".  */
2753
2754 static const unsigned char powi_table[POWI_TABLE_SIZE] =
2755   {
2756       0,   1,   1,   2,   2,   3,   3,   4,  /*   0 -   7 */
2757       4,   6,   5,   6,   6,  10,   7,   9,  /*   8 -  15 */
2758       8,  16,   9,  16,  10,  12,  11,  13,  /*  16 -  23 */
2759      12,  17,  13,  18,  14,  24,  15,  26,  /*  24 -  31 */
2760      16,  17,  17,  19,  18,  33,  19,  26,  /*  32 -  39 */
2761      20,  25,  21,  40,  22,  27,  23,  44,  /*  40 -  47 */
2762      24,  32,  25,  34,  26,  29,  27,  44,  /*  48 -  55 */
2763      28,  31,  29,  34,  30,  60,  31,  36,  /*  56 -  63 */
2764      32,  64,  33,  34,  34,  46,  35,  37,  /*  64 -  71 */
2765      36,  65,  37,  50,  38,  48,  39,  69,  /*  72 -  79 */
2766      40,  49,  41,  43,  42,  51,  43,  58,  /*  80 -  87 */
2767      44,  64,  45,  47,  46,  59,  47,  76,  /*  88 -  95 */
2768      48,  65,  49,  66,  50,  67,  51,  66,  /*  96 - 103 */
2769      52,  70,  53,  74,  54, 104,  55,  74,  /* 104 - 111 */
2770      56,  64,  57,  69,  58,  78,  59,  68,  /* 112 - 119 */
2771      60,  61,  61,  80,  62,  75,  63,  68,  /* 120 - 127 */
2772      64,  65,  65, 128,  66, 129,  67,  90,  /* 128 - 135 */
2773      68,  73,  69, 131,  70,  94,  71,  88,  /* 136 - 143 */
2774      72, 128,  73,  98,  74, 132,  75, 121,  /* 144 - 151 */
2775      76, 102,  77, 124,  78, 132,  79, 106,  /* 152 - 159 */
2776      80,  97,  81, 160,  82,  99,  83, 134,  /* 160 - 167 */
2777      84,  86,  85,  95,  86, 160,  87, 100,  /* 168 - 175 */
2778      88, 113,  89,  98,  90, 107,  91, 122,  /* 176 - 183 */
2779      92, 111,  93, 102,  94, 126,  95, 150,  /* 184 - 191 */
2780      96, 128,  97, 130,  98, 133,  99, 195,  /* 192 - 199 */
2781     100, 128, 101, 123, 102, 164, 103, 138,  /* 200 - 207 */
2782     104, 145, 105, 146, 106, 109, 107, 149,  /* 208 - 215 */
2783     108, 200, 109, 146, 110, 170, 111, 157,  /* 216 - 223 */
2784     112, 128, 113, 130, 114, 182, 115, 132,  /* 224 - 231 */
2785     116, 200, 117, 132, 118, 158, 119, 206,  /* 232 - 239 */
2786     120, 240, 121, 162, 122, 147, 123, 152,  /* 240 - 247 */
2787     124, 166, 125, 214, 126, 138, 127, 153,  /* 248 - 255 */
2788   };
2789
2790
2791 /* Return the number of multiplications required to calculate
2792    powi(x,n) where n is less than POWI_TABLE_SIZE.  This is a
2793    subroutine of powi_cost.  CACHE is an array indicating
2794    which exponents have already been calculated.  */
2795
2796 static int
2797 powi_lookup_cost (unsigned HOST_WIDE_INT n, bool *cache)
2798 {
2799   /* If we've already calculated this exponent, then this evaluation
2800      doesn't require any additional multiplications.  */
2801   if (cache[n])
2802     return 0;
2803
2804   cache[n] = true;
2805   return powi_lookup_cost (n - powi_table[n], cache)
2806          + powi_lookup_cost (powi_table[n], cache) + 1;
2807 }
2808
2809 /* Return the number of multiplications required to calculate
2810    powi(x,n) for an arbitrary x, given the exponent N.  This
2811    function needs to be kept in sync with expand_powi below.  */
2812
2813 static int
2814 powi_cost (HOST_WIDE_INT n)
2815 {
2816   bool cache[POWI_TABLE_SIZE];
2817   unsigned HOST_WIDE_INT digit;
2818   unsigned HOST_WIDE_INT val;
2819   int result;
2820
2821   if (n == 0)
2822     return 0;
2823
2824   /* Ignore the reciprocal when calculating the cost.  */
2825   val = (n < 0) ? -n : n;
2826
2827   /* Initialize the exponent cache.  */
2828   memset (cache, 0, POWI_TABLE_SIZE * sizeof (bool));
2829   cache[1] = true;
2830
2831   result = 0;
2832
2833   while (val >= POWI_TABLE_SIZE)
2834     {
2835       if (val & 1)
2836         {
2837           digit = val & ((1 << POWI_WINDOW_SIZE) - 1);
2838           result += powi_lookup_cost (digit, cache)
2839                     + POWI_WINDOW_SIZE + 1;
2840           val >>= POWI_WINDOW_SIZE;
2841         }
2842       else
2843         {
2844           val >>= 1;
2845           result++;
2846         }
2847     }
2848
2849   return result + powi_lookup_cost (val, cache);
2850 }
2851
2852 /* Recursive subroutine of expand_powi.  This function takes the array,
2853    CACHE, of already calculated exponents and an exponent N and returns
2854    an RTX that corresponds to CACHE[1]**N, as calculated in mode MODE.  */
2855
2856 static rtx
2857 expand_powi_1 (enum machine_mode mode, unsigned HOST_WIDE_INT n, rtx *cache)
2858 {
2859   unsigned HOST_WIDE_INT digit;
2860   rtx target, result;
2861   rtx op0, op1;
2862
2863   if (n < POWI_TABLE_SIZE)
2864     {
2865       if (cache[n])
2866         return cache[n];
2867
2868       target = gen_reg_rtx (mode);
2869       cache[n] = target;
2870
2871       op0 = expand_powi_1 (mode, n - powi_table[n], cache);
2872       op1 = expand_powi_1 (mode, powi_table[n], cache);
2873     }
2874   else if (n & 1)
2875     {
2876       target = gen_reg_rtx (mode);
2877       digit = n & ((1 << POWI_WINDOW_SIZE) - 1);
2878       op0 = expand_powi_1 (mode, n - digit, cache);
2879       op1 = expand_powi_1 (mode, digit, cache);
2880     }
2881   else
2882     {
2883       target = gen_reg_rtx (mode);
2884       op0 = expand_powi_1 (mode, n >> 1, cache);
2885       op1 = op0;
2886     }
2887
2888   result = expand_mult (mode, op0, op1, target, 0);
2889   if (result != target)
2890     emit_move_insn (target, result);
2891   return target;
2892 }
2893
2894 /* Expand the RTL to evaluate powi(x,n) in mode MODE.  X is the
2895    floating point operand in mode MODE, and N is the exponent.  This
2896    function needs to be kept in sync with powi_cost above.  */
2897
2898 static rtx
2899 expand_powi (rtx x, enum machine_mode mode, HOST_WIDE_INT n)
2900 {
2901   rtx cache[POWI_TABLE_SIZE];
2902   rtx result;
2903
2904   if (n == 0)
2905     return CONST1_RTX (mode);
2906
2907   memset (cache, 0, sizeof (cache));
2908   cache[1] = x;
2909
2910   result = expand_powi_1 (mode, (n < 0) ? -n : n, cache);
2911
2912   /* If the original exponent was negative, reciprocate the result.  */
2913   if (n < 0)
2914     result = expand_binop (mode, sdiv_optab, CONST1_RTX (mode),
2915                            result, NULL_RTX, 0, OPTAB_LIB_WIDEN);
2916
2917   return result;
2918 }
2919
2920 /* Fold a builtin function call to pow, powf, or powl into a series of sqrts or
2921    cbrts.  Return NULL_RTX if no simplification can be made or expand the tree
2922    if we can simplify it.  */
2923 static rtx
2924 expand_builtin_pow_root (location_t loc, tree arg0, tree arg1, tree type,
2925                          rtx subtarget)
2926 {
2927   if (TREE_CODE (arg1) == REAL_CST
2928       && !TREE_OVERFLOW (arg1)
2929       && flag_unsafe_math_optimizations)
2930     {
2931       enum machine_mode mode = TYPE_MODE (type);
2932       tree sqrtfn = mathfn_built_in (type, BUILT_IN_SQRT);
2933       tree cbrtfn = mathfn_built_in (type, BUILT_IN_CBRT);
2934       REAL_VALUE_TYPE c = TREE_REAL_CST (arg1);
2935       tree op = NULL_TREE;
2936
2937       if (sqrtfn)
2938         {
2939           /* Optimize pow (x, 0.5) into sqrt.  */
2940           if (REAL_VALUES_EQUAL (c, dconsthalf))
2941             op = build_call_nofold_loc (loc, sqrtfn, 1, arg0);
2942
2943           else
2944             {
2945               REAL_VALUE_TYPE dconst1_4 = dconst1;
2946               REAL_VALUE_TYPE dconst3_4;
2947               SET_REAL_EXP (&dconst1_4, REAL_EXP (&dconst1_4) - 2);
2948
2949               real_from_integer (&dconst3_4, VOIDmode, 3, 0, 0);
2950               SET_REAL_EXP (&dconst3_4, REAL_EXP (&dconst3_4) - 2);
2951
2952               /* Optimize pow (x, 0.25) into sqrt (sqrt (x)).  Assume on most
2953                  machines that a builtin sqrt instruction is smaller than a
2954                  call to pow with 0.25, so do this optimization even if
2955                  -Os.  */
2956               if (REAL_VALUES_EQUAL (c, dconst1_4))
2957                 {
2958                   op = build_call_nofold_loc (loc, sqrtfn, 1, arg0);
2959                   op = build_call_nofold_loc (loc, sqrtfn, 1, op);
2960                 }
2961
2962               /* Optimize pow (x, 0.75) = sqrt (x) * sqrt (sqrt (x)) unless we
2963                  are optimizing for space.  */
2964               else if (optimize_insn_for_speed_p ()
2965                        && !TREE_SIDE_EFFECTS (arg0)
2966                        && REAL_VALUES_EQUAL (c, dconst3_4))
2967                 {
2968                   tree sqrt1 = build_call_expr_loc (loc, sqrtfn, 1, arg0);
2969                   tree sqrt2 = builtin_save_expr (sqrt1);
2970                   tree sqrt3 = build_call_expr_loc (loc, sqrtfn, 1, sqrt1);
2971                   op = fold_build2_loc (loc, MULT_EXPR, type, sqrt2, sqrt3);
2972                 }
2973             }
2974         }
2975
2976       /* Check whether we can do cbrt insstead of pow (x, 1./3.) and
2977          cbrt/sqrts instead of pow (x, 1./6.).  */
2978       if (cbrtfn && ! op
2979           && (tree_expr_nonnegative_p (arg0) || !HONOR_NANS (mode)))
2980         {
2981           /* First try 1/3.  */
2982           REAL_VALUE_TYPE dconst1_3
2983             = real_value_truncate (mode, dconst_third ());
2984
2985           if (REAL_VALUES_EQUAL (c, dconst1_3))
2986             op = build_call_nofold_loc (loc, cbrtfn, 1, arg0);
2987
2988               /* Now try 1/6.  */
2989           else if (optimize_insn_for_speed_p ())
2990             {
2991               REAL_VALUE_TYPE dconst1_6 = dconst1_3;
2992               SET_REAL_EXP (&dconst1_6, REAL_EXP (&dconst1_6) - 1);
2993
2994               if (REAL_VALUES_EQUAL (c, dconst1_6))
2995                 {
2996                   op = build_call_nofold_loc (loc, sqrtfn, 1, arg0);
2997                   op = build_call_nofold_loc (loc, cbrtfn, 1, op);
2998                 }
2999             }
3000         }
3001
3002       if (op)
3003         return expand_expr (op, subtarget, mode, EXPAND_NORMAL);
3004     }
3005
3006   return NULL_RTX;
3007 }
3008
3009 /* Expand a call to the pow built-in mathematical function.  Return NULL_RTX if
3010    a normal call should be emitted rather than expanding the function
3011    in-line.  EXP is the expression that is a call to the builtin
3012    function; if convenient, the result should be placed in TARGET.  */
3013
3014 static rtx
3015 expand_builtin_pow (tree exp, rtx target, rtx subtarget)
3016 {
3017   tree arg0, arg1;
3018   tree fn, narg0;
3019   tree type = TREE_TYPE (exp);
3020   REAL_VALUE_TYPE cint, c, c2;
3021   HOST_WIDE_INT n;
3022   rtx op, op2;
3023   enum machine_mode mode = TYPE_MODE (type);
3024
3025   if (! validate_arglist (exp, REAL_TYPE, REAL_TYPE, VOID_TYPE))
3026     return NULL_RTX;
3027
3028   arg0 = CALL_EXPR_ARG (exp, 0);
3029   arg1 = CALL_EXPR_ARG (exp, 1);
3030
3031   if (TREE_CODE (arg1) != REAL_CST
3032       || TREE_OVERFLOW (arg1))
3033     return expand_builtin_mathfn_2 (exp, target, subtarget);
3034
3035   /* Handle constant exponents.  */
3036
3037   /* For integer valued exponents we can expand to an optimal multiplication
3038      sequence using expand_powi.  */
3039   c = TREE_REAL_CST (arg1);
3040   n = real_to_integer (&c);
3041   real_from_integer (&cint, VOIDmode, n, n < 0 ? -1 : 0, 0);
3042   if (real_identical (&c, &cint)
3043       && ((n >= -1 && n <= 2)
3044           || (flag_unsafe_math_optimizations
3045               && optimize_insn_for_speed_p ()
3046               && powi_cost (n) <= POWI_MAX_MULTS)))
3047     {
3048       op = expand_expr (arg0, subtarget, VOIDmode, EXPAND_NORMAL);
3049       if (n != 1)
3050         {
3051           op = force_reg (mode, op);
3052           op = expand_powi (op, mode, n);
3053         }
3054       return op;
3055     }
3056
3057   narg0 = builtin_save_expr (arg0);
3058
3059   /* If the exponent is not integer valued, check if it is half of an integer.
3060      In this case we can expand to sqrt (x) * x**(n/2).  */
3061   fn = mathfn_built_in (type, BUILT_IN_SQRT);
3062   if (fn != NULL_TREE)
3063     {
3064       real_arithmetic (&c2, MULT_EXPR, &c, &dconst2);
3065       n = real_to_integer (&c2);
3066       real_from_integer (&cint, VOIDmode, n, n < 0 ? -1 : 0, 0);
3067       if (real_identical (&c2, &cint)
3068           && ((flag_unsafe_math_optimizations
3069                && optimize_insn_for_speed_p ()
3070                && powi_cost (n/2) <= POWI_MAX_MULTS)
3071               /* Even the c == 0.5 case cannot be done unconditionally
3072                  when we need to preserve signed zeros, as
3073                  pow (-0, 0.5) is +0, while sqrt(-0) is -0.  */
3074               || (!HONOR_SIGNED_ZEROS (mode) && n == 1)
3075               /* For c == 1.5 we can assume that x * sqrt (x) is always
3076                  smaller than pow (x, 1.5) if sqrt will not be expanded
3077                  as a call.  */
3078               || (n == 3
3079                   && optab_handler (sqrt_optab, mode) != CODE_FOR_nothing)))
3080         {
3081           tree call_expr = build_call_nofold_loc (EXPR_LOCATION (exp), fn, 1,
3082                                                   narg0);
3083           /* Use expand_expr in case the newly built call expression
3084              was folded to a non-call.  */
3085           op = expand_expr (call_expr, subtarget, mode, EXPAND_NORMAL);
3086           if (n != 1)
3087             {
3088               op2 = expand_expr (narg0, subtarget, VOIDmode, EXPAND_NORMAL);
3089               op2 = force_reg (mode, op2);
3090               op2 = expand_powi (op2, mode, abs (n / 2));
3091               op = expand_simple_binop (mode, MULT, op, op2, NULL_RTX,
3092                                         0, OPTAB_LIB_WIDEN);
3093               /* If the original exponent was negative, reciprocate the
3094                  result.  */
3095               if (n < 0)
3096                 op = expand_binop (mode, sdiv_optab, CONST1_RTX (mode),
3097                                    op, NULL_RTX, 0, OPTAB_LIB_WIDEN);
3098             }
3099           return op;
3100         }
3101     }
3102
3103   /* Check whether we can do a series of sqrt or cbrt's instead of the pow
3104      call.  */
3105   op = expand_builtin_pow_root (EXPR_LOCATION (exp), arg0, arg1, type,
3106                                 subtarget);
3107   if (op)
3108     return op;
3109
3110   /* Try if the exponent is a third of an integer.  In this case
3111      we can expand to x**(n/3) * cbrt(x)**(n%3).  As cbrt (x) is
3112      different from pow (x, 1./3.) due to rounding and behavior
3113      with negative x we need to constrain this transformation to
3114      unsafe math and positive x or finite math.  */
3115   fn = mathfn_built_in (type, BUILT_IN_CBRT);
3116   if (fn != NULL_TREE
3117       && flag_unsafe_math_optimizations
3118       && (tree_expr_nonnegative_p (arg0)
3119           || !HONOR_NANS (mode)))
3120     {
3121       REAL_VALUE_TYPE dconst3;
3122       real_from_integer (&dconst3, VOIDmode, 3, 0, 0);
3123       real_arithmetic (&c2, MULT_EXPR, &c, &dconst3);
3124       real_round (&c2, mode, &c2);
3125       n = real_to_integer (&c2);
3126       real_from_integer (&cint, VOIDmode, n, n < 0 ? -1 : 0, 0);
3127       real_arithmetic (&c2, RDIV_EXPR, &cint, &dconst3);
3128       real_convert (&c2, mode, &c2);
3129       if (real_identical (&c2, &c)
3130           && ((optimize_insn_for_speed_p ()
3131                && powi_cost (n/3) <= POWI_MAX_MULTS)
3132               || n == 1))
3133         {
3134           tree call_expr = build_call_nofold_loc (EXPR_LOCATION (exp), fn, 1,
3135                                                   narg0);
3136           op = expand_builtin (call_expr, NULL_RTX, subtarget, mode, 0);
3137           if (abs (n) % 3 == 2)
3138             op = expand_simple_binop (mode, MULT, op, op, op,
3139                                       0, OPTAB_LIB_WIDEN);
3140           if (n != 1)
3141             {
3142               op2 = expand_expr (narg0, subtarget, VOIDmode, EXPAND_NORMAL);
3143               op2 = force_reg (mode, op2);
3144               op2 = expand_powi (op2, mode, abs (n / 3));
3145               op = expand_simple_binop (mode, MULT, op, op2, NULL_RTX,
3146                                         0, OPTAB_LIB_WIDEN);
3147               /* If the original exponent was negative, reciprocate the
3148                  result.  */
3149               if (n < 0)
3150                 op = expand_binop (mode, sdiv_optab, CONST1_RTX (mode),
3151                                    op, NULL_RTX, 0, OPTAB_LIB_WIDEN);
3152             }
3153           return op;
3154         }
3155     }
3156
3157   /* Fall back to optab expansion.  */
3158   return expand_builtin_mathfn_2 (exp, target, subtarget);
3159 }
3160
3161 /* Expand a call to the powi built-in mathematical function.  Return NULL_RTX if
3162    a normal call should be emitted rather than expanding the function
3163    in-line.  EXP is the expression that is a call to the builtin
3164    function; if convenient, the result should be placed in TARGET.  */
3165
3166 static rtx
3167 expand_builtin_powi (tree exp, rtx target, rtx subtarget)
3168 {
3169   tree arg0, arg1;
3170   rtx op0, op1;
3171   enum machine_mode mode;
3172   enum machine_mode mode2;
3173
3174   if (! validate_arglist (exp, REAL_TYPE, INTEGER_TYPE, VOID_TYPE))
3175     return NULL_RTX;
3176
3177   arg0 = CALL_EXPR_ARG (exp, 0);
3178   arg1 = CALL_EXPR_ARG (exp, 1);
3179   mode = TYPE_MODE (TREE_TYPE (exp));
3180
3181   /* Handle constant power.  */
3182
3183   if (TREE_CODE (arg1) == INTEGER_CST
3184       && !TREE_OVERFLOW (arg1))
3185     {
3186       HOST_WIDE_INT n = TREE_INT_CST_LOW (arg1);
3187
3188       /* If the exponent is -1, 0, 1 or 2, then expand_powi is exact.
3189          Otherwise, check the number of multiplications required.  */
3190       if ((TREE_INT_CST_HIGH (arg1) == 0
3191            || TREE_INT_CST_HIGH (arg1) == -1)
3192           && ((n >= -1 && n <= 2)
3193               || (optimize_insn_for_speed_p ()
3194                   && powi_cost (n) <= POWI_MAX_MULTS)))
3195         {
3196           op0 = expand_expr (arg0, subtarget, VOIDmode, EXPAND_NORMAL);
3197           op0 = force_reg (mode, op0);
3198           return expand_powi (op0, mode, n);
3199         }
3200     }
3201
3202   /* Emit a libcall to libgcc.  */
3203
3204   /* Mode of the 2nd argument must match that of an int.  */
3205   mode2 = mode_for_size (INT_TYPE_SIZE, MODE_INT, 0);
3206
3207   if (target == NULL_RTX)
3208     target = gen_reg_rtx (mode);
3209
3210   op0 = expand_expr (arg0, subtarget, mode, EXPAND_NORMAL);
3211   if (GET_MODE (op0) != mode)
3212     op0 = convert_to_mode (mode, op0, 0);
3213   op1 = expand_expr (arg1, NULL_RTX, mode2, EXPAND_NORMAL);
3214   if (GET_MODE (op1) != mode2)
3215     op1 = convert_to_mode (mode2, op1, 0);
3216
3217   target = emit_library_call_value (optab_libfunc (powi_optab, mode),
3218                                     target, LCT_CONST, mode, 2,
3219                                     op0, mode, op1, mode2);
3220
3221   return target;
3222 }
3223
3224 /* Expand expression EXP which is a call to the strlen builtin.  Return
3225    NULL_RTX if we failed the caller should emit a normal call, otherwise
3226    try to get the result in TARGET, if convenient.  */
3227
3228 static rtx
3229 expand_builtin_strlen (tree exp, rtx target,
3230                        enum machine_mode target_mode)
3231 {
3232   if (!validate_arglist (exp, POINTER_TYPE, VOID_TYPE))
3233     return NULL_RTX;
3234   else
3235     {
3236       rtx pat;
3237       tree len;
3238       tree src = CALL_EXPR_ARG (exp, 0);
3239       rtx result, src_reg, char_rtx, before_strlen;
3240       enum machine_mode insn_mode = target_mode, char_mode;
3241       enum insn_code icode = CODE_FOR_nothing;
3242       int align;
3243
3244       /* If the length can be computed at compile-time, return it.  */
3245       len = c_strlen (src, 0);
3246       if (len)
3247         return expand_expr (len, target, target_mode, EXPAND_NORMAL);
3248
3249       /* If the length can be computed at compile-time and is constant
3250          integer, but there are side-effects in src, evaluate
3251          src for side-effects, then return len.
3252          E.g. x = strlen (i++ ? "xfoo" + 1 : "bar");
3253          can be optimized into: i++; x = 3;  */
3254       len = c_strlen (src, 1);
3255       if (len && TREE_CODE (len) == INTEGER_CST)
3256         {
3257           expand_expr (src, const0_rtx, VOIDmode, EXPAND_NORMAL);
3258           return expand_expr (len, target, target_mode, EXPAND_NORMAL);
3259         }
3260
3261       align = get_pointer_alignment (src, BIGGEST_ALIGNMENT) / BITS_PER_UNIT;
3262
3263       /* If SRC is not a pointer type, don't do this operation inline.  */
3264       if (align == 0)
3265         return NULL_RTX;
3266
3267       /* Bail out if we can't compute strlen in the right mode.  */
3268       while (insn_mode != VOIDmode)
3269         {
3270           icode = optab_handler (strlen_optab, insn_mode);
3271           if (icode != CODE_FOR_nothing)
3272             break;
3273
3274           insn_mode = GET_MODE_WIDER_MODE (insn_mode);
3275         }
3276       if (insn_mode == VOIDmode)
3277         return NULL_RTX;
3278
3279       /* Make a place to write the result of the instruction.  */
3280       result = target;
3281       if (! (result != 0
3282              && REG_P (result)
3283              && GET_MODE (result) == insn_mode
3284              && REGNO (result) >= FIRST_PSEUDO_REGISTER))
3285         result = gen_reg_rtx (insn_mode);
3286
3287       /* Make a place to hold the source address.  We will not expand
3288          the actual source until we are sure that the expansion will
3289          not fail -- there are trees that cannot be expanded twice.  */
3290       src_reg = gen_reg_rtx (Pmode);
3291
3292       /* Mark the beginning of the strlen sequence so we can emit the
3293          source operand later.  */
3294       before_strlen = get_last_insn ();
3295
3296       char_rtx = const0_rtx;
3297       char_mode = insn_data[(int) icode].operand[2].mode;
3298       if (! (*insn_data[(int) icode].operand[2].predicate) (char_rtx,
3299                                                             char_mode))
3300         char_rtx = copy_to_mode_reg (char_mode, char_rtx);
3301
3302       pat = GEN_FCN (icode) (result, gen_rtx_MEM (BLKmode, src_reg),
3303                              char_rtx, GEN_INT (align));
3304       if (! pat)
3305         return NULL_RTX;
3306       emit_insn (pat);
3307
3308       /* Now that we are assured of success, expand the source.  */
3309       start_sequence ();
3310       pat = expand_expr (src, src_reg, ptr_mode, EXPAND_NORMAL);
3311       if (pat != src_reg)
3312         emit_move_insn (src_reg, pat);
3313       pat = get_insns ();
3314       end_sequence ();
3315
3316       if (before_strlen)
3317         emit_insn_after (pat, before_strlen);
3318       else
3319         emit_insn_before (pat, get_insns ());
3320
3321       /* Return the value in the proper mode for this function.  */
3322       if (GET_MODE (result) == target_mode)
3323         target = result;
3324       else if (target != 0)
3325         convert_move (target, result, 0);
3326       else
3327         target = convert_to_mode (target_mode, result, 0);
3328
3329       return target;
3330     }
3331 }
3332
3333 /* Callback routine for store_by_pieces.  Read GET_MODE_BITSIZE (MODE)
3334    bytes from constant string DATA + OFFSET and return it as target
3335    constant.  */
3336
3337 static rtx
3338 builtin_memcpy_read_str (void *data, HOST_WIDE_INT offset,
3339                          enum machine_mode mode)
3340 {
3341   const char *str = (const char *) data;
3342
3343   gcc_assert (offset >= 0
3344               && ((unsigned HOST_WIDE_INT) offset + GET_MODE_SIZE (mode)
3345                   <= strlen (str) + 1));
3346
3347   return c_readstr (str + offset, mode);
3348 }
3349
3350 /* Expand a call EXP to the memcpy builtin.
3351    Return NULL_RTX if we failed, the caller should emit a normal call,
3352    otherwise try to get the result in TARGET, if convenient (and in
3353    mode MODE if that's convenient).  */
3354
3355 static rtx
3356 expand_builtin_memcpy (tree exp, rtx target)
3357 {
3358   if (!validate_arglist (exp,
3359                          POINTER_TYPE, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
3360     return NULL_RTX;
3361   else
3362     {
3363       tree dest = CALL_EXPR_ARG (exp, 0);
3364       tree src = CALL_EXPR_ARG (exp, 1);
3365       tree len = CALL_EXPR_ARG (exp, 2);
3366       const char *src_str;
3367       unsigned int src_align = get_pointer_alignment (src, BIGGEST_ALIGNMENT);
3368       unsigned int dest_align
3369         = get_pointer_alignment (dest, BIGGEST_ALIGNMENT);
3370       rtx dest_mem, src_mem, dest_addr, len_rtx;
3371       HOST_WIDE_INT expected_size = -1;
3372       unsigned int expected_align = 0;
3373
3374       /* If DEST is not a pointer type, call the normal function.  */
3375       if (dest_align == 0)
3376         return NULL_RTX;
3377
3378       /* If either SRC is not a pointer type, don't do this
3379          operation in-line.  */
3380       if (src_align == 0)
3381         return NULL_RTX;
3382
3383       if (currently_expanding_gimple_stmt)
3384         stringop_block_profile (currently_expanding_gimple_stmt,
3385                                 &expected_align, &expected_size);
3386
3387       if (expected_align < dest_align)
3388         expected_align = dest_align;
3389       dest_mem = get_memory_rtx (dest, len);
3390       set_mem_align (dest_mem, dest_align);
3391       len_rtx = expand_normal (len);
3392       src_str = c_getstr (src);
3393
3394       /* If SRC is a string constant and block move would be done
3395          by pieces, we can avoid loading the string from memory
3396          and only stored the computed constants.  */
3397       if (src_str
3398           && CONST_INT_P (len_rtx)
3399           && (unsigned HOST_WIDE_INT) INTVAL (len_rtx) <= strlen (src_str) + 1
3400           && can_store_by_pieces (INTVAL (len_rtx), builtin_memcpy_read_str,
3401                                   CONST_CAST (char *, src_str),
3402                                   dest_align, false))
3403         {
3404           dest_mem = store_by_pieces (dest_mem, INTVAL (len_rtx),
3405                                       builtin_memcpy_read_str,
3406                                       CONST_CAST (char *, src_str),
3407                                       dest_align, false, 0);
3408           dest_mem = force_operand (XEXP (dest_mem, 0), target);
3409           dest_mem = convert_memory_address (ptr_mode, dest_mem);
3410           return dest_mem;
3411         }
3412
3413       src_mem = get_memory_rtx (src, len);
3414       set_mem_align (src_mem, src_align);
3415
3416       /* Copy word part most expediently.  */
3417       dest_addr = emit_block_move_hints (dest_mem, src_mem, len_rtx,
3418                                          CALL_EXPR_TAILCALL (exp)
3419                                          ? BLOCK_OP_TAILCALL : BLOCK_OP_NORMAL,
3420                                          expected_align, expected_size);
3421
3422       if (dest_addr == 0)
3423         {
3424           dest_addr = force_operand (XEXP (dest_mem, 0), target);
3425           dest_addr = convert_memory_address (ptr_mode, dest_addr);
3426         }
3427       return dest_addr;
3428     }
3429 }
3430
3431 /* Expand a call EXP to the mempcpy builtin.
3432    Return NULL_RTX if we failed; the caller should emit a normal call,
3433    otherwise try to get the result in TARGET, if convenient (and in
3434    mode MODE if that's convenient).  If ENDP is 0 return the
3435    destination pointer, if ENDP is 1 return the end pointer ala
3436    mempcpy, and if ENDP is 2 return the end pointer minus one ala
3437    stpcpy.  */
3438
3439 static rtx
3440 expand_builtin_mempcpy (tree exp, rtx target, enum machine_mode mode)
3441 {
3442   if (!validate_arglist (exp,
3443                          POINTER_TYPE, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
3444     return NULL_RTX;
3445   else
3446     {
3447       tree dest = CALL_EXPR_ARG (exp, 0);
3448       tree src = CALL_EXPR_ARG (exp, 1);
3449       tree len = CALL_EXPR_ARG (exp, 2);
3450       return expand_builtin_mempcpy_args (dest, src, len,
3451                                           target, mode, /*endp=*/ 1);
3452     }
3453 }
3454
3455 /* Helper function to do the actual work for expand_builtin_mempcpy.  The
3456    arguments to the builtin_mempcpy call DEST, SRC, and LEN are broken out
3457    so that this can also be called without constructing an actual CALL_EXPR.
3458    The other arguments and return value are the same as for
3459    expand_builtin_mempcpy.  */
3460
3461 static rtx
3462 expand_builtin_mempcpy_args (tree dest, tree src, tree len,
3463                              rtx target, enum machine_mode mode, int endp)
3464 {
3465     /* If return value is ignored, transform mempcpy into memcpy.  */
3466   if (target == const0_rtx && implicit_built_in_decls[BUILT_IN_MEMCPY])
3467     {
3468       tree fn = implicit_built_in_decls[BUILT_IN_MEMCPY];
3469       tree result = build_call_nofold_loc (UNKNOWN_LOCATION, fn, 3,
3470                                            dest, src, len);
3471       return expand_expr (result, target, mode, EXPAND_NORMAL);
3472     }
3473   else
3474     {
3475       const char *src_str;
3476       unsigned int src_align = get_pointer_alignment (src, BIGGEST_ALIGNMENT);
3477       unsigned int dest_align
3478         = get_pointer_alignment (dest, BIGGEST_ALIGNMENT);
3479       rtx dest_mem, src_mem, len_rtx;
3480
3481       /* If either SRC or DEST is not a pointer type, don't do this
3482          operation in-line.  */
3483       if (dest_align == 0 || src_align == 0)
3484         return NULL_RTX;
3485
3486       /* If LEN is not constant, call the normal function.  */
3487       if (! host_integerp (len, 1))
3488         return NULL_RTX;
3489
3490       len_rtx = expand_normal (len);
3491       src_str = c_getstr (src);
3492
3493       /* If SRC is a string constant and block move would be done
3494          by pieces, we can avoid loading the string from memory
3495          and only stored the computed constants.  */
3496       if (src_str
3497           && CONST_INT_P (len_rtx)
3498           && (unsigned HOST_WIDE_INT) INTVAL (len_rtx) <= strlen (src_str) + 1
3499           && can_store_by_pieces (INTVAL (len_rtx), builtin_memcpy_read_str,
3500                                   CONST_CAST (char *, src_str),
3501                                   dest_align, false))
3502         {
3503           dest_mem = get_memory_rtx (dest, len);
3504           set_mem_align (dest_mem, dest_align);
3505           dest_mem = store_by_pieces (dest_mem, INTVAL (len_rtx),
3506                                       builtin_memcpy_read_str,
3507                                       CONST_CAST (char *, src_str),
3508                                       dest_align, false, endp);
3509           dest_mem = force_operand (XEXP (dest_mem, 0), NULL_RTX);
3510           dest_mem = convert_memory_address (ptr_mode, dest_mem);
3511           return dest_mem;
3512         }
3513
3514       if (CONST_INT_P (len_rtx)
3515           && can_move_by_pieces (INTVAL (len_rtx),
3516                                  MIN (dest_align, src_align)))
3517         {
3518           dest_mem = get_memory_rtx (dest, len);
3519           set_mem_align (dest_mem, dest_align);
3520           src_mem = get_memory_rtx (src, len);
3521           set_mem_align (src_mem, src_align);
3522           dest_mem = move_by_pieces (dest_mem, src_mem, INTVAL (len_rtx),
3523                                      MIN (dest_align, src_align), endp);
3524           dest_mem = force_operand (XEXP (dest_mem, 0), NULL_RTX);
3525           dest_mem = convert_memory_address (ptr_mode, dest_mem);
3526           return dest_mem;
3527         }
3528
3529       return NULL_RTX;
3530     }
3531 }
3532
3533 #ifndef HAVE_movstr
3534 # define HAVE_movstr 0
3535 # define CODE_FOR_movstr CODE_FOR_nothing
3536 #endif
3537
3538 /* Expand into a movstr instruction, if one is available.  Return NULL_RTX if
3539    we failed, the caller should emit a normal call, otherwise try to
3540    get the result in TARGET, if convenient.  If ENDP is 0 return the
3541    destination pointer, if ENDP is 1 return the end pointer ala
3542    mempcpy, and if ENDP is 2 return the end pointer minus one ala
3543    stpcpy.  */
3544
3545 static rtx
3546 expand_movstr (tree dest, tree src, rtx target, int endp)
3547 {
3548   rtx end;
3549   rtx dest_mem;
3550   rtx src_mem;
3551   rtx insn;
3552   const struct insn_data_d * data;
3553
3554   if (!HAVE_movstr)
3555     return NULL_RTX;
3556
3557   dest_mem = get_memory_rtx (dest, NULL);
3558   src_mem = get_memory_rtx (src, NULL);
3559   data = insn_data + CODE_FOR_movstr;
3560   if (!endp)
3561     {
3562       target = force_reg (Pmode, XEXP (dest_mem, 0));
3563       dest_mem = replace_equiv_address (dest_mem, target);
3564       end = gen_reg_rtx (Pmode);
3565     }
3566   else
3567     {
3568       if (target == 0
3569           || target == const0_rtx
3570           || ! (*data->operand[0].predicate) (target, Pmode))
3571         {
3572           end = gen_reg_rtx (Pmode);
3573           if (target != const0_rtx)
3574             target = end;
3575         }
3576       else
3577         end = target;
3578     }
3579
3580   if (data->operand[0].mode != VOIDmode)
3581     end = gen_lowpart (data->operand[0].mode, end);
3582
3583   insn = data->genfun (end, dest_mem, src_mem);
3584
3585   gcc_assert (insn);
3586
3587   emit_insn (insn);
3588
3589   /* movstr is supposed to set end to the address of the NUL
3590      terminator.  If the caller requested a mempcpy-like return value,
3591      adjust it.  */
3592   if (endp == 1 && target != const0_rtx)
3593     {
3594       rtx tem = plus_constant (gen_lowpart (GET_MODE (target), end), 1);
3595       emit_move_insn (target, force_operand (tem, NULL_RTX));
3596     }
3597
3598   return target;
3599 }
3600
3601 /* Expand expression EXP, which is a call to the strcpy builtin.  Return
3602    NULL_RTX if we failed the caller should emit a normal call, otherwise
3603    try to get the result in TARGET, if convenient (and in mode MODE if that's
3604    convenient).  */
3605
3606 static rtx
3607 expand_builtin_strcpy (tree exp, rtx target)
3608 {
3609   if (validate_arglist (exp, POINTER_TYPE, POINTER_TYPE, VOID_TYPE))
3610    {
3611      tree dest = CALL_EXPR_ARG (exp, 0);
3612      tree src = CALL_EXPR_ARG (exp, 1);
3613      return expand_builtin_strcpy_args (dest, src, target);
3614    }
3615    return NULL_RTX;
3616 }
3617
3618 /* Helper function to do the actual work for expand_builtin_strcpy.  The
3619    arguments to the builtin_strcpy call DEST and SRC are broken out
3620    so that this can also be called without constructing an actual CALL_EXPR.
3621    The other arguments and return value are the same as for
3622    expand_builtin_strcpy.  */
3623
3624 static rtx
3625 expand_builtin_strcpy_args (tree dest, tree src, rtx target)
3626 {
3627   return expand_movstr (dest, src, target, /*endp=*/0);
3628 }
3629
3630 /* Expand a call EXP to the stpcpy builtin.
3631    Return NULL_RTX if we failed the caller should emit a normal call,
3632    otherwise try to get the result in TARGET, if convenient (and in
3633    mode MODE if that's convenient).  */
3634
3635 static rtx
3636 expand_builtin_stpcpy (tree exp, rtx target, enum machine_mode mode)
3637 {
3638   tree dst, src;
3639   location_t loc = EXPR_LOCATION (exp);
3640
3641   if (!validate_arglist (exp, POINTER_TYPE, POINTER_TYPE, VOID_TYPE))
3642     return NULL_RTX;
3643
3644   dst = CALL_EXPR_ARG (exp, 0);
3645   src = CALL_EXPR_ARG (exp, 1);
3646
3647   /* If return value is ignored, transform stpcpy into strcpy.  */
3648   if (target == const0_rtx && implicit_built_in_decls[BUILT_IN_STRCPY])
3649     {
3650       tree fn = implicit_built_in_decls[BUILT_IN_STRCPY];
3651       tree result = build_call_nofold_loc (loc, fn, 2, dst, src);
3652       return expand_expr (result, target, mode, EXPAND_NORMAL);
3653     }
3654   else
3655     {
3656       tree len, lenp1;
3657       rtx ret;
3658
3659       /* Ensure we get an actual string whose length can be evaluated at
3660          compile-time, not an expression containing a string.  This is
3661          because the latter will potentially produce pessimized code
3662          when used to produce the return value.  */
3663       if (! c_getstr (src) || ! (len = c_strlen (src, 0)))
3664         return expand_movstr (dst, src, target, /*endp=*/2);
3665
3666       lenp1 = size_binop_loc (loc, PLUS_EXPR, len, ssize_int (1));
3667       ret = expand_builtin_mempcpy_args (dst, src, lenp1,
3668                                          target, mode, /*endp=*/2);
3669
3670       if (ret)
3671         return ret;
3672
3673       if (TREE_CODE (len) == INTEGER_CST)
3674         {
3675           rtx len_rtx = expand_normal (len);
3676
3677           if (CONST_INT_P (len_rtx))
3678             {
3679               ret = expand_builtin_strcpy_args (dst, src, target);
3680
3681               if (ret)
3682                 {
3683                   if (! target)
3684                     {
3685                       if (mode != VOIDmode)
3686                         target = gen_reg_rtx (mode);
3687                       else
3688                         target = gen_reg_rtx (GET_MODE (ret));
3689                     }
3690                   if (GET_MODE (target) != GET_MODE (ret))
3691                     ret = gen_lowpart (GET_MODE (target), ret);
3692
3693                   ret = plus_constant (ret, INTVAL (len_rtx));
3694                   ret = emit_move_insn (target, force_operand (ret, NULL_RTX));
3695                   gcc_assert (ret);
3696
3697                   return target;
3698                 }
3699             }
3700         }
3701
3702       return expand_movstr (dst, src, target, /*endp=*/2);
3703     }
3704 }
3705
3706 /* Callback routine for store_by_pieces.  Read GET_MODE_BITSIZE (MODE)
3707    bytes from constant string DATA + OFFSET and return it as target
3708    constant.  */
3709
3710 rtx
3711 builtin_strncpy_read_str (void *data, HOST_WIDE_INT offset,
3712                           enum machine_mode mode)
3713 {
3714   const char *str = (const char *) data;
3715
3716   if ((unsigned HOST_WIDE_INT) offset > strlen (str))
3717     return const0_rtx;
3718
3719   return c_readstr (str + offset, mode);
3720 }
3721
3722 /* Expand expression EXP, which is a call to the strncpy builtin.  Return
3723    NULL_RTX if we failed the caller should emit a normal call.  */
3724
3725 static rtx
3726 expand_builtin_strncpy (tree exp, rtx target)
3727 {
3728   location_t loc = EXPR_LOCATION (exp);
3729
3730   if (validate_arglist (exp,
3731                         POINTER_TYPE, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
3732     {
3733       tree dest = CALL_EXPR_ARG (exp, 0);
3734       tree src = CALL_EXPR_ARG (exp, 1);
3735       tree len = CALL_EXPR_ARG (exp, 2);
3736       tree slen = c_strlen (src, 1);
3737
3738       /* We must be passed a constant len and src parameter.  */
3739       if (!host_integerp (len, 1) || !slen || !host_integerp (slen, 1))
3740         return NULL_RTX;
3741
3742       slen = size_binop_loc (loc, PLUS_EXPR, slen, ssize_int (1));
3743
3744       /* We're required to pad with trailing zeros if the requested
3745          len is greater than strlen(s2)+1.  In that case try to
3746          use store_by_pieces, if it fails, punt.  */
3747       if (tree_int_cst_lt (slen, len))
3748         {
3749           unsigned int dest_align
3750             = get_pointer_alignment (dest, BIGGEST_ALIGNMENT);
3751           const char *p = c_getstr (src);
3752           rtx dest_mem;
3753
3754           if (!p || dest_align == 0 || !host_integerp (len, 1)
3755               || !can_store_by_pieces (tree_low_cst (len, 1),
3756                                        builtin_strncpy_read_str,
3757                                        CONST_CAST (char *, p),
3758                                        dest_align, false))
3759             return NULL_RTX;
3760
3761           dest_mem = get_memory_rtx (dest, len);
3762           store_by_pieces (dest_mem, tree_low_cst (len, 1),
3763                            builtin_strncpy_read_str,
3764                            CONST_CAST (char *, p), dest_align, false, 0);
3765           dest_mem = force_operand (XEXP (dest_mem, 0), target);
3766           dest_mem = convert_memory_address (ptr_mode, dest_mem);
3767           return dest_mem;
3768         }
3769     }
3770   return NULL_RTX;
3771 }
3772
3773 /* Callback routine for store_by_pieces.  Read GET_MODE_BITSIZE (MODE)
3774    bytes from constant string DATA + OFFSET and return it as target
3775    constant.  */
3776
3777 rtx
3778 builtin_memset_read_str (void *data, HOST_WIDE_INT offset ATTRIBUTE_UNUSED,
3779                          enum machine_mode mode)
3780 {
3781   const char *c = (const char *) data;
3782   char *p = XALLOCAVEC (char, GET_MODE_SIZE (mode));
3783
3784   memset (p, *c, GET_MODE_SIZE (mode));
3785
3786   return c_readstr (p, mode);
3787 }
3788
3789 /* Callback routine for store_by_pieces.  Return the RTL of a register
3790    containing GET_MODE_SIZE (MODE) consecutive copies of the unsigned
3791    char value given in the RTL register data.  For example, if mode is
3792    4 bytes wide, return the RTL for 0x01010101*data.  */
3793
3794 static rtx
3795 builtin_memset_gen_str (void *data, HOST_WIDE_INT offset ATTRIBUTE_UNUSED,
3796                         enum machine_mode mode)
3797 {
3798   rtx target, coeff;
3799   size_t size;
3800   char *p;
3801
3802   size = GET_MODE_SIZE (mode);
3803   if (size == 1)
3804     return (rtx) data;
3805
3806   p = XALLOCAVEC (char, size);
3807   memset (p, 1, size);
3808   coeff = c_readstr (p, mode);
3809
3810   target = convert_to_mode (mode, (rtx) data, 1);
3811   target = expand_mult (mode, target, coeff, NULL_RTX, 1);
3812   return force_reg (mode, target);
3813 }
3814
3815 /* Expand expression EXP, which is a call to the memset builtin.  Return
3816    NULL_RTX if we failed the caller should emit a normal call, otherwise
3817    try to get the result in TARGET, if convenient (and in mode MODE if that's
3818    convenient).  */
3819
3820 static rtx
3821 expand_builtin_memset (tree exp, rtx target, enum machine_mode mode)
3822 {
3823   if (!validate_arglist (exp,
3824                          POINTER_TYPE, INTEGER_TYPE, INTEGER_TYPE, VOID_TYPE))
3825     return NULL_RTX;
3826   else
3827     {
3828       tree dest = CALL_EXPR_ARG (exp, 0);
3829       tree val = CALL_EXPR_ARG (exp, 1);
3830       tree len = CALL_EXPR_ARG (exp, 2);
3831       return expand_builtin_memset_args (dest, val, len, target, mode, exp);
3832     }
3833 }
3834
3835 /* Helper function to do the actual work for expand_builtin_memset.  The
3836    arguments to the builtin_memset call DEST, VAL, and LEN are broken out
3837    so that this can also be called without constructing an actual CALL_EXPR.
3838    The other arguments and return value are the same as for
3839    expand_builtin_memset.  */
3840
3841 static rtx
3842 expand_builtin_memset_args (tree dest, tree val, tree len,
3843                             rtx target, enum machine_mode mode, tree orig_exp)
3844 {
3845   tree fndecl, fn;
3846   enum built_in_function fcode;
3847   char c;
3848   unsigned int dest_align;
3849   rtx dest_mem, dest_addr, len_rtx;
3850   HOST_WIDE_INT expected_size = -1;
3851   unsigned int expected_align = 0;
3852
3853   dest_align = get_pointer_alignment (dest, BIGGEST_ALIGNMENT);
3854
3855   /* If DEST is not a pointer type, don't do this operation in-line.  */
3856   if (dest_align == 0)
3857     return NULL_RTX;
3858
3859   if (currently_expanding_gimple_stmt)
3860     stringop_block_profile (currently_expanding_gimple_stmt,
3861                             &expected_align, &expected_size);
3862
3863   if (expected_align < dest_align)
3864     expected_align = dest_align;
3865
3866   /* If the LEN parameter is zero, return DEST.  */
3867   if (integer_zerop (len))
3868     {
3869       /* Evaluate and ignore VAL in case it has side-effects.  */
3870       expand_expr (val, const0_rtx, VOIDmode, EXPAND_NORMAL);
3871       return expand_expr (dest, target, mode, EXPAND_NORMAL);
3872     }
3873
3874   /* Stabilize the arguments in case we fail.  */
3875   dest = builtin_save_expr (dest);
3876   val = builtin_save_expr (val);
3877   len = builtin_save_expr (len);
3878
3879   len_rtx = expand_normal (len);
3880   dest_mem = get_memory_rtx (dest, len);
3881
3882   if (TREE_CODE (val) != INTEGER_CST)
3883     {
3884       rtx val_rtx;
3885
3886       val_rtx = expand_normal (val);
3887       val_rtx = convert_to_mode (TYPE_MODE (unsigned_char_type_node),
3888                                  val_rtx, 0);
3889
3890       /* Assume that we can memset by pieces if we can store
3891        * the coefficients by pieces (in the required modes).
3892        * We can't pass builtin_memset_gen_str as that emits RTL.  */
3893       c = 1;
3894       if (host_integerp (len, 1)
3895           && can_store_by_pieces (tree_low_cst (len, 1),
3896                                   builtin_memset_read_str, &c, dest_align,
3897                                   true))
3898         {
3899           val_rtx = force_reg (TYPE_MODE (unsigned_char_type_node),
3900                                val_rtx);
3901           store_by_pieces (dest_mem, tree_low_cst (len, 1),
3902                            builtin_memset_gen_str, val_rtx, dest_align,
3903                            true, 0);
3904         }
3905       else if (!set_storage_via_setmem (dest_mem, len_rtx, val_rtx,
3906                                         dest_align, expected_align,
3907                                         expected_size))
3908         goto do_libcall;
3909
3910       dest_mem = force_operand (XEXP (dest_mem, 0), NULL_RTX);
3911       dest_mem = convert_memory_address (ptr_mode, dest_mem);
3912       return dest_mem;
3913     }
3914
3915   if (target_char_cast (val, &c))
3916     goto do_libcall;
3917
3918   if (c)
3919     {
3920       if (host_integerp (len, 1)
3921           && can_store_by_pieces (tree_low_cst (len, 1),
3922                                   builtin_memset_read_str, &c, dest_align,
3923                                   true))
3924         store_by_pieces (dest_mem, tree_low_cst (len, 1),
3925                          builtin_memset_read_str, &c, dest_align, true, 0);
3926       else if (!set_storage_via_setmem (dest_mem, len_rtx, GEN_INT (c),
3927                                         dest_align, expected_align,
3928                                         expected_size))
3929         goto do_libcall;
3930
3931       dest_mem = force_operand (XEXP (dest_mem, 0), NULL_RTX);
3932       dest_mem = convert_memory_address (ptr_mode, dest_mem);
3933       return dest_mem;
3934     }
3935
3936   set_mem_align (dest_mem, dest_align);
3937   dest_addr = clear_storage_hints (dest_mem, len_rtx,
3938                                    CALL_EXPR_TAILCALL (orig_exp)
3939                                    ? BLOCK_OP_TAILCALL : BLOCK_OP_NORMAL,
3940                                    expected_align, expected_size);
3941
3942   if (dest_addr == 0)
3943     {
3944       dest_addr = force_operand (XEXP (dest_mem, 0), NULL_RTX);
3945       dest_addr = convert_memory_address (ptr_mode, dest_addr);
3946     }
3947
3948   return dest_addr;
3949
3950  do_libcall:
3951   fndecl = get_callee_fndecl (orig_exp);
3952   fcode = DECL_FUNCTION_CODE (fndecl);
3953   if (fcode == BUILT_IN_MEMSET)
3954     fn = build_call_nofold_loc (EXPR_LOCATION (orig_exp), fndecl, 3,
3955                                 dest, val, len);
3956   else if (fcode == BUILT_IN_BZERO)
3957     fn = build_call_nofold_loc (EXPR_LOCATION (orig_exp), fndecl, 2,
3958                                 dest, len);
3959   else
3960     gcc_unreachable ();
3961   gcc_assert (TREE_CODE (fn) == CALL_EXPR);
3962   CALL_EXPR_TAILCALL (fn) = CALL_EXPR_TAILCALL (orig_exp);
3963   return expand_call (fn, target, target == const0_rtx);
3964 }
3965
3966 /* Expand expression EXP, which is a call to the bzero builtin.  Return
3967    NULL_RTX if we failed the caller should emit a normal call.  */
3968
3969 static rtx
3970 expand_builtin_bzero (tree exp)
3971 {
3972   tree dest, size;
3973   location_t loc = EXPR_LOCATION (exp);
3974
3975   if (!validate_arglist (exp, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
3976     return NULL_RTX;
3977
3978   dest = CALL_EXPR_ARG (exp, 0);
3979   size = CALL_EXPR_ARG (exp, 1);
3980
3981   /* New argument list transforming bzero(ptr x, int y) to
3982      memset(ptr x, int 0, size_t y).   This is done this way
3983      so that if it isn't expanded inline, we fallback to
3984      calling bzero instead of memset.  */
3985
3986   return expand_builtin_memset_args (dest, integer_zero_node,
3987                                      fold_convert_loc (loc, sizetype, size),
3988                                      const0_rtx, VOIDmode, exp);
3989 }
3990
3991 /* Expand expression EXP, which is a call to the memcmp built-in function.
3992    Return NULL_RTX if we failed and the
3993    caller should emit a normal call, otherwise try to get the result in
3994    TARGET, if convenient (and in mode MODE, if that's convenient).  */
3995
3996 static rtx
3997 expand_builtin_memcmp (tree exp, ATTRIBUTE_UNUSED rtx target,
3998                        ATTRIBUTE_UNUSED enum machine_mode mode)
3999 {
4000   location_t loc ATTRIBUTE_UNUSED = EXPR_LOCATION (exp);
4001
4002   if (!validate_arglist (exp,
4003                          POINTER_TYPE, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
4004     return NULL_RTX;
4005
4006 #if defined HAVE_cmpmemsi || defined HAVE_cmpstrnsi
4007   {
4008     rtx arg1_rtx, arg2_rtx, arg3_rtx;
4009     rtx result;
4010     rtx insn;
4011     tree arg1 = CALL_EXPR_ARG (exp, 0);
4012     tree arg2 = CALL_EXPR_ARG (exp, 1);
4013     tree len = CALL_EXPR_ARG (exp, 2);
4014
4015     int arg1_align
4016       = get_pointer_alignment (arg1, BIGGEST_ALIGNMENT) / BITS_PER_UNIT;
4017     int arg2_align
4018       = get_pointer_alignment (arg2, BIGGEST_ALIGNMENT) / BITS_PER_UNIT;
4019     enum machine_mode insn_mode;
4020
4021 #ifdef HAVE_cmpmemsi
4022     if (HAVE_cmpmemsi)
4023       insn_mode = insn_data[(int) CODE_FOR_cmpmemsi].operand[0].mode;
4024     else
4025 #endif
4026 #ifdef HAVE_cmpstrnsi
4027     if (HAVE_cmpstrnsi)
4028       insn_mode = insn_data[(int) CODE_FOR_cmpstrnsi].operand[0].mode;
4029     else
4030 #endif
4031       return NULL_RTX;
4032
4033     /* If we don't have POINTER_TYPE, call the function.  */
4034     if (arg1_align == 0 || arg2_align == 0)
4035       return NULL_RTX;
4036
4037     /* Make a place to write the result of the instruction.  */
4038     result = target;
4039     if (! (result != 0
4040            && REG_P (result) && GET_MODE (result) == insn_mode
4041            && REGNO (result) >= FIRST_PSEUDO_REGISTER))
4042       result = gen_reg_rtx (insn_mode);
4043
4044     arg1_rtx = get_memory_rtx (arg1, len);
4045     arg2_rtx = get_memory_rtx (arg2, len);
4046     arg3_rtx = expand_normal (fold_convert_loc (loc, sizetype, len));
4047
4048     /* Set MEM_SIZE as appropriate.  */
4049     if (CONST_INT_P (arg3_rtx))
4050       {
4051         set_mem_size (arg1_rtx, arg3_rtx);
4052         set_mem_size (arg2_rtx, arg3_rtx);
4053       }
4054
4055 #ifdef HAVE_cmpmemsi
4056     if (HAVE_cmpmemsi)
4057       insn = gen_cmpmemsi (result, arg1_rtx, arg2_rtx, arg3_rtx,
4058                            GEN_INT (MIN (arg1_align, arg2_align)));
4059     else
4060 #endif
4061 #ifdef HAVE_cmpstrnsi
4062     if (HAVE_cmpstrnsi)
4063       insn = gen_cmpstrnsi (result, arg1_rtx, arg2_rtx, arg3_rtx,
4064                             GEN_INT (MIN (arg1_align, arg2_align)));
4065     else
4066 #endif
4067       gcc_unreachable ();
4068
4069     if (insn)
4070       emit_insn (insn);
4071     else
4072       emit_library_call_value (memcmp_libfunc, result, LCT_PURE,
4073                                TYPE_MODE (integer_type_node), 3,
4074                                XEXP (arg1_rtx, 0), Pmode,
4075                                XEXP (arg2_rtx, 0), Pmode,
4076                                convert_to_mode (TYPE_MODE (sizetype), arg3_rtx,
4077                                                 TYPE_UNSIGNED (sizetype)),
4078                                TYPE_MODE (sizetype));
4079
4080     /* Return the value in the proper mode for this function.  */
4081     mode = TYPE_MODE (TREE_TYPE (exp));
4082     if (GET_MODE (result) == mode)
4083       return result;
4084     else if (target != 0)
4085       {
4086         convert_move (target, result, 0);
4087         return target;
4088       }
4089     else
4090       return convert_to_mode (mode, result, 0);
4091   }
4092 #endif
4093
4094   return NULL_RTX;
4095 }
4096
4097 /* Expand expression EXP, which is a call to the strcmp builtin.  Return NULL_RTX
4098    if we failed the caller should emit a normal call, otherwise try to get
4099    the result in TARGET, if convenient.  */
4100
4101 static rtx
4102 expand_builtin_strcmp (tree exp, ATTRIBUTE_UNUSED rtx target)
4103 {
4104   if (!validate_arglist (exp, POINTER_TYPE, POINTER_TYPE, VOID_TYPE))
4105     return NULL_RTX;
4106
4107 #if defined HAVE_cmpstrsi || defined HAVE_cmpstrnsi
4108   if (direct_optab_handler (cmpstr_optab, SImode) != CODE_FOR_nothing
4109       || direct_optab_handler (cmpstrn_optab, SImode) != CODE_FOR_nothing)
4110     {
4111       rtx arg1_rtx, arg2_rtx;
4112       rtx result, insn = NULL_RTX;
4113       tree fndecl, fn;
4114       tree arg1 = CALL_EXPR_ARG (exp, 0);
4115       tree arg2 = CALL_EXPR_ARG (exp, 1);
4116
4117       int arg1_align
4118         = get_pointer_alignment (arg1, BIGGEST_ALIGNMENT) / BITS_PER_UNIT;
4119       int arg2_align
4120         = get_pointer_alignment (arg2, BIGGEST_ALIGNMENT) / BITS_PER_UNIT;
4121
4122       /* If we don't have POINTER_TYPE, call the function.  */
4123       if (arg1_align == 0 || arg2_align == 0)
4124         return NULL_RTX;
4125
4126       /* Stabilize the arguments in case gen_cmpstr(n)si fail.  */
4127       arg1 = builtin_save_expr (arg1);
4128       arg2 = builtin_save_expr (arg2);
4129
4130       arg1_rtx = get_memory_rtx (arg1, NULL);
4131       arg2_rtx = get_memory_rtx (arg2, NULL);
4132
4133 #ifdef HAVE_cmpstrsi
4134       /* Try to call cmpstrsi.  */
4135       if (HAVE_cmpstrsi)
4136         {
4137           enum machine_mode insn_mode
4138             = insn_data[(int) CODE_FOR_cmpstrsi].operand[0].mode;
4139
4140           /* Make a place to write the result of the instruction.  */
4141           result = target;
4142           if (! (result != 0
4143                  && REG_P (result) && GET_MODE (result) == insn_mode
4144                  && REGNO (result) >= FIRST_PSEUDO_REGISTER))
4145             result = gen_reg_rtx (insn_mode);
4146
4147           insn = gen_cmpstrsi (result, arg1_rtx, arg2_rtx,
4148                                GEN_INT (MIN (arg1_align, arg2_align)));
4149         }
4150 #endif
4151 #ifdef HAVE_cmpstrnsi
4152       /* Try to determine at least one length and call cmpstrnsi.  */
4153       if (!insn && HAVE_cmpstrnsi)
4154         {
4155           tree len;
4156           rtx arg3_rtx;
4157
4158           enum machine_mode insn_mode
4159             = insn_data[(int) CODE_FOR_cmpstrnsi].operand[0].mode;
4160           tree len1 = c_strlen (arg1, 1);
4161           tree len2 = c_strlen (arg2, 1);
4162
4163           if (len1)
4164             len1 = size_binop (PLUS_EXPR, ssize_int (1), len1);
4165           if (len2)
4166             len2 = size_binop (PLUS_EXPR, ssize_int (1), len2);
4167
4168           /* If we don't have a constant length for the first, use the length
4169              of the second, if we know it.  We don't require a constant for
4170              this case; some cost analysis could be done if both are available
4171              but neither is constant.  For now, assume they're equally cheap,
4172              unless one has side effects.  If both strings have constant lengths,
4173              use the smaller.  */
4174
4175           if (!len1)
4176             len = len2;
4177           else if (!len2)
4178             len = len1;
4179           else if (TREE_SIDE_EFFECTS (len1))
4180             len = len2;
4181           else if (TREE_SIDE_EFFECTS (len2))
4182             len = len1;
4183           else if (TREE_CODE (len1) != INTEGER_CST)
4184             len = len2;
4185           else if (TREE_CODE (len2) != INTEGER_CST)
4186             len = len1;
4187           else if (tree_int_cst_lt (len1, len2))
4188             len = len1;
4189           else
4190             len = len2;
4191
4192           /* If both arguments have side effects, we cannot optimize.  */
4193           if (!len || TREE_SIDE_EFFECTS (len))
4194             goto do_libcall;
4195
4196           arg3_rtx = expand_normal (len);
4197
4198           /* Make a place to write the result of the instruction.  */
4199           result = target;
4200           if (! (result != 0
4201                  && REG_P (result) && GET_MODE (result) == insn_mode
4202                  && REGNO (result) >= FIRST_PSEUDO_REGISTER))
4203             result = gen_reg_rtx (insn_mode);
4204
4205           insn = gen_cmpstrnsi (result, arg1_rtx, arg2_rtx, arg3_rtx,
4206                                 GEN_INT (MIN (arg1_align, arg2_align)));
4207         }
4208 #endif
4209
4210       if (insn)
4211         {
4212           enum machine_mode mode;
4213           emit_insn (insn);
4214
4215           /* Return the value in the proper mode for this function.  */
4216           mode = TYPE_MODE (TREE_TYPE (exp));
4217           if (GET_MODE (result) == mode)
4218             return result;
4219           if (target == 0)
4220             return convert_to_mode (mode, result, 0);
4221           convert_move (target, result, 0);
4222           return target;
4223         }
4224
4225       /* Expand the library call ourselves using a stabilized argument
4226          list to avoid re-evaluating the function's arguments twice.  */
4227 #ifdef HAVE_cmpstrnsi
4228     do_libcall:
4229 #endif
4230       fndecl = get_callee_fndecl (exp);
4231       fn = build_call_nofold_loc (EXPR_LOCATION (exp), fndecl, 2, arg1, arg2);
4232       gcc_assert (TREE_CODE (fn) == CALL_EXPR);
4233       CALL_EXPR_TAILCALL (fn) = CALL_EXPR_TAILCALL (exp);
4234       return expand_call (fn, target, target == const0_rtx);
4235     }
4236 #endif
4237   return NULL_RTX;
4238 }
4239
4240 /* Expand expression EXP, which is a call to the strncmp builtin. Return
4241    NULL_RTX if we failed the caller should emit a normal call, otherwise try to get
4242    the result in TARGET, if convenient.  */
4243
4244 static rtx
4245 expand_builtin_strncmp (tree exp, ATTRIBUTE_UNUSED rtx target,
4246                         ATTRIBUTE_UNUSED enum machine_mode mode)
4247 {
4248   location_t loc ATTRIBUTE_UNUSED = EXPR_LOCATION (exp);
4249
4250   if (!validate_arglist (exp,
4251                          POINTER_TYPE, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
4252     return NULL_RTX;
4253
4254   /* If c_strlen can determine an expression for one of the string
4255      lengths, and it doesn't have side effects, then emit cmpstrnsi
4256      using length MIN(strlen(string)+1, arg3).  */
4257 #ifdef HAVE_cmpstrnsi
4258   if (HAVE_cmpstrnsi)
4259   {
4260     tree len, len1, len2;
4261     rtx arg1_rtx, arg2_rtx, arg3_rtx;
4262     rtx result, insn;
4263     tree fndecl, fn;
4264     tree arg1 = CALL_EXPR_ARG (exp, 0);
4265     tree arg2 = CALL_EXPR_ARG (exp, 1);
4266     tree arg3 = CALL_EXPR_ARG (exp, 2);
4267
4268     int arg1_align
4269       = get_pointer_alignment (arg1, BIGGEST_ALIGNMENT) / BITS_PER_UNIT;
4270     int arg2_align
4271       = get_pointer_alignment (arg2, BIGGEST_ALIGNMENT) / BITS_PER_UNIT;
4272     enum machine_mode insn_mode
4273       = insn_data[(int) CODE_FOR_cmpstrnsi].operand[0].mode;
4274
4275     len1 = c_strlen (arg1, 1);
4276     len2 = c_strlen (arg2, 1);
4277
4278     if (len1)
4279       len1 = size_binop_loc (loc, PLUS_EXPR, ssize_int (1), len1);
4280     if (len2)
4281       len2 = size_binop_loc (loc, PLUS_EXPR, ssize_int (1), len2);
4282
4283     /* If we don't have a constant length for the first, use the length
4284        of the second, if we know it.  We don't require a constant for
4285        this case; some cost analysis could be done if both are available
4286        but neither is constant.  For now, assume they're equally cheap,
4287        unless one has side effects.  If both strings have constant lengths,
4288        use the smaller.  */
4289
4290     if (!len1)
4291       len = len2;
4292     else if (!len2)
4293       len = len1;
4294     else if (TREE_SIDE_EFFECTS (len1))
4295       len = len2;
4296     else if (TREE_SIDE_EFFECTS (len2))
4297       len = len1;
4298     else if (TREE_CODE (len1) != INTEGER_CST)
4299       len = len2;
4300     else if (TREE_CODE (len2) != INTEGER_CST)
4301       len = len1;
4302     else if (tree_int_cst_lt (len1, len2))
4303       len = len1;
4304     else
4305       len = len2;
4306
4307     /* If both arguments have side effects, we cannot optimize.  */
4308     if (!len || TREE_SIDE_EFFECTS (len))
4309       return NULL_RTX;
4310
4311     /* The actual new length parameter is MIN(len,arg3).  */
4312     len = fold_build2_loc (loc, MIN_EXPR, TREE_TYPE (len), len,
4313                        fold_convert_loc (loc, TREE_TYPE (len), arg3));
4314
4315     /* If we don't have POINTER_TYPE, call the function.  */
4316     if (arg1_align == 0 || arg2_align == 0)
4317       return NULL_RTX;
4318
4319     /* Make a place to write the result of the instruction.  */
4320     result = target;
4321     if (! (result != 0
4322            && REG_P (result) && GET_MODE (result) == insn_mode
4323            && REGNO (result) >= FIRST_PSEUDO_REGISTER))
4324       result = gen_reg_rtx (insn_mode);
4325
4326     /* Stabilize the arguments in case gen_cmpstrnsi fails.  */
4327     arg1 = builtin_save_expr (arg1);
4328     arg2 = builtin_save_expr (arg2);
4329     len = builtin_save_expr (len);
4330
4331     arg1_rtx = get_memory_rtx (arg1, len);
4332     arg2_rtx = get_memory_rtx (arg2, len);
4333     arg3_rtx = expand_normal (len);
4334     insn = gen_cmpstrnsi (result, arg1_rtx, arg2_rtx, arg3_rtx,
4335                           GEN_INT (MIN (arg1_align, arg2_align)));
4336     if (insn)
4337       {
4338         emit_insn (insn);
4339
4340         /* Return the value in the proper mode for this function.  */
4341         mode = TYPE_MODE (TREE_TYPE (exp));
4342         if (GET_MODE (result) == mode)
4343           return result;
4344         if (target == 0)
4345           return convert_to_mode (mode, result, 0);
4346         convert_move (target, result, 0);
4347         return target;
4348       }
4349
4350     /* Expand the library call ourselves using a stabilized argument
4351        list to avoid re-evaluating the function's arguments twice.  */
4352     fndecl = get_callee_fndecl (exp);
4353     fn = build_call_nofold_loc (EXPR_LOCATION (exp), fndecl, 3,
4354                                 arg1, arg2, len);
4355     gcc_assert (TREE_CODE (fn) == CALL_EXPR);
4356     CALL_EXPR_TAILCALL (fn) = CALL_EXPR_TAILCALL (exp);
4357     return expand_call (fn, target, target == const0_rtx);
4358   }
4359 #endif
4360   return NULL_RTX;
4361 }
4362
4363 /* Expand a call to __builtin_saveregs, generating the result in TARGET,
4364    if that's convenient.  */
4365
4366 rtx
4367 expand_builtin_saveregs (void)
4368 {
4369   rtx val, seq;
4370
4371   /* Don't do __builtin_saveregs more than once in a function.
4372      Save the result of the first call and reuse it.  */
4373   if (saveregs_value != 0)
4374     return saveregs_value;
4375
4376   /* When this function is called, it means that registers must be
4377      saved on entry to this function.  So we migrate the call to the
4378      first insn of this function.  */
4379
4380   start_sequence ();
4381
4382   /* Do whatever the machine needs done in this case.  */
4383   val = targetm.calls.expand_builtin_saveregs ();
4384
4385   seq = get_insns ();
4386   end_sequence ();
4387
4388   saveregs_value = val;
4389
4390   /* Put the insns after the NOTE that starts the function.  If this
4391      is inside a start_sequence, make the outer-level insn chain current, so
4392      the code is placed at the start of the function.  */
4393   push_topmost_sequence ();
4394   emit_insn_after (seq, entry_of_function ());
4395   pop_topmost_sequence ();
4396
4397   return val;
4398 }
4399
4400 /* Expand a call to __builtin_next_arg.  */
4401
4402 static rtx
4403 expand_builtin_next_arg (void)
4404 {
4405   /* Checking arguments is already done in fold_builtin_next_arg
4406      that must be called before this function.  */
4407   return expand_binop (ptr_mode, add_optab,
4408                        crtl->args.internal_arg_pointer,
4409                        crtl->args.arg_offset_rtx,
4410                        NULL_RTX, 0, OPTAB_LIB_WIDEN);
4411 }
4412
4413 /* Make it easier for the backends by protecting the valist argument
4414    from multiple evaluations.  */
4415
4416 static tree
4417 stabilize_va_list_loc (location_t loc, tree valist, int needs_lvalue)
4418 {
4419   tree vatype = targetm.canonical_va_list_type (TREE_TYPE (valist));
4420
4421   /* The current way of determining the type of valist is completely
4422      bogus.  We should have the information on the va builtin instead.  */
4423   if (!vatype)
4424     vatype = targetm.fn_abi_va_list (cfun->decl);
4425
4426   if (TREE_CODE (vatype) == ARRAY_TYPE)
4427     {
4428       if (TREE_SIDE_EFFECTS (valist))
4429         valist = save_expr (valist);
4430
4431       /* For this case, the backends will be expecting a pointer to
4432          vatype, but it's possible we've actually been given an array
4433          (an actual TARGET_CANONICAL_VA_LIST_TYPE (valist)).
4434          So fix it.  */
4435       if (TREE_CODE (TREE_TYPE (valist)) == ARRAY_TYPE)
4436         {
4437           tree p1 = build_pointer_type (TREE_TYPE (vatype));
4438           valist = build_fold_addr_expr_with_type_loc (loc, valist, p1);
4439         }
4440     }
4441   else
4442     {
4443       tree pt = build_pointer_type (vatype);
4444
4445       if (! needs_lvalue)
4446         {
4447           if (! TREE_SIDE_EFFECTS (valist))
4448             return valist;
4449
4450           valist = fold_build1_loc (loc, ADDR_EXPR, pt, valist);
4451           TREE_SIDE_EFFECTS (valist) = 1;
4452         }
4453
4454       if (TREE_SIDE_EFFECTS (valist))
4455         valist = save_expr (valist);
4456       valist = fold_build2_loc (loc, MEM_REF,
4457                                 vatype, valist, build_int_cst (pt, 0));
4458     }
4459
4460   return valist;
4461 }
4462
4463 /* The "standard" definition of va_list is void*.  */
4464
4465 tree
4466 std_build_builtin_va_list (void)
4467 {
4468   return ptr_type_node;
4469 }
4470
4471 /* The "standard" abi va_list is va_list_type_node.  */
4472
4473 tree
4474 std_fn_abi_va_list (tree fndecl ATTRIBUTE_UNUSED)
4475 {
4476   return va_list_type_node;
4477 }
4478
4479 /* The "standard" type of va_list is va_list_type_node.  */
4480
4481 tree
4482 std_canonical_va_list_type (tree type)
4483 {
4484   tree wtype, htype;
4485
4486   if (INDIRECT_REF_P (type))
4487     type = TREE_TYPE (type);
4488   else if (POINTER_TYPE_P (type) && POINTER_TYPE_P (TREE_TYPE(type)))
4489     type = TREE_TYPE (type);
4490   wtype = va_list_type_node;
4491   htype = type;
4492   /* Treat structure va_list types.  */
4493   if (TREE_CODE (wtype) == RECORD_TYPE && POINTER_TYPE_P (htype))
4494     htype = TREE_TYPE (htype);
4495   else if (TREE_CODE (wtype) == ARRAY_TYPE)
4496     {
4497       /* If va_list is an array type, the argument may have decayed
4498          to a pointer type, e.g. by being passed to another function.
4499          In that case, unwrap both types so that we can compare the
4500          underlying records.  */
4501       if (TREE_CODE (htype) == ARRAY_TYPE
4502           || POINTER_TYPE_P (htype))
4503         {
4504           wtype = TREE_TYPE (wtype);
4505           htype = TREE_TYPE (htype);
4506         }
4507     }
4508   if (TYPE_MAIN_VARIANT (wtype) == TYPE_MAIN_VARIANT (htype))
4509     return va_list_type_node;
4510
4511   return NULL_TREE;
4512 }
4513
4514 /* The "standard" implementation of va_start: just assign `nextarg' to
4515    the variable.  */
4516
4517 void
4518 std_expand_builtin_va_start (tree valist, rtx nextarg)
4519 {
4520   rtx va_r = expand_expr (valist, NULL_RTX, VOIDmode, EXPAND_WRITE);
4521   convert_move (va_r, nextarg, 0);
4522 }
4523
4524 /* Expand EXP, a call to __builtin_va_start.  */
4525
4526 static rtx
4527 expand_builtin_va_start (tree exp)
4528 {
4529   rtx nextarg;
4530   tree valist;
4531   location_t loc = EXPR_LOCATION (exp);
4532
4533   if (call_expr_nargs (exp) < 2)
4534     {
4535       error_at (loc, "too few arguments to function %<va_start%>");
4536       return const0_rtx;
4537     }
4538
4539   if (fold_builtin_next_arg (exp, true))
4540     return const0_rtx;
4541
4542   nextarg = expand_builtin_next_arg ();
4543   valist = stabilize_va_list_loc (loc, CALL_EXPR_ARG (exp, 0), 1);
4544
4545   if (targetm.expand_builtin_va_start)
4546     targetm.expand_builtin_va_start (valist, nextarg);
4547   else
4548     std_expand_builtin_va_start (valist, nextarg);
4549
4550   return const0_rtx;
4551 }
4552
4553 /* The "standard" implementation of va_arg: read the value from the
4554    current (padded) address and increment by the (padded) size.  */
4555
4556 tree
4557 std_gimplify_va_arg_expr (tree valist, tree type, gimple_seq *pre_p,
4558                           gimple_seq *post_p)
4559 {
4560   tree addr, t, type_size, rounded_size, valist_tmp;
4561   unsigned HOST_WIDE_INT align, boundary;
4562   bool indirect;
4563
4564 #ifdef ARGS_GROW_DOWNWARD
4565   /* All of the alignment and movement below is for args-grow-up machines.
4566      As of 2004, there are only 3 ARGS_GROW_DOWNWARD targets, and they all
4567      implement their own specialized gimplify_va_arg_expr routines.  */
4568   gcc_unreachable ();
4569 #endif
4570
4571   indirect = pass_by_reference (NULL, TYPE_MODE (type), type, false);
4572   if (indirect)
4573     type = build_pointer_type (type);
4574
4575   align = PARM_BOUNDARY / BITS_PER_UNIT;
4576   boundary = FUNCTION_ARG_BOUNDARY (TYPE_MODE (type), type);
4577
4578   /* When we align parameter on stack for caller, if the parameter
4579      alignment is beyond MAX_SUPPORTED_STACK_ALIGNMENT, it will be
4580      aligned at MAX_SUPPORTED_STACK_ALIGNMENT.  We will match callee
4581      here with caller.  */
4582   if (boundary > MAX_SUPPORTED_STACK_ALIGNMENT)
4583     boundary = MAX_SUPPORTED_STACK_ALIGNMENT;
4584
4585   boundary /= BITS_PER_UNIT;
4586
4587   /* Hoist the valist value into a temporary for the moment.  */
4588   valist_tmp = get_initialized_tmp_var (valist, pre_p, NULL);
4589
4590   /* va_list pointer is aligned to PARM_BOUNDARY.  If argument actually
4591      requires greater alignment, we must perform dynamic alignment.  */
4592   if (boundary > align
4593       && !integer_zerop (TYPE_SIZE (type)))
4594     {
4595       t = build2 (MODIFY_EXPR, TREE_TYPE (valist), valist_tmp,
4596                   fold_build2 (POINTER_PLUS_EXPR,
4597                                TREE_TYPE (valist),
4598                                valist_tmp, size_int (boundary - 1)));
4599       gimplify_and_add (t, pre_p);
4600
4601       t = fold_convert (sizetype, valist_tmp);
4602       t = build2 (MODIFY_EXPR, TREE_TYPE (valist), valist_tmp,
4603                   fold_convert (TREE_TYPE (valist),
4604                                 fold_build2 (BIT_AND_EXPR, sizetype, t,
4605                                              size_int (-boundary))));
4606       gimplify_and_add (t, pre_p);
4607     }
4608   else
4609     boundary = align;
4610
4611   /* If the actual alignment is less than the alignment of the type,
4612      adjust the type accordingly so that we don't assume strict alignment
4613      when dereferencing the pointer.  */
4614   boundary *= BITS_PER_UNIT;
4615   if (boundary < TYPE_ALIGN (type))
4616     {
4617       type = build_variant_type_copy (type);
4618       TYPE_ALIGN (type) = boundary;
4619     }
4620
4621   /* Compute the rounded size of the type.  */
4622   type_size = size_in_bytes (type);
4623   rounded_size = round_up (type_size, align);
4624
4625   /* Reduce rounded_size so it's sharable with the postqueue.  */
4626   gimplify_expr (&rounded_size, pre_p, post_p, is_gimple_val, fb_rvalue);
4627
4628   /* Get AP.  */
4629   addr = valist_tmp;
4630   if (PAD_VARARGS_DOWN && !integer_zerop (rounded_size))
4631     {
4632       /* Small args are padded downward.  */
4633       t = fold_build2_loc (input_location, GT_EXPR, sizetype,
4634                        rounded_size, size_int (align));
4635       t = fold_build3 (COND_EXPR, sizetype, t, size_zero_node,
4636                        size_binop (MINUS_EXPR, rounded_size, type_size));
4637       addr = fold_build2 (POINTER_PLUS_EXPR,
4638                           TREE_TYPE (addr), addr, t);
4639     }
4640
4641   /* Compute new value for AP.  */
4642   t = build2 (POINTER_PLUS_EXPR, TREE_TYPE (valist), valist_tmp, rounded_size);
4643   t = build2 (MODIFY_EXPR, TREE_TYPE (valist), valist, t);
4644   gimplify_and_add (t, pre_p);
4645
4646   addr = fold_convert (build_pointer_type (type), addr);
4647
4648   if (indirect)
4649     addr = build_va_arg_indirect_ref (addr);
4650
4651   return build_va_arg_indirect_ref (addr);
4652 }
4653
4654 /* Build an indirect-ref expression over the given TREE, which represents a
4655    piece of a va_arg() expansion.  */
4656 tree
4657 build_va_arg_indirect_ref (tree addr)
4658 {
4659   addr = build_fold_indirect_ref_loc (EXPR_LOCATION (addr), addr);
4660
4661   if (flag_mudflap) /* Don't instrument va_arg INDIRECT_REF.  */
4662     mf_mark (addr);
4663
4664   return addr;
4665 }
4666
4667 /* Return a dummy expression of type TYPE in order to keep going after an
4668    error.  */
4669
4670 static tree
4671 dummy_object (tree type)
4672 {
4673   tree t = build_int_cst (build_pointer_type (type), 0);
4674   return build1 (INDIRECT_REF, type, t);
4675 }
4676
4677 /* Gimplify __builtin_va_arg, aka VA_ARG_EXPR, which is not really a
4678    builtin function, but a very special sort of operator.  */
4679
4680 enum gimplify_status
4681 gimplify_va_arg_expr (tree *expr_p, gimple_seq *pre_p, gimple_seq *post_p)
4682 {
4683   tree promoted_type, have_va_type;
4684   tree valist = TREE_OPERAND (*expr_p, 0);
4685   tree type = TREE_TYPE (*expr_p);
4686   tree t;
4687   location_t loc = EXPR_LOCATION (*expr_p);
4688
4689   /* Verify that valist is of the proper type.  */
4690   have_va_type = TREE_TYPE (valist);
4691   if (have_va_type == error_mark_node)
4692     return GS_ERROR;
4693   have_va_type = targetm.canonical_va_list_type (have_va_type);
4694
4695   if (have_va_type == NULL_TREE)
4696     {
4697       error_at (loc, "first argument to %<va_arg%> not of type %<va_list%>");
4698       return GS_ERROR;
4699     }
4700
4701   /* Generate a diagnostic for requesting data of a type that cannot
4702      be passed through `...' due to type promotion at the call site.  */
4703   if ((promoted_type = lang_hooks.types.type_promotes_to (type))
4704            != type)
4705     {
4706       static bool gave_help;
4707       bool warned;
4708
4709       /* Unfortunately, this is merely undefined, rather than a constraint
4710          violation, so we cannot make this an error.  If this call is never
4711          executed, the program is still strictly conforming.  */
4712       warned = warning_at (loc, 0,
4713                            "%qT is promoted to %qT when passed through %<...%>",
4714                            type, promoted_type);
4715       if (!gave_help && warned)
4716         {
4717           gave_help = true;
4718           inform (loc, "(so you should pass %qT not %qT to %<va_arg%>)",
4719                   promoted_type, type);
4720         }
4721
4722       /* We can, however, treat "undefined" any way we please.
4723          Call abort to encourage the user to fix the program.  */
4724       if (warned)
4725         inform (loc, "if this code is reached, the program will abort");
4726       /* Before the abort, allow the evaluation of the va_list
4727          expression to exit or longjmp.  */
4728       gimplify_and_add (valist, pre_p);
4729       t = build_call_expr_loc (loc,
4730                                implicit_built_in_decls[BUILT_IN_TRAP], 0);
4731       gimplify_and_add (t, pre_p);
4732
4733       /* This is dead code, but go ahead and finish so that the
4734          mode of the result comes out right.  */
4735       *expr_p = dummy_object (type);
4736       return GS_ALL_DONE;
4737     }
4738   else
4739     {
4740       /* Make it easier for the backends by protecting the valist argument
4741          from multiple evaluations.  */
4742       if (TREE_CODE (have_va_type) == ARRAY_TYPE)
4743         {
4744           /* For this case, the backends will be expecting a pointer to
4745              TREE_TYPE (abi), but it's possible we've
4746              actually been given an array (an actual TARGET_FN_ABI_VA_LIST).
4747              So fix it.  */
4748           if (TREE_CODE (TREE_TYPE (valist)) == ARRAY_TYPE)
4749             {
4750               tree p1 = build_pointer_type (TREE_TYPE (have_va_type));
4751               valist = fold_convert_loc (loc, p1,
4752                                          build_fold_addr_expr_loc (loc, valist));
4753             }
4754
4755           gimplify_expr (&valist, pre_p, post_p, is_gimple_val, fb_rvalue);
4756         }
4757       else
4758         gimplify_expr (&valist, pre_p, post_p, is_gimple_min_lval, fb_lvalue);
4759
4760       if (!targetm.gimplify_va_arg_expr)
4761         /* FIXME: Once most targets are converted we should merely
4762            assert this is non-null.  */
4763         return GS_ALL_DONE;
4764
4765       *expr_p = targetm.gimplify_va_arg_expr (valist, type, pre_p, post_p);
4766       return GS_OK;
4767     }
4768 }
4769
4770 /* Expand EXP, a call to __builtin_va_end.  */
4771
4772 static rtx
4773 expand_builtin_va_end (tree exp)
4774 {
4775   tree valist = CALL_EXPR_ARG (exp, 0);
4776
4777   /* Evaluate for side effects, if needed.  I hate macros that don't
4778      do that.  */
4779   if (TREE_SIDE_EFFECTS (valist))
4780     expand_expr (valist, const0_rtx, VOIDmode, EXPAND_NORMAL);
4781
4782   return const0_rtx;
4783 }
4784
4785 /* Expand EXP, a call to __builtin_va_copy.  We do this as a
4786    builtin rather than just as an assignment in stdarg.h because of the
4787    nastiness of array-type va_list types.  */
4788
4789 static rtx
4790 expand_builtin_va_copy (tree exp)
4791 {
4792   tree dst, src, t;
4793   location_t loc = EXPR_LOCATION (exp);
4794
4795   dst = CALL_EXPR_ARG (exp, 0);
4796   src = CALL_EXPR_ARG (exp, 1);
4797
4798   dst = stabilize_va_list_loc (loc, dst, 1);
4799   src = stabilize_va_list_loc (loc, src, 0);
4800
4801   gcc_assert (cfun != NULL && cfun->decl != NULL_TREE);
4802
4803   if (TREE_CODE (targetm.fn_abi_va_list (cfun->decl)) != ARRAY_TYPE)
4804     {
4805       t = build2 (MODIFY_EXPR, targetm.fn_abi_va_list (cfun->decl), dst, src);
4806       TREE_SIDE_EFFECTS (t) = 1;
4807       expand_expr (t, const0_rtx, VOIDmode, EXPAND_NORMAL);
4808     }
4809   else
4810     {
4811       rtx dstb, srcb, size;
4812
4813       /* Evaluate to pointers.  */
4814       dstb = expand_expr (dst, NULL_RTX, Pmode, EXPAND_NORMAL);
4815       srcb = expand_expr (src, NULL_RTX, Pmode, EXPAND_NORMAL);
4816       size = expand_expr (TYPE_SIZE_UNIT (targetm.fn_abi_va_list (cfun->decl)),
4817                   NULL_RTX, VOIDmode, EXPAND_NORMAL);
4818
4819       dstb = convert_memory_address (Pmode, dstb);
4820       srcb = convert_memory_address (Pmode, srcb);
4821
4822       /* "Dereference" to BLKmode memories.  */
4823       dstb = gen_rtx_MEM (BLKmode, dstb);
4824       set_mem_alias_set (dstb, get_alias_set (TREE_TYPE (TREE_TYPE (dst))));
4825       set_mem_align (dstb, TYPE_ALIGN (targetm.fn_abi_va_list (cfun->decl)));
4826       srcb = gen_rtx_MEM (BLKmode, srcb);
4827       set_mem_alias_set (srcb, get_alias_set (TREE_TYPE (TREE_TYPE (src))));
4828       set_mem_align (srcb, TYPE_ALIGN (targetm.fn_abi_va_list (cfun->decl)));
4829
4830       /* Copy.  */
4831       emit_block_move (dstb, srcb, size, BLOCK_OP_NORMAL);
4832     }
4833
4834   return const0_rtx;
4835 }
4836
4837 /* Expand a call to one of the builtin functions __builtin_frame_address or
4838    __builtin_return_address.  */
4839
4840 static rtx
4841 expand_builtin_frame_address (tree fndecl, tree exp)
4842 {
4843   /* The argument must be a nonnegative integer constant.
4844      It counts the number of frames to scan up the stack.
4845      The value is the return address saved in that frame.  */
4846   if (call_expr_nargs (exp) == 0)
4847     /* Warning about missing arg was already issued.  */
4848     return const0_rtx;
4849   else if (! host_integerp (CALL_EXPR_ARG (exp, 0), 1))
4850     {
4851       if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_FRAME_ADDRESS)
4852         error ("invalid argument to %<__builtin_frame_address%>");
4853       else
4854         error ("invalid argument to %<__builtin_return_address%>");
4855       return const0_rtx;
4856     }
4857   else
4858     {
4859       rtx tem
4860         = expand_builtin_return_addr (DECL_FUNCTION_CODE (fndecl),
4861                                       tree_low_cst (CALL_EXPR_ARG (exp, 0), 1));
4862
4863       /* Some ports cannot access arbitrary stack frames.  */
4864       if (tem == NULL)
4865         {
4866           if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_FRAME_ADDRESS)
4867             warning (0, "unsupported argument to %<__builtin_frame_address%>");
4868           else
4869             warning (0, "unsupported argument to %<__builtin_return_address%>");
4870           return const0_rtx;
4871         }
4872
4873       /* For __builtin_frame_address, return what we've got.  */
4874       if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_FRAME_ADDRESS)
4875         return tem;
4876
4877       if (!REG_P (tem)
4878           && ! CONSTANT_P (tem))
4879         tem = copy_to_mode_reg (Pmode, tem);
4880       return tem;
4881     }
4882 }
4883
4884 /* Expand EXP, a call to the alloca builtin.  Return NULL_RTX if
4885    we failed and the caller should emit a normal call, otherwise try to get
4886    the result in TARGET, if convenient.  */
4887
4888 static rtx
4889 expand_builtin_alloca (tree exp, rtx target)
4890 {
4891   rtx op0;
4892   rtx result;
4893
4894   /* Emit normal call if marked not-inlineable.  */
4895   if (CALL_CANNOT_INLINE_P (exp))
4896     return NULL_RTX;
4897
4898   if (!validate_arglist (exp, INTEGER_TYPE, VOID_TYPE))
4899     return NULL_RTX;
4900
4901   /* Compute the argument.  */
4902   op0 = expand_normal (CALL_EXPR_ARG (exp, 0));
4903
4904   /* Allocate the desired space.  */
4905   result = allocate_dynamic_stack_space (op0, target, BITS_PER_UNIT);
4906   result = convert_memory_address (ptr_mode, result);
4907
4908   return result;
4909 }
4910
4911 /* Expand a call to a bswap builtin with argument ARG0.  MODE
4912    is the mode to expand with.  */
4913
4914 static rtx
4915 expand_builtin_bswap (tree exp, rtx target, rtx subtarget)
4916 {
4917   enum machine_mode mode;
4918   tree arg;
4919   rtx op0;
4920
4921   if (!validate_arglist (exp, INTEGER_TYPE, VOID_TYPE))
4922     return NULL_RTX;
4923
4924   arg = CALL_EXPR_ARG (exp, 0);
4925   mode = TYPE_MODE (TREE_TYPE (arg));
4926   op0 = expand_expr (arg, subtarget, VOIDmode, EXPAND_NORMAL);
4927
4928   target = expand_unop (mode, bswap_optab, op0, target, 1);
4929
4930   gcc_assert (target);
4931
4932   return convert_to_mode (mode, target, 0);
4933 }
4934
4935 /* Expand a call to a unary builtin in EXP.
4936    Return NULL_RTX if a normal call should be emitted rather than expanding the
4937    function in-line.  If convenient, the result should be placed in TARGET.
4938    SUBTARGET may be used as the target for computing one of EXP's operands.  */
4939
4940 static rtx
4941 expand_builtin_unop (enum machine_mode target_mode, tree exp, rtx target,
4942                      rtx subtarget, optab op_optab)
4943 {
4944   rtx op0;
4945
4946   if (!validate_arglist (exp, INTEGER_TYPE, VOID_TYPE))
4947     return NULL_RTX;
4948
4949   /* Compute the argument.  */
4950   op0 = expand_expr (CALL_EXPR_ARG (exp, 0), subtarget,
4951                      VOIDmode, EXPAND_NORMAL);
4952   /* Compute op, into TARGET if possible.
4953      Set TARGET to wherever the result comes back.  */
4954   target = expand_unop (TYPE_MODE (TREE_TYPE (CALL_EXPR_ARG (exp, 0))),
4955                         op_optab, op0, target, 1);
4956   gcc_assert (target);
4957
4958   return convert_to_mode (target_mode, target, 0);
4959 }
4960
4961 /* Expand a call to __builtin_expect.  We just return our argument
4962    as the builtin_expect semantic should've been already executed by
4963    tree branch prediction pass. */
4964
4965 static rtx
4966 expand_builtin_expect (tree exp, rtx target)
4967 {
4968   tree arg;
4969
4970   if (call_expr_nargs (exp) < 2)
4971     return const0_rtx;
4972   arg = CALL_EXPR_ARG (exp, 0);
4973
4974   target = expand_expr (arg, target, VOIDmode, EXPAND_NORMAL);
4975   /* When guessing was done, the hints should be already stripped away.  */
4976   gcc_assert (!flag_guess_branch_prob
4977               || optimize == 0 || seen_error ());
4978   return target;
4979 }
4980
4981 void
4982 expand_builtin_trap (void)
4983 {
4984 #ifdef HAVE_trap
4985   if (HAVE_trap)
4986     emit_insn (gen_trap ());
4987   else
4988 #endif
4989     emit_library_call (abort_libfunc, LCT_NORETURN, VOIDmode, 0);
4990   emit_barrier ();
4991 }
4992
4993 /* Expand a call to __builtin_unreachable.  We do nothing except emit
4994    a barrier saying that control flow will not pass here.
4995
4996    It is the responsibility of the program being compiled to ensure
4997    that control flow does never reach __builtin_unreachable.  */
4998 static void
4999 expand_builtin_unreachable (void)
5000 {
5001   emit_barrier ();
5002 }
5003
5004 /* Expand EXP, a call to fabs, fabsf or fabsl.
5005    Return NULL_RTX if a normal call should be emitted rather than expanding
5006    the function inline.  If convenient, the result should be placed
5007    in TARGET.  SUBTARGET may be used as the target for computing
5008    the operand.  */
5009
5010 static rtx
5011 expand_builtin_fabs (tree exp, rtx target, rtx subtarget)
5012 {
5013   enum machine_mode mode;
5014   tree arg;
5015   rtx op0;
5016
5017   if (!validate_arglist (exp, REAL_TYPE, VOID_TYPE))
5018     return NULL_RTX;
5019
5020   arg = CALL_EXPR_ARG (exp, 0);
5021   CALL_EXPR_ARG (exp, 0) = arg = builtin_save_expr (arg);
5022   mode = TYPE_MODE (TREE_TYPE (arg));
5023   op0 = expand_expr (arg, subtarget, VOIDmode, EXPAND_NORMAL);
5024   return expand_abs (mode, op0, target, 0, safe_from_p (target, arg, 1));
5025 }
5026
5027 /* Expand EXP, a call to copysign, copysignf, or copysignl.
5028    Return NULL is a normal call should be emitted rather than expanding the
5029    function inline.  If convenient, the result should be placed in TARGET.
5030    SUBTARGET may be used as the target for computing the operand.  */
5031
5032 static rtx
5033 expand_builtin_copysign (tree exp, rtx target, rtx subtarget)
5034 {
5035   rtx op0, op1;
5036   tree arg;
5037
5038   if (!validate_arglist (exp, REAL_TYPE, REAL_TYPE, VOID_TYPE))
5039     return NULL_RTX;
5040
5041   arg = CALL_EXPR_ARG (exp, 0);
5042   op0 = expand_expr (arg, subtarget, VOIDmode, EXPAND_NORMAL);
5043
5044   arg = CALL_EXPR_ARG (exp, 1);
5045   op1 = expand_normal (arg);
5046
5047   return expand_copysign (op0, op1, target);
5048 }
5049
5050 /* Create a new constant string literal and return a char* pointer to it.
5051    The STRING_CST value is the LEN characters at STR.  */
5052 tree
5053 build_string_literal (int len, const char *str)
5054 {
5055   tree t, elem, index, type;
5056
5057   t = build_string (len, str);
5058   elem = build_type_variant (char_type_node, 1, 0);
5059   index = build_index_type (size_int (len - 1));
5060   type = build_array_type (elem, index);
5061   TREE_TYPE (t) = type;
5062   TREE_CONSTANT (t) = 1;
5063   TREE_READONLY (t) = 1;
5064   TREE_STATIC (t) = 1;
5065
5066   type = build_pointer_type (elem);
5067   t = build1 (ADDR_EXPR, type,
5068               build4 (ARRAY_REF, elem,
5069                       t, integer_zero_node, NULL_TREE, NULL_TREE));
5070   return t;
5071 }
5072
5073 /* Expand a call to either the entry or exit function profiler.  */
5074
5075 static rtx
5076 expand_builtin_profile_func (bool exitp)
5077 {
5078   rtx this_rtx, which;
5079
5080   this_rtx = DECL_RTL (current_function_decl);
5081   gcc_assert (MEM_P (this_rtx));
5082   this_rtx = XEXP (this_rtx, 0);
5083
5084   if (exitp)
5085     which = profile_function_exit_libfunc;
5086   else
5087     which = profile_function_entry_libfunc;
5088
5089   emit_library_call (which, LCT_NORMAL, VOIDmode, 2, this_rtx, Pmode,
5090                      expand_builtin_return_addr (BUILT_IN_RETURN_ADDRESS,
5091                                                  0),
5092                      Pmode);
5093
5094   return const0_rtx;
5095 }
5096
5097 /* Expand a call to __builtin___clear_cache.  */
5098
5099 static rtx
5100 expand_builtin___clear_cache (tree exp ATTRIBUTE_UNUSED)
5101 {
5102 #ifndef HAVE_clear_cache
5103 #ifdef CLEAR_INSN_CACHE
5104   /* There is no "clear_cache" insn, and __clear_cache() in libgcc
5105      does something.  Just do the default expansion to a call to
5106      __clear_cache().  */
5107   return NULL_RTX;
5108 #else
5109   /* There is no "clear_cache" insn, and __clear_cache() in libgcc
5110      does nothing.  There is no need to call it.  Do nothing.  */
5111   return const0_rtx;
5112 #endif /* CLEAR_INSN_CACHE */
5113 #else
5114   /* We have a "clear_cache" insn, and it will handle everything.  */
5115   tree begin, end;
5116   rtx begin_rtx, end_rtx;
5117   enum insn_code icode;
5118
5119   /* We must not expand to a library call.  If we did, any
5120      fallback library function in libgcc that might contain a call to
5121      __builtin___clear_cache() would recurse infinitely.  */
5122   if (!validate_arglist (exp, POINTER_TYPE, POINTER_TYPE, VOID_TYPE))
5123     {
5124       error ("both arguments to %<__builtin___clear_cache%> must be pointers");
5125       return const0_rtx;
5126     }
5127
5128   if (HAVE_clear_cache)
5129     {
5130       icode = CODE_FOR_clear_cache;
5131
5132       begin = CALL_EXPR_ARG (exp, 0);
5133       begin_rtx = expand_expr (begin, NULL_RTX, Pmode, EXPAND_NORMAL);
5134       begin_rtx = convert_memory_address (Pmode, begin_rtx);
5135       if (!insn_data[icode].operand[0].predicate (begin_rtx, Pmode))
5136         begin_rtx = copy_to_mode_reg (Pmode, begin_rtx);
5137
5138       end = CALL_EXPR_ARG (exp, 1);
5139       end_rtx = expand_expr (end, NULL_RTX, Pmode, EXPAND_NORMAL);
5140       end_rtx = convert_memory_address (Pmode, end_rtx);
5141       if (!insn_data[icode].operand[1].predicate (end_rtx, Pmode))
5142         end_rtx = copy_to_mode_reg (Pmode, end_rtx);
5143
5144       emit_insn (gen_clear_cache (begin_rtx, end_rtx));
5145     }
5146   return const0_rtx;
5147 #endif /* HAVE_clear_cache */
5148 }
5149
5150 /* Given a trampoline address, make sure it satisfies TRAMPOLINE_ALIGNMENT.  */
5151
5152 static rtx
5153 round_trampoline_addr (rtx tramp)
5154 {
5155   rtx temp, addend, mask;
5156
5157   /* If we don't need too much alignment, we'll have been guaranteed
5158      proper alignment by get_trampoline_type.  */
5159   if (TRAMPOLINE_ALIGNMENT <= STACK_BOUNDARY)
5160     return tramp;
5161
5162   /* Round address up to desired boundary.  */
5163   temp = gen_reg_rtx (Pmode);
5164   addend = GEN_INT (TRAMPOLINE_ALIGNMENT / BITS_PER_UNIT - 1);
5165   mask = GEN_INT (-TRAMPOLINE_ALIGNMENT / BITS_PER_UNIT);
5166
5167   temp  = expand_simple_binop (Pmode, PLUS, tramp, addend,
5168                                temp, 0, OPTAB_LIB_WIDEN);
5169   tramp = expand_simple_binop (Pmode, AND, temp, mask,
5170                                temp, 0, OPTAB_LIB_WIDEN);
5171
5172   return tramp;
5173 }
5174
5175 static rtx
5176 expand_builtin_init_trampoline (tree exp)
5177 {
5178   tree t_tramp, t_func, t_chain;
5179   rtx m_tramp, r_tramp, r_chain, tmp;
5180
5181   if (!validate_arglist (exp, POINTER_TYPE, POINTER_TYPE,
5182                          POINTER_TYPE, VOID_TYPE))
5183     return NULL_RTX;
5184
5185   t_tramp = CALL_EXPR_ARG (exp, 0);
5186   t_func = CALL_EXPR_ARG (exp, 1);
5187   t_chain = CALL_EXPR_ARG (exp, 2);
5188
5189   r_tramp = expand_normal (t_tramp);
5190   m_tramp = gen_rtx_MEM (BLKmode, r_tramp);
5191   MEM_NOTRAP_P (m_tramp) = 1;
5192
5193   /* The TRAMP argument should be the address of a field within the
5194      local function's FRAME decl.  Let's see if we can fill in the
5195      to fill in the MEM_ATTRs for this memory.  */
5196   if (TREE_CODE (t_tramp) == ADDR_EXPR)
5197     set_mem_attributes_minus_bitpos (m_tramp, TREE_OPERAND (t_tramp, 0),
5198                                      true, 0);
5199
5200   tmp = round_trampoline_addr (r_tramp);
5201   if (tmp != r_tramp)
5202     {
5203       m_tramp = change_address (m_tramp, BLKmode, tmp);
5204       set_mem_align (m_tramp, TRAMPOLINE_ALIGNMENT);
5205       set_mem_size (m_tramp, GEN_INT (TRAMPOLINE_SIZE));
5206     }
5207
5208   /* The FUNC argument should be the address of the nested function.
5209      Extract the actual function decl to pass to the hook.  */
5210   gcc_assert (TREE_CODE (t_func) == ADDR_EXPR);
5211   t_func = TREE_OPERAND (t_func, 0);
5212   gcc_assert (TREE_CODE (t_func) == FUNCTION_DECL);
5213
5214   r_chain = expand_normal (t_chain);
5215
5216   /* Generate insns to initialize the trampoline.  */
5217   targetm.calls.trampoline_init (m_tramp, t_func, r_chain);
5218
5219   trampolines_created = 1;
5220
5221   warning_at (DECL_SOURCE_LOCATION (t_func), OPT_Wtrampolines,
5222               "trampoline generated for nested function %qD", t_func);
5223
5224   return const0_rtx;
5225 }
5226
5227 static rtx
5228 expand_builtin_adjust_trampoline (tree exp)
5229 {
5230   rtx tramp;
5231
5232   if (!validate_arglist (exp, POINTER_TYPE, VOID_TYPE))
5233     return NULL_RTX;
5234
5235   tramp = expand_normal (CALL_EXPR_ARG (exp, 0));
5236   tramp = round_trampoline_addr (tramp);
5237   if (targetm.calls.trampoline_adjust_address)
5238     tramp = targetm.calls.trampoline_adjust_address (tramp);
5239
5240   return tramp;
5241 }
5242
5243 /* Expand the call EXP to the built-in signbit, signbitf or signbitl
5244    function.  The function first checks whether the back end provides
5245    an insn to implement signbit for the respective mode.  If not, it
5246    checks whether the floating point format of the value is such that
5247    the sign bit can be extracted.  If that is not the case, the
5248    function returns NULL_RTX to indicate that a normal call should be
5249    emitted rather than expanding the function in-line.  EXP is the
5250    expression that is a call to the builtin function; if convenient,
5251    the result should be placed in TARGET.  */
5252 static rtx
5253 expand_builtin_signbit (tree exp, rtx target)
5254 {
5255   const struct real_format *fmt;
5256   enum machine_mode fmode, imode, rmode;
5257   tree arg;
5258   int word, bitpos;
5259   enum insn_code icode;
5260   rtx temp;
5261   location_t loc = EXPR_LOCATION (exp);
5262
5263   if (!validate_arglist (exp, REAL_TYPE, VOID_TYPE))
5264     return NULL_RTX;
5265
5266   arg = CALL_EXPR_ARG (exp, 0);
5267   fmode = TYPE_MODE (TREE_TYPE (arg));
5268   rmode = TYPE_MODE (TREE_TYPE (exp));
5269   fmt = REAL_MODE_FORMAT (fmode);
5270
5271   arg = builtin_save_expr (arg);
5272
5273   /* Expand the argument yielding a RTX expression. */
5274   temp = expand_normal (arg);
5275
5276   /* Check if the back end provides an insn that handles signbit for the
5277      argument's mode. */
5278   icode = optab_handler (signbit_optab, fmode);
5279   if (icode != CODE_FOR_nothing)
5280     {
5281       rtx last = get_last_insn ();
5282       target = gen_reg_rtx (TYPE_MODE (TREE_TYPE (exp)));
5283       if (maybe_emit_unop_insn (icode, target, temp, UNKNOWN))
5284         return target;
5285       delete_insns_since (last);
5286     }
5287
5288   /* For floating point formats without a sign bit, implement signbit
5289      as "ARG < 0.0".  */
5290   bitpos = fmt->signbit_ro;
5291   if (bitpos < 0)
5292   {
5293     /* But we can't do this if the format supports signed zero.  */
5294     if (fmt->has_signed_zero && HONOR_SIGNED_ZEROS (fmode))
5295       return NULL_RTX;
5296
5297     arg = fold_build2_loc (loc, LT_EXPR, TREE_TYPE (exp), arg,
5298                        build_real (TREE_TYPE (arg), dconst0));
5299     return expand_expr (arg, target, VOIDmode, EXPAND_NORMAL);
5300   }
5301
5302   if (GET_MODE_SIZE (fmode) <= UNITS_PER_WORD)
5303     {
5304       imode = int_mode_for_mode (fmode);
5305       if (imode == BLKmode)
5306         return NULL_RTX;
5307       temp = gen_lowpart (imode, temp);
5308     }
5309   else
5310     {
5311       imode = word_mode;
5312       /* Handle targets with different FP word orders.  */
5313       if (FLOAT_WORDS_BIG_ENDIAN)
5314         word = (GET_MODE_BITSIZE (fmode) - bitpos) / BITS_PER_WORD;
5315       else
5316         word = bitpos / BITS_PER_WORD;
5317       temp = operand_subword_force (temp, word, fmode);
5318       bitpos = bitpos % BITS_PER_WORD;
5319     }
5320
5321   /* Force the intermediate word_mode (or narrower) result into a
5322      register.  This avoids attempting to create paradoxical SUBREGs
5323      of floating point modes below.  */
5324   temp = force_reg (imode, temp);
5325
5326   /* If the bitpos is within the "result mode" lowpart, the operation
5327      can be implement with a single bitwise AND.  Otherwise, we need
5328      a right shift and an AND.  */
5329
5330   if (bitpos < GET_MODE_BITSIZE (rmode))
5331     {
5332       double_int mask = double_int_setbit (double_int_zero, bitpos);
5333
5334       if (GET_MODE_SIZE (imode) > GET_MODE_SIZE (rmode))
5335         temp = gen_lowpart (rmode, temp);
5336       temp = expand_binop (rmode, and_optab, temp,
5337                            immed_double_int_const (mask, rmode),
5338                            NULL_RTX, 1, OPTAB_LIB_WIDEN);
5339     }
5340   else
5341     {
5342       /* Perform a logical right shift to place the signbit in the least
5343          significant bit, then truncate the result to the desired mode
5344          and mask just this bit.  */
5345       temp = expand_shift (RSHIFT_EXPR, imode, temp,
5346                            build_int_cst (NULL_TREE, bitpos), NULL_RTX, 1);
5347       temp = gen_lowpart (rmode, temp);
5348       temp = expand_binop (rmode, and_optab, temp, const1_rtx,
5349                            NULL_RTX, 1, OPTAB_LIB_WIDEN);
5350     }
5351
5352   return temp;
5353 }
5354
5355 /* Expand fork or exec calls.  TARGET is the desired target of the
5356    call.  EXP is the call. FN is the
5357    identificator of the actual function.  IGNORE is nonzero if the
5358    value is to be ignored.  */
5359
5360 static rtx
5361 expand_builtin_fork_or_exec (tree fn, tree exp, rtx target, int ignore)
5362 {
5363   tree id, decl;
5364   tree call;
5365
5366   /* If we are not profiling, just call the function.  */
5367   if (!profile_arc_flag)
5368     return NULL_RTX;
5369
5370   /* Otherwise call the wrapper.  This should be equivalent for the rest of
5371      compiler, so the code does not diverge, and the wrapper may run the
5372      code necessary for keeping the profiling sane.  */
5373
5374   switch (DECL_FUNCTION_CODE (fn))
5375     {
5376     case BUILT_IN_FORK:
5377       id = get_identifier ("__gcov_fork");
5378       break;
5379
5380     case BUILT_IN_EXECL:
5381       id = get_identifier ("__gcov_execl");
5382       break;
5383
5384     case BUILT_IN_EXECV:
5385       id = get_identifier ("__gcov_execv");
5386       break;
5387
5388     case BUILT_IN_EXECLP:
5389       id = get_identifier ("__gcov_execlp");
5390       break;
5391
5392     case BUILT_IN_EXECLE:
5393       id = get_identifier ("__gcov_execle");
5394       break;
5395
5396     case BUILT_IN_EXECVP:
5397       id = get_identifier ("__gcov_execvp");
5398       break;
5399
5400     case BUILT_IN_EXECVE:
5401       id = get_identifier ("__gcov_execve");
5402       break;
5403
5404     default:
5405       gcc_unreachable ();
5406     }
5407
5408   decl = build_decl (DECL_SOURCE_LOCATION (fn),
5409                      FUNCTION_DECL, id, TREE_TYPE (fn));
5410   DECL_EXTERNAL (decl) = 1;
5411   TREE_PUBLIC (decl) = 1;
5412   DECL_ARTIFICIAL (decl) = 1;
5413   TREE_NOTHROW (decl) = 1;
5414   DECL_VISIBILITY (decl) = VISIBILITY_DEFAULT;
5415   DECL_VISIBILITY_SPECIFIED (decl) = 1;
5416   call = rewrite_call_expr (EXPR_LOCATION (exp), exp, 0, decl, 0);
5417   return expand_call (call, target, ignore);
5418  }
5419
5420
5421 \f
5422 /* Reconstitute a mode for a __sync intrinsic operation.  Since the type of
5423    the pointer in these functions is void*, the tree optimizers may remove
5424    casts.  The mode computed in expand_builtin isn't reliable either, due
5425    to __sync_bool_compare_and_swap.
5426
5427    FCODE_DIFF should be fcode - base, where base is the FOO_1 code for the
5428    group of builtins.  This gives us log2 of the mode size.  */
5429
5430 static inline enum machine_mode
5431 get_builtin_sync_mode (int fcode_diff)
5432 {
5433   /* The size is not negotiable, so ask not to get BLKmode in return
5434      if the target indicates that a smaller size would be better.  */
5435   return mode_for_size (BITS_PER_UNIT << fcode_diff, MODE_INT, 0);
5436 }
5437
5438 /* Expand the memory expression LOC and return the appropriate memory operand
5439    for the builtin_sync operations.  */
5440
5441 static rtx
5442 get_builtin_sync_mem (tree loc, enum machine_mode mode)
5443 {
5444   rtx addr, mem;
5445
5446   addr = expand_expr (loc, NULL_RTX, ptr_mode, EXPAND_SUM);
5447   addr = convert_memory_address (Pmode, addr);
5448
5449   /* Note that we explicitly do not want any alias information for this
5450      memory, so that we kill all other live memories.  Otherwise we don't
5451      satisfy the full barrier semantics of the intrinsic.  */
5452   mem = validize_mem (gen_rtx_MEM (mode, addr));
5453
5454   set_mem_align (mem, get_pointer_alignment (loc, BIGGEST_ALIGNMENT));
5455   set_mem_alias_set (mem, ALIAS_SET_MEMORY_BARRIER);
5456   MEM_VOLATILE_P (mem) = 1;
5457
5458   return mem;
5459 }
5460
5461 /* Expand the __sync_xxx_and_fetch and __sync_fetch_and_xxx intrinsics.
5462    EXP is the CALL_EXPR.  CODE is the rtx code
5463    that corresponds to the arithmetic or logical operation from the name;
5464    an exception here is that NOT actually means NAND.  TARGET is an optional
5465    place for us to store the results; AFTER is true if this is the
5466    fetch_and_xxx form.  IGNORE is true if we don't actually care about
5467    the result of the operation at all.  */
5468
5469 static rtx
5470 expand_builtin_sync_operation (enum machine_mode mode, tree exp,
5471                                enum rtx_code code, bool after,
5472                                rtx target, bool ignore)
5473 {
5474   rtx val, mem;
5475   enum machine_mode old_mode;
5476   location_t loc = EXPR_LOCATION (exp);
5477
5478   if (code == NOT && warn_sync_nand)
5479     {
5480       tree fndecl = get_callee_fndecl (exp);
5481       enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
5482
5483       static bool warned_f_a_n, warned_n_a_f;
5484
5485       switch (fcode)
5486         {
5487         case BUILT_IN_FETCH_AND_NAND_1:
5488         case BUILT_IN_FETCH_AND_NAND_2:
5489         case BUILT_IN_FETCH_AND_NAND_4:
5490         case BUILT_IN_FETCH_AND_NAND_8:
5491         case BUILT_IN_FETCH_AND_NAND_16:
5492
5493           if (warned_f_a_n)
5494             break;
5495
5496           fndecl = implicit_built_in_decls[BUILT_IN_FETCH_AND_NAND_N];
5497           inform (loc, "%qD changed semantics in GCC 4.4", fndecl);
5498           warned_f_a_n = true;
5499           break;
5500
5501         case BUILT_IN_NAND_AND_FETCH_1:
5502         case BUILT_IN_NAND_AND_FETCH_2:
5503         case BUILT_IN_NAND_AND_FETCH_4:
5504         case BUILT_IN_NAND_AND_FETCH_8:
5505         case BUILT_IN_NAND_AND_FETCH_16:
5506
5507           if (warned_n_a_f)
5508             break;
5509
5510           fndecl = implicit_built_in_decls[BUILT_IN_NAND_AND_FETCH_N];
5511           inform (loc, "%qD changed semantics in GCC 4.4", fndecl);
5512           warned_n_a_f = true;
5513           break;
5514
5515         default:
5516           gcc_unreachable ();
5517         }
5518     }
5519
5520   /* Expand the operands.  */
5521   mem = get_builtin_sync_mem (CALL_EXPR_ARG (exp, 0), mode);
5522
5523   val = expand_expr (CALL_EXPR_ARG (exp, 1), NULL_RTX, mode, EXPAND_NORMAL);
5524   /* If VAL is promoted to a wider mode, convert it back to MODE.  Take care
5525      of CONST_INTs, where we know the old_mode only from the call argument.  */
5526   old_mode = GET_MODE (val);
5527   if (old_mode == VOIDmode)
5528     old_mode = TYPE_MODE (TREE_TYPE (CALL_EXPR_ARG (exp, 1)));
5529   val = convert_modes (mode, old_mode, val, 1);
5530
5531   if (ignore)
5532     return expand_sync_operation (mem, val, code);
5533   else
5534     return expand_sync_fetch_operation (mem, val, code, after, target);
5535 }
5536
5537 /* Expand the __sync_val_compare_and_swap and __sync_bool_compare_and_swap
5538    intrinsics. EXP is the CALL_EXPR.  IS_BOOL is
5539    true if this is the boolean form.  TARGET is a place for us to store the
5540    results; this is NOT optional if IS_BOOL is true.  */
5541
5542 static rtx
5543 expand_builtin_compare_and_swap (enum machine_mode mode, tree exp,
5544                                  bool is_bool, rtx target)
5545 {
5546   rtx old_val, new_val, mem;
5547   enum machine_mode old_mode;
5548
5549   /* Expand the operands.  */
5550   mem = get_builtin_sync_mem (CALL_EXPR_ARG (exp, 0), mode);
5551
5552
5553   old_val = expand_expr (CALL_EXPR_ARG (exp, 1), NULL_RTX,
5554                          mode, EXPAND_NORMAL);
5555   /* If VAL is promoted to a wider mode, convert it back to MODE.  Take care
5556      of CONST_INTs, where we know the old_mode only from the call argument.  */
5557   old_mode = GET_MODE (old_val);
5558   if (old_mode == VOIDmode)
5559     old_mode = TYPE_MODE (TREE_TYPE (CALL_EXPR_ARG (exp, 1)));
5560   old_val = convert_modes (mode, old_mode, old_val, 1);
5561
5562   new_val = expand_expr (CALL_EXPR_ARG (exp, 2), NULL_RTX,
5563                          mode, EXPAND_NORMAL);
5564   /* If VAL is promoted to a wider mode, convert it back to MODE.  Take care
5565      of CONST_INTs, where we know the old_mode only from the call argument.  */
5566   old_mode = GET_MODE (new_val);
5567   if (old_mode == VOIDmode)
5568     old_mode = TYPE_MODE (TREE_TYPE (CALL_EXPR_ARG (exp, 2)));
5569   new_val = convert_modes (mode, old_mode, new_val, 1);
5570
5571   if (is_bool)
5572     return expand_bool_compare_and_swap (mem, old_val, new_val, target);
5573   else
5574     return expand_val_compare_and_swap (mem, old_val, new_val, target);
5575 }
5576
5577 /* Expand the __sync_lock_test_and_set intrinsic.  Note that the most
5578    general form is actually an atomic exchange, and some targets only
5579    support a reduced form with the second argument being a constant 1.
5580    EXP is the CALL_EXPR; TARGET is an optional place for us to store
5581    the results.  */
5582
5583 static rtx
5584 expand_builtin_lock_test_and_set (enum machine_mode mode, tree exp,
5585                                   rtx target)
5586 {
5587   rtx val, mem;
5588   enum machine_mode old_mode;
5589
5590   /* Expand the operands.  */
5591   mem = get_builtin_sync_mem (CALL_EXPR_ARG (exp, 0), mode);
5592   val = expand_expr (CALL_EXPR_ARG (exp, 1), NULL_RTX, mode, EXPAND_NORMAL);
5593   /* If VAL is promoted to a wider mode, convert it back to MODE.  Take care
5594      of CONST_INTs, where we know the old_mode only from the call argument.  */
5595   old_mode = GET_MODE (val);
5596   if (old_mode == VOIDmode)
5597     old_mode = TYPE_MODE (TREE_TYPE (CALL_EXPR_ARG (exp, 1)));
5598   val = convert_modes (mode, old_mode, val, 1);
5599
5600   return expand_sync_lock_test_and_set (mem, val, target);
5601 }
5602
5603 /* Expand the __sync_synchronize intrinsic.  */
5604
5605 static void
5606 expand_builtin_synchronize (void)
5607 {
5608   gimple x;
5609   VEC (tree, gc) *v_clobbers;
5610
5611 #ifdef HAVE_memory_barrier
5612   if (HAVE_memory_barrier)
5613     {
5614       emit_insn (gen_memory_barrier ());
5615       return;
5616     }
5617 #endif
5618
5619   if (synchronize_libfunc != NULL_RTX)
5620     {
5621       emit_library_call (synchronize_libfunc, LCT_NORMAL, VOIDmode, 0);
5622       return;
5623     }
5624
5625   /* If no explicit memory barrier instruction is available, create an
5626      empty asm stmt with a memory clobber.  */
5627   v_clobbers = VEC_alloc (tree, gc, 1);
5628   VEC_quick_push (tree, v_clobbers,
5629                   tree_cons (NULL, build_string (6, "memory"), NULL));
5630   x = gimple_build_asm_vec ("", NULL, NULL, v_clobbers, NULL);
5631   gimple_asm_set_volatile (x, true);
5632   expand_asm_stmt (x);
5633 }
5634
5635 /* Expand the __sync_lock_release intrinsic.  EXP is the CALL_EXPR.  */
5636
5637 static void
5638 expand_builtin_lock_release (enum machine_mode mode, tree exp)
5639 {
5640   enum insn_code icode;
5641   rtx mem, insn;
5642   rtx val = const0_rtx;
5643
5644   /* Expand the operands.  */
5645   mem = get_builtin_sync_mem (CALL_EXPR_ARG (exp, 0), mode);
5646
5647   /* If there is an explicit operation in the md file, use it.  */
5648   icode = direct_optab_handler (sync_lock_release_optab, mode);
5649   if (icode != CODE_FOR_nothing)
5650     {
5651       if (!insn_data[icode].operand[1].predicate (val, mode))
5652         val = force_reg (mode, val);
5653
5654       insn = GEN_FCN (icode) (mem, val);
5655       if (insn)
5656         {
5657           emit_insn (insn);
5658           return;
5659         }
5660     }
5661
5662   /* Otherwise we can implement this operation by emitting a barrier
5663      followed by a store of zero.  */
5664   expand_builtin_synchronize ();
5665   emit_move_insn (mem, val);
5666 }
5667 \f
5668 /* Expand an expression EXP that calls a built-in function,
5669    with result going to TARGET if that's convenient
5670    (and in mode MODE if that's convenient).
5671    SUBTARGET may be used as the target for computing one of EXP's operands.
5672    IGNORE is nonzero if the value is to be ignored.  */
5673
5674 rtx
5675 expand_builtin (tree exp, rtx target, rtx subtarget, enum machine_mode mode,
5676                 int ignore)
5677 {
5678   tree fndecl = get_callee_fndecl (exp);
5679   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
5680   enum machine_mode target_mode = TYPE_MODE (TREE_TYPE (exp));
5681
5682   if (DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_MD)
5683     return targetm.expand_builtin (exp, target, subtarget, mode, ignore);
5684
5685   /* When not optimizing, generate calls to library functions for a certain
5686      set of builtins.  */
5687   if (!optimize
5688       && !called_as_built_in (fndecl)
5689       && DECL_ASSEMBLER_NAME_SET_P (fndecl)
5690       && fcode != BUILT_IN_ALLOCA
5691       && fcode != BUILT_IN_FREE)
5692     return expand_call (exp, target, ignore);
5693
5694   /* The built-in function expanders test for target == const0_rtx
5695      to determine whether the function's result will be ignored.  */
5696   if (ignore)
5697     target = const0_rtx;
5698
5699   /* If the result of a pure or const built-in function is ignored, and
5700      none of its arguments are volatile, we can avoid expanding the
5701      built-in call and just evaluate the arguments for side-effects.  */
5702   if (target == const0_rtx
5703       && (DECL_PURE_P (fndecl) || TREE_READONLY (fndecl)))
5704     {
5705       bool volatilep = false;
5706       tree arg;
5707       call_expr_arg_iterator iter;
5708
5709       FOR_EACH_CALL_EXPR_ARG (arg, iter, exp)
5710         if (TREE_THIS_VOLATILE (arg))
5711           {
5712             volatilep = true;
5713             break;
5714           }
5715
5716       if (! volatilep)
5717         {
5718           FOR_EACH_CALL_EXPR_ARG (arg, iter, exp)
5719             expand_expr (arg, const0_rtx, VOIDmode, EXPAND_NORMAL);
5720           return const0_rtx;
5721         }
5722     }
5723
5724   switch (fcode)
5725     {
5726     CASE_FLT_FN (BUILT_IN_FABS):
5727       target = expand_builtin_fabs (exp, target, subtarget);
5728       if (target)
5729         return target;
5730       break;
5731
5732     CASE_FLT_FN (BUILT_IN_COPYSIGN):
5733       target = expand_builtin_copysign (exp, target, subtarget);
5734       if (target)
5735         return target;
5736       break;
5737
5738       /* Just do a normal library call if we were unable to fold
5739          the values.  */
5740     CASE_FLT_FN (BUILT_IN_CABS):
5741       break;
5742
5743     CASE_FLT_FN (BUILT_IN_EXP):
5744     CASE_FLT_FN (BUILT_IN_EXP10):
5745     CASE_FLT_FN (BUILT_IN_POW10):
5746     CASE_FLT_FN (BUILT_IN_EXP2):
5747     CASE_FLT_FN (BUILT_IN_EXPM1):
5748     CASE_FLT_FN (BUILT_IN_LOGB):
5749     CASE_FLT_FN (BUILT_IN_LOG):
5750     CASE_FLT_FN (BUILT_IN_LOG10):
5751     CASE_FLT_FN (BUILT_IN_LOG2):
5752     CASE_FLT_FN (BUILT_IN_LOG1P):
5753     CASE_FLT_FN (BUILT_IN_TAN):
5754     CASE_FLT_FN (BUILT_IN_ASIN):
5755     CASE_FLT_FN (BUILT_IN_ACOS):
5756     CASE_FLT_FN (BUILT_IN_ATAN):
5757     CASE_FLT_FN (BUILT_IN_SIGNIFICAND):
5758       /* Treat these like sqrt only if unsafe math optimizations are allowed,
5759          because of possible accuracy problems.  */
5760       if (! flag_unsafe_math_optimizations)
5761         break;
5762     CASE_FLT_FN (BUILT_IN_SQRT):
5763     CASE_FLT_FN (BUILT_IN_FLOOR):
5764     CASE_FLT_FN (BUILT_IN_CEIL):
5765     CASE_FLT_FN (BUILT_IN_TRUNC):
5766     CASE_FLT_FN (BUILT_IN_ROUND):
5767     CASE_FLT_FN (BUILT_IN_NEARBYINT):
5768     CASE_FLT_FN (BUILT_IN_RINT):
5769       target = expand_builtin_mathfn (exp, target, subtarget);
5770       if (target)
5771         return target;
5772       break;
5773
5774     CASE_FLT_FN (BUILT_IN_ILOGB):
5775       if (! flag_unsafe_math_optimizations)
5776         break;
5777     CASE_FLT_FN (BUILT_IN_ISINF):
5778     CASE_FLT_FN (BUILT_IN_FINITE):
5779     case BUILT_IN_ISFINITE:
5780     case BUILT_IN_ISNORMAL:
5781       target = expand_builtin_interclass_mathfn (exp, target, subtarget);
5782       if (target)
5783         return target;
5784       break;
5785
5786     CASE_FLT_FN (BUILT_IN_LCEIL):
5787     CASE_FLT_FN (BUILT_IN_LLCEIL):
5788     CASE_FLT_FN (BUILT_IN_LFLOOR):
5789     CASE_FLT_FN (BUILT_IN_LLFLOOR):
5790       target = expand_builtin_int_roundingfn (exp, target);
5791       if (target)
5792         return target;
5793       break;
5794
5795     CASE_FLT_FN (BUILT_IN_LRINT):
5796     CASE_FLT_FN (BUILT_IN_LLRINT):
5797     CASE_FLT_FN (BUILT_IN_LROUND):
5798     CASE_FLT_FN (BUILT_IN_LLROUND):
5799       target = expand_builtin_int_roundingfn_2 (exp, target);
5800       if (target)
5801         return target;
5802       break;
5803
5804     CASE_FLT_FN (BUILT_IN_POW):
5805       target = expand_builtin_pow (exp, target, subtarget);
5806       if (target)
5807         return target;
5808       break;
5809
5810     CASE_FLT_FN (BUILT_IN_POWI):
5811       target = expand_builtin_powi (exp, target, subtarget);
5812       if (target)
5813         return target;
5814       break;
5815
5816     CASE_FLT_FN (BUILT_IN_ATAN2):
5817     CASE_FLT_FN (BUILT_IN_LDEXP):
5818     CASE_FLT_FN (BUILT_IN_SCALB):
5819     CASE_FLT_FN (BUILT_IN_SCALBN):
5820     CASE_FLT_FN (BUILT_IN_SCALBLN):
5821       if (! flag_unsafe_math_optimizations)
5822         break;
5823
5824     CASE_FLT_FN (BUILT_IN_FMOD):
5825     CASE_FLT_FN (BUILT_IN_REMAINDER):
5826     CASE_FLT_FN (BUILT_IN_DREM):
5827       target = expand_builtin_mathfn_2 (exp, target, subtarget);
5828       if (target)
5829         return target;
5830       break;
5831
5832     CASE_FLT_FN (BUILT_IN_CEXPI):
5833       target = expand_builtin_cexpi (exp, target, subtarget);
5834       gcc_assert (target);
5835       return target;
5836
5837     CASE_FLT_FN (BUILT_IN_SIN):
5838     CASE_FLT_FN (BUILT_IN_COS):
5839       if (! flag_unsafe_math_optimizations)
5840         break;
5841       target = expand_builtin_mathfn_3 (exp, target, subtarget);
5842       if (target)
5843         return target;
5844       break;
5845
5846     CASE_FLT_FN (BUILT_IN_SINCOS):
5847       if (! flag_unsafe_math_optimizations)
5848         break;
5849       target = expand_builtin_sincos (exp);
5850       if (target)
5851         return target;
5852       break;
5853
5854     case BUILT_IN_APPLY_ARGS:
5855       return expand_builtin_apply_args ();
5856
5857       /* __builtin_apply (FUNCTION, ARGUMENTS, ARGSIZE) invokes
5858          FUNCTION with a copy of the parameters described by
5859          ARGUMENTS, and ARGSIZE.  It returns a block of memory
5860          allocated on the stack into which is stored all the registers
5861          that might possibly be used for returning the result of a
5862          function.  ARGUMENTS is the value returned by
5863          __builtin_apply_args.  ARGSIZE is the number of bytes of
5864          arguments that must be copied.  ??? How should this value be
5865          computed?  We'll also need a safe worst case value for varargs
5866          functions.  */
5867     case BUILT_IN_APPLY:
5868       if (!validate_arglist (exp, POINTER_TYPE,
5869                              POINTER_TYPE, INTEGER_TYPE, VOID_TYPE)
5870           && !validate_arglist (exp, REFERENCE_TYPE,
5871                                 POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
5872         return const0_rtx;
5873       else
5874         {
5875           rtx ops[3];
5876
5877           ops[0] = expand_normal (CALL_EXPR_ARG (exp, 0));
5878           ops[1] = expand_normal (CALL_EXPR_ARG (exp, 1));
5879           ops[2] = expand_normal (CALL_EXPR_ARG (exp, 2));
5880
5881           return expand_builtin_apply (ops[0], ops[1], ops[2]);
5882         }
5883
5884       /* __builtin_return (RESULT) causes the function to return the
5885          value described by RESULT.  RESULT is address of the block of
5886          memory returned by __builtin_apply.  */
5887     case BUILT_IN_RETURN:
5888       if (validate_arglist (exp, POINTER_TYPE, VOID_TYPE))
5889         expand_builtin_return (expand_normal (CALL_EXPR_ARG (exp, 0)));
5890       return const0_rtx;
5891
5892     case BUILT_IN_SAVEREGS:
5893       return expand_builtin_saveregs ();
5894
5895     case BUILT_IN_VA_ARG_PACK:
5896       /* All valid uses of __builtin_va_arg_pack () are removed during
5897          inlining.  */
5898       error ("%Kinvalid use of %<__builtin_va_arg_pack ()%>", exp);
5899       return const0_rtx;
5900
5901     case BUILT_IN_VA_ARG_PACK_LEN:
5902       /* All valid uses of __builtin_va_arg_pack_len () are removed during
5903          inlining.  */
5904       error ("%Kinvalid use of %<__builtin_va_arg_pack_len ()%>", exp);
5905       return const0_rtx;
5906
5907       /* Return the address of the first anonymous stack arg.  */
5908     case BUILT_IN_NEXT_ARG:
5909       if (fold_builtin_next_arg (exp, false))
5910         return const0_rtx;
5911       return expand_builtin_next_arg ();
5912
5913     case BUILT_IN_CLEAR_CACHE:
5914       target = expand_builtin___clear_cache (exp);
5915       if (target)
5916         return target;
5917       break;
5918
5919     case BUILT_IN_CLASSIFY_TYPE:
5920       return expand_builtin_classify_type (exp);
5921
5922     case BUILT_IN_CONSTANT_P:
5923       return const0_rtx;
5924
5925     case BUILT_IN_FRAME_ADDRESS:
5926     case BUILT_IN_RETURN_ADDRESS:
5927       return expand_builtin_frame_address (fndecl, exp);
5928
5929     /* Returns the address of the area where the structure is returned.
5930        0 otherwise.  */
5931     case BUILT_IN_AGGREGATE_INCOMING_ADDRESS:
5932       if (call_expr_nargs (exp) != 0
5933           || ! AGGREGATE_TYPE_P (TREE_TYPE (TREE_TYPE (current_function_decl)))
5934           || !MEM_P (DECL_RTL (DECL_RESULT (current_function_decl))))
5935         return const0_rtx;
5936       else
5937         return XEXP (DECL_RTL (DECL_RESULT (current_function_decl)), 0);
5938
5939     case BUILT_IN_ALLOCA:
5940       target = expand_builtin_alloca (exp, target);
5941       if (target)
5942         return target;
5943       break;
5944
5945     case BUILT_IN_STACK_SAVE:
5946       return expand_stack_save ();
5947
5948     case BUILT_IN_STACK_RESTORE:
5949       expand_stack_restore (CALL_EXPR_ARG (exp, 0));
5950       return const0_rtx;
5951
5952     case BUILT_IN_BSWAP32:
5953     case BUILT_IN_BSWAP64:
5954       target = expand_builtin_bswap (exp, target, subtarget);
5955
5956       if (target)
5957         return target;
5958       break;
5959
5960     CASE_INT_FN (BUILT_IN_FFS):
5961     case BUILT_IN_FFSIMAX:
5962       target = expand_builtin_unop (target_mode, exp, target,
5963                                     subtarget, ffs_optab);
5964       if (target)
5965         return target;
5966       break;
5967
5968     CASE_INT_FN (BUILT_IN_CLZ):
5969     case BUILT_IN_CLZIMAX:
5970       target = expand_builtin_unop (target_mode, exp, target,
5971                                     subtarget, clz_optab);
5972       if (target)
5973         return target;
5974       break;
5975
5976     CASE_INT_FN (BUILT_IN_CTZ):
5977     case BUILT_IN_CTZIMAX:
5978       target = expand_builtin_unop (target_mode, exp, target,
5979                                     subtarget, ctz_optab);
5980       if (target)
5981         return target;
5982       break;
5983
5984     CASE_INT_FN (BUILT_IN_POPCOUNT):
5985     case BUILT_IN_POPCOUNTIMAX:
5986       target = expand_builtin_unop (target_mode, exp, target,
5987                                     subtarget, popcount_optab);
5988       if (target)
5989         return target;
5990       break;
5991
5992     CASE_INT_FN (BUILT_IN_PARITY):
5993     case BUILT_IN_PARITYIMAX:
5994       target = expand_builtin_unop (target_mode, exp, target,
5995                                     subtarget, parity_optab);
5996       if (target)
5997         return target;
5998       break;
5999
6000     case BUILT_IN_STRLEN:
6001       target = expand_builtin_strlen (exp, target, target_mode);
6002       if (target)
6003         return target;
6004       break;
6005
6006     case BUILT_IN_STRCPY:
6007       target = expand_builtin_strcpy (exp, target);
6008       if (target)
6009         return target;
6010       break;
6011
6012     case BUILT_IN_STRNCPY:
6013       target = expand_builtin_strncpy (exp, target);
6014       if (target)
6015         return target;
6016       break;
6017
6018     case BUILT_IN_STPCPY:
6019       target = expand_builtin_stpcpy (exp, target, mode);
6020       if (target)
6021         return target;
6022       break;
6023
6024     case BUILT_IN_MEMCPY:
6025       target = expand_builtin_memcpy (exp, target);
6026       if (target)
6027         return target;
6028       break;
6029
6030     case BUILT_IN_MEMPCPY:
6031       target = expand_builtin_mempcpy (exp, target, mode);
6032       if (target)
6033         return target;
6034       break;
6035
6036     case BUILT_IN_MEMSET:
6037       target = expand_builtin_memset (exp, target, mode);
6038       if (target)
6039         return target;
6040       break;
6041
6042     case BUILT_IN_BZERO:
6043       target = expand_builtin_bzero (exp);
6044       if (target)
6045         return target;
6046       break;
6047
6048     case BUILT_IN_STRCMP:
6049       target = expand_builtin_strcmp (exp, target);
6050       if (target)
6051         return target;
6052       break;
6053
6054     case BUILT_IN_STRNCMP:
6055       target = expand_builtin_strncmp (exp, target, mode);
6056       if (target)
6057         return target;
6058       break;
6059
6060     case BUILT_IN_BCMP:
6061     case BUILT_IN_MEMCMP:
6062       target = expand_builtin_memcmp (exp, target, mode);
6063       if (target)
6064         return target;
6065       break;
6066
6067     case BUILT_IN_SETJMP:
6068       /* This should have been lowered to the builtins below.  */
6069       gcc_unreachable ();
6070
6071     case BUILT_IN_SETJMP_SETUP:
6072       /* __builtin_setjmp_setup is passed a pointer to an array of five words
6073           and the receiver label.  */
6074       if (validate_arglist (exp, POINTER_TYPE, POINTER_TYPE, VOID_TYPE))
6075         {
6076           rtx buf_addr = expand_expr (CALL_EXPR_ARG (exp, 0), subtarget,
6077                                       VOIDmode, EXPAND_NORMAL);
6078           tree label = TREE_OPERAND (CALL_EXPR_ARG (exp, 1), 0);
6079           rtx label_r = label_rtx (label);
6080
6081           /* This is copied from the handling of non-local gotos.  */
6082           expand_builtin_setjmp_setup (buf_addr, label_r);
6083           nonlocal_goto_handler_labels
6084             = gen_rtx_EXPR_LIST (VOIDmode, label_r,
6085                                  nonlocal_goto_handler_labels);
6086           /* ??? Do not let expand_label treat us as such since we would
6087              not want to be both on the list of non-local labels and on
6088              the list of forced labels.  */
6089           FORCED_LABEL (label) = 0;
6090           return const0_rtx;
6091         }
6092       break;
6093
6094     case BUILT_IN_SETJMP_DISPATCHER:
6095        /* __builtin_setjmp_dispatcher is passed the dispatcher label.  */
6096       if (validate_arglist (exp, POINTER_TYPE, VOID_TYPE))
6097         {
6098           tree label = TREE_OPERAND (CALL_EXPR_ARG (exp, 0), 0);
6099           rtx label_r = label_rtx (label);
6100
6101           /* Remove the dispatcher label from the list of non-local labels
6102              since the receiver labels have been added to it above.  */
6103           remove_node_from_expr_list (label_r, &nonlocal_goto_handler_labels);
6104           return const0_rtx;
6105         }
6106       break;
6107
6108     case BUILT_IN_SETJMP_RECEIVER:
6109        /* __builtin_setjmp_receiver is passed the receiver label.  */
6110       if (validate_arglist (exp, POINTER_TYPE, VOID_TYPE))
6111         {
6112           tree label = TREE_OPERAND (CALL_EXPR_ARG (exp, 0), 0);
6113           rtx label_r = label_rtx (label);
6114
6115           expand_builtin_setjmp_receiver (label_r);
6116           return const0_rtx;
6117         }
6118       break;
6119
6120       /* __builtin_longjmp is passed a pointer to an array of five words.
6121          It's similar to the C library longjmp function but works with
6122          __builtin_setjmp above.  */
6123     case BUILT_IN_LONGJMP:
6124       if (validate_arglist (exp, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
6125         {
6126           rtx buf_addr = expand_expr (CALL_EXPR_ARG (exp, 0), subtarget,
6127                                       VOIDmode, EXPAND_NORMAL);
6128           rtx value = expand_normal (CALL_EXPR_ARG (exp, 1));
6129
6130           if (value != const1_rtx)
6131             {
6132               error ("%<__builtin_longjmp%> second argument must be 1");
6133               return const0_rtx;
6134             }
6135
6136           expand_builtin_longjmp (buf_addr, value);
6137           return const0_rtx;
6138         }
6139       break;
6140
6141     case BUILT_IN_NONLOCAL_GOTO:
6142       target = expand_builtin_nonlocal_goto (exp);
6143       if (target)
6144         return target;
6145       break;
6146
6147       /* This updates the setjmp buffer that is its argument with the value
6148          of the current stack pointer.  */
6149     case BUILT_IN_UPDATE_SETJMP_BUF:
6150       if (validate_arglist (exp, POINTER_TYPE, VOID_TYPE))
6151         {
6152           rtx buf_addr
6153             = expand_normal (CALL_EXPR_ARG (exp, 0));
6154
6155           expand_builtin_update_setjmp_buf (buf_addr);
6156           return const0_rtx;
6157         }
6158       break;
6159
6160     case BUILT_IN_TRAP:
6161       expand_builtin_trap ();
6162       return const0_rtx;
6163
6164     case BUILT_IN_UNREACHABLE:
6165       expand_builtin_unreachable ();
6166       return const0_rtx;
6167
6168     CASE_FLT_FN (BUILT_IN_SIGNBIT):
6169     case BUILT_IN_SIGNBITD32:
6170     case BUILT_IN_SIGNBITD64:
6171     case BUILT_IN_SIGNBITD128:
6172       target = expand_builtin_signbit (exp, target);
6173       if (target)
6174         return target;
6175       break;
6176
6177       /* Various hooks for the DWARF 2 __throw routine.  */
6178     case BUILT_IN_UNWIND_INIT:
6179       expand_builtin_unwind_init ();
6180       return const0_rtx;
6181     case BUILT_IN_DWARF_CFA:
6182       return virtual_cfa_rtx;
6183 #ifdef DWARF2_UNWIND_INFO
6184     case BUILT_IN_DWARF_SP_COLUMN:
6185       return expand_builtin_dwarf_sp_column ();
6186     case BUILT_IN_INIT_DWARF_REG_SIZES:
6187       expand_builtin_init_dwarf_reg_sizes (CALL_EXPR_ARG (exp, 0));
6188       return const0_rtx;
6189 #endif
6190     case BUILT_IN_FROB_RETURN_ADDR:
6191       return expand_builtin_frob_return_addr (CALL_EXPR_ARG (exp, 0));
6192     case BUILT_IN_EXTRACT_RETURN_ADDR:
6193       return expand_builtin_extract_return_addr (CALL_EXPR_ARG (exp, 0));
6194     case BUILT_IN_EH_RETURN:
6195       expand_builtin_eh_return (CALL_EXPR_ARG (exp, 0),
6196                                 CALL_EXPR_ARG (exp, 1));
6197       return const0_rtx;
6198 #ifdef EH_RETURN_DATA_REGNO
6199     case BUILT_IN_EH_RETURN_DATA_REGNO:
6200       return expand_builtin_eh_return_data_regno (exp);
6201 #endif
6202     case BUILT_IN_EXTEND_POINTER:
6203       return expand_builtin_extend_pointer (CALL_EXPR_ARG (exp, 0));
6204     case BUILT_IN_EH_POINTER:
6205       return expand_builtin_eh_pointer (exp);
6206     case BUILT_IN_EH_FILTER:
6207       return expand_builtin_eh_filter (exp);
6208     case BUILT_IN_EH_COPY_VALUES:
6209       return expand_builtin_eh_copy_values (exp);
6210
6211     case BUILT_IN_VA_START:
6212       return expand_builtin_va_start (exp);
6213     case BUILT_IN_VA_END:
6214       return expand_builtin_va_end (exp);
6215     case BUILT_IN_VA_COPY:
6216       return expand_builtin_va_copy (exp);
6217     case BUILT_IN_EXPECT:
6218       return expand_builtin_expect (exp, target);
6219     case BUILT_IN_PREFETCH:
6220       expand_builtin_prefetch (exp);
6221       return const0_rtx;
6222
6223     case BUILT_IN_PROFILE_FUNC_ENTER:
6224       return expand_builtin_profile_func (false);
6225     case BUILT_IN_PROFILE_FUNC_EXIT:
6226       return expand_builtin_profile_func (true);
6227
6228     case BUILT_IN_INIT_TRAMPOLINE:
6229       return expand_builtin_init_trampoline (exp);
6230     case BUILT_IN_ADJUST_TRAMPOLINE:
6231       return expand_builtin_adjust_trampoline (exp);
6232
6233     case BUILT_IN_FORK:
6234     case BUILT_IN_EXECL:
6235     case BUILT_IN_EXECV:
6236     case BUILT_IN_EXECLP:
6237     case BUILT_IN_EXECLE:
6238     case BUILT_IN_EXECVP:
6239     case BUILT_IN_EXECVE:
6240       target = expand_builtin_fork_or_exec (fndecl, exp, target, ignore);
6241       if (target)
6242         return target;
6243       break;
6244
6245     case BUILT_IN_FETCH_AND_ADD_1:
6246     case BUILT_IN_FETCH_AND_ADD_2:
6247     case BUILT_IN_FETCH_AND_ADD_4:
6248     case BUILT_IN_FETCH_AND_ADD_8:
6249     case BUILT_IN_FETCH_AND_ADD_16:
6250       mode = get_builtin_sync_mode (fcode - BUILT_IN_FETCH_AND_ADD_1);
6251       target = expand_builtin_sync_operation (mode, exp, PLUS,
6252                                               false, target, ignore);
6253       if (target)
6254         return target;
6255       break;
6256
6257     case BUILT_IN_FETCH_AND_SUB_1:
6258     case BUILT_IN_FETCH_AND_SUB_2:
6259     case BUILT_IN_FETCH_AND_SUB_4:
6260     case BUILT_IN_FETCH_AND_SUB_8:
6261     case BUILT_IN_FETCH_AND_SUB_16:
6262       mode = get_builtin_sync_mode (fcode - BUILT_IN_FETCH_AND_SUB_1);
6263       target = expand_builtin_sync_operation (mode, exp, MINUS,
6264                                               false, target, ignore);
6265       if (target)
6266         return target;
6267       break;
6268
6269     case BUILT_IN_FETCH_AND_OR_1:
6270     case BUILT_IN_FETCH_AND_OR_2:
6271     case BUILT_IN_FETCH_AND_OR_4:
6272     case BUILT_IN_FETCH_AND_OR_8:
6273     case BUILT_IN_FETCH_AND_OR_16:
6274       mode = get_builtin_sync_mode (fcode - BUILT_IN_FETCH_AND_OR_1);
6275       target = expand_builtin_sync_operation (mode, exp, IOR,
6276                                               false, target, ignore);
6277       if (target)
6278         return target;
6279       break;
6280
6281     case BUILT_IN_FETCH_AND_AND_1:
6282     case BUILT_IN_FETCH_AND_AND_2:
6283     case BUILT_IN_FETCH_AND_AND_4:
6284     case BUILT_IN_FETCH_AND_AND_8:
6285     case BUILT_IN_FETCH_AND_AND_16:
6286       mode = get_builtin_sync_mode (fcode - BUILT_IN_FETCH_AND_AND_1);
6287       target = expand_builtin_sync_operation (mode, exp, AND,
6288                                               false, target, ignore);
6289       if (target)
6290         return target;
6291       break;
6292
6293     case BUILT_IN_FETCH_AND_XOR_1:
6294     case BUILT_IN_FETCH_AND_XOR_2:
6295     case BUILT_IN_FETCH_AND_XOR_4:
6296     case BUILT_IN_FETCH_AND_XOR_8:
6297     case BUILT_IN_FETCH_AND_XOR_16:
6298       mode = get_builtin_sync_mode (fcode - BUILT_IN_FETCH_AND_XOR_1);
6299       target = expand_builtin_sync_operation (mode, exp, XOR,
6300                                               false, target, ignore);
6301       if (target)
6302         return target;
6303       break;
6304
6305     case BUILT_IN_FETCH_AND_NAND_1:
6306     case BUILT_IN_FETCH_AND_NAND_2:
6307     case BUILT_IN_FETCH_AND_NAND_4:
6308     case BUILT_IN_FETCH_AND_NAND_8:
6309     case BUILT_IN_FETCH_AND_NAND_16:
6310       mode = get_builtin_sync_mode (fcode - BUILT_IN_FETCH_AND_NAND_1);
6311       target = expand_builtin_sync_operation (mode, exp, NOT,
6312                                               false, target, ignore);
6313       if (target)
6314         return target;
6315       break;
6316
6317     case BUILT_IN_ADD_AND_FETCH_1:
6318     case BUILT_IN_ADD_AND_FETCH_2:
6319     case BUILT_IN_ADD_AND_FETCH_4:
6320     case BUILT_IN_ADD_AND_FETCH_8:
6321     case BUILT_IN_ADD_AND_FETCH_16:
6322       mode = get_builtin_sync_mode (fcode - BUILT_IN_ADD_AND_FETCH_1);
6323       target = expand_builtin_sync_operation (mode, exp, PLUS,
6324                                               true, target, ignore);
6325       if (target)
6326         return target;
6327       break;
6328
6329     case BUILT_IN_SUB_AND_FETCH_1:
6330     case BUILT_IN_SUB_AND_FETCH_2:
6331     case BUILT_IN_SUB_AND_FETCH_4:
6332     case BUILT_IN_SUB_AND_FETCH_8:
6333     case BUILT_IN_SUB_AND_FETCH_16:
6334       mode = get_builtin_sync_mode (fcode - BUILT_IN_SUB_AND_FETCH_1);
6335       target = expand_builtin_sync_operation (mode, exp, MINUS,
6336                                               true, target, ignore);
6337       if (target)
6338         return target;
6339       break;
6340
6341     case BUILT_IN_OR_AND_FETCH_1:
6342     case BUILT_IN_OR_AND_FETCH_2:
6343     case BUILT_IN_OR_AND_FETCH_4:
6344     case BUILT_IN_OR_AND_FETCH_8:
6345     case BUILT_IN_OR_AND_FETCH_16:
6346       mode = get_builtin_sync_mode (fcode - BUILT_IN_OR_AND_FETCH_1);
6347       target = expand_builtin_sync_operation (mode, exp, IOR,
6348                                               true, target, ignore);
6349       if (target)
6350         return target;
6351       break;
6352
6353     case BUILT_IN_AND_AND_FETCH_1:
6354     case BUILT_IN_AND_AND_FETCH_2:
6355     case BUILT_IN_AND_AND_FETCH_4:
6356     case BUILT_IN_AND_AND_FETCH_8:
6357     case BUILT_IN_AND_AND_FETCH_16:
6358       mode = get_builtin_sync_mode (fcode - BUILT_IN_AND_AND_FETCH_1);
6359       target = expand_builtin_sync_operation (mode, exp, AND,
6360                                               true, target, ignore);
6361       if (target)
6362         return target;
6363       break;
6364
6365     case BUILT_IN_XOR_AND_FETCH_1:
6366     case BUILT_IN_XOR_AND_FETCH_2:
6367     case BUILT_IN_XOR_AND_FETCH_4:
6368     case BUILT_IN_XOR_AND_FETCH_8:
6369     case BUILT_IN_XOR_AND_FETCH_16:
6370       mode = get_builtin_sync_mode (fcode - BUILT_IN_XOR_AND_FETCH_1);
6371       target = expand_builtin_sync_operation (mode, exp, XOR,
6372                                               true, target, ignore);
6373       if (target)
6374         return target;
6375       break;
6376
6377     case BUILT_IN_NAND_AND_FETCH_1:
6378     case BUILT_IN_NAND_AND_FETCH_2:
6379     case BUILT_IN_NAND_AND_FETCH_4:
6380     case BUILT_IN_NAND_AND_FETCH_8:
6381     case BUILT_IN_NAND_AND_FETCH_16:
6382       mode = get_builtin_sync_mode (fcode - BUILT_IN_NAND_AND_FETCH_1);
6383       target = expand_builtin_sync_operation (mode, exp, NOT,
6384                                               true, target, ignore);
6385       if (target)
6386         return target;
6387       break;
6388
6389     case BUILT_IN_BOOL_COMPARE_AND_SWAP_1:
6390     case BUILT_IN_BOOL_COMPARE_AND_SWAP_2:
6391     case BUILT_IN_BOOL_COMPARE_AND_SWAP_4:
6392     case BUILT_IN_BOOL_COMPARE_AND_SWAP_8:
6393     case BUILT_IN_BOOL_COMPARE_AND_SWAP_16:
6394       if (mode == VOIDmode)
6395         mode = TYPE_MODE (boolean_type_node);
6396       if (!target || !register_operand (target, mode))
6397         target = gen_reg_rtx (mode);
6398
6399       mode = get_builtin_sync_mode (fcode - BUILT_IN_BOOL_COMPARE_AND_SWAP_1);
6400       target = expand_builtin_compare_and_swap (mode, exp, true, target);
6401       if (target)
6402         return target;
6403       break;
6404
6405     case BUILT_IN_VAL_COMPARE_AND_SWAP_1:
6406     case BUILT_IN_VAL_COMPARE_AND_SWAP_2:
6407     case BUILT_IN_VAL_COMPARE_AND_SWAP_4:
6408     case BUILT_IN_VAL_COMPARE_AND_SWAP_8:
6409     case BUILT_IN_VAL_COMPARE_AND_SWAP_16:
6410       mode = get_builtin_sync_mode (fcode - BUILT_IN_VAL_COMPARE_AND_SWAP_1);
6411       target = expand_builtin_compare_and_swap (mode, exp, false, target);
6412       if (target)
6413         return target;
6414       break;
6415
6416     case BUILT_IN_LOCK_TEST_AND_SET_1:
6417     case BUILT_IN_LOCK_TEST_AND_SET_2:
6418     case BUILT_IN_LOCK_TEST_AND_SET_4:
6419     case BUILT_IN_LOCK_TEST_AND_SET_8:
6420     case BUILT_IN_LOCK_TEST_AND_SET_16:
6421       mode = get_builtin_sync_mode (fcode - BUILT_IN_LOCK_TEST_AND_SET_1);
6422       target = expand_builtin_lock_test_and_set (mode, exp, target);
6423       if (target)
6424         return target;
6425       break;
6426
6427     case BUILT_IN_LOCK_RELEASE_1:
6428     case BUILT_IN_LOCK_RELEASE_2:
6429     case BUILT_IN_LOCK_RELEASE_4:
6430     case BUILT_IN_LOCK_RELEASE_8:
6431     case BUILT_IN_LOCK_RELEASE_16:
6432       mode = get_builtin_sync_mode (fcode - BUILT_IN_LOCK_RELEASE_1);
6433       expand_builtin_lock_release (mode, exp);
6434       return const0_rtx;
6435
6436     case BUILT_IN_SYNCHRONIZE:
6437       expand_builtin_synchronize ();
6438       return const0_rtx;
6439
6440     case BUILT_IN_OBJECT_SIZE:
6441       return expand_builtin_object_size (exp);
6442
6443     case BUILT_IN_MEMCPY_CHK:
6444     case BUILT_IN_MEMPCPY_CHK:
6445     case BUILT_IN_MEMMOVE_CHK:
6446     case BUILT_IN_MEMSET_CHK:
6447       target = expand_builtin_memory_chk (exp, target, mode, fcode);
6448       if (target)
6449         return target;
6450       break;
6451
6452     case BUILT_IN_STRCPY_CHK:
6453     case BUILT_IN_STPCPY_CHK:
6454     case BUILT_IN_STRNCPY_CHK:
6455     case BUILT_IN_STRCAT_CHK:
6456     case BUILT_IN_STRNCAT_CHK:
6457     case BUILT_IN_SNPRINTF_CHK:
6458     case BUILT_IN_VSNPRINTF_CHK:
6459       maybe_emit_chk_warning (exp, fcode);
6460       break;
6461
6462     case BUILT_IN_SPRINTF_CHK:
6463     case BUILT_IN_VSPRINTF_CHK:
6464       maybe_emit_sprintf_chk_warning (exp, fcode);
6465       break;
6466
6467     case BUILT_IN_FREE:
6468       maybe_emit_free_warning (exp);
6469       break;
6470
6471     default:    /* just do library call, if unknown builtin */
6472       break;
6473     }
6474
6475   /* The switch statement above can drop through to cause the function
6476      to be called normally.  */
6477   return expand_call (exp, target, ignore);
6478 }
6479
6480 /* Determine whether a tree node represents a call to a built-in
6481    function.  If the tree T is a call to a built-in function with
6482    the right number of arguments of the appropriate types, return
6483    the DECL_FUNCTION_CODE of the call, e.g. BUILT_IN_SQRT.
6484    Otherwise the return value is END_BUILTINS.  */
6485
6486 enum built_in_function
6487 builtin_mathfn_code (const_tree t)
6488 {
6489   const_tree fndecl, arg, parmlist;
6490   const_tree argtype, parmtype;
6491   const_call_expr_arg_iterator iter;
6492
6493   if (TREE_CODE (t) != CALL_EXPR
6494       || TREE_CODE (CALL_EXPR_FN (t)) != ADDR_EXPR)
6495     return END_BUILTINS;
6496
6497   fndecl = get_callee_fndecl (t);
6498   if (fndecl == NULL_TREE
6499       || TREE_CODE (fndecl) != FUNCTION_DECL
6500       || ! DECL_BUILT_IN (fndecl)
6501       || DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_MD)
6502     return END_BUILTINS;
6503
6504   parmlist = TYPE_ARG_TYPES (TREE_TYPE (fndecl));
6505   init_const_call_expr_arg_iterator (t, &iter);
6506   for (; parmlist; parmlist = TREE_CHAIN (parmlist))
6507     {
6508       /* If a function doesn't take a variable number of arguments,
6509          the last element in the list will have type `void'.  */
6510       parmtype = TREE_VALUE (parmlist);
6511       if (VOID_TYPE_P (parmtype))
6512         {
6513           if (more_const_call_expr_args_p (&iter))
6514             return END_BUILTINS;
6515           return DECL_FUNCTION_CODE (fndecl);
6516         }
6517
6518       if (! more_const_call_expr_args_p (&iter))
6519         return END_BUILTINS;
6520
6521       arg = next_const_call_expr_arg (&iter);
6522       argtype = TREE_TYPE (arg);
6523
6524       if (SCALAR_FLOAT_TYPE_P (parmtype))
6525         {
6526           if (! SCALAR_FLOAT_TYPE_P (argtype))
6527             return END_BUILTINS;
6528         }
6529       else if (COMPLEX_FLOAT_TYPE_P (parmtype))
6530         {
6531           if (! COMPLEX_FLOAT_TYPE_P (argtype))
6532             return END_BUILTINS;
6533         }
6534       else if (POINTER_TYPE_P (parmtype))
6535         {
6536           if (! POINTER_TYPE_P (argtype))
6537             return END_BUILTINS;
6538         }
6539       else if (INTEGRAL_TYPE_P (parmtype))
6540         {
6541           if (! INTEGRAL_TYPE_P (argtype))
6542             return END_BUILTINS;
6543         }
6544       else
6545         return END_BUILTINS;
6546     }
6547
6548   /* Variable-length argument list.  */
6549   return DECL_FUNCTION_CODE (fndecl);
6550 }
6551
6552 /* Fold a call to __builtin_constant_p, if we know its argument ARG will
6553    evaluate to a constant.  */
6554
6555 static tree
6556 fold_builtin_constant_p (tree arg)
6557 {
6558   /* We return 1 for a numeric type that's known to be a constant
6559      value at compile-time or for an aggregate type that's a
6560      literal constant.  */
6561   STRIP_NOPS (arg);
6562
6563   /* If we know this is a constant, emit the constant of one.  */
6564   if (CONSTANT_CLASS_P (arg)
6565       || (TREE_CODE (arg) == CONSTRUCTOR
6566           && TREE_CONSTANT (arg)))
6567     return integer_one_node;
6568   if (TREE_CODE (arg) == ADDR_EXPR)
6569     {
6570        tree op = TREE_OPERAND (arg, 0);
6571        if (TREE_CODE (op) == STRING_CST
6572            || (TREE_CODE (op) == ARRAY_REF
6573                && integer_zerop (TREE_OPERAND (op, 1))
6574                && TREE_CODE (TREE_OPERAND (op, 0)) == STRING_CST))
6575          return integer_one_node;
6576     }
6577
6578   /* If this expression has side effects, show we don't know it to be a
6579      constant.  Likewise if it's a pointer or aggregate type since in
6580      those case we only want literals, since those are only optimized
6581      when generating RTL, not later.
6582      And finally, if we are compiling an initializer, not code, we
6583      need to return a definite result now; there's not going to be any
6584      more optimization done.  */
6585   if (TREE_SIDE_EFFECTS (arg)
6586       || AGGREGATE_TYPE_P (TREE_TYPE (arg))
6587       || POINTER_TYPE_P (TREE_TYPE (arg))
6588       || cfun == 0
6589       || folding_initializer)
6590     return integer_zero_node;
6591
6592   return NULL_TREE;
6593 }
6594
6595 /* Create builtin_expect with PRED and EXPECTED as its arguments and
6596    return it as a truthvalue.  */
6597
6598 static tree
6599 build_builtin_expect_predicate (location_t loc, tree pred, tree expected)
6600 {
6601   tree fn, arg_types, pred_type, expected_type, call_expr, ret_type;
6602
6603   fn = built_in_decls[BUILT_IN_EXPECT];
6604   arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
6605   ret_type = TREE_TYPE (TREE_TYPE (fn));
6606   pred_type = TREE_VALUE (arg_types);
6607   expected_type = TREE_VALUE (TREE_CHAIN (arg_types));
6608
6609   pred = fold_convert_loc (loc, pred_type, pred);
6610   expected = fold_convert_loc (loc, expected_type, expected);
6611   call_expr = build_call_expr_loc (loc, fn, 2, pred, expected);
6612
6613   return build2 (NE_EXPR, TREE_TYPE (pred), call_expr,
6614                  build_int_cst (ret_type, 0));
6615 }
6616
6617 /* Fold a call to builtin_expect with arguments ARG0 and ARG1.  Return
6618    NULL_TREE if no simplification is possible.  */
6619
6620 static tree
6621 fold_builtin_expect (location_t loc, tree arg0, tree arg1)
6622 {
6623   tree inner, fndecl;
6624   enum tree_code code;
6625
6626   /* If this is a builtin_expect within a builtin_expect keep the
6627      inner one.  See through a comparison against a constant.  It
6628      might have been added to create a thruthvalue.  */
6629   inner = arg0;
6630   if (COMPARISON_CLASS_P (inner)
6631       && TREE_CODE (TREE_OPERAND (inner, 1)) == INTEGER_CST)
6632     inner = TREE_OPERAND (inner, 0);
6633
6634   if (TREE_CODE (inner) == CALL_EXPR
6635       && (fndecl = get_callee_fndecl (inner))
6636       && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL
6637       && DECL_FUNCTION_CODE (fndecl) == BUILT_IN_EXPECT)
6638     return arg0;
6639
6640   /* Distribute the expected value over short-circuiting operators.
6641      See through the cast from truthvalue_type_node to long.  */
6642   inner = arg0;
6643   while (TREE_CODE (inner) == NOP_EXPR
6644          && INTEGRAL_TYPE_P (TREE_TYPE (inner))
6645          && INTEGRAL_TYPE_P (TREE_TYPE (TREE_OPERAND (inner, 0))))
6646     inner = TREE_OPERAND (inner, 0);
6647
6648   code = TREE_CODE (inner);
6649   if (code == TRUTH_ANDIF_EXPR || code == TRUTH_ORIF_EXPR)
6650     {
6651       tree op0 = TREE_OPERAND (inner, 0);
6652       tree op1 = TREE_OPERAND (inner, 1);
6653
6654       op0 = build_builtin_expect_predicate (loc, op0, arg1);
6655       op1 = build_builtin_expect_predicate (loc, op1, arg1);
6656       inner = build2 (code, TREE_TYPE (inner), op0, op1);
6657
6658       return fold_convert_loc (loc, TREE_TYPE (arg0), inner);
6659     }
6660
6661   /* If the argument isn't invariant then there's nothing else we can do.  */
6662   if (!TREE_CONSTANT (arg0))
6663     return NULL_TREE;
6664
6665   /* If we expect that a comparison against the argument will fold to
6666      a constant return the constant.  In practice, this means a true
6667      constant or the address of a non-weak symbol.  */
6668   inner = arg0;
6669   STRIP_NOPS (inner);
6670   if (TREE_CODE (inner) == ADDR_EXPR)
6671     {
6672       do
6673         {
6674           inner = TREE_OPERAND (inner, 0);
6675         }
6676       while (TREE_CODE (inner) == COMPONENT_REF
6677              || TREE_CODE (inner) == ARRAY_REF);
6678       if ((TREE_CODE (inner) == VAR_DECL
6679            || TREE_CODE (inner) == FUNCTION_DECL)
6680           && DECL_WEAK (inner))
6681         return NULL_TREE;
6682     }
6683
6684   /* Otherwise, ARG0 already has the proper type for the return value.  */
6685   return arg0;
6686 }
6687
6688 /* Fold a call to __builtin_classify_type with argument ARG.  */
6689
6690 static tree
6691 fold_builtin_classify_type (tree arg)
6692 {
6693   if (arg == 0)
6694     return build_int_cst (NULL_TREE, no_type_class);
6695
6696   return build_int_cst (NULL_TREE, type_to_class (TREE_TYPE (arg)));
6697 }
6698
6699 /* Fold a call to __builtin_strlen with argument ARG.  */
6700
6701 static tree
6702 fold_builtin_strlen (location_t loc, tree type, tree arg)
6703 {
6704   if (!validate_arg (arg, POINTER_TYPE))
6705     return NULL_TREE;
6706   else
6707     {
6708       tree len = c_strlen (arg, 0);
6709
6710       if (len)
6711         return fold_convert_loc (loc, type, len);
6712
6713       return NULL_TREE;
6714     }
6715 }
6716
6717 /* Fold a call to __builtin_inf or __builtin_huge_val.  */
6718
6719 static tree
6720 fold_builtin_inf (location_t loc, tree type, int warn)
6721 {
6722   REAL_VALUE_TYPE real;
6723
6724   /* __builtin_inff is intended to be usable to define INFINITY on all
6725      targets.  If an infinity is not available, INFINITY expands "to a
6726      positive constant of type float that overflows at translation
6727      time", footnote "In this case, using INFINITY will violate the
6728      constraint in 6.4.4 and thus require a diagnostic." (C99 7.12#4).
6729      Thus we pedwarn to ensure this constraint violation is
6730      diagnosed.  */
6731   if (!MODE_HAS_INFINITIES (TYPE_MODE (type)) && warn)
6732     pedwarn (loc, 0, "target format does not support infinity");
6733
6734   real_inf (&real);
6735   return build_real (type, real);
6736 }
6737
6738 /* Fold a call to __builtin_nan or __builtin_nans with argument ARG.  */
6739
6740 static tree
6741 fold_builtin_nan (tree arg, tree type, int quiet)
6742 {
6743   REAL_VALUE_TYPE real;
6744   const char *str;
6745
6746   if (!validate_arg (arg, POINTER_TYPE))
6747     return NULL_TREE;
6748   str = c_getstr (arg);
6749   if (!str)
6750     return NULL_TREE;
6751
6752   if (!real_nan (&real, str, quiet, TYPE_MODE (type)))
6753     return NULL_TREE;
6754
6755   return build_real (type, real);
6756 }
6757
6758 /* Return true if the floating point expression T has an integer value.
6759    We also allow +Inf, -Inf and NaN to be considered integer values.  */
6760
6761 static bool
6762 integer_valued_real_p (tree t)
6763 {
6764   switch (TREE_CODE (t))
6765     {
6766     case FLOAT_EXPR:
6767       return true;
6768
6769     case ABS_EXPR:
6770     case SAVE_EXPR:
6771       return integer_valued_real_p (TREE_OPERAND (t, 0));
6772
6773     case COMPOUND_EXPR:
6774     case MODIFY_EXPR:
6775     case BIND_EXPR:
6776       return integer_valued_real_p (TREE_OPERAND (t, 1));
6777
6778     case PLUS_EXPR:
6779     case MINUS_EXPR:
6780     case MULT_EXPR:
6781     case MIN_EXPR:
6782     case MAX_EXPR:
6783       return integer_valued_real_p (TREE_OPERAND (t, 0))
6784              && integer_valued_real_p (TREE_OPERAND (t, 1));
6785
6786     case COND_EXPR:
6787       return integer_valued_real_p (TREE_OPERAND (t, 1))
6788              && integer_valued_real_p (TREE_OPERAND (t, 2));
6789
6790     case REAL_CST:
6791       return real_isinteger (TREE_REAL_CST_PTR (t), TYPE_MODE (TREE_TYPE (t)));
6792
6793     case NOP_EXPR:
6794       {
6795         tree type = TREE_TYPE (TREE_OPERAND (t, 0));
6796         if (TREE_CODE (type) == INTEGER_TYPE)
6797           return true;
6798         if (TREE_CODE (type) == REAL_TYPE)
6799           return integer_valued_real_p (TREE_OPERAND (t, 0));
6800         break;
6801       }
6802
6803     case CALL_EXPR:
6804       switch (builtin_mathfn_code (t))
6805         {
6806         CASE_FLT_FN (BUILT_IN_CEIL):
6807         CASE_FLT_FN (BUILT_IN_FLOOR):
6808         CASE_FLT_FN (BUILT_IN_NEARBYINT):
6809         CASE_FLT_FN (BUILT_IN_RINT):
6810         CASE_FLT_FN (BUILT_IN_ROUND):
6811         CASE_FLT_FN (BUILT_IN_TRUNC):
6812           return true;
6813
6814         CASE_FLT_FN (BUILT_IN_FMIN):
6815         CASE_FLT_FN (BUILT_IN_FMAX):
6816           return integer_valued_real_p (CALL_EXPR_ARG (t, 0))
6817             && integer_valued_real_p (CALL_EXPR_ARG (t, 1));
6818
6819         default:
6820           break;
6821         }
6822       break;
6823
6824     default:
6825       break;
6826     }
6827   return false;
6828 }
6829
6830 /* FNDECL is assumed to be a builtin where truncation can be propagated
6831    across (for instance floor((double)f) == (double)floorf (f).
6832    Do the transformation for a call with argument ARG.  */
6833
6834 static tree
6835 fold_trunc_transparent_mathfn (location_t loc, tree fndecl, tree arg)
6836 {
6837   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
6838
6839   if (!validate_arg (arg, REAL_TYPE))
6840     return NULL_TREE;
6841
6842   /* Integer rounding functions are idempotent.  */
6843   if (fcode == builtin_mathfn_code (arg))
6844     return arg;
6845
6846   /* If argument is already integer valued, and we don't need to worry
6847      about setting errno, there's no need to perform rounding.  */
6848   if (! flag_errno_math && integer_valued_real_p (arg))
6849     return arg;
6850
6851   if (optimize)
6852     {
6853       tree arg0 = strip_float_extensions (arg);
6854       tree ftype = TREE_TYPE (TREE_TYPE (fndecl));
6855       tree newtype = TREE_TYPE (arg0);
6856       tree decl;
6857
6858       if (TYPE_PRECISION (newtype) < TYPE_PRECISION (ftype)
6859           && (decl = mathfn_built_in (newtype, fcode)))
6860         return fold_convert_loc (loc, ftype,
6861                                  build_call_expr_loc (loc, decl, 1,
6862                                                   fold_convert_loc (loc,
6863                                                                     newtype,
6864                                                                     arg0)));
6865     }
6866   return NULL_TREE;
6867 }
6868
6869 /* FNDECL is assumed to be builtin which can narrow the FP type of
6870    the argument, for instance lround((double)f) -> lroundf (f).
6871    Do the transformation for a call with argument ARG.  */
6872
6873 static tree
6874 fold_fixed_mathfn (location_t loc, tree fndecl, tree arg)
6875 {
6876   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
6877
6878   if (!validate_arg (arg, REAL_TYPE))
6879     return NULL_TREE;
6880
6881   /* If argument is already integer valued, and we don't need to worry
6882      about setting errno, there's no need to perform rounding.  */
6883   if (! flag_errno_math && integer_valued_real_p (arg))
6884     return fold_build1_loc (loc, FIX_TRUNC_EXPR,
6885                         TREE_TYPE (TREE_TYPE (fndecl)), arg);
6886
6887   if (optimize)
6888     {
6889       tree ftype = TREE_TYPE (arg);
6890       tree arg0 = strip_float_extensions (arg);
6891       tree newtype = TREE_TYPE (arg0);
6892       tree decl;
6893
6894       if (TYPE_PRECISION (newtype) < TYPE_PRECISION (ftype)
6895           && (decl = mathfn_built_in (newtype, fcode)))
6896         return build_call_expr_loc (loc, decl, 1,
6897                                 fold_convert_loc (loc, newtype, arg0));
6898     }
6899
6900   /* Canonicalize llround (x) to lround (x) on LP64 targets where
6901      sizeof (long long) == sizeof (long).  */
6902   if (TYPE_PRECISION (long_long_integer_type_node)
6903       == TYPE_PRECISION (long_integer_type_node))
6904     {
6905       tree newfn = NULL_TREE;
6906       switch (fcode)
6907         {
6908         CASE_FLT_FN (BUILT_IN_LLCEIL):
6909           newfn = mathfn_built_in (TREE_TYPE (arg), BUILT_IN_LCEIL);
6910           break;
6911
6912         CASE_FLT_FN (BUILT_IN_LLFLOOR):
6913           newfn = mathfn_built_in (TREE_TYPE (arg), BUILT_IN_LFLOOR);
6914           break;
6915
6916         CASE_FLT_FN (BUILT_IN_LLROUND):
6917           newfn = mathfn_built_in (TREE_TYPE (arg), BUILT_IN_LROUND);
6918           break;
6919
6920         CASE_FLT_FN (BUILT_IN_LLRINT):
6921           newfn = mathfn_built_in (TREE_TYPE (arg), BUILT_IN_LRINT);
6922           break;
6923
6924         default:
6925           break;
6926         }
6927
6928       if (newfn)
6929         {
6930           tree newcall = build_call_expr_loc (loc, newfn, 1, arg);
6931           return fold_convert_loc (loc,
6932                                    TREE_TYPE (TREE_TYPE (fndecl)), newcall);
6933         }
6934     }
6935
6936   return NULL_TREE;
6937 }
6938
6939 /* Fold call to builtin cabs, cabsf or cabsl with argument ARG.  TYPE is the
6940    return type.  Return NULL_TREE if no simplification can be made.  */
6941
6942 static tree
6943 fold_builtin_cabs (location_t loc, tree arg, tree type, tree fndecl)
6944 {
6945   tree res;
6946
6947   if (!validate_arg (arg, COMPLEX_TYPE)
6948       || TREE_CODE (TREE_TYPE (TREE_TYPE (arg))) != REAL_TYPE)
6949     return NULL_TREE;
6950
6951   /* Calculate the result when the argument is a constant.  */
6952   if (TREE_CODE (arg) == COMPLEX_CST
6953       && (res = do_mpfr_arg2 (TREE_REALPART (arg), TREE_IMAGPART (arg),
6954                               type, mpfr_hypot)))
6955     return res;
6956
6957   if (TREE_CODE (arg) == COMPLEX_EXPR)
6958     {
6959       tree real = TREE_OPERAND (arg, 0);
6960       tree imag = TREE_OPERAND (arg, 1);
6961
6962       /* If either part is zero, cabs is fabs of the other.  */
6963       if (real_zerop (real))
6964         return fold_build1_loc (loc, ABS_EXPR, type, imag);
6965       if (real_zerop (imag))
6966         return fold_build1_loc (loc, ABS_EXPR, type, real);
6967
6968       /* cabs(x+xi) -> fabs(x)*sqrt(2).  */
6969       if (flag_unsafe_math_optimizations
6970           && operand_equal_p (real, imag, OEP_PURE_SAME))
6971         {
6972           const REAL_VALUE_TYPE sqrt2_trunc
6973             = real_value_truncate (TYPE_MODE (type), dconst_sqrt2 ());
6974           STRIP_NOPS (real);
6975           return fold_build2_loc (loc, MULT_EXPR, type,
6976                               fold_build1_loc (loc, ABS_EXPR, type, real),
6977                               build_real (type, sqrt2_trunc));
6978         }
6979     }
6980
6981   /* Optimize cabs(-z) and cabs(conj(z)) as cabs(z).  */
6982   if (TREE_CODE (arg) == NEGATE_EXPR
6983       || TREE_CODE (arg) == CONJ_EXPR)
6984     return build_call_expr_loc (loc, fndecl, 1, TREE_OPERAND (arg, 0));
6985
6986   /* Don't do this when optimizing for size.  */
6987   if (flag_unsafe_math_optimizations
6988       && optimize && optimize_function_for_speed_p (cfun))
6989     {
6990       tree sqrtfn = mathfn_built_in (type, BUILT_IN_SQRT);
6991
6992       if (sqrtfn != NULL_TREE)
6993         {
6994           tree rpart, ipart, result;
6995
6996           arg = builtin_save_expr (arg);
6997
6998           rpart = fold_build1_loc (loc, REALPART_EXPR, type, arg);
6999           ipart = fold_build1_loc (loc, IMAGPART_EXPR, type, arg);
7000
7001           rpart = builtin_save_expr (rpart);
7002           ipart = builtin_save_expr (ipart);
7003
7004           result = fold_build2_loc (loc, PLUS_EXPR, type,
7005                                 fold_build2_loc (loc, MULT_EXPR, type,
7006                                              rpart, rpart),
7007                                 fold_build2_loc (loc, MULT_EXPR, type,
7008                                              ipart, ipart));
7009
7010           return build_call_expr_loc (loc, sqrtfn, 1, result);
7011         }
7012     }
7013
7014   return NULL_TREE;
7015 }
7016
7017 /* Build a complex (inf +- 0i) for the result of cproj.  TYPE is the
7018    complex tree type of the result.  If NEG is true, the imaginary
7019    zero is negative.  */
7020
7021 static tree
7022 build_complex_cproj (tree type, bool neg)
7023 {
7024   REAL_VALUE_TYPE rinf, rzero = dconst0;
7025   
7026   real_inf (&rinf);
7027   rzero.sign = neg;
7028   return build_complex (type, build_real (TREE_TYPE (type), rinf),
7029                         build_real (TREE_TYPE (type), rzero));
7030 }
7031
7032 /* Fold call to builtin cproj, cprojf or cprojl with argument ARG.  TYPE is the
7033    return type.  Return NULL_TREE if no simplification can be made.  */
7034
7035 static tree
7036 fold_builtin_cproj (location_t loc, tree arg, tree type)
7037 {
7038   if (!validate_arg (arg, COMPLEX_TYPE)
7039       || TREE_CODE (TREE_TYPE (TREE_TYPE (arg))) != REAL_TYPE)
7040     return NULL_TREE;
7041
7042   /* If there are no infinities, return arg.  */
7043   if (! HONOR_INFINITIES (TYPE_MODE (TREE_TYPE (type))))
7044     return non_lvalue_loc (loc, arg);
7045
7046   /* Calculate the result when the argument is a constant.  */
7047   if (TREE_CODE (arg) == COMPLEX_CST)
7048     {
7049       const REAL_VALUE_TYPE *real = TREE_REAL_CST_PTR (TREE_REALPART (arg));
7050       const REAL_VALUE_TYPE *imag = TREE_REAL_CST_PTR (TREE_IMAGPART (arg));
7051       
7052       if (real_isinf (real) || real_isinf (imag))
7053         return build_complex_cproj (type, imag->sign);
7054       else
7055         return arg;
7056     }
7057   else if (TREE_CODE (arg) == COMPLEX_EXPR)
7058     {
7059       tree real = TREE_OPERAND (arg, 0);
7060       tree imag = TREE_OPERAND (arg, 1);
7061
7062       STRIP_NOPS (real);
7063       STRIP_NOPS (imag);
7064       
7065       /* If the real part is inf and the imag part is known to be
7066          nonnegative, return (inf + 0i).  Remember side-effects are
7067          possible in the imag part.  */
7068       if (TREE_CODE (real) == REAL_CST
7069           && real_isinf (TREE_REAL_CST_PTR (real))
7070           && tree_expr_nonnegative_p (imag))
7071         return omit_one_operand_loc (loc, type,
7072                                      build_complex_cproj (type, false),
7073                                      arg);
7074       
7075       /* If the imag part is inf, return (inf+I*copysign(0,imag)).
7076          Remember side-effects are possible in the real part.  */
7077       if (TREE_CODE (imag) == REAL_CST
7078           && real_isinf (TREE_REAL_CST_PTR (imag)))
7079         return
7080           omit_one_operand_loc (loc, type,
7081                                 build_complex_cproj (type, TREE_REAL_CST_PTR
7082                                                      (imag)->sign), arg);
7083     }
7084
7085   return NULL_TREE;
7086 }
7087
7088 /* Fold a builtin function call to sqrt, sqrtf, or sqrtl with argument ARG.
7089    Return NULL_TREE if no simplification can be made.  */
7090
7091 static tree
7092 fold_builtin_sqrt (location_t loc, tree arg, tree type)
7093 {
7094
7095   enum built_in_function fcode;
7096   tree res;
7097
7098   if (!validate_arg (arg, REAL_TYPE))
7099     return NULL_TREE;
7100
7101   /* Calculate the result when the argument is a constant.  */
7102   if ((res = do_mpfr_arg1 (arg, type, mpfr_sqrt, &dconst0, NULL, true)))
7103     return res;
7104
7105   /* Optimize sqrt(expN(x)) = expN(x*0.5).  */
7106   fcode = builtin_mathfn_code (arg);
7107   if (flag_unsafe_math_optimizations && BUILTIN_EXPONENT_P (fcode))
7108     {
7109       tree expfn = TREE_OPERAND (CALL_EXPR_FN (arg), 0);
7110       arg = fold_build2_loc (loc, MULT_EXPR, type,
7111                          CALL_EXPR_ARG (arg, 0),
7112                          build_real (type, dconsthalf));
7113       return build_call_expr_loc (loc, expfn, 1, arg);
7114     }
7115
7116   /* Optimize sqrt(Nroot(x)) -> pow(x,1/(2*N)).  */
7117   if (flag_unsafe_math_optimizations && BUILTIN_ROOT_P (fcode))
7118     {
7119       tree powfn = mathfn_built_in (type, BUILT_IN_POW);
7120
7121       if (powfn)
7122         {
7123           tree arg0 = CALL_EXPR_ARG (arg, 0);
7124           tree tree_root;
7125           /* The inner root was either sqrt or cbrt.  */
7126           /* This was a conditional expression but it triggered a bug
7127              in Sun C 5.5.  */
7128           REAL_VALUE_TYPE dconstroot;
7129           if (BUILTIN_SQRT_P (fcode))
7130             dconstroot = dconsthalf;
7131           else
7132             dconstroot = dconst_third ();
7133
7134           /* Adjust for the outer root.  */
7135           SET_REAL_EXP (&dconstroot, REAL_EXP (&dconstroot) - 1);
7136           dconstroot = real_value_truncate (TYPE_MODE (type), dconstroot);
7137           tree_root = build_real (type, dconstroot);
7138           return build_call_expr_loc (loc, powfn, 2, arg0, tree_root);
7139         }
7140     }
7141
7142   /* Optimize sqrt(pow(x,y)) = pow(|x|,y*0.5).  */
7143   if (flag_unsafe_math_optimizations
7144       && (fcode == BUILT_IN_POW
7145           || fcode == BUILT_IN_POWF
7146           || fcode == BUILT_IN_POWL))
7147     {
7148       tree powfn = TREE_OPERAND (CALL_EXPR_FN (arg), 0);
7149       tree arg0 = CALL_EXPR_ARG (arg, 0);
7150       tree arg1 = CALL_EXPR_ARG (arg, 1);
7151       tree narg1;
7152       if (!tree_expr_nonnegative_p (arg0))
7153         arg0 = build1 (ABS_EXPR, type, arg0);
7154       narg1 = fold_build2_loc (loc, MULT_EXPR, type, arg1,
7155                            build_real (type, dconsthalf));
7156       return build_call_expr_loc (loc, powfn, 2, arg0, narg1);
7157     }
7158
7159   return NULL_TREE;
7160 }
7161
7162 /* Fold a builtin function call to cbrt, cbrtf, or cbrtl with argument ARG.
7163    Return NULL_TREE if no simplification can be made.  */
7164
7165 static tree
7166 fold_builtin_cbrt (location_t loc, tree arg, tree type)
7167 {
7168   const enum built_in_function fcode = builtin_mathfn_code (arg);
7169   tree res;
7170
7171   if (!validate_arg (arg, REAL_TYPE))
7172     return NULL_TREE;
7173
7174   /* Calculate the result when the argument is a constant.  */
7175   if ((res = do_mpfr_arg1 (arg, type, mpfr_cbrt, NULL, NULL, 0)))
7176     return res;
7177
7178   if (flag_unsafe_math_optimizations)
7179     {
7180       /* Optimize cbrt(expN(x)) -> expN(x/3).  */
7181       if (BUILTIN_EXPONENT_P (fcode))
7182         {
7183           tree expfn = TREE_OPERAND (CALL_EXPR_FN (arg), 0);
7184           const REAL_VALUE_TYPE third_trunc =
7185             real_value_truncate (TYPE_MODE (type), dconst_third ());
7186           arg = fold_build2_loc (loc, MULT_EXPR, type,
7187                              CALL_EXPR_ARG (arg, 0),
7188                              build_real (type, third_trunc));
7189           return build_call_expr_loc (loc, expfn, 1, arg);
7190         }
7191
7192       /* Optimize cbrt(sqrt(x)) -> pow(x,1/6).  */
7193       if (BUILTIN_SQRT_P (fcode))
7194         {
7195           tree powfn = mathfn_built_in (type, BUILT_IN_POW);
7196
7197           if (powfn)
7198             {
7199               tree arg0 = CALL_EXPR_ARG (arg, 0);
7200               tree tree_root;
7201               REAL_VALUE_TYPE dconstroot = dconst_third ();
7202
7203               SET_REAL_EXP (&dconstroot, REAL_EXP (&dconstroot) - 1);
7204               dconstroot = real_value_truncate (TYPE_MODE (type), dconstroot);
7205               tree_root = build_real (type, dconstroot);
7206               return build_call_expr_loc (loc, powfn, 2, arg0, tree_root);
7207             }
7208         }
7209
7210       /* Optimize cbrt(cbrt(x)) -> pow(x,1/9) iff x is nonnegative.  */
7211       if (BUILTIN_CBRT_P (fcode))
7212         {
7213           tree arg0 = CALL_EXPR_ARG (arg, 0);
7214           if (tree_expr_nonnegative_p (arg0))
7215             {
7216               tree powfn = mathfn_built_in (type, BUILT_IN_POW);
7217
7218               if (powfn)
7219                 {
7220                   tree tree_root;
7221                   REAL_VALUE_TYPE dconstroot;
7222
7223                   real_arithmetic (&dconstroot, MULT_EXPR,
7224                                    dconst_third_ptr (), dconst_third_ptr ());
7225                   dconstroot = real_value_truncate (TYPE_MODE (type), dconstroot);
7226                   tree_root = build_real (type, dconstroot);
7227                   return build_call_expr_loc (loc, powfn, 2, arg0, tree_root);
7228                 }
7229             }
7230         }
7231
7232       /* Optimize cbrt(pow(x,y)) -> pow(x,y/3) iff x is nonnegative.  */
7233       if (fcode == BUILT_IN_POW
7234           || fcode == BUILT_IN_POWF
7235           || fcode == BUILT_IN_POWL)
7236         {
7237           tree arg00 = CALL_EXPR_ARG (arg, 0);
7238           tree arg01 = CALL_EXPR_ARG (arg, 1);
7239           if (tree_expr_nonnegative_p (arg00))
7240             {
7241               tree powfn = TREE_OPERAND (CALL_EXPR_FN (arg), 0);
7242               const REAL_VALUE_TYPE dconstroot
7243                 = real_value_truncate (TYPE_MODE (type), dconst_third ());
7244               tree narg01 = fold_build2_loc (loc, MULT_EXPR, type, arg01,
7245                                          build_real (type, dconstroot));
7246               return build_call_expr_loc (loc, powfn, 2, arg00, narg01);
7247             }
7248         }
7249     }
7250   return NULL_TREE;
7251 }
7252
7253 /* Fold function call to builtin cos, cosf, or cosl with argument ARG.
7254    TYPE is the type of the return value.  Return NULL_TREE if no
7255    simplification can be made.  */
7256
7257 static tree
7258 fold_builtin_cos (location_t loc,
7259                   tree arg, tree type, tree fndecl)
7260 {
7261   tree res, narg;
7262
7263   if (!validate_arg (arg, REAL_TYPE))
7264     return NULL_TREE;
7265
7266   /* Calculate the result when the argument is a constant.  */
7267   if ((res = do_mpfr_arg1 (arg, type, mpfr_cos, NULL, NULL, 0)))
7268     return res;
7269
7270   /* Optimize cos(-x) into cos (x).  */
7271   if ((narg = fold_strip_sign_ops (arg)))
7272     return build_call_expr_loc (loc, fndecl, 1, narg);
7273
7274   return NULL_TREE;
7275 }
7276
7277 /* Fold function call to builtin cosh, coshf, or coshl with argument ARG.
7278    Return NULL_TREE if no simplification can be made.  */
7279
7280 static tree
7281 fold_builtin_cosh (location_t loc, tree arg, tree type, tree fndecl)
7282 {
7283   if (validate_arg (arg, REAL_TYPE))
7284     {
7285       tree res, narg;
7286
7287       /* Calculate the result when the argument is a constant.  */
7288       if ((res = do_mpfr_arg1 (arg, type, mpfr_cosh, NULL, NULL, 0)))
7289         return res;
7290
7291       /* Optimize cosh(-x) into cosh (x).  */
7292       if ((narg = fold_strip_sign_ops (arg)))
7293         return build_call_expr_loc (loc, fndecl, 1, narg);
7294     }
7295
7296   return NULL_TREE;
7297 }
7298
7299 /* Fold function call to builtin ccos (or ccosh if HYPER is TRUE) with
7300    argument ARG.  TYPE is the type of the return value.  Return
7301    NULL_TREE if no simplification can be made.  */
7302
7303 static tree
7304 fold_builtin_ccos (location_t loc, tree arg, tree type, tree fndecl,
7305                    bool hyper)
7306 {
7307   if (validate_arg (arg, COMPLEX_TYPE)
7308       && TREE_CODE (TREE_TYPE (TREE_TYPE (arg))) == REAL_TYPE)
7309     {
7310       tree tmp;
7311
7312       /* Calculate the result when the argument is a constant.  */
7313       if ((tmp = do_mpc_arg1 (arg, type, (hyper ? mpc_cosh : mpc_cos))))
7314         return tmp;
7315
7316       /* Optimize fn(-x) into fn(x).  */
7317       if ((tmp = fold_strip_sign_ops (arg)))
7318         return build_call_expr_loc (loc, fndecl, 1, tmp);
7319     }
7320
7321   return NULL_TREE;
7322 }
7323
7324 /* Fold function call to builtin tan, tanf, or tanl with argument ARG.
7325    Return NULL_TREE if no simplification can be made.  */
7326
7327 static tree
7328 fold_builtin_tan (tree arg, tree type)
7329 {
7330   enum built_in_function fcode;
7331   tree res;
7332
7333   if (!validate_arg (arg, REAL_TYPE))
7334     return NULL_TREE;
7335
7336   /* Calculate the result when the argument is a constant.  */
7337   if ((res = do_mpfr_arg1 (arg, type, mpfr_tan, NULL, NULL, 0)))
7338     return res;
7339
7340   /* Optimize tan(atan(x)) = x.  */
7341   fcode = builtin_mathfn_code (arg);
7342   if (flag_unsafe_math_optimizations
7343       && (fcode == BUILT_IN_ATAN
7344           || fcode == BUILT_IN_ATANF
7345           || fcode == BUILT_IN_ATANL))
7346     return CALL_EXPR_ARG (arg, 0);
7347
7348   return NULL_TREE;
7349 }
7350
7351 /* Fold function call to builtin sincos, sincosf, or sincosl.  Return
7352    NULL_TREE if no simplification can be made.  */
7353
7354 static tree
7355 fold_builtin_sincos (location_t loc,
7356                      tree arg0, tree arg1, tree arg2)
7357 {
7358   tree type;
7359   tree res, fn, call;
7360
7361   if (!validate_arg (arg0, REAL_TYPE)
7362       || !validate_arg (arg1, POINTER_TYPE)
7363       || !validate_arg (arg2, POINTER_TYPE))
7364     return NULL_TREE;
7365
7366   type = TREE_TYPE (arg0);
7367
7368   /* Calculate the result when the argument is a constant.  */
7369   if ((res = do_mpfr_sincos (arg0, arg1, arg2)))
7370     return res;
7371
7372   /* Canonicalize sincos to cexpi.  */
7373   if (!TARGET_C99_FUNCTIONS)
7374     return NULL_TREE;
7375   fn = mathfn_built_in (type, BUILT_IN_CEXPI);
7376   if (!fn)
7377     return NULL_TREE;
7378
7379   call = build_call_expr_loc (loc, fn, 1, arg0);
7380   call = builtin_save_expr (call);
7381
7382   return build2 (COMPOUND_EXPR, void_type_node,
7383                  build2 (MODIFY_EXPR, void_type_node,
7384                          build_fold_indirect_ref_loc (loc, arg1),
7385                          build1 (IMAGPART_EXPR, type, call)),
7386                  build2 (MODIFY_EXPR, void_type_node,
7387                          build_fold_indirect_ref_loc (loc, arg2),
7388                          build1 (REALPART_EXPR, type, call)));
7389 }
7390
7391 /* Fold function call to builtin cexp, cexpf, or cexpl.  Return
7392    NULL_TREE if no simplification can be made.  */
7393
7394 static tree
7395 fold_builtin_cexp (location_t loc, tree arg0, tree type)
7396 {
7397   tree rtype;
7398   tree realp, imagp, ifn;
7399   tree res;
7400
7401   if (!validate_arg (arg0, COMPLEX_TYPE)
7402       || TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) != REAL_TYPE)
7403     return NULL_TREE;
7404
7405   /* Calculate the result when the argument is a constant.  */
7406   if ((res = do_mpc_arg1 (arg0, type, mpc_exp)))
7407     return res;
7408
7409   rtype = TREE_TYPE (TREE_TYPE (arg0));
7410
7411   /* In case we can figure out the real part of arg0 and it is constant zero
7412      fold to cexpi.  */
7413   if (!TARGET_C99_FUNCTIONS)
7414     return NULL_TREE;
7415   ifn = mathfn_built_in (rtype, BUILT_IN_CEXPI);
7416   if (!ifn)
7417     return NULL_TREE;
7418
7419   if ((realp = fold_unary_loc (loc, REALPART_EXPR, rtype, arg0))
7420       && real_zerop (realp))
7421     {
7422       tree narg = fold_build1_loc (loc, IMAGPART_EXPR, rtype, arg0);
7423       return build_call_expr_loc (loc, ifn, 1, narg);
7424     }
7425
7426   /* In case we can easily decompose real and imaginary parts split cexp
7427      to exp (r) * cexpi (i).  */
7428   if (flag_unsafe_math_optimizations
7429       && realp)
7430     {
7431       tree rfn, rcall, icall;
7432
7433       rfn = mathfn_built_in (rtype, BUILT_IN_EXP);
7434       if (!rfn)
7435         return NULL_TREE;
7436
7437       imagp = fold_unary_loc (loc, IMAGPART_EXPR, rtype, arg0);
7438       if (!imagp)
7439         return NULL_TREE;
7440
7441       icall = build_call_expr_loc (loc, ifn, 1, imagp);
7442       icall = builtin_save_expr (icall);
7443       rcall = build_call_expr_loc (loc, rfn, 1, realp);
7444       rcall = builtin_save_expr (rcall);
7445       return fold_build2_loc (loc, COMPLEX_EXPR, type,
7446                           fold_build2_loc (loc, MULT_EXPR, rtype,
7447                                        rcall,
7448                                        fold_build1_loc (loc, REALPART_EXPR,
7449                                                     rtype, icall)),
7450                           fold_build2_loc (loc, MULT_EXPR, rtype,
7451                                        rcall,
7452                                        fold_build1_loc (loc, IMAGPART_EXPR,
7453                                                     rtype, icall)));
7454     }
7455
7456   return NULL_TREE;
7457 }
7458
7459 /* Fold function call to builtin trunc, truncf or truncl with argument ARG.
7460    Return NULL_TREE if no simplification can be made.  */
7461
7462 static tree
7463 fold_builtin_trunc (location_t loc, tree fndecl, tree arg)
7464 {
7465   if (!validate_arg (arg, REAL_TYPE))
7466     return NULL_TREE;
7467
7468   /* Optimize trunc of constant value.  */
7469   if (TREE_CODE (arg) == REAL_CST && !TREE_OVERFLOW (arg))
7470     {
7471       REAL_VALUE_TYPE r, x;
7472       tree type = TREE_TYPE (TREE_TYPE (fndecl));
7473
7474       x = TREE_REAL_CST (arg);
7475       real_trunc (&r, TYPE_MODE (type), &x);
7476       return build_real (type, r);
7477     }
7478
7479   return fold_trunc_transparent_mathfn (loc, fndecl, arg);
7480 }
7481
7482 /* Fold function call to builtin floor, floorf or floorl with argument ARG.
7483    Return NULL_TREE if no simplification can be made.  */
7484
7485 static tree
7486 fold_builtin_floor (location_t loc, tree fndecl, tree arg)
7487 {
7488   if (!validate_arg (arg, REAL_TYPE))
7489     return NULL_TREE;
7490
7491   /* Optimize floor of constant value.  */
7492   if (TREE_CODE (arg) == REAL_CST && !TREE_OVERFLOW (arg))
7493     {
7494       REAL_VALUE_TYPE x;
7495
7496       x = TREE_REAL_CST (arg);
7497       if (! REAL_VALUE_ISNAN (x) || ! flag_errno_math)
7498         {
7499           tree type = TREE_TYPE (TREE_TYPE (fndecl));
7500           REAL_VALUE_TYPE r;
7501
7502           real_floor (&r, TYPE_MODE (type), &x);
7503           return build_real (type, r);
7504         }
7505     }
7506
7507   /* Fold floor (x) where x is nonnegative to trunc (x).  */
7508   if (tree_expr_nonnegative_p (arg))
7509     {
7510       tree truncfn = mathfn_built_in (TREE_TYPE (arg), BUILT_IN_TRUNC);
7511       if (truncfn)
7512         return build_call_expr_loc (loc, truncfn, 1, arg);
7513     }
7514
7515   return fold_trunc_transparent_mathfn (loc, fndecl, arg);
7516 }
7517
7518 /* Fold function call to builtin ceil, ceilf or ceill with argument ARG.
7519    Return NULL_TREE if no simplification can be made.  */
7520
7521 static tree
7522 fold_builtin_ceil (location_t loc, tree fndecl, tree arg)
7523 {
7524   if (!validate_arg (arg, REAL_TYPE))
7525     return NULL_TREE;
7526
7527   /* Optimize ceil of constant value.  */
7528   if (TREE_CODE (arg) == REAL_CST && !TREE_OVERFLOW (arg))
7529     {
7530       REAL_VALUE_TYPE x;
7531
7532       x = TREE_REAL_CST (arg);
7533       if (! REAL_VALUE_ISNAN (x) || ! flag_errno_math)
7534         {
7535           tree type = TREE_TYPE (TREE_TYPE (fndecl));
7536           REAL_VALUE_TYPE r;
7537
7538           real_ceil (&r, TYPE_MODE (type), &x);
7539           return build_real (type, r);
7540         }
7541     }
7542
7543   return fold_trunc_transparent_mathfn (loc, fndecl, arg);
7544 }
7545
7546 /* Fold function call to builtin round, roundf or roundl with argument ARG.
7547    Return NULL_TREE if no simplification can be made.  */
7548
7549 static tree
7550 fold_builtin_round (location_t loc, tree fndecl, tree arg)
7551 {
7552   if (!validate_arg (arg, REAL_TYPE))
7553     return NULL_TREE;
7554
7555   /* Optimize round of constant value.  */
7556   if (TREE_CODE (arg) == REAL_CST && !TREE_OVERFLOW (arg))
7557     {
7558       REAL_VALUE_TYPE x;
7559
7560       x = TREE_REAL_CST (arg);
7561       if (! REAL_VALUE_ISNAN (x) || ! flag_errno_math)
7562         {
7563           tree type = TREE_TYPE (TREE_TYPE (fndecl));
7564           REAL_VALUE_TYPE r;
7565
7566           real_round (&r, TYPE_MODE (type), &x);
7567           return build_real (type, r);
7568         }
7569     }
7570
7571   return fold_trunc_transparent_mathfn (loc, fndecl, arg);
7572 }
7573
7574 /* Fold function call to builtin lround, lroundf or lroundl (or the
7575    corresponding long long versions) and other rounding functions.  ARG
7576    is the argument to the call.  Return NULL_TREE if no simplification
7577    can be made.  */
7578
7579 static tree
7580 fold_builtin_int_roundingfn (location_t loc, tree fndecl, tree arg)
7581 {
7582   if (!validate_arg (arg, REAL_TYPE))
7583     return NULL_TREE;
7584
7585   /* Optimize lround of constant value.  */
7586   if (TREE_CODE (arg) == REAL_CST && !TREE_OVERFLOW (arg))
7587     {
7588       const REAL_VALUE_TYPE x = TREE_REAL_CST (arg);
7589
7590       if (real_isfinite (&x))
7591         {
7592           tree itype = TREE_TYPE (TREE_TYPE (fndecl));
7593           tree ftype = TREE_TYPE (arg);
7594           double_int val;
7595           REAL_VALUE_TYPE r;
7596
7597           switch (DECL_FUNCTION_CODE (fndecl))
7598             {
7599             CASE_FLT_FN (BUILT_IN_LFLOOR):
7600             CASE_FLT_FN (BUILT_IN_LLFLOOR):
7601               real_floor (&r, TYPE_MODE (ftype), &x);
7602               break;
7603
7604             CASE_FLT_FN (BUILT_IN_LCEIL):
7605             CASE_FLT_FN (BUILT_IN_LLCEIL):
7606               real_ceil (&r, TYPE_MODE (ftype), &x);
7607               break;
7608
7609             CASE_FLT_FN (BUILT_IN_LROUND):
7610             CASE_FLT_FN (BUILT_IN_LLROUND):
7611               real_round (&r, TYPE_MODE (ftype), &x);
7612               break;
7613
7614             default:
7615               gcc_unreachable ();
7616             }
7617
7618           real_to_integer2 ((HOST_WIDE_INT *)&val.low, &val.high, &r);
7619           if (double_int_fits_to_tree_p (itype, val))
7620             return double_int_to_tree (itype, val);
7621         }
7622     }
7623
7624   switch (DECL_FUNCTION_CODE (fndecl))
7625     {
7626     CASE_FLT_FN (BUILT_IN_LFLOOR):
7627     CASE_FLT_FN (BUILT_IN_LLFLOOR):
7628       /* Fold lfloor (x) where x is nonnegative to FIX_TRUNC (x).  */
7629       if (tree_expr_nonnegative_p (arg))
7630         return fold_build1_loc (loc, FIX_TRUNC_EXPR,
7631                             TREE_TYPE (TREE_TYPE (fndecl)), arg);
7632       break;
7633     default:;
7634     }
7635
7636   return fold_fixed_mathfn (loc, fndecl, arg);
7637 }
7638
7639 /* Fold function call to builtin ffs, clz, ctz, popcount and parity
7640    and their long and long long variants (i.e. ffsl and ffsll).  ARG is
7641    the argument to the call.  Return NULL_TREE if no simplification can
7642    be made.  */
7643
7644 static tree
7645 fold_builtin_bitop (tree fndecl, tree arg)
7646 {
7647   if (!validate_arg (arg, INTEGER_TYPE))
7648     return NULL_TREE;
7649
7650   /* Optimize for constant argument.  */
7651   if (TREE_CODE (arg) == INTEGER_CST && !TREE_OVERFLOW (arg))
7652     {
7653       HOST_WIDE_INT hi, width, result;
7654       unsigned HOST_WIDE_INT lo;
7655       tree type;
7656
7657       type = TREE_TYPE (arg);
7658       width = TYPE_PRECISION (type);
7659       lo = TREE_INT_CST_LOW (arg);
7660
7661       /* Clear all the bits that are beyond the type's precision.  */
7662       if (width > HOST_BITS_PER_WIDE_INT)
7663         {
7664           hi = TREE_INT_CST_HIGH (arg);
7665           if (width < 2 * HOST_BITS_PER_WIDE_INT)
7666             hi &= ~((HOST_WIDE_INT) (-1) >> (width - HOST_BITS_PER_WIDE_INT));
7667         }
7668       else
7669         {
7670           hi = 0;
7671           if (width < HOST_BITS_PER_WIDE_INT)
7672             lo &= ~((unsigned HOST_WIDE_INT) (-1) << width);
7673         }
7674
7675       switch (DECL_FUNCTION_CODE (fndecl))
7676         {
7677         CASE_INT_FN (BUILT_IN_FFS):
7678           if (lo != 0)
7679             result = exact_log2 (lo & -lo) + 1;
7680           else if (hi != 0)
7681             result = HOST_BITS_PER_WIDE_INT + exact_log2 (hi & -hi) + 1;
7682           else
7683             result = 0;
7684           break;
7685
7686         CASE_INT_FN (BUILT_IN_CLZ):
7687           if (hi != 0)
7688             result = width - floor_log2 (hi) - 1 - HOST_BITS_PER_WIDE_INT;
7689           else if (lo != 0)
7690             result = width - floor_log2 (lo) - 1;
7691           else if (! CLZ_DEFINED_VALUE_AT_ZERO (TYPE_MODE (type), result))
7692             result = width;
7693           break;
7694
7695         CASE_INT_FN (BUILT_IN_CTZ):
7696           if (lo != 0)
7697             result = exact_log2 (lo & -lo);
7698           else if (hi != 0)
7699             result = HOST_BITS_PER_WIDE_INT + exact_log2 (hi & -hi);
7700           else if (! CTZ_DEFINED_VALUE_AT_ZERO (TYPE_MODE (type), result))
7701             result = width;
7702           break;
7703
7704         CASE_INT_FN (BUILT_IN_POPCOUNT):
7705           result = 0;
7706           while (lo)
7707             result++, lo &= lo - 1;
7708           while (hi)
7709             result++, hi &= hi - 1;
7710           break;
7711
7712         CASE_INT_FN (BUILT_IN_PARITY):
7713           result = 0;
7714           while (lo)
7715             result++, lo &= lo - 1;
7716           while (hi)
7717             result++, hi &= hi - 1;
7718           result &= 1;
7719           break;
7720
7721         default:
7722           gcc_unreachable ();
7723         }
7724
7725       return build_int_cst (TREE_TYPE (TREE_TYPE (fndecl)), result);
7726     }
7727
7728   return NULL_TREE;
7729 }
7730
7731 /* Fold function call to builtin_bswap and the long and long long
7732    variants.  Return NULL_TREE if no simplification can be made.  */
7733 static tree
7734 fold_builtin_bswap (tree fndecl, tree arg)
7735 {
7736   if (! validate_arg (arg, INTEGER_TYPE))
7737     return NULL_TREE;
7738
7739   /* Optimize constant value.  */
7740   if (TREE_CODE (arg) == INTEGER_CST && !TREE_OVERFLOW (arg))
7741     {
7742       HOST_WIDE_INT hi, width, r_hi = 0;
7743       unsigned HOST_WIDE_INT lo, r_lo = 0;
7744       tree type;
7745
7746       type = TREE_TYPE (arg);
7747       width = TYPE_PRECISION (type);
7748       lo = TREE_INT_CST_LOW (arg);
7749       hi = TREE_INT_CST_HIGH (arg);
7750
7751       switch (DECL_FUNCTION_CODE (fndecl))
7752         {
7753           case BUILT_IN_BSWAP32:
7754           case BUILT_IN_BSWAP64:
7755             {
7756               int s;
7757
7758               for (s = 0; s < width; s += 8)
7759                 {
7760                   int d = width - s - 8;
7761                   unsigned HOST_WIDE_INT byte;
7762
7763                   if (s < HOST_BITS_PER_WIDE_INT)
7764                     byte = (lo >> s) & 0xff;
7765                   else
7766                     byte = (hi >> (s - HOST_BITS_PER_WIDE_INT)) & 0xff;
7767
7768                   if (d < HOST_BITS_PER_WIDE_INT)
7769                     r_lo |= byte << d;
7770                   else
7771                     r_hi |= byte << (d - HOST_BITS_PER_WIDE_INT);
7772                 }
7773             }
7774
7775             break;
7776
7777         default:
7778           gcc_unreachable ();
7779         }
7780
7781       if (width < HOST_BITS_PER_WIDE_INT)
7782         return build_int_cst (TREE_TYPE (TREE_TYPE (fndecl)), r_lo);
7783       else
7784         return build_int_cst_wide (TREE_TYPE (TREE_TYPE (fndecl)), r_lo, r_hi);
7785     }
7786
7787   return NULL_TREE;
7788 }
7789
7790 /* A subroutine of fold_builtin to fold the various logarithmic
7791    functions.  Return NULL_TREE if no simplification can me made.
7792    FUNC is the corresponding MPFR logarithm function.  */
7793
7794 static tree
7795 fold_builtin_logarithm (location_t loc, tree fndecl, tree arg,
7796                         int (*func)(mpfr_ptr, mpfr_srcptr, mp_rnd_t))
7797 {
7798   if (validate_arg (arg, REAL_TYPE))
7799     {
7800       tree type = TREE_TYPE (TREE_TYPE (fndecl));
7801       tree res;
7802       const enum built_in_function fcode = builtin_mathfn_code (arg);
7803
7804       /* Calculate the result when the argument is a constant.  */
7805       if ((res = do_mpfr_arg1 (arg, type, func, &dconst0, NULL, false)))
7806         return res;
7807
7808       /* Special case, optimize logN(expN(x)) = x.  */
7809       if (flag_unsafe_math_optimizations
7810           && ((func == mpfr_log
7811                && (fcode == BUILT_IN_EXP
7812                    || fcode == BUILT_IN_EXPF
7813                    || fcode == BUILT_IN_EXPL))
7814               || (func == mpfr_log2
7815                   && (fcode == BUILT_IN_EXP2
7816                       || fcode == BUILT_IN_EXP2F
7817                       || fcode == BUILT_IN_EXP2L))
7818               || (func == mpfr_log10 && (BUILTIN_EXP10_P (fcode)))))
7819         return fold_convert_loc (loc, type, CALL_EXPR_ARG (arg, 0));
7820
7821       /* Optimize logN(func()) for various exponential functions.  We
7822          want to determine the value "x" and the power "exponent" in
7823          order to transform logN(x**exponent) into exponent*logN(x).  */
7824       if (flag_unsafe_math_optimizations)
7825         {
7826           tree exponent = 0, x = 0;
7827
7828           switch (fcode)
7829           {
7830           CASE_FLT_FN (BUILT_IN_EXP):
7831             /* Prepare to do logN(exp(exponent) -> exponent*logN(e).  */
7832             x = build_real (type, real_value_truncate (TYPE_MODE (type),
7833                                                        dconst_e ()));
7834             exponent = CALL_EXPR_ARG (arg, 0);
7835             break;
7836           CASE_FLT_FN (BUILT_IN_EXP2):
7837             /* Prepare to do logN(exp2(exponent) -> exponent*logN(2).  */
7838             x = build_real (type, dconst2);
7839             exponent = CALL_EXPR_ARG (arg, 0);
7840             break;
7841           CASE_FLT_FN (BUILT_IN_EXP10):
7842           CASE_FLT_FN (BUILT_IN_POW10):
7843             /* Prepare to do logN(exp10(exponent) -> exponent*logN(10).  */
7844             {
7845               REAL_VALUE_TYPE dconst10;
7846               real_from_integer (&dconst10, VOIDmode, 10, 0, 0);
7847               x = build_real (type, dconst10);
7848             }
7849             exponent = CALL_EXPR_ARG (arg, 0);
7850             break;
7851           CASE_FLT_FN (BUILT_IN_SQRT):
7852             /* Prepare to do logN(sqrt(x) -> 0.5*logN(x).  */
7853             x = CALL_EXPR_ARG (arg, 0);
7854             exponent = build_real (type, dconsthalf);
7855             break;
7856           CASE_FLT_FN (BUILT_IN_CBRT):
7857             /* Prepare to do logN(cbrt(x) -> (1/3)*logN(x).  */
7858             x = CALL_EXPR_ARG (arg, 0);
7859             exponent = build_real (type, real_value_truncate (TYPE_MODE (type),
7860                                                               dconst_third ()));
7861             break;
7862           CASE_FLT_FN (BUILT_IN_POW):
7863             /* Prepare to do logN(pow(x,exponent) -> exponent*logN(x).  */
7864             x = CALL_EXPR_ARG (arg, 0);
7865             exponent = CALL_EXPR_ARG (arg, 1);
7866             break;
7867           default:
7868             break;
7869           }
7870
7871           /* Now perform the optimization.  */
7872           if (x && exponent)
7873             {
7874               tree logfn = build_call_expr_loc (loc, fndecl, 1, x);
7875               return fold_build2_loc (loc, MULT_EXPR, type, exponent, logfn);
7876             }
7877         }
7878     }
7879
7880   return NULL_TREE;
7881 }
7882
7883 /* Fold a builtin function call to hypot, hypotf, or hypotl.  Return
7884    NULL_TREE if no simplification can be made.  */
7885
7886 static tree
7887 fold_builtin_hypot (location_t loc, tree fndecl,
7888                     tree arg0, tree arg1, tree type)
7889 {
7890   tree res, narg0, narg1;
7891
7892   if (!validate_arg (arg0, REAL_TYPE)
7893       || !validate_arg (arg1, REAL_TYPE))
7894     return NULL_TREE;
7895
7896   /* Calculate the result when the argument is a constant.  */
7897   if ((res = do_mpfr_arg2 (arg0, arg1, type, mpfr_hypot)))
7898     return res;
7899
7900   /* If either argument to hypot has a negate or abs, strip that off.
7901      E.g. hypot(-x,fabs(y)) -> hypot(x,y).  */
7902   narg0 = fold_strip_sign_ops (arg0);
7903   narg1 = fold_strip_sign_ops (arg1);
7904   if (narg0 || narg1)
7905     {
7906       return build_call_expr_loc (loc, fndecl, 2, narg0 ? narg0 : arg0,
7907                               narg1 ? narg1 : arg1);
7908     }
7909
7910   /* If either argument is zero, hypot is fabs of the other.  */
7911   if (real_zerop (arg0))
7912     return fold_build1_loc (loc, ABS_EXPR, type, arg1);
7913   else if (real_zerop (arg1))
7914     return fold_build1_loc (loc, ABS_EXPR, type, arg0);
7915
7916   /* hypot(x,x) -> fabs(x)*sqrt(2).  */
7917   if (flag_unsafe_math_optimizations
7918       && operand_equal_p (arg0, arg1, OEP_PURE_SAME))
7919     {
7920       const REAL_VALUE_TYPE sqrt2_trunc
7921         = real_value_truncate (TYPE_MODE (type), dconst_sqrt2 ());
7922       return fold_build2_loc (loc, MULT_EXPR, type,
7923                           fold_build1_loc (loc, ABS_EXPR, type, arg0),
7924                           build_real (type, sqrt2_trunc));
7925     }
7926
7927   return NULL_TREE;
7928 }
7929
7930
7931 /* Fold a builtin function call to pow, powf, or powl.  Return
7932    NULL_TREE if no simplification can be made.  */
7933 static tree
7934 fold_builtin_pow (location_t loc, tree fndecl, tree arg0, tree arg1, tree type)
7935 {
7936   tree res;
7937
7938   if (!validate_arg (arg0, REAL_TYPE)
7939        || !validate_arg (arg1, REAL_TYPE))
7940     return NULL_TREE;
7941
7942   /* Calculate the result when the argument is a constant.  */
7943   if ((res = do_mpfr_arg2 (arg0, arg1, type, mpfr_pow)))
7944     return res;
7945
7946   /* Optimize pow(1.0,y) = 1.0.  */
7947   if (real_onep (arg0))
7948     return omit_one_operand_loc (loc, type, build_real (type, dconst1), arg1);
7949
7950   if (TREE_CODE (arg1) == REAL_CST
7951       && !TREE_OVERFLOW (arg1))
7952     {
7953       REAL_VALUE_TYPE cint;
7954       REAL_VALUE_TYPE c;
7955       HOST_WIDE_INT n;
7956
7957       c = TREE_REAL_CST (arg1);
7958
7959       /* Optimize pow(x,0.0) = 1.0.  */
7960       if (REAL_VALUES_EQUAL (c, dconst0))
7961         return omit_one_operand_loc (loc, type, build_real (type, dconst1),
7962                                  arg0);
7963
7964       /* Optimize pow(x,1.0) = x.  */
7965       if (REAL_VALUES_EQUAL (c, dconst1))
7966         return arg0;
7967
7968       /* Optimize pow(x,-1.0) = 1.0/x.  */
7969       if (REAL_VALUES_EQUAL (c, dconstm1))
7970         return fold_build2_loc (loc, RDIV_EXPR, type,
7971                             build_real (type, dconst1), arg0);
7972
7973       /* Optimize pow(x,0.5) = sqrt(x).  */
7974       if (flag_unsafe_math_optimizations
7975           && REAL_VALUES_EQUAL (c, dconsthalf))
7976         {
7977           tree sqrtfn = mathfn_built_in (type, BUILT_IN_SQRT);
7978
7979           if (sqrtfn != NULL_TREE)
7980             return build_call_expr_loc (loc, sqrtfn, 1, arg0);
7981         }
7982
7983       /* Optimize pow(x,1.0/3.0) = cbrt(x).  */
7984       if (flag_unsafe_math_optimizations)
7985         {
7986           const REAL_VALUE_TYPE dconstroot
7987             = real_value_truncate (TYPE_MODE (type), dconst_third ());
7988
7989           if (REAL_VALUES_EQUAL (c, dconstroot))
7990             {
7991               tree cbrtfn = mathfn_built_in (type, BUILT_IN_CBRT);
7992               if (cbrtfn != NULL_TREE)
7993                 return build_call_expr_loc (loc, cbrtfn, 1, arg0);
7994             }
7995         }
7996
7997       /* Check for an integer exponent.  */
7998       n = real_to_integer (&c);
7999       real_from_integer (&cint, VOIDmode, n, n < 0 ? -1 : 0, 0);
8000       if (real_identical (&c, &cint))
8001         {
8002           /* Attempt to evaluate pow at compile-time, unless this should
8003              raise an exception.  */
8004           if (TREE_CODE (arg0) == REAL_CST
8005               && !TREE_OVERFLOW (arg0)
8006               && (n > 0
8007                   || (!flag_trapping_math && !flag_errno_math)
8008                   || !REAL_VALUES_EQUAL (TREE_REAL_CST (arg0), dconst0)))
8009             {
8010               REAL_VALUE_TYPE x;
8011               bool inexact;
8012
8013               x = TREE_REAL_CST (arg0);
8014               inexact = real_powi (&x, TYPE_MODE (type), &x, n);
8015               if (flag_unsafe_math_optimizations || !inexact)
8016                 return build_real (type, x);
8017             }
8018
8019           /* Strip sign ops from even integer powers.  */
8020           if ((n & 1) == 0 && flag_unsafe_math_optimizations)
8021             {
8022               tree narg0 = fold_strip_sign_ops (arg0);
8023               if (narg0)
8024                 return build_call_expr_loc (loc, fndecl, 2, narg0, arg1);
8025             }
8026         }
8027     }
8028
8029   if (flag_unsafe_math_optimizations)
8030     {
8031       const enum built_in_function fcode = builtin_mathfn_code (arg0);
8032
8033       /* Optimize pow(expN(x),y) = expN(x*y).  */
8034       if (BUILTIN_EXPONENT_P (fcode))
8035         {
8036           tree expfn = TREE_OPERAND (CALL_EXPR_FN (arg0), 0);
8037           tree arg = CALL_EXPR_ARG (arg0, 0);
8038           arg = fold_build2_loc (loc, MULT_EXPR, type, arg, arg1);
8039           return build_call_expr_loc (loc, expfn, 1, arg);
8040         }
8041
8042       /* Optimize pow(sqrt(x),y) = pow(x,y*0.5).  */
8043       if (BUILTIN_SQRT_P (fcode))
8044         {
8045           tree narg0 = CALL_EXPR_ARG (arg0, 0);
8046           tree narg1 = fold_build2_loc (loc, MULT_EXPR, type, arg1,
8047                                     build_real (type, dconsthalf));
8048           return build_call_expr_loc (loc, fndecl, 2, narg0, narg1);
8049         }
8050
8051       /* Optimize pow(cbrt(x),y) = pow(x,y/3) iff x is nonnegative.  */
8052       if (BUILTIN_CBRT_P (fcode))
8053         {
8054           tree arg = CALL_EXPR_ARG (arg0, 0);
8055           if (tree_expr_nonnegative_p (arg))
8056             {
8057               const REAL_VALUE_TYPE dconstroot
8058                 = real_value_truncate (TYPE_MODE (type), dconst_third ());
8059               tree narg1 = fold_build2_loc (loc, MULT_EXPR, type, arg1,
8060                                         build_real (type, dconstroot));
8061               return build_call_expr_loc (loc, fndecl, 2, arg, narg1);
8062             }
8063         }
8064
8065       /* Optimize pow(pow(x,y),z) = pow(x,y*z) iff x is nonnegative.  */
8066       if (fcode == BUILT_IN_POW
8067           || fcode == BUILT_IN_POWF
8068           || fcode == BUILT_IN_POWL)
8069         {
8070           tree arg00 = CALL_EXPR_ARG (arg0, 0);
8071           if (tree_expr_nonnegative_p (arg00))
8072             {
8073               tree arg01 = CALL_EXPR_ARG (arg0, 1);
8074               tree narg1 = fold_build2_loc (loc, MULT_EXPR, type, arg01, arg1);
8075               return build_call_expr_loc (loc, fndecl, 2, arg00, narg1);
8076             }
8077         }
8078     }
8079
8080   return NULL_TREE;
8081 }
8082
8083 /* Fold a builtin function call to powi, powif, or powil with argument ARG.
8084    Return NULL_TREE if no simplification can be made.  */
8085 static tree
8086 fold_builtin_powi (location_t loc, tree fndecl ATTRIBUTE_UNUSED,
8087                    tree arg0, tree arg1, tree type)
8088 {
8089   if (!validate_arg (arg0, REAL_TYPE)
8090       || !validate_arg (arg1, INTEGER_TYPE))
8091     return NULL_TREE;
8092
8093   /* Optimize pow(1.0,y) = 1.0.  */
8094   if (real_onep (arg0))
8095     return omit_one_operand_loc (loc, type, build_real (type, dconst1), arg1);
8096
8097   if (host_integerp (arg1, 0))
8098     {
8099       HOST_WIDE_INT c = TREE_INT_CST_LOW (arg1);
8100
8101       /* Evaluate powi at compile-time.  */
8102       if (TREE_CODE (arg0) == REAL_CST
8103           && !TREE_OVERFLOW (arg0))
8104         {
8105           REAL_VALUE_TYPE x;
8106           x = TREE_REAL_CST (arg0);
8107           real_powi (&x, TYPE_MODE (type), &x, c);
8108           return build_real (type, x);
8109         }
8110
8111       /* Optimize pow(x,0) = 1.0.  */
8112       if (c == 0)
8113         return omit_one_operand_loc (loc, type, build_real (type, dconst1),
8114                                  arg0);
8115
8116       /* Optimize pow(x,1) = x.  */
8117       if (c == 1)
8118         return arg0;
8119
8120       /* Optimize pow(x,-1) = 1.0/x.  */
8121       if (c == -1)
8122         return fold_build2_loc (loc, RDIV_EXPR, type,
8123                            build_real (type, dconst1), arg0);
8124     }
8125
8126   return NULL_TREE;
8127 }
8128
8129 /* A subroutine of fold_builtin to fold the various exponent
8130    functions.  Return NULL_TREE if no simplification can be made.
8131    FUNC is the corresponding MPFR exponent function.  */
8132
8133 static tree
8134 fold_builtin_exponent (location_t loc, tree fndecl, tree arg,
8135                        int (*func)(mpfr_ptr, mpfr_srcptr, mp_rnd_t))
8136 {
8137   if (validate_arg (arg, REAL_TYPE))
8138     {
8139       tree type = TREE_TYPE (TREE_TYPE (fndecl));
8140       tree res;
8141
8142       /* Calculate the result when the argument is a constant.  */
8143       if ((res = do_mpfr_arg1 (arg, type, func, NULL, NULL, 0)))
8144         return res;
8145
8146       /* Optimize expN(logN(x)) = x.  */
8147       if (flag_unsafe_math_optimizations)
8148         {
8149           const enum built_in_function fcode = builtin_mathfn_code (arg);
8150
8151           if ((func == mpfr_exp
8152                && (fcode == BUILT_IN_LOG
8153                    || fcode == BUILT_IN_LOGF
8154                    || fcode == BUILT_IN_LOGL))
8155               || (func == mpfr_exp2
8156                   && (fcode == BUILT_IN_LOG2
8157                       || fcode == BUILT_IN_LOG2F
8158                       || fcode == BUILT_IN_LOG2L))
8159               || (func == mpfr_exp10
8160                   && (fcode == BUILT_IN_LOG10
8161                       || fcode == BUILT_IN_LOG10F
8162                       || fcode == BUILT_IN_LOG10L)))
8163             return fold_convert_loc (loc, type, CALL_EXPR_ARG (arg, 0));
8164         }
8165     }
8166
8167   return NULL_TREE;
8168 }
8169
8170 /* Return true if VAR is a VAR_DECL or a component thereof.  */
8171
8172 static bool
8173 var_decl_component_p (tree var)
8174 {
8175   tree inner = var;
8176   while (handled_component_p (inner))
8177     inner = TREE_OPERAND (inner, 0);
8178   return SSA_VAR_P (inner);
8179 }
8180
8181 /* Fold function call to builtin memset.  Return
8182    NULL_TREE if no simplification can be made.  */
8183
8184 static tree
8185 fold_builtin_memset (location_t loc, tree dest, tree c, tree len,
8186                      tree type, bool ignore)
8187 {
8188   tree var, ret, etype;
8189   unsigned HOST_WIDE_INT length, cval;
8190
8191   if (! validate_arg (dest, POINTER_TYPE)
8192       || ! validate_arg (c, INTEGER_TYPE)
8193       || ! validate_arg (len, INTEGER_TYPE))
8194     return NULL_TREE;
8195
8196   if (! host_integerp (len, 1))
8197     return NULL_TREE;
8198
8199   /* If the LEN parameter is zero, return DEST.  */
8200   if (integer_zerop (len))
8201     return omit_one_operand_loc (loc, type, dest, c);
8202
8203   if (! host_integerp (c, 1) || TREE_SIDE_EFFECTS (dest))
8204     return NULL_TREE;
8205
8206   var = dest;
8207   STRIP_NOPS (var);
8208   if (TREE_CODE (var) != ADDR_EXPR)
8209     return NULL_TREE;
8210
8211   var = TREE_OPERAND (var, 0);
8212   if (TREE_THIS_VOLATILE (var))
8213     return NULL_TREE;
8214
8215   etype = TREE_TYPE (var);
8216   if (TREE_CODE (etype) == ARRAY_TYPE)
8217     etype = TREE_TYPE (etype);
8218
8219   if (!INTEGRAL_TYPE_P (etype)
8220       && !POINTER_TYPE_P (etype))
8221     return NULL_TREE;
8222
8223   if (! var_decl_component_p (var))
8224     return NULL_TREE;
8225
8226   length = tree_low_cst (len, 1);
8227   if (GET_MODE_SIZE (TYPE_MODE (etype)) != length
8228       || get_pointer_alignment (dest, BIGGEST_ALIGNMENT) / BITS_PER_UNIT
8229          < (int) length)
8230     return NULL_TREE;
8231
8232   if (length > HOST_BITS_PER_WIDE_INT / BITS_PER_UNIT)
8233     return NULL_TREE;
8234
8235   if (integer_zerop (c))
8236     cval = 0;
8237   else
8238     {
8239       if (CHAR_BIT != 8 || BITS_PER_UNIT != 8 || HOST_BITS_PER_WIDE_INT > 64)
8240         return NULL_TREE;
8241
8242       cval = tree_low_cst (c, 1);
8243       cval &= 0xff;
8244       cval |= cval << 8;
8245       cval |= cval << 16;
8246       cval |= (cval << 31) << 1;
8247     }
8248
8249   ret = build_int_cst_type (etype, cval);
8250   var = build_fold_indirect_ref_loc (loc,
8251                                  fold_convert_loc (loc,
8252                                                    build_pointer_type (etype),
8253                                                    dest));
8254   ret = build2 (MODIFY_EXPR, etype, var, ret);
8255   if (ignore)
8256     return ret;
8257
8258   return omit_one_operand_loc (loc, type, dest, ret);
8259 }
8260
8261 /* Fold function call to builtin memset.  Return
8262    NULL_TREE if no simplification can be made.  */
8263
8264 static tree
8265 fold_builtin_bzero (location_t loc, tree dest, tree size, bool ignore)
8266 {
8267   if (! validate_arg (dest, POINTER_TYPE)
8268       || ! validate_arg (size, INTEGER_TYPE))
8269     return NULL_TREE;
8270
8271   if (!ignore)
8272     return NULL_TREE;
8273
8274   /* New argument list transforming bzero(ptr x, int y) to
8275      memset(ptr x, int 0, size_t y).   This is done this way
8276      so that if it isn't expanded inline, we fallback to
8277      calling bzero instead of memset.  */
8278
8279   return fold_builtin_memset (loc, dest, integer_zero_node,
8280                               fold_convert_loc (loc, sizetype, size),
8281                               void_type_node, ignore);
8282 }
8283
8284 /* Fold function call to builtin mem{{,p}cpy,move}.  Return
8285    NULL_TREE if no simplification can be made.
8286    If ENDP is 0, return DEST (like memcpy).
8287    If ENDP is 1, return DEST+LEN (like mempcpy).
8288    If ENDP is 2, return DEST+LEN-1 (like stpcpy).
8289    If ENDP is 3, return DEST, additionally *SRC and *DEST may overlap
8290    (memmove).   */
8291
8292 static tree
8293 fold_builtin_memory_op (location_t loc, tree dest, tree src,
8294                         tree len, tree type, bool ignore, int endp)
8295 {
8296   tree destvar, srcvar, expr;
8297
8298   if (! validate_arg (dest, POINTER_TYPE)
8299       || ! validate_arg (src, POINTER_TYPE)
8300       || ! validate_arg (len, INTEGER_TYPE))
8301     return NULL_TREE;
8302
8303   /* If the LEN parameter is zero, return DEST.  */
8304   if (integer_zerop (len))
8305     return omit_one_operand_loc (loc, type, dest, src);
8306
8307   /* If SRC and DEST are the same (and not volatile), return
8308      DEST{,+LEN,+LEN-1}.  */
8309   if (operand_equal_p (src, dest, 0))
8310     expr = len;
8311   else
8312     {
8313       tree srctype, desttype;
8314       int src_align, dest_align;
8315       tree off0;
8316
8317       if (endp == 3)
8318         {
8319           src_align = get_pointer_alignment (src, BIGGEST_ALIGNMENT);
8320           dest_align = get_pointer_alignment (dest, BIGGEST_ALIGNMENT);
8321
8322           /* Both DEST and SRC must be pointer types.
8323              ??? This is what old code did.  Is the testing for pointer types
8324              really mandatory?
8325
8326              If either SRC is readonly or length is 1, we can use memcpy.  */
8327           if (!dest_align || !src_align)
8328             return NULL_TREE;
8329           if (readonly_data_expr (src)
8330               || (host_integerp (len, 1)
8331                   && (MIN (src_align, dest_align) / BITS_PER_UNIT
8332                       >= tree_low_cst (len, 1))))
8333             {
8334               tree fn = implicit_built_in_decls[BUILT_IN_MEMCPY];
8335               if (!fn)
8336                 return NULL_TREE;
8337               return build_call_expr_loc (loc, fn, 3, dest, src, len);
8338             }
8339
8340           /* If *src and *dest can't overlap, optimize into memcpy as well.  */
8341           if (TREE_CODE (src) == ADDR_EXPR
8342               && TREE_CODE (dest) == ADDR_EXPR)
8343             {
8344               tree src_base, dest_base, fn;
8345               HOST_WIDE_INT src_offset = 0, dest_offset = 0;
8346               HOST_WIDE_INT size = -1;
8347               HOST_WIDE_INT maxsize = -1;
8348
8349               srcvar = TREE_OPERAND (src, 0);
8350               src_base = get_ref_base_and_extent (srcvar, &src_offset,
8351                                                   &size, &maxsize);
8352               destvar = TREE_OPERAND (dest, 0);
8353               dest_base = get_ref_base_and_extent (destvar, &dest_offset,
8354                                                    &size, &maxsize);
8355               if (host_integerp (len, 1))
8356                 maxsize = tree_low_cst (len, 1);
8357               else
8358                 maxsize = -1;
8359               src_offset /= BITS_PER_UNIT;
8360               dest_offset /= BITS_PER_UNIT;
8361               if (SSA_VAR_P (src_base)
8362                   && SSA_VAR_P (dest_base))
8363                 {
8364                   if (operand_equal_p (src_base, dest_base, 0)
8365                       && ranges_overlap_p (src_offset, maxsize,
8366                                            dest_offset, maxsize))
8367                     return NULL_TREE;
8368                 }
8369               else if (TREE_CODE (src_base) == MEM_REF
8370                        && TREE_CODE (dest_base) == MEM_REF)
8371                 {
8372                   double_int off;
8373                   if (! operand_equal_p (TREE_OPERAND (src_base, 0),
8374                                          TREE_OPERAND (dest_base, 0), 0))
8375                     return NULL_TREE;
8376                   off = double_int_add (mem_ref_offset (src_base),
8377                                         shwi_to_double_int (src_offset));
8378                   if (!double_int_fits_in_shwi_p (off))
8379                     return NULL_TREE;
8380                   src_offset = off.low;
8381                   off = double_int_add (mem_ref_offset (dest_base),
8382                                         shwi_to_double_int (dest_offset));
8383                   if (!double_int_fits_in_shwi_p (off))
8384                     return NULL_TREE;
8385                   dest_offset = off.low;
8386                   if (ranges_overlap_p (src_offset, maxsize,
8387                                         dest_offset, maxsize))
8388                     return NULL_TREE;
8389                 }
8390               else
8391                 return NULL_TREE;
8392
8393               fn = implicit_built_in_decls[BUILT_IN_MEMCPY];
8394               if (!fn)
8395                 return NULL_TREE;
8396               return build_call_expr_loc (loc, fn, 3, dest, src, len);
8397             }
8398           return NULL_TREE;
8399         }
8400
8401       if (!host_integerp (len, 0))
8402         return NULL_TREE;
8403       /* FIXME:
8404          This logic lose for arguments like (type *)malloc (sizeof (type)),
8405          since we strip the casts of up to VOID return value from malloc.
8406          Perhaps we ought to inherit type from non-VOID argument here?  */
8407       STRIP_NOPS (src);
8408       STRIP_NOPS (dest);
8409       /* As we fold (void *)(p + CST) to (void *)p + CST undo this here.  */
8410       if (TREE_CODE (src) == POINTER_PLUS_EXPR)
8411         {
8412           tree tem = TREE_OPERAND (src, 0);
8413           STRIP_NOPS (tem);
8414           if (tem != TREE_OPERAND (src, 0))
8415             src = build1 (NOP_EXPR, TREE_TYPE (tem), src);
8416         }
8417       if (TREE_CODE (dest) == POINTER_PLUS_EXPR)
8418         {
8419           tree tem = TREE_OPERAND (dest, 0);
8420           STRIP_NOPS (tem);
8421           if (tem != TREE_OPERAND (dest, 0))
8422             dest = build1 (NOP_EXPR, TREE_TYPE (tem), dest);
8423         }
8424       srctype = TREE_TYPE (TREE_TYPE (src));
8425       if (srctype
8426           && TREE_CODE (srctype) == ARRAY_TYPE
8427           && !tree_int_cst_equal (TYPE_SIZE_UNIT (srctype), len))
8428         {
8429           srctype = TREE_TYPE (srctype);
8430           STRIP_NOPS (src);
8431           src = build1 (NOP_EXPR, build_pointer_type (srctype), src);
8432         }
8433       desttype = TREE_TYPE (TREE_TYPE (dest));
8434       if (desttype
8435           && TREE_CODE (desttype) == ARRAY_TYPE
8436           && !tree_int_cst_equal (TYPE_SIZE_UNIT (desttype), len))
8437         {
8438           desttype = TREE_TYPE (desttype);
8439           STRIP_NOPS (dest);
8440           dest = build1 (NOP_EXPR, build_pointer_type (desttype), dest);
8441         }
8442       if (!srctype || !desttype
8443           || TREE_ADDRESSABLE (srctype)
8444           || TREE_ADDRESSABLE (desttype)
8445           || !TYPE_SIZE_UNIT (srctype)
8446           || !TYPE_SIZE_UNIT (desttype)
8447           || TREE_CODE (TYPE_SIZE_UNIT (srctype)) != INTEGER_CST
8448           || TREE_CODE (TYPE_SIZE_UNIT (desttype)) != INTEGER_CST)
8449         return NULL_TREE;
8450
8451       src_align = get_pointer_alignment (src, BIGGEST_ALIGNMENT);
8452       dest_align = get_pointer_alignment (dest, BIGGEST_ALIGNMENT);
8453       if (dest_align < (int) TYPE_ALIGN (desttype)
8454           || src_align < (int) TYPE_ALIGN (srctype))
8455         return NULL_TREE;
8456
8457       if (!ignore)
8458         dest = builtin_save_expr (dest);
8459
8460       /* Build accesses at offset zero with a ref-all character type.  */
8461       off0 = build_int_cst (build_pointer_type_for_mode (char_type_node,
8462                                                          ptr_mode, true), 0);
8463
8464       destvar = dest;
8465       STRIP_NOPS (destvar);
8466       if (TREE_CODE (destvar) == ADDR_EXPR
8467           && var_decl_component_p (TREE_OPERAND (destvar, 0))
8468           && tree_int_cst_equal (TYPE_SIZE_UNIT (desttype), len))
8469         destvar = fold_build2 (MEM_REF, desttype, destvar, off0);
8470       else
8471         destvar = NULL_TREE;
8472
8473       srcvar = src;
8474       STRIP_NOPS (srcvar);
8475       if (TREE_CODE (srcvar) == ADDR_EXPR
8476           && var_decl_component_p (TREE_OPERAND (srcvar, 0))
8477           && tree_int_cst_equal (TYPE_SIZE_UNIT (srctype), len)
8478           && (!STRICT_ALIGNMENT
8479               || !destvar
8480               || src_align >= (int) TYPE_ALIGN (desttype)))
8481         srcvar = fold_build2 (MEM_REF, destvar ? desttype : srctype,
8482                               srcvar, off0);
8483       else
8484         srcvar = NULL_TREE;
8485
8486       if (srcvar == NULL_TREE && destvar == NULL_TREE)
8487         return NULL_TREE;
8488
8489       if (srcvar == NULL_TREE)
8490         {
8491           if (STRICT_ALIGNMENT
8492               && src_align < (int) TYPE_ALIGN (desttype))
8493             return NULL_TREE;
8494           STRIP_NOPS (src);
8495           srcvar = fold_build2 (MEM_REF, desttype, src, off0);
8496         }
8497       else if (destvar == NULL_TREE)
8498         {
8499           if (STRICT_ALIGNMENT
8500               && dest_align < (int) TYPE_ALIGN (srctype))
8501             return NULL_TREE;
8502           STRIP_NOPS (dest);
8503           destvar = fold_build2 (MEM_REF, srctype, dest, off0);
8504         }
8505
8506       expr = build2 (MODIFY_EXPR, TREE_TYPE (destvar), destvar, srcvar);
8507     }
8508
8509   if (ignore)
8510     return expr;
8511
8512   if (endp == 0 || endp == 3)
8513     return omit_one_operand_loc (loc, type, dest, expr);
8514
8515   if (expr == len)
8516     expr = NULL_TREE;
8517
8518   if (endp == 2)
8519     len = fold_build2_loc (loc, MINUS_EXPR, TREE_TYPE (len), len,
8520                        ssize_int (1));
8521
8522   len = fold_convert_loc (loc, sizetype, len);
8523   dest = fold_build2_loc (loc, POINTER_PLUS_EXPR, TREE_TYPE (dest), dest, len);
8524   dest = fold_convert_loc (loc, type, dest);
8525   if (expr)
8526     dest = omit_one_operand_loc (loc, type, dest, expr);
8527   return dest;
8528 }
8529
8530 /* Fold function call to builtin strcpy with arguments DEST and SRC.
8531    If LEN is not NULL, it represents the length of the string to be
8532    copied.  Return NULL_TREE if no simplification can be made.  */
8533
8534 tree
8535 fold_builtin_strcpy (location_t loc, tree fndecl, tree dest, tree src, tree len)
8536 {
8537   tree fn;
8538
8539   if (!validate_arg (dest, POINTER_TYPE)
8540       || !validate_arg (src, POINTER_TYPE))
8541     return NULL_TREE;
8542
8543   /* If SRC and DEST are the same (and not volatile), return DEST.  */
8544   if (operand_equal_p (src, dest, 0))
8545     return fold_convert_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)), dest);
8546
8547   if (optimize_function_for_size_p (cfun))
8548     return NULL_TREE;
8549
8550   fn = implicit_built_in_decls[BUILT_IN_MEMCPY];
8551   if (!fn)
8552     return NULL_TREE;
8553
8554   if (!len)
8555     {
8556       len = c_strlen (src, 1);
8557       if (! len || TREE_SIDE_EFFECTS (len))
8558         return NULL_TREE;
8559     }
8560
8561   len = size_binop_loc (loc, PLUS_EXPR, len, ssize_int (1));
8562   return fold_convert_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)),
8563                            build_call_expr_loc (loc, fn, 3, dest, src, len));
8564 }
8565
8566 /* Fold function call to builtin stpcpy with arguments DEST and SRC.
8567    Return NULL_TREE if no simplification can be made.  */
8568
8569 static tree
8570 fold_builtin_stpcpy (location_t loc, tree fndecl, tree dest, tree src)
8571 {
8572   tree fn, len, lenp1, call, type;
8573
8574   if (!validate_arg (dest, POINTER_TYPE)
8575       || !validate_arg (src, POINTER_TYPE))
8576     return NULL_TREE;
8577
8578   len = c_strlen (src, 1);
8579   if (!len
8580       || TREE_CODE (len) != INTEGER_CST)
8581     return NULL_TREE;
8582
8583   if (optimize_function_for_size_p (cfun)
8584       /* If length is zero it's small enough.  */
8585       && !integer_zerop (len))
8586     return NULL_TREE;
8587
8588   fn = implicit_built_in_decls[BUILT_IN_MEMCPY];
8589   if (!fn)
8590     return NULL_TREE;
8591
8592   lenp1 = size_binop_loc (loc, PLUS_EXPR, len, ssize_int (1));
8593   /* We use dest twice in building our expression.  Save it from
8594      multiple expansions.  */
8595   dest = builtin_save_expr (dest);
8596   call = build_call_expr_loc (loc, fn, 3, dest, src, lenp1);
8597
8598   type = TREE_TYPE (TREE_TYPE (fndecl));
8599   len = fold_convert_loc (loc, sizetype, len);
8600   dest = fold_build2_loc (loc, POINTER_PLUS_EXPR, TREE_TYPE (dest), dest, len);
8601   dest = fold_convert_loc (loc, type, dest);
8602   dest = omit_one_operand_loc (loc, type, dest, call);
8603   return dest;
8604 }
8605
8606 /* Fold function call to builtin strncpy with arguments DEST, SRC, and LEN.
8607    If SLEN is not NULL, it represents the length of the source string.
8608    Return NULL_TREE if no simplification can be made.  */
8609
8610 tree
8611 fold_builtin_strncpy (location_t loc, tree fndecl, tree dest,
8612                       tree src, tree len, tree slen)
8613 {
8614   tree fn;
8615
8616   if (!validate_arg (dest, POINTER_TYPE)
8617       || !validate_arg (src, POINTER_TYPE)
8618       || !validate_arg (len, INTEGER_TYPE))
8619     return NULL_TREE;
8620
8621   /* If the LEN parameter is zero, return DEST.  */
8622   if (integer_zerop (len))
8623     return omit_one_operand_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)), dest, src);
8624
8625   /* We can't compare slen with len as constants below if len is not a
8626      constant.  */
8627   if (len == 0 || TREE_CODE (len) != INTEGER_CST)
8628     return NULL_TREE;
8629
8630   if (!slen)
8631     slen = c_strlen (src, 1);
8632
8633   /* Now, we must be passed a constant src ptr parameter.  */
8634   if (slen == 0 || TREE_CODE (slen) != INTEGER_CST)
8635     return NULL_TREE;
8636
8637   slen = size_binop_loc (loc, PLUS_EXPR, slen, ssize_int (1));
8638
8639   /* We do not support simplification of this case, though we do
8640      support it when expanding trees into RTL.  */
8641   /* FIXME: generate a call to __builtin_memset.  */
8642   if (tree_int_cst_lt (slen, len))
8643     return NULL_TREE;
8644
8645   /* OK transform into builtin memcpy.  */
8646   fn = implicit_built_in_decls[BUILT_IN_MEMCPY];
8647   if (!fn)
8648     return NULL_TREE;
8649   return fold_convert_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)),
8650                            build_call_expr_loc (loc, fn, 3, dest, src, len));
8651 }
8652
8653 /* Fold function call to builtin memchr.  ARG1, ARG2 and LEN are the
8654    arguments to the call, and TYPE is its return type.
8655    Return NULL_TREE if no simplification can be made.  */
8656
8657 static tree
8658 fold_builtin_memchr (location_t loc, tree arg1, tree arg2, tree len, tree type)
8659 {
8660   if (!validate_arg (arg1, POINTER_TYPE)
8661       || !validate_arg (arg2, INTEGER_TYPE)
8662       || !validate_arg (len, INTEGER_TYPE))
8663     return NULL_TREE;
8664   else
8665     {
8666       const char *p1;
8667
8668       if (TREE_CODE (arg2) != INTEGER_CST
8669           || !host_integerp (len, 1))
8670         return NULL_TREE;
8671
8672       p1 = c_getstr (arg1);
8673       if (p1 && compare_tree_int (len, strlen (p1) + 1) <= 0)
8674         {
8675           char c;
8676           const char *r;
8677           tree tem;
8678
8679           if (target_char_cast (arg2, &c))
8680             return NULL_TREE;
8681
8682           r = (char *) memchr (p1, c, tree_low_cst (len, 1));
8683
8684           if (r == NULL)
8685             return build_int_cst (TREE_TYPE (arg1), 0);
8686
8687           tem = fold_build2_loc (loc, POINTER_PLUS_EXPR, TREE_TYPE (arg1), arg1,
8688                              size_int (r - p1));
8689           return fold_convert_loc (loc, type, tem);
8690         }
8691       return NULL_TREE;
8692     }
8693 }
8694
8695 /* Fold function call to builtin memcmp with arguments ARG1 and ARG2.
8696    Return NULL_TREE if no simplification can be made.  */
8697
8698 static tree
8699 fold_builtin_memcmp (location_t loc, tree arg1, tree arg2, tree len)
8700 {
8701   const char *p1, *p2;
8702
8703   if (!validate_arg (arg1, POINTER_TYPE)
8704       || !validate_arg (arg2, POINTER_TYPE)
8705       || !validate_arg (len, INTEGER_TYPE))
8706     return NULL_TREE;
8707
8708   /* If the LEN parameter is zero, return zero.  */
8709   if (integer_zerop (len))
8710     return omit_two_operands_loc (loc, integer_type_node, integer_zero_node,
8711                               arg1, arg2);
8712
8713   /* If ARG1 and ARG2 are the same (and not volatile), return zero.  */
8714   if (operand_equal_p (arg1, arg2, 0))
8715     return omit_one_operand_loc (loc, integer_type_node, integer_zero_node, len);
8716
8717   p1 = c_getstr (arg1);
8718   p2 = c_getstr (arg2);
8719
8720   /* If all arguments are constant, and the value of len is not greater
8721      than the lengths of arg1 and arg2, evaluate at compile-time.  */
8722   if (host_integerp (len, 1) && p1 && p2
8723       && compare_tree_int (len, strlen (p1) + 1) <= 0
8724       && compare_tree_int (len, strlen (p2) + 1) <= 0)
8725     {
8726       const int r = memcmp (p1, p2, tree_low_cst (len, 1));
8727
8728       if (r > 0)
8729         return integer_one_node;
8730       else if (r < 0)
8731         return integer_minus_one_node;
8732       else
8733         return integer_zero_node;
8734     }
8735
8736   /* If len parameter is one, return an expression corresponding to
8737      (*(const unsigned char*)arg1 - (const unsigned char*)arg2).  */
8738   if (host_integerp (len, 1) && tree_low_cst (len, 1) == 1)
8739     {
8740       tree cst_uchar_node = build_type_variant (unsigned_char_type_node, 1, 0);
8741       tree cst_uchar_ptr_node
8742         = build_pointer_type_for_mode (cst_uchar_node, ptr_mode, true);
8743
8744       tree ind1
8745         = fold_convert_loc (loc, integer_type_node,
8746                             build1 (INDIRECT_REF, cst_uchar_node,
8747                                     fold_convert_loc (loc,
8748                                                       cst_uchar_ptr_node,
8749                                                       arg1)));
8750       tree ind2
8751         = fold_convert_loc (loc, integer_type_node,
8752                             build1 (INDIRECT_REF, cst_uchar_node,
8753                                     fold_convert_loc (loc,
8754                                                       cst_uchar_ptr_node,
8755                                                       arg2)));
8756       return fold_build2_loc (loc, MINUS_EXPR, integer_type_node, ind1, ind2);
8757     }
8758
8759   return NULL_TREE;
8760 }
8761
8762 /* Fold function call to builtin strcmp with arguments ARG1 and ARG2.
8763    Return NULL_TREE if no simplification can be made.  */
8764
8765 static tree
8766 fold_builtin_strcmp (location_t loc, tree arg1, tree arg2)
8767 {
8768   const char *p1, *p2;
8769
8770   if (!validate_arg (arg1, POINTER_TYPE)
8771       || !validate_arg (arg2, POINTER_TYPE))
8772     return NULL_TREE;
8773
8774   /* If ARG1 and ARG2 are the same (and not volatile), return zero.  */
8775   if (operand_equal_p (arg1, arg2, 0))
8776     return integer_zero_node;
8777
8778   p1 = c_getstr (arg1);
8779   p2 = c_getstr (arg2);
8780
8781   if (p1 && p2)
8782     {
8783       const int i = strcmp (p1, p2);
8784       if (i < 0)
8785         return integer_minus_one_node;
8786       else if (i > 0)
8787         return integer_one_node;
8788       else
8789         return integer_zero_node;
8790     }
8791
8792   /* If the second arg is "", return *(const unsigned char*)arg1.  */
8793   if (p2 && *p2 == '\0')
8794     {
8795       tree cst_uchar_node = build_type_variant (unsigned_char_type_node, 1, 0);
8796       tree cst_uchar_ptr_node
8797         = build_pointer_type_for_mode (cst_uchar_node, ptr_mode, true);
8798
8799       return fold_convert_loc (loc, integer_type_node,
8800                                build1 (INDIRECT_REF, cst_uchar_node,
8801                                        fold_convert_loc (loc,
8802                                                          cst_uchar_ptr_node,
8803                                                          arg1)));
8804     }
8805
8806   /* If the first arg is "", return -*(const unsigned char*)arg2.  */
8807   if (p1 && *p1 == '\0')
8808     {
8809       tree cst_uchar_node = build_type_variant (unsigned_char_type_node, 1, 0);
8810       tree cst_uchar_ptr_node
8811         = build_pointer_type_for_mode (cst_uchar_node, ptr_mode, true);
8812
8813       tree temp
8814         = fold_convert_loc (loc, integer_type_node,
8815                             build1 (INDIRECT_REF, cst_uchar_node,
8816                                     fold_convert_loc (loc,
8817                                                       cst_uchar_ptr_node,
8818                                                       arg2)));
8819       return fold_build1_loc (loc, NEGATE_EXPR, integer_type_node, temp);
8820     }
8821
8822   return NULL_TREE;
8823 }
8824
8825 /* Fold function call to builtin strncmp with arguments ARG1, ARG2, and LEN.
8826    Return NULL_TREE if no simplification can be made.  */
8827
8828 static tree
8829 fold_builtin_strncmp (location_t loc, tree arg1, tree arg2, tree len)
8830 {
8831   const char *p1, *p2;
8832
8833   if (!validate_arg (arg1, POINTER_TYPE)
8834       || !validate_arg (arg2, POINTER_TYPE)
8835       || !validate_arg (len, INTEGER_TYPE))
8836     return NULL_TREE;
8837
8838   /* If the LEN parameter is zero, return zero.  */
8839   if (integer_zerop (len))
8840     return omit_two_operands_loc (loc, integer_type_node, integer_zero_node,
8841                               arg1, arg2);
8842
8843   /* If ARG1 and ARG2 are the same (and not volatile), return zero.  */
8844   if (operand_equal_p (arg1, arg2, 0))
8845     return omit_one_operand_loc (loc, integer_type_node, integer_zero_node, len);
8846
8847   p1 = c_getstr (arg1);
8848   p2 = c_getstr (arg2);
8849
8850   if (host_integerp (len, 1) && p1 && p2)
8851     {
8852       const int i = strncmp (p1, p2, tree_low_cst (len, 1));
8853       if (i > 0)
8854         return integer_one_node;
8855       else if (i < 0)
8856         return integer_minus_one_node;
8857       else
8858         return integer_zero_node;
8859     }
8860
8861   /* If the second arg is "", and the length is greater than zero,
8862      return *(const unsigned char*)arg1.  */
8863   if (p2 && *p2 == '\0'
8864       && TREE_CODE (len) == INTEGER_CST
8865       && tree_int_cst_sgn (len) == 1)
8866     {
8867       tree cst_uchar_node = build_type_variant (unsigned_char_type_node, 1, 0);
8868       tree cst_uchar_ptr_node
8869         = build_pointer_type_for_mode (cst_uchar_node, ptr_mode, true);
8870
8871       return fold_convert_loc (loc, integer_type_node,
8872                                build1 (INDIRECT_REF, cst_uchar_node,
8873                                        fold_convert_loc (loc,
8874                                                          cst_uchar_ptr_node,
8875                                                          arg1)));
8876     }
8877
8878   /* If the first arg is "", and the length is greater than zero,
8879      return -*(const unsigned char*)arg2.  */
8880   if (p1 && *p1 == '\0'
8881       && TREE_CODE (len) == INTEGER_CST
8882       && tree_int_cst_sgn (len) == 1)
8883     {
8884       tree cst_uchar_node = build_type_variant (unsigned_char_type_node, 1, 0);
8885       tree cst_uchar_ptr_node
8886         = build_pointer_type_for_mode (cst_uchar_node, ptr_mode, true);
8887
8888       tree temp = fold_convert_loc (loc, integer_type_node,
8889                                     build1 (INDIRECT_REF, cst_uchar_node,
8890                                             fold_convert_loc (loc,
8891                                                               cst_uchar_ptr_node,
8892                                                               arg2)));
8893       return fold_build1_loc (loc, NEGATE_EXPR, integer_type_node, temp);
8894     }
8895
8896   /* If len parameter is one, return an expression corresponding to
8897      (*(const unsigned char*)arg1 - (const unsigned char*)arg2).  */
8898   if (host_integerp (len, 1) && tree_low_cst (len, 1) == 1)
8899     {
8900       tree cst_uchar_node = build_type_variant (unsigned_char_type_node, 1, 0);
8901       tree cst_uchar_ptr_node
8902         = build_pointer_type_for_mode (cst_uchar_node, ptr_mode, true);
8903
8904       tree ind1 = fold_convert_loc (loc, integer_type_node,
8905                                     build1 (INDIRECT_REF, cst_uchar_node,
8906                                             fold_convert_loc (loc,
8907                                                               cst_uchar_ptr_node,
8908                                                               arg1)));
8909       tree ind2 = fold_convert_loc (loc, integer_type_node,
8910                                     build1 (INDIRECT_REF, cst_uchar_node,
8911                                             fold_convert_loc (loc,
8912                                                               cst_uchar_ptr_node,
8913                                                               arg2)));
8914       return fold_build2_loc (loc, MINUS_EXPR, integer_type_node, ind1, ind2);
8915     }
8916
8917   return NULL_TREE;
8918 }
8919
8920 /* Fold function call to builtin signbit, signbitf or signbitl with argument
8921    ARG.  Return NULL_TREE if no simplification can be made.  */
8922
8923 static tree
8924 fold_builtin_signbit (location_t loc, tree arg, tree type)
8925 {
8926   tree temp;
8927
8928   if (!validate_arg (arg, REAL_TYPE))
8929     return NULL_TREE;
8930
8931   /* If ARG is a compile-time constant, determine the result.  */
8932   if (TREE_CODE (arg) == REAL_CST
8933       && !TREE_OVERFLOW (arg))
8934     {
8935       REAL_VALUE_TYPE c;
8936
8937       c = TREE_REAL_CST (arg);
8938       temp = REAL_VALUE_NEGATIVE (c) ? integer_one_node : integer_zero_node;
8939       return fold_convert_loc (loc, type, temp);
8940     }
8941
8942   /* If ARG is non-negative, the result is always zero.  */
8943   if (tree_expr_nonnegative_p (arg))
8944     return omit_one_operand_loc (loc, type, integer_zero_node, arg);
8945
8946   /* If ARG's format doesn't have signed zeros, return "arg < 0.0".  */
8947   if (!HONOR_SIGNED_ZEROS (TYPE_MODE (TREE_TYPE (arg))))
8948     return fold_build2_loc (loc, LT_EXPR, type, arg,
8949                         build_real (TREE_TYPE (arg), dconst0));
8950
8951   return NULL_TREE;
8952 }
8953
8954 /* Fold function call to builtin copysign, copysignf or copysignl with
8955    arguments ARG1 and ARG2.  Return NULL_TREE if no simplification can
8956    be made.  */
8957
8958 static tree
8959 fold_builtin_copysign (location_t loc, tree fndecl,
8960                        tree arg1, tree arg2, tree type)
8961 {
8962   tree tem;
8963
8964   if (!validate_arg (arg1, REAL_TYPE)
8965       || !validate_arg (arg2, REAL_TYPE))
8966     return NULL_TREE;
8967
8968   /* copysign(X,X) is X.  */
8969   if (operand_equal_p (arg1, arg2, 0))
8970     return fold_convert_loc (loc, type, arg1);
8971
8972   /* If ARG1 and ARG2 are compile-time constants, determine the result.  */
8973   if (TREE_CODE (arg1) == REAL_CST
8974       && TREE_CODE (arg2) == REAL_CST
8975       && !TREE_OVERFLOW (arg1)
8976       && !TREE_OVERFLOW (arg2))
8977     {
8978       REAL_VALUE_TYPE c1, c2;
8979
8980       c1 = TREE_REAL_CST (arg1);
8981       c2 = TREE_REAL_CST (arg2);
8982       /* c1.sign := c2.sign.  */
8983       real_copysign (&c1, &c2);
8984       return build_real (type, c1);
8985     }
8986
8987   /* copysign(X, Y) is fabs(X) when Y is always non-negative.
8988      Remember to evaluate Y for side-effects.  */
8989   if (tree_expr_nonnegative_p (arg2))
8990     return omit_one_operand_loc (loc, type,
8991                              fold_build1_loc (loc, ABS_EXPR, type, arg1),
8992                              arg2);
8993
8994   /* Strip sign changing operations for the first argument.  */
8995   tem = fold_strip_sign_ops (arg1);
8996   if (tem)
8997     return build_call_expr_loc (loc, fndecl, 2, tem, arg2);
8998
8999   return NULL_TREE;
9000 }
9001
9002 /* Fold a call to builtin isascii with argument ARG.  */
9003
9004 static tree
9005 fold_builtin_isascii (location_t loc, tree arg)
9006 {
9007   if (!validate_arg (arg, INTEGER_TYPE))
9008     return NULL_TREE;
9009   else
9010     {
9011       /* Transform isascii(c) -> ((c & ~0x7f) == 0).  */
9012       arg = fold_build2 (BIT_AND_EXPR, integer_type_node, arg,
9013                          build_int_cst (NULL_TREE,
9014                                         ~ (unsigned HOST_WIDE_INT) 0x7f));
9015       return fold_build2_loc (loc, EQ_EXPR, integer_type_node,
9016                           arg, integer_zero_node);
9017     }
9018 }
9019
9020 /* Fold a call to builtin toascii with argument ARG.  */
9021
9022 static tree
9023 fold_builtin_toascii (location_t loc, tree arg)
9024 {
9025   if (!validate_arg (arg, INTEGER_TYPE))
9026     return NULL_TREE;
9027
9028   /* Transform toascii(c) -> (c & 0x7f).  */
9029   return fold_build2_loc (loc, BIT_AND_EXPR, integer_type_node, arg,
9030                       build_int_cst (NULL_TREE, 0x7f));
9031 }
9032
9033 /* Fold a call to builtin isdigit with argument ARG.  */
9034
9035 static tree
9036 fold_builtin_isdigit (location_t loc, tree arg)
9037 {
9038   if (!validate_arg (arg, INTEGER_TYPE))
9039     return NULL_TREE;
9040   else
9041     {
9042       /* Transform isdigit(c) -> (unsigned)(c) - '0' <= 9.  */
9043       /* According to the C standard, isdigit is unaffected by locale.
9044          However, it definitely is affected by the target character set.  */
9045       unsigned HOST_WIDE_INT target_digit0
9046         = lang_hooks.to_target_charset ('0');
9047
9048       if (target_digit0 == 0)
9049         return NULL_TREE;
9050
9051       arg = fold_convert_loc (loc, unsigned_type_node, arg);
9052       arg = fold_build2 (MINUS_EXPR, unsigned_type_node, arg,
9053                          build_int_cst (unsigned_type_node, target_digit0));
9054       return fold_build2_loc (loc, LE_EXPR, integer_type_node, arg,
9055                           build_int_cst (unsigned_type_node, 9));
9056     }
9057 }
9058
9059 /* Fold a call to fabs, fabsf or fabsl with argument ARG.  */
9060
9061 static tree
9062 fold_builtin_fabs (location_t loc, tree arg, tree type)
9063 {
9064   if (!validate_arg (arg, REAL_TYPE))
9065     return NULL_TREE;
9066
9067   arg = fold_convert_loc (loc, type, arg);
9068   if (TREE_CODE (arg) == REAL_CST)
9069     return fold_abs_const (arg, type);
9070   return fold_build1_loc (loc, ABS_EXPR, type, arg);
9071 }
9072
9073 /* Fold a call to abs, labs, llabs or imaxabs with argument ARG.  */
9074
9075 static tree
9076 fold_builtin_abs (location_t loc, tree arg, tree type)
9077 {
9078   if (!validate_arg (arg, INTEGER_TYPE))
9079     return NULL_TREE;
9080
9081   arg = fold_convert_loc (loc, type, arg);
9082   if (TREE_CODE (arg) == INTEGER_CST)
9083     return fold_abs_const (arg, type);
9084   return fold_build1_loc (loc, ABS_EXPR, type, arg);
9085 }
9086
9087 /* Fold a call to builtin fmin or fmax.  */
9088
9089 static tree
9090 fold_builtin_fmin_fmax (location_t loc, tree arg0, tree arg1,
9091                         tree type, bool max)
9092 {
9093   if (validate_arg (arg0, REAL_TYPE) && validate_arg (arg1, REAL_TYPE))
9094     {
9095       /* Calculate the result when the argument is a constant.  */
9096       tree res = do_mpfr_arg2 (arg0, arg1, type, (max ? mpfr_max : mpfr_min));
9097
9098       if (res)
9099         return res;
9100
9101       /* If either argument is NaN, return the other one.  Avoid the
9102          transformation if we get (and honor) a signalling NaN.  Using
9103          omit_one_operand() ensures we create a non-lvalue.  */
9104       if (TREE_CODE (arg0) == REAL_CST
9105           && real_isnan (&TREE_REAL_CST (arg0))
9106           && (! HONOR_SNANS (TYPE_MODE (TREE_TYPE (arg0)))
9107               || ! TREE_REAL_CST (arg0).signalling))
9108         return omit_one_operand_loc (loc, type, arg1, arg0);
9109       if (TREE_CODE (arg1) == REAL_CST
9110           && real_isnan (&TREE_REAL_CST (arg1))
9111           && (! HONOR_SNANS (TYPE_MODE (TREE_TYPE (arg1)))
9112               || ! TREE_REAL_CST (arg1).signalling))
9113         return omit_one_operand_loc (loc, type, arg0, arg1);
9114
9115       /* Transform fmin/fmax(x,x) -> x.  */
9116       if (operand_equal_p (arg0, arg1, OEP_PURE_SAME))
9117         return omit_one_operand_loc (loc, type, arg0, arg1);
9118
9119       /* Convert fmin/fmax to MIN_EXPR/MAX_EXPR.  C99 requires these
9120          functions to return the numeric arg if the other one is NaN.
9121          These tree codes don't honor that, so only transform if
9122          -ffinite-math-only is set.  C99 doesn't require -0.0 to be
9123          handled, so we don't have to worry about it either.  */
9124       if (flag_finite_math_only)
9125         return fold_build2_loc (loc, (max ? MAX_EXPR : MIN_EXPR), type,
9126                             fold_convert_loc (loc, type, arg0),
9127                             fold_convert_loc (loc, type, arg1));
9128     }
9129   return NULL_TREE;
9130 }
9131
9132 /* Fold a call to builtin carg(a+bi) -> atan2(b,a).  */
9133
9134 static tree
9135 fold_builtin_carg (location_t loc, tree arg, tree type)
9136 {
9137   if (validate_arg (arg, COMPLEX_TYPE)
9138       && TREE_CODE (TREE_TYPE (TREE_TYPE (arg))) == REAL_TYPE)
9139     {
9140       tree atan2_fn = mathfn_built_in (type, BUILT_IN_ATAN2);
9141
9142       if (atan2_fn)
9143         {
9144           tree new_arg = builtin_save_expr (arg);
9145           tree r_arg = fold_build1_loc (loc, REALPART_EXPR, type, new_arg);
9146           tree i_arg = fold_build1_loc (loc, IMAGPART_EXPR, type, new_arg);
9147           return build_call_expr_loc (loc, atan2_fn, 2, i_arg, r_arg);
9148         }
9149     }
9150
9151   return NULL_TREE;
9152 }
9153
9154 /* Fold a call to builtin logb/ilogb.  */
9155
9156 static tree
9157 fold_builtin_logb (location_t loc, tree arg, tree rettype)
9158 {
9159   if (! validate_arg (arg, REAL_TYPE))
9160     return NULL_TREE;
9161
9162   STRIP_NOPS (arg);
9163
9164   if (TREE_CODE (arg) == REAL_CST && ! TREE_OVERFLOW (arg))
9165     {
9166       const REAL_VALUE_TYPE *const value = TREE_REAL_CST_PTR (arg);
9167
9168       switch (value->cl)
9169       {
9170       case rvc_nan:
9171       case rvc_inf:
9172         /* If arg is Inf or NaN and we're logb, return it.  */
9173         if (TREE_CODE (rettype) == REAL_TYPE)
9174           return fold_convert_loc (loc, rettype, arg);
9175         /* Fall through... */
9176       case rvc_zero:
9177         /* Zero may set errno and/or raise an exception for logb, also
9178            for ilogb we don't know FP_ILOGB0.  */
9179         return NULL_TREE;
9180       case rvc_normal:
9181         /* For normal numbers, proceed iff radix == 2.  In GCC,
9182            normalized significands are in the range [0.5, 1.0).  We
9183            want the exponent as if they were [1.0, 2.0) so get the
9184            exponent and subtract 1.  */
9185         if (REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (arg)))->b == 2)
9186           return fold_convert_loc (loc, rettype,
9187                                    build_int_cst (NULL_TREE,
9188                                                   REAL_EXP (value)-1));
9189         break;
9190       }
9191     }
9192
9193   return NULL_TREE;
9194 }
9195
9196 /* Fold a call to builtin significand, if radix == 2.  */
9197
9198 static tree
9199 fold_builtin_significand (location_t loc, tree arg, tree rettype)
9200 {
9201   if (! validate_arg (arg, REAL_TYPE))
9202     return NULL_TREE;
9203
9204   STRIP_NOPS (arg);
9205
9206   if (TREE_CODE (arg) == REAL_CST && ! TREE_OVERFLOW (arg))
9207     {
9208       const REAL_VALUE_TYPE *const value = TREE_REAL_CST_PTR (arg);
9209
9210       switch (value->cl)
9211       {
9212       case rvc_zero:
9213       case rvc_nan:
9214       case rvc_inf:
9215         /* If arg is +-0, +-Inf or +-NaN, then return it.  */
9216         return fold_convert_loc (loc, rettype, arg);
9217       case rvc_normal:
9218         /* For normal numbers, proceed iff radix == 2.  */
9219         if (REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (arg)))->b == 2)
9220           {
9221             REAL_VALUE_TYPE result = *value;
9222             /* In GCC, normalized significands are in the range [0.5,
9223                1.0).  We want them to be [1.0, 2.0) so set the
9224                exponent to 1.  */
9225             SET_REAL_EXP (&result, 1);
9226             return build_real (rettype, result);
9227           }
9228         break;
9229       }
9230     }
9231
9232   return NULL_TREE;
9233 }
9234
9235 /* Fold a call to builtin frexp, we can assume the base is 2.  */
9236
9237 static tree
9238 fold_builtin_frexp (location_t loc, tree arg0, tree arg1, tree rettype)
9239 {
9240   if (! validate_arg (arg0, REAL_TYPE) || ! validate_arg (arg1, POINTER_TYPE))
9241     return NULL_TREE;
9242
9243   STRIP_NOPS (arg0);
9244
9245   if (!(TREE_CODE (arg0) == REAL_CST && ! TREE_OVERFLOW (arg0)))
9246     return NULL_TREE;
9247
9248   arg1 = build_fold_indirect_ref_loc (loc, arg1);
9249
9250   /* Proceed if a valid pointer type was passed in.  */
9251   if (TYPE_MAIN_VARIANT (TREE_TYPE (arg1)) == integer_type_node)
9252     {
9253       const REAL_VALUE_TYPE *const value = TREE_REAL_CST_PTR (arg0);
9254       tree frac, exp;
9255
9256       switch (value->cl)
9257       {
9258       case rvc_zero:
9259         /* For +-0, return (*exp = 0, +-0).  */
9260         exp = integer_zero_node;
9261         frac = arg0;
9262         break;
9263       case rvc_nan:
9264       case rvc_inf:
9265         /* For +-NaN or +-Inf, *exp is unspecified, return arg0.  */
9266         return omit_one_operand_loc (loc, rettype, arg0, arg1);
9267       case rvc_normal:
9268         {
9269           /* Since the frexp function always expects base 2, and in
9270              GCC normalized significands are already in the range
9271              [0.5, 1.0), we have exactly what frexp wants.  */
9272           REAL_VALUE_TYPE frac_rvt = *value;
9273           SET_REAL_EXP (&frac_rvt, 0);
9274           frac = build_real (rettype, frac_rvt);
9275           exp = build_int_cst (NULL_TREE, REAL_EXP (value));
9276         }
9277         break;
9278       default:
9279         gcc_unreachable ();
9280       }
9281
9282       /* Create the COMPOUND_EXPR (*arg1 = trunc, frac). */
9283       arg1 = fold_build2_loc (loc, MODIFY_EXPR, rettype, arg1, exp);
9284       TREE_SIDE_EFFECTS (arg1) = 1;
9285       return fold_build2_loc (loc, COMPOUND_EXPR, rettype, arg1, frac);
9286     }
9287
9288   return NULL_TREE;
9289 }
9290
9291 /* Fold a call to builtin ldexp or scalbn/scalbln.  If LDEXP is true
9292    then we can assume the base is two.  If it's false, then we have to
9293    check the mode of the TYPE parameter in certain cases.  */
9294
9295 static tree
9296 fold_builtin_load_exponent (location_t loc, tree arg0, tree arg1,
9297                             tree type, bool ldexp)
9298 {
9299   if (validate_arg (arg0, REAL_TYPE) && validate_arg (arg1, INTEGER_TYPE))
9300     {
9301       STRIP_NOPS (arg0);
9302       STRIP_NOPS (arg1);
9303
9304       /* If arg0 is 0, Inf or NaN, or if arg1 is 0, then return arg0.  */
9305       if (real_zerop (arg0) || integer_zerop (arg1)
9306           || (TREE_CODE (arg0) == REAL_CST
9307               && !real_isfinite (&TREE_REAL_CST (arg0))))
9308         return omit_one_operand_loc (loc, type, arg0, arg1);
9309
9310       /* If both arguments are constant, then try to evaluate it.  */
9311       if ((ldexp || REAL_MODE_FORMAT (TYPE_MODE (type))->b == 2)
9312           && TREE_CODE (arg0) == REAL_CST && !TREE_OVERFLOW (arg0)
9313           && host_integerp (arg1, 0))
9314         {
9315           /* Bound the maximum adjustment to twice the range of the
9316              mode's valid exponents.  Use abs to ensure the range is
9317              positive as a sanity check.  */
9318           const long max_exp_adj = 2 *
9319             labs (REAL_MODE_FORMAT (TYPE_MODE (type))->emax
9320                  - REAL_MODE_FORMAT (TYPE_MODE (type))->emin);
9321
9322           /* Get the user-requested adjustment.  */
9323           const HOST_WIDE_INT req_exp_adj = tree_low_cst (arg1, 0);
9324
9325           /* The requested adjustment must be inside this range.  This
9326              is a preliminary cap to avoid things like overflow, we
9327              may still fail to compute the result for other reasons.  */
9328           if (-max_exp_adj < req_exp_adj && req_exp_adj < max_exp_adj)
9329             {
9330               REAL_VALUE_TYPE initial_result;
9331
9332               real_ldexp (&initial_result, &TREE_REAL_CST (arg0), req_exp_adj);
9333
9334               /* Ensure we didn't overflow.  */
9335               if (! real_isinf (&initial_result))
9336                 {
9337                   const REAL_VALUE_TYPE trunc_result
9338                     = real_value_truncate (TYPE_MODE (type), initial_result);
9339
9340                   /* Only proceed if the target mode can hold the
9341                      resulting value.  */
9342                   if (REAL_VALUES_EQUAL (initial_result, trunc_result))
9343                     return build_real (type, trunc_result);
9344                 }
9345             }
9346         }
9347     }
9348
9349   return NULL_TREE;
9350 }
9351
9352 /* Fold a call to builtin modf.  */
9353
9354 static tree
9355 fold_builtin_modf (location_t loc, tree arg0, tree arg1, tree rettype)
9356 {
9357   if (! validate_arg (arg0, REAL_TYPE) || ! validate_arg (arg1, POINTER_TYPE))
9358     return NULL_TREE;
9359
9360   STRIP_NOPS (arg0);
9361
9362   if (!(TREE_CODE (arg0) == REAL_CST && ! TREE_OVERFLOW (arg0)))
9363     return NULL_TREE;
9364
9365   arg1 = build_fold_indirect_ref_loc (loc, arg1);
9366
9367   /* Proceed if a valid pointer type was passed in.  */
9368   if (TYPE_MAIN_VARIANT (TREE_TYPE (arg1)) == TYPE_MAIN_VARIANT (rettype))
9369     {
9370       const REAL_VALUE_TYPE *const value = TREE_REAL_CST_PTR (arg0);
9371       REAL_VALUE_TYPE trunc, frac;
9372
9373       switch (value->cl)
9374       {
9375       case rvc_nan:
9376       case rvc_zero:
9377         /* For +-NaN or +-0, return (*arg1 = arg0, arg0).  */
9378         trunc = frac = *value;
9379         break;
9380       case rvc_inf:
9381         /* For +-Inf, return (*arg1 = arg0, +-0).  */
9382         frac = dconst0;
9383         frac.sign = value->sign;
9384         trunc = *value;
9385         break;
9386       case rvc_normal:
9387         /* Return (*arg1 = trunc(arg0), arg0-trunc(arg0)).  */
9388         real_trunc (&trunc, VOIDmode, value);
9389         real_arithmetic (&frac, MINUS_EXPR, value, &trunc);
9390         /* If the original number was negative and already
9391            integral, then the fractional part is -0.0.  */
9392         if (value->sign && frac.cl == rvc_zero)
9393           frac.sign = value->sign;
9394         break;
9395       }
9396
9397       /* Create the COMPOUND_EXPR (*arg1 = trunc, frac). */
9398       arg1 = fold_build2_loc (loc, MODIFY_EXPR, rettype, arg1,
9399                           build_real (rettype, trunc));
9400       TREE_SIDE_EFFECTS (arg1) = 1;
9401       return fold_build2_loc (loc, COMPOUND_EXPR, rettype, arg1,
9402                           build_real (rettype, frac));
9403     }
9404
9405   return NULL_TREE;
9406 }
9407
9408 /* Given a location LOC, an interclass builtin function decl FNDECL
9409    and its single argument ARG, return an folded expression computing
9410    the same, or NULL_TREE if we either couldn't or didn't want to fold
9411    (the latter happen if there's an RTL instruction available).  */
9412
9413 static tree
9414 fold_builtin_interclass_mathfn (location_t loc, tree fndecl, tree arg)
9415 {
9416   enum machine_mode mode;
9417
9418   if (!validate_arg (arg, REAL_TYPE))
9419     return NULL_TREE;
9420
9421   if (interclass_mathfn_icode (arg, fndecl) != CODE_FOR_nothing)
9422     return NULL_TREE;
9423
9424   mode = TYPE_MODE (TREE_TYPE (arg));
9425
9426   /* If there is no optab, try generic code.  */
9427   switch (DECL_FUNCTION_CODE (fndecl))
9428     {
9429       tree result;
9430
9431     CASE_FLT_FN (BUILT_IN_ISINF):
9432       {
9433         /* isinf(x) -> isgreater(fabs(x),DBL_MAX).  */
9434         tree const isgr_fn = built_in_decls[BUILT_IN_ISGREATER];
9435         tree const type = TREE_TYPE (arg);
9436         REAL_VALUE_TYPE r;
9437         char buf[128];
9438
9439         get_max_float (REAL_MODE_FORMAT (mode), buf, sizeof (buf));
9440         real_from_string (&r, buf);
9441         result = build_call_expr (isgr_fn, 2,
9442                                   fold_build1_loc (loc, ABS_EXPR, type, arg),
9443                                   build_real (type, r));
9444         return result;
9445       }
9446     CASE_FLT_FN (BUILT_IN_FINITE):
9447     case BUILT_IN_ISFINITE:
9448       {
9449         /* isfinite(x) -> islessequal(fabs(x),DBL_MAX).  */
9450         tree const isle_fn = built_in_decls[BUILT_IN_ISLESSEQUAL];
9451         tree const type = TREE_TYPE (arg);
9452         REAL_VALUE_TYPE r;
9453         char buf[128];
9454
9455         get_max_float (REAL_MODE_FORMAT (mode), buf, sizeof (buf));
9456         real_from_string (&r, buf);
9457         result = build_call_expr (isle_fn, 2,
9458                                   fold_build1_loc (loc, ABS_EXPR, type, arg),
9459                                   build_real (type, r));
9460         /*result = fold_build2_loc (loc, UNGT_EXPR,
9461                                   TREE_TYPE (TREE_TYPE (fndecl)),
9462                                   fold_build1_loc (loc, ABS_EXPR, type, arg),
9463                                   build_real (type, r));
9464         result = fold_build1_loc (loc, TRUTH_NOT_EXPR,
9465                                   TREE_TYPE (TREE_TYPE (fndecl)),
9466                                   result);*/
9467         return result;
9468       }
9469     case BUILT_IN_ISNORMAL:
9470       {
9471         /* isnormal(x) -> isgreaterequal(fabs(x),DBL_MIN) &
9472            islessequal(fabs(x),DBL_MAX).  */
9473         tree const isle_fn = built_in_decls[BUILT_IN_ISLESSEQUAL];
9474         tree const isge_fn = built_in_decls[BUILT_IN_ISGREATEREQUAL];
9475         tree const type = TREE_TYPE (arg);
9476         REAL_VALUE_TYPE rmax, rmin;
9477         char buf[128];
9478
9479         get_max_float (REAL_MODE_FORMAT (mode), buf, sizeof (buf));
9480         real_from_string (&rmax, buf);
9481         sprintf (buf, "0x1p%d", REAL_MODE_FORMAT (mode)->emin - 1);
9482         real_from_string (&rmin, buf);
9483         arg = builtin_save_expr (fold_build1_loc (loc, ABS_EXPR, type, arg));
9484         result = build_call_expr (isle_fn, 2, arg,
9485                                   build_real (type, rmax));
9486         result = fold_build2 (BIT_AND_EXPR, integer_type_node, result,
9487                               build_call_expr (isge_fn, 2, arg,
9488                                                build_real (type, rmin)));
9489         return result;
9490       }
9491     default:
9492       break;
9493     }
9494
9495   return NULL_TREE;
9496 }
9497
9498 /* Fold a call to __builtin_isnan(), __builtin_isinf, __builtin_finite.
9499    ARG is the argument for the call.  */
9500
9501 static tree
9502 fold_builtin_classify (location_t loc, tree fndecl, tree arg, int builtin_index)
9503 {
9504   tree type = TREE_TYPE (TREE_TYPE (fndecl));
9505   REAL_VALUE_TYPE r;
9506
9507   if (!validate_arg (arg, REAL_TYPE))
9508     return NULL_TREE;
9509
9510   switch (builtin_index)
9511     {
9512     case BUILT_IN_ISINF:
9513       if (!HONOR_INFINITIES (TYPE_MODE (TREE_TYPE (arg))))
9514         return omit_one_operand_loc (loc, type, integer_zero_node, arg);
9515
9516       if (TREE_CODE (arg) == REAL_CST)
9517         {
9518           r = TREE_REAL_CST (arg);
9519           if (real_isinf (&r))
9520             return real_compare (GT_EXPR, &r, &dconst0)
9521                    ? integer_one_node : integer_minus_one_node;
9522           else
9523             return integer_zero_node;
9524         }
9525
9526       return NULL_TREE;
9527
9528     case BUILT_IN_ISINF_SIGN:
9529       {
9530         /* isinf_sign(x) -> isinf(x) ? (signbit(x) ? -1 : 1) : 0 */
9531         /* In a boolean context, GCC will fold the inner COND_EXPR to
9532            1.  So e.g. "if (isinf_sign(x))" would be folded to just
9533            "if (isinf(x) ? 1 : 0)" which becomes "if (isinf(x))". */
9534         tree signbit_fn = mathfn_built_in_1 (TREE_TYPE (arg), BUILT_IN_SIGNBIT, 0);
9535         tree isinf_fn = built_in_decls[BUILT_IN_ISINF];
9536         tree tmp = NULL_TREE;
9537
9538         arg = builtin_save_expr (arg);
9539
9540         if (signbit_fn && isinf_fn)
9541           {
9542             tree signbit_call = build_call_expr_loc (loc, signbit_fn, 1, arg);
9543             tree isinf_call = build_call_expr_loc (loc, isinf_fn, 1, arg);
9544
9545             signbit_call = fold_build2_loc (loc, NE_EXPR, integer_type_node,
9546                                         signbit_call, integer_zero_node);
9547             isinf_call = fold_build2_loc (loc, NE_EXPR, integer_type_node,
9548                                       isinf_call, integer_zero_node);
9549
9550             tmp = fold_build3_loc (loc, COND_EXPR, integer_type_node, signbit_call,
9551                                integer_minus_one_node, integer_one_node);
9552             tmp = fold_build3_loc (loc, COND_EXPR, integer_type_node,
9553                                isinf_call, tmp,
9554                                integer_zero_node);
9555           }
9556
9557         return tmp;
9558       }
9559
9560     case BUILT_IN_ISFINITE:
9561       if (!HONOR_NANS (TYPE_MODE (TREE_TYPE (arg)))
9562           && !HONOR_INFINITIES (TYPE_MODE (TREE_TYPE (arg))))
9563         return omit_one_operand_loc (loc, type, integer_one_node, arg);
9564
9565       if (TREE_CODE (arg) == REAL_CST)
9566         {
9567           r = TREE_REAL_CST (arg);
9568           return real_isfinite (&r) ? integer_one_node : integer_zero_node;
9569         }
9570
9571       return NULL_TREE;
9572
9573     case BUILT_IN_ISNAN:
9574       if (!HONOR_NANS (TYPE_MODE (TREE_TYPE (arg))))
9575         return omit_one_operand_loc (loc, type, integer_zero_node, arg);
9576
9577       if (TREE_CODE (arg) == REAL_CST)
9578         {
9579           r = TREE_REAL_CST (arg);
9580           return real_isnan (&r) ? integer_one_node : integer_zero_node;
9581         }
9582
9583       arg = builtin_save_expr (arg);
9584       return fold_build2_loc (loc, UNORDERED_EXPR, type, arg, arg);
9585
9586     default:
9587       gcc_unreachable ();
9588     }
9589 }
9590
9591 /* Fold a call to __builtin_fpclassify(int, int, int, int, int, ...).
9592    This builtin will generate code to return the appropriate floating
9593    point classification depending on the value of the floating point
9594    number passed in.  The possible return values must be supplied as
9595    int arguments to the call in the following order: FP_NAN, FP_INFINITE,
9596    FP_NORMAL, FP_SUBNORMAL and FP_ZERO.  The ellipses is for exactly
9597    one floating point argument which is "type generic".  */
9598
9599 static tree
9600 fold_builtin_fpclassify (location_t loc, tree exp)
9601 {
9602   tree fp_nan, fp_infinite, fp_normal, fp_subnormal, fp_zero,
9603     arg, type, res, tmp;
9604   enum machine_mode mode;
9605   REAL_VALUE_TYPE r;
9606   char buf[128];
9607
9608   /* Verify the required arguments in the original call.  */
9609   if (!validate_arglist (exp, INTEGER_TYPE, INTEGER_TYPE,
9610                          INTEGER_TYPE, INTEGER_TYPE,
9611                          INTEGER_TYPE, REAL_TYPE, VOID_TYPE))
9612     return NULL_TREE;
9613
9614   fp_nan = CALL_EXPR_ARG (exp, 0);
9615   fp_infinite = CALL_EXPR_ARG (exp, 1);
9616   fp_normal = CALL_EXPR_ARG (exp, 2);
9617   fp_subnormal = CALL_EXPR_ARG (exp, 3);
9618   fp_zero = CALL_EXPR_ARG (exp, 4);
9619   arg = CALL_EXPR_ARG (exp, 5);
9620   type = TREE_TYPE (arg);
9621   mode = TYPE_MODE (type);
9622   arg = builtin_save_expr (fold_build1_loc (loc, ABS_EXPR, type, arg));
9623
9624   /* fpclassify(x) ->
9625        isnan(x) ? FP_NAN :
9626          (fabs(x) == Inf ? FP_INFINITE :
9627            (fabs(x) >= DBL_MIN ? FP_NORMAL :
9628              (x == 0 ? FP_ZERO : FP_SUBNORMAL))).  */
9629
9630   tmp = fold_build2_loc (loc, EQ_EXPR, integer_type_node, arg,
9631                      build_real (type, dconst0));
9632   res = fold_build3_loc (loc, COND_EXPR, integer_type_node,
9633                      tmp, fp_zero, fp_subnormal);
9634
9635   sprintf (buf, "0x1p%d", REAL_MODE_FORMAT (mode)->emin - 1);
9636   real_from_string (&r, buf);
9637   tmp = fold_build2_loc (loc, GE_EXPR, integer_type_node,
9638                      arg, build_real (type, r));
9639   res = fold_build3_loc (loc, COND_EXPR, integer_type_node, tmp, fp_normal, res);
9640
9641   if (HONOR_INFINITIES (mode))
9642     {
9643       real_inf (&r);
9644       tmp = fold_build2_loc (loc, EQ_EXPR, integer_type_node, arg,
9645                          build_real (type, r));
9646       res = fold_build3_loc (loc, COND_EXPR, integer_type_node, tmp,
9647                          fp_infinite, res);
9648     }
9649
9650   if (HONOR_NANS (mode))
9651     {
9652       tmp = fold_build2_loc (loc, ORDERED_EXPR, integer_type_node, arg, arg);
9653       res = fold_build3_loc (loc, COND_EXPR, integer_type_node, tmp, res, fp_nan);
9654     }
9655
9656   return res;
9657 }
9658
9659 /* Fold a call to an unordered comparison function such as
9660    __builtin_isgreater().  FNDECL is the FUNCTION_DECL for the function
9661    being called and ARG0 and ARG1 are the arguments for the call.
9662    UNORDERED_CODE and ORDERED_CODE are comparison codes that give
9663    the opposite of the desired result.  UNORDERED_CODE is used
9664    for modes that can hold NaNs and ORDERED_CODE is used for
9665    the rest.  */
9666
9667 static tree
9668 fold_builtin_unordered_cmp (location_t loc, tree fndecl, tree arg0, tree arg1,
9669                             enum tree_code unordered_code,
9670                             enum tree_code ordered_code)
9671 {
9672   tree type = TREE_TYPE (TREE_TYPE (fndecl));
9673   enum tree_code code;
9674   tree type0, type1;
9675   enum tree_code code0, code1;
9676   tree cmp_type = NULL_TREE;
9677
9678   type0 = TREE_TYPE (arg0);
9679   type1 = TREE_TYPE (arg1);
9680
9681   code0 = TREE_CODE (type0);
9682   code1 = TREE_CODE (type1);
9683
9684   if (code0 == REAL_TYPE && code1 == REAL_TYPE)
9685     /* Choose the wider of two real types.  */
9686     cmp_type = TYPE_PRECISION (type0) >= TYPE_PRECISION (type1)
9687       ? type0 : type1;
9688   else if (code0 == REAL_TYPE && code1 == INTEGER_TYPE)
9689     cmp_type = type0;
9690   else if (code0 == INTEGER_TYPE && code1 == REAL_TYPE)
9691     cmp_type = type1;
9692
9693   arg0 = fold_convert_loc (loc, cmp_type, arg0);
9694   arg1 = fold_convert_loc (loc, cmp_type, arg1);
9695
9696   if (unordered_code == UNORDERED_EXPR)
9697     {
9698       if (!HONOR_NANS (TYPE_MODE (TREE_TYPE (arg0))))
9699         return omit_two_operands_loc (loc, type, integer_zero_node, arg0, arg1);
9700       return fold_build2_loc (loc, UNORDERED_EXPR, type, arg0, arg1);
9701     }
9702
9703   code = HONOR_NANS (TYPE_MODE (TREE_TYPE (arg0))) ? unordered_code
9704                                                    : ordered_code;
9705   return fold_build1_loc (loc, TRUTH_NOT_EXPR, type,
9706                       fold_build2_loc (loc, code, type, arg0, arg1));
9707 }
9708
9709 /* Fold a call to built-in function FNDECL with 0 arguments.
9710    IGNORE is true if the result of the function call is ignored.  This
9711    function returns NULL_TREE if no simplification was possible.  */
9712
9713 static tree
9714 fold_builtin_0 (location_t loc, tree fndecl, bool ignore ATTRIBUTE_UNUSED)
9715 {
9716   tree type = TREE_TYPE (TREE_TYPE (fndecl));
9717   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
9718   switch (fcode)
9719     {
9720     CASE_FLT_FN (BUILT_IN_INF):
9721     case BUILT_IN_INFD32:
9722     case BUILT_IN_INFD64:
9723     case BUILT_IN_INFD128:
9724       return fold_builtin_inf (loc, type, true);
9725
9726     CASE_FLT_FN (BUILT_IN_HUGE_VAL):
9727       return fold_builtin_inf (loc, type, false);
9728
9729     case BUILT_IN_CLASSIFY_TYPE:
9730       return fold_builtin_classify_type (NULL_TREE);
9731
9732     default:
9733       break;
9734     }
9735   return NULL_TREE;
9736 }
9737
9738 /* Fold a call to built-in function FNDECL with 1 argument, ARG0.
9739    IGNORE is true if the result of the function call is ignored.  This
9740    function returns NULL_TREE if no simplification was possible.  */
9741
9742 static tree
9743 fold_builtin_1 (location_t loc, tree fndecl, tree arg0, bool ignore)
9744 {
9745   tree type = TREE_TYPE (TREE_TYPE (fndecl));
9746   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
9747   switch (fcode)
9748     {
9749     case BUILT_IN_CONSTANT_P:
9750       {
9751         tree val = fold_builtin_constant_p (arg0);
9752
9753         /* Gimplification will pull the CALL_EXPR for the builtin out of
9754            an if condition.  When not optimizing, we'll not CSE it back.
9755            To avoid link error types of regressions, return false now.  */
9756         if (!val && !optimize)
9757           val = integer_zero_node;
9758
9759         return val;
9760       }
9761
9762     case BUILT_IN_CLASSIFY_TYPE:
9763       return fold_builtin_classify_type (arg0);
9764
9765     case BUILT_IN_STRLEN:
9766       return fold_builtin_strlen (loc, type, arg0);
9767
9768     CASE_FLT_FN (BUILT_IN_FABS):
9769       return fold_builtin_fabs (loc, arg0, type);
9770
9771     case BUILT_IN_ABS:
9772     case BUILT_IN_LABS:
9773     case BUILT_IN_LLABS:
9774     case BUILT_IN_IMAXABS:
9775       return fold_builtin_abs (loc, arg0, type);
9776
9777     CASE_FLT_FN (BUILT_IN_CONJ):
9778       if (validate_arg (arg0, COMPLEX_TYPE)
9779         && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
9780         return fold_build1_loc (loc, CONJ_EXPR, type, arg0);
9781     break;
9782
9783     CASE_FLT_FN (BUILT_IN_CREAL):
9784       if (validate_arg (arg0, COMPLEX_TYPE)
9785         && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
9786         return non_lvalue_loc (loc, fold_build1_loc (loc, REALPART_EXPR, type, arg0));;
9787     break;
9788
9789     CASE_FLT_FN (BUILT_IN_CIMAG):
9790       if (validate_arg (arg0, COMPLEX_TYPE)
9791           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
9792         return non_lvalue_loc (loc, fold_build1_loc (loc, IMAGPART_EXPR, type, arg0));
9793     break;
9794
9795     CASE_FLT_FN (BUILT_IN_CCOS):
9796       return fold_builtin_ccos(loc, arg0, type, fndecl, /*hyper=*/ false);
9797
9798     CASE_FLT_FN (BUILT_IN_CCOSH):
9799       return fold_builtin_ccos(loc, arg0, type, fndecl, /*hyper=*/ true);
9800
9801     CASE_FLT_FN (BUILT_IN_CPROJ):
9802       return fold_builtin_cproj(loc, arg0, type);
9803
9804     CASE_FLT_FN (BUILT_IN_CSIN):
9805       if (validate_arg (arg0, COMPLEX_TYPE)
9806           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
9807         return do_mpc_arg1 (arg0, type, mpc_sin);
9808     break;
9809
9810     CASE_FLT_FN (BUILT_IN_CSINH):
9811       if (validate_arg (arg0, COMPLEX_TYPE)
9812           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
9813         return do_mpc_arg1 (arg0, type, mpc_sinh);
9814     break;
9815
9816     CASE_FLT_FN (BUILT_IN_CTAN):
9817       if (validate_arg (arg0, COMPLEX_TYPE)
9818           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
9819         return do_mpc_arg1 (arg0, type, mpc_tan);
9820     break;
9821
9822     CASE_FLT_FN (BUILT_IN_CTANH):
9823       if (validate_arg (arg0, COMPLEX_TYPE)
9824           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
9825         return do_mpc_arg1 (arg0, type, mpc_tanh);
9826     break;
9827
9828     CASE_FLT_FN (BUILT_IN_CLOG):
9829       if (validate_arg (arg0, COMPLEX_TYPE)
9830           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
9831         return do_mpc_arg1 (arg0, type, mpc_log);
9832     break;
9833
9834     CASE_FLT_FN (BUILT_IN_CSQRT):
9835       if (validate_arg (arg0, COMPLEX_TYPE)
9836           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
9837         return do_mpc_arg1 (arg0, type, mpc_sqrt);
9838     break;
9839
9840     CASE_FLT_FN (BUILT_IN_CASIN):
9841       if (validate_arg (arg0, COMPLEX_TYPE)
9842           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
9843         return do_mpc_arg1 (arg0, type, mpc_asin);
9844     break;
9845
9846     CASE_FLT_FN (BUILT_IN_CACOS):
9847       if (validate_arg (arg0, COMPLEX_TYPE)
9848           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
9849         return do_mpc_arg1 (arg0, type, mpc_acos);
9850     break;
9851
9852     CASE_FLT_FN (BUILT_IN_CATAN):
9853       if (validate_arg (arg0, COMPLEX_TYPE)
9854           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
9855         return do_mpc_arg1 (arg0, type, mpc_atan);
9856     break;
9857
9858     CASE_FLT_FN (BUILT_IN_CASINH):
9859       if (validate_arg (arg0, COMPLEX_TYPE)
9860           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
9861         return do_mpc_arg1 (arg0, type, mpc_asinh);
9862     break;
9863
9864     CASE_FLT_FN (BUILT_IN_CACOSH):
9865       if (validate_arg (arg0, COMPLEX_TYPE)
9866           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
9867         return do_mpc_arg1 (arg0, type, mpc_acosh);
9868     break;
9869
9870     CASE_FLT_FN (BUILT_IN_CATANH):
9871       if (validate_arg (arg0, COMPLEX_TYPE)
9872           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE)
9873         return do_mpc_arg1 (arg0, type, mpc_atanh);
9874     break;
9875
9876     CASE_FLT_FN (BUILT_IN_CABS):
9877       return fold_builtin_cabs (loc, arg0, type, fndecl);
9878
9879     CASE_FLT_FN (BUILT_IN_CARG):
9880       return fold_builtin_carg (loc, arg0, type);
9881
9882     CASE_FLT_FN (BUILT_IN_SQRT):
9883       return fold_builtin_sqrt (loc, arg0, type);
9884
9885     CASE_FLT_FN (BUILT_IN_CBRT):
9886       return fold_builtin_cbrt (loc, arg0, type);
9887
9888     CASE_FLT_FN (BUILT_IN_ASIN):
9889       if (validate_arg (arg0, REAL_TYPE))
9890         return do_mpfr_arg1 (arg0, type, mpfr_asin,
9891                              &dconstm1, &dconst1, true);
9892     break;
9893
9894     CASE_FLT_FN (BUILT_IN_ACOS):
9895       if (validate_arg (arg0, REAL_TYPE))
9896         return do_mpfr_arg1 (arg0, type, mpfr_acos,
9897                              &dconstm1, &dconst1, true);
9898     break;
9899
9900     CASE_FLT_FN (BUILT_IN_ATAN):
9901       if (validate_arg (arg0, REAL_TYPE))
9902         return do_mpfr_arg1 (arg0, type, mpfr_atan, NULL, NULL, 0);
9903     break;
9904
9905     CASE_FLT_FN (BUILT_IN_ASINH):
9906       if (validate_arg (arg0, REAL_TYPE))
9907         return do_mpfr_arg1 (arg0, type, mpfr_asinh, NULL, NULL, 0);
9908     break;
9909
9910     CASE_FLT_FN (BUILT_IN_ACOSH):
9911       if (validate_arg (arg0, REAL_TYPE))
9912         return do_mpfr_arg1 (arg0, type, mpfr_acosh,
9913                              &dconst1, NULL, true);
9914     break;
9915
9916     CASE_FLT_FN (BUILT_IN_ATANH):
9917       if (validate_arg (arg0, REAL_TYPE))
9918         return do_mpfr_arg1 (arg0, type, mpfr_atanh,
9919                              &dconstm1, &dconst1, false);
9920     break;
9921
9922     CASE_FLT_FN (BUILT_IN_SIN):
9923       if (validate_arg (arg0, REAL_TYPE))
9924         return do_mpfr_arg1 (arg0, type, mpfr_sin, NULL, NULL, 0);
9925     break;
9926
9927     CASE_FLT_FN (BUILT_IN_COS):
9928       return fold_builtin_cos (loc, arg0, type, fndecl);
9929
9930     CASE_FLT_FN (BUILT_IN_TAN):
9931       return fold_builtin_tan (arg0, type);
9932
9933     CASE_FLT_FN (BUILT_IN_CEXP):
9934       return fold_builtin_cexp (loc, arg0, type);
9935
9936     CASE_FLT_FN (BUILT_IN_CEXPI):
9937       if (validate_arg (arg0, REAL_TYPE))
9938         return do_mpfr_sincos (arg0, NULL_TREE, NULL_TREE);
9939     break;
9940
9941     CASE_FLT_FN (BUILT_IN_SINH):
9942       if (validate_arg (arg0, REAL_TYPE))
9943         return do_mpfr_arg1 (arg0, type, mpfr_sinh, NULL, NULL, 0);
9944     break;
9945
9946     CASE_FLT_FN (BUILT_IN_COSH):
9947       return fold_builtin_cosh (loc, arg0, type, fndecl);
9948
9949     CASE_FLT_FN (BUILT_IN_TANH):
9950       if (validate_arg (arg0, REAL_TYPE))
9951         return do_mpfr_arg1 (arg0, type, mpfr_tanh, NULL, NULL, 0);
9952     break;
9953
9954     CASE_FLT_FN (BUILT_IN_ERF):
9955       if (validate_arg (arg0, REAL_TYPE))
9956         return do_mpfr_arg1 (arg0, type, mpfr_erf, NULL, NULL, 0);
9957     break;
9958
9959     CASE_FLT_FN (BUILT_IN_ERFC):
9960       if (validate_arg (arg0, REAL_TYPE))
9961         return do_mpfr_arg1 (arg0, type, mpfr_erfc, NULL, NULL, 0);
9962     break;
9963
9964     CASE_FLT_FN (BUILT_IN_TGAMMA):
9965       if (validate_arg (arg0, REAL_TYPE))
9966         return do_mpfr_arg1 (arg0, type, mpfr_gamma, NULL, NULL, 0);
9967     break;
9968
9969     CASE_FLT_FN (BUILT_IN_EXP):
9970       return fold_builtin_exponent (loc, fndecl, arg0, mpfr_exp);
9971
9972     CASE_FLT_FN (BUILT_IN_EXP2):
9973       return fold_builtin_exponent (loc, fndecl, arg0, mpfr_exp2);
9974
9975     CASE_FLT_FN (BUILT_IN_EXP10):
9976     CASE_FLT_FN (BUILT_IN_POW10):
9977       return fold_builtin_exponent (loc, fndecl, arg0, mpfr_exp10);
9978
9979     CASE_FLT_FN (BUILT_IN_EXPM1):
9980       if (validate_arg (arg0, REAL_TYPE))
9981         return do_mpfr_arg1 (arg0, type, mpfr_expm1, NULL, NULL, 0);
9982     break;
9983
9984     CASE_FLT_FN (BUILT_IN_LOG):
9985     return fold_builtin_logarithm (loc, fndecl, arg0, mpfr_log);
9986
9987     CASE_FLT_FN (BUILT_IN_LOG2):
9988       return fold_builtin_logarithm (loc, fndecl, arg0, mpfr_log2);
9989
9990     CASE_FLT_FN (BUILT_IN_LOG10):
9991       return fold_builtin_logarithm (loc, fndecl, arg0, mpfr_log10);
9992
9993     CASE_FLT_FN (BUILT_IN_LOG1P):
9994       if (validate_arg (arg0, REAL_TYPE))
9995         return do_mpfr_arg1 (arg0, type, mpfr_log1p,
9996                              &dconstm1, NULL, false);
9997     break;
9998
9999     CASE_FLT_FN (BUILT_IN_J0):
10000       if (validate_arg (arg0, REAL_TYPE))
10001         return do_mpfr_arg1 (arg0, type, mpfr_j0,
10002                              NULL, NULL, 0);
10003     break;
10004
10005     CASE_FLT_FN (BUILT_IN_J1):
10006       if (validate_arg (arg0, REAL_TYPE))
10007         return do_mpfr_arg1 (arg0, type, mpfr_j1,
10008                              NULL, NULL, 0);
10009     break;
10010
10011     CASE_FLT_FN (BUILT_IN_Y0):
10012       if (validate_arg (arg0, REAL_TYPE))
10013         return do_mpfr_arg1 (arg0, type, mpfr_y0,
10014                              &dconst0, NULL, false);
10015     break;
10016
10017     CASE_FLT_FN (BUILT_IN_Y1):
10018       if (validate_arg (arg0, REAL_TYPE))
10019         return do_mpfr_arg1 (arg0, type, mpfr_y1,
10020                              &dconst0, NULL, false);
10021     break;
10022
10023     CASE_FLT_FN (BUILT_IN_NAN):
10024     case BUILT_IN_NAND32:
10025     case BUILT_IN_NAND64:
10026     case BUILT_IN_NAND128:
10027       return fold_builtin_nan (arg0, type, true);
10028
10029     CASE_FLT_FN (BUILT_IN_NANS):
10030       return fold_builtin_nan (arg0, type, false);
10031
10032     CASE_FLT_FN (BUILT_IN_FLOOR):
10033       return fold_builtin_floor (loc, fndecl, arg0);
10034
10035     CASE_FLT_FN (BUILT_IN_CEIL):
10036       return fold_builtin_ceil (loc, fndecl, arg0);
10037
10038     CASE_FLT_FN (BUILT_IN_TRUNC):
10039       return fold_builtin_trunc (loc, fndecl, arg0);
10040
10041     CASE_FLT_FN (BUILT_IN_ROUND):
10042       return fold_builtin_round (loc, fndecl, arg0);
10043
10044     CASE_FLT_FN (BUILT_IN_NEARBYINT):
10045     CASE_FLT_FN (BUILT_IN_RINT):
10046       return fold_trunc_transparent_mathfn (loc, fndecl, arg0);
10047
10048     CASE_FLT_FN (BUILT_IN_LCEIL):
10049     CASE_FLT_FN (BUILT_IN_LLCEIL):
10050     CASE_FLT_FN (BUILT_IN_LFLOOR):
10051     CASE_FLT_FN (BUILT_IN_LLFLOOR):
10052     CASE_FLT_FN (BUILT_IN_LROUND):
10053     CASE_FLT_FN (BUILT_IN_LLROUND):
10054       return fold_builtin_int_roundingfn (loc, fndecl, arg0);
10055
10056     CASE_FLT_FN (BUILT_IN_LRINT):
10057     CASE_FLT_FN (BUILT_IN_LLRINT):
10058       return fold_fixed_mathfn (loc, fndecl, arg0);
10059
10060     case BUILT_IN_BSWAP32:
10061     case BUILT_IN_BSWAP64:
10062       return fold_builtin_bswap (fndecl, arg0);
10063
10064     CASE_INT_FN (BUILT_IN_FFS):
10065     CASE_INT_FN (BUILT_IN_CLZ):
10066     CASE_INT_FN (BUILT_IN_CTZ):
10067     CASE_INT_FN (BUILT_IN_POPCOUNT):
10068     CASE_INT_FN (BUILT_IN_PARITY):
10069       return fold_builtin_bitop (fndecl, arg0);
10070
10071     CASE_FLT_FN (BUILT_IN_SIGNBIT):
10072       return fold_builtin_signbit (loc, arg0, type);
10073
10074     CASE_FLT_FN (BUILT_IN_SIGNIFICAND):
10075       return fold_builtin_significand (loc, arg0, type);
10076
10077     CASE_FLT_FN (BUILT_IN_ILOGB):
10078     CASE_FLT_FN (BUILT_IN_LOGB):
10079       return fold_builtin_logb (loc, arg0, type);
10080
10081     case BUILT_IN_ISASCII:
10082       return fold_builtin_isascii (loc, arg0);
10083
10084     case BUILT_IN_TOASCII:
10085       return fold_builtin_toascii (loc, arg0);
10086
10087     case BUILT_IN_ISDIGIT:
10088       return fold_builtin_isdigit (loc, arg0);
10089
10090     CASE_FLT_FN (BUILT_IN_FINITE):
10091     case BUILT_IN_FINITED32:
10092     case BUILT_IN_FINITED64:
10093     case BUILT_IN_FINITED128:
10094     case BUILT_IN_ISFINITE:
10095       {
10096         tree ret = fold_builtin_classify (loc, fndecl, arg0, BUILT_IN_ISFINITE);
10097         if (ret)
10098           return ret;
10099         return fold_builtin_interclass_mathfn (loc, fndecl, arg0);
10100       }
10101
10102     CASE_FLT_FN (BUILT_IN_ISINF):
10103     case BUILT_IN_ISINFD32:
10104     case BUILT_IN_ISINFD64:
10105     case BUILT_IN_ISINFD128:
10106       {
10107         tree ret = fold_builtin_classify (loc, fndecl, arg0, BUILT_IN_ISINF);
10108         if (ret)
10109           return ret;
10110         return fold_builtin_interclass_mathfn (loc, fndecl, arg0);
10111       }
10112
10113     case BUILT_IN_ISNORMAL:
10114       return fold_builtin_interclass_mathfn (loc, fndecl, arg0);
10115
10116     case BUILT_IN_ISINF_SIGN:
10117       return fold_builtin_classify (loc, fndecl, arg0, BUILT_IN_ISINF_SIGN);
10118
10119     CASE_FLT_FN (BUILT_IN_ISNAN):
10120     case BUILT_IN_ISNAND32:
10121     case BUILT_IN_ISNAND64:
10122     case BUILT_IN_ISNAND128:
10123       return fold_builtin_classify (loc, fndecl, arg0, BUILT_IN_ISNAN);
10124
10125     case BUILT_IN_PRINTF:
10126     case BUILT_IN_PRINTF_UNLOCKED:
10127     case BUILT_IN_VPRINTF:
10128       return fold_builtin_printf (loc, fndecl, arg0, NULL_TREE, ignore, fcode);
10129
10130     case BUILT_IN_FREE:
10131       if (integer_zerop (arg0))
10132         return build_empty_stmt (loc);
10133       break;
10134
10135     default:
10136       break;
10137     }
10138
10139   return NULL_TREE;
10140
10141 }
10142
10143 /* Fold a call to built-in function FNDECL with 2 arguments, ARG0 and ARG1.
10144    IGNORE is true if the result of the function call is ignored.  This
10145    function returns NULL_TREE if no simplification was possible.  */
10146
10147 static tree
10148 fold_builtin_2 (location_t loc, tree fndecl, tree arg0, tree arg1, bool ignore)
10149 {
10150   tree type = TREE_TYPE (TREE_TYPE (fndecl));
10151   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
10152
10153   switch (fcode)
10154     {
10155     CASE_FLT_FN (BUILT_IN_JN):
10156       if (validate_arg (arg0, INTEGER_TYPE)
10157           && validate_arg (arg1, REAL_TYPE))
10158         return do_mpfr_bessel_n (arg0, arg1, type, mpfr_jn, NULL, 0);
10159     break;
10160
10161     CASE_FLT_FN (BUILT_IN_YN):
10162       if (validate_arg (arg0, INTEGER_TYPE)
10163           && validate_arg (arg1, REAL_TYPE))
10164         return do_mpfr_bessel_n (arg0, arg1, type, mpfr_yn,
10165                                  &dconst0, false);
10166     break;
10167
10168     CASE_FLT_FN (BUILT_IN_DREM):
10169     CASE_FLT_FN (BUILT_IN_REMAINDER):
10170       if (validate_arg (arg0, REAL_TYPE)
10171           && validate_arg(arg1, REAL_TYPE))
10172         return do_mpfr_arg2 (arg0, arg1, type, mpfr_remainder);
10173     break;
10174
10175     CASE_FLT_FN_REENT (BUILT_IN_GAMMA): /* GAMMA_R */
10176     CASE_FLT_FN_REENT (BUILT_IN_LGAMMA): /* LGAMMA_R */
10177       if (validate_arg (arg0, REAL_TYPE)
10178           && validate_arg(arg1, POINTER_TYPE))
10179         return do_mpfr_lgamma_r (arg0, arg1, type);
10180     break;
10181
10182     CASE_FLT_FN (BUILT_IN_ATAN2):
10183       if (validate_arg (arg0, REAL_TYPE)
10184           && validate_arg(arg1, REAL_TYPE))
10185         return do_mpfr_arg2 (arg0, arg1, type, mpfr_atan2);
10186     break;
10187
10188     CASE_FLT_FN (BUILT_IN_FDIM):
10189       if (validate_arg (arg0, REAL_TYPE)
10190           && validate_arg(arg1, REAL_TYPE))
10191         return do_mpfr_arg2 (arg0, arg1, type, mpfr_dim);
10192     break;
10193
10194     CASE_FLT_FN (BUILT_IN_HYPOT):
10195       return fold_builtin_hypot (loc, fndecl, arg0, arg1, type);
10196
10197     CASE_FLT_FN (BUILT_IN_CPOW):
10198       if (validate_arg (arg0, COMPLEX_TYPE)
10199           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE
10200           && validate_arg (arg1, COMPLEX_TYPE)
10201           && TREE_CODE (TREE_TYPE (TREE_TYPE (arg1))) == REAL_TYPE)
10202         return do_mpc_arg2 (arg0, arg1, type, /*do_nonfinite=*/ 0, mpc_pow);
10203     break;
10204
10205     CASE_FLT_FN (BUILT_IN_LDEXP):
10206       return fold_builtin_load_exponent (loc, arg0, arg1, type, /*ldexp=*/true);
10207     CASE_FLT_FN (BUILT_IN_SCALBN):
10208     CASE_FLT_FN (BUILT_IN_SCALBLN):
10209       return fold_builtin_load_exponent (loc, arg0, arg1,
10210                                          type, /*ldexp=*/false);
10211
10212     CASE_FLT_FN (BUILT_IN_FREXP):
10213       return fold_builtin_frexp (loc, arg0, arg1, type);
10214
10215     CASE_FLT_FN (BUILT_IN_MODF):
10216       return fold_builtin_modf (loc, arg0, arg1, type);
10217
10218     case BUILT_IN_BZERO:
10219       return fold_builtin_bzero (loc, arg0, arg1, ignore);
10220
10221     case BUILT_IN_FPUTS:
10222       return fold_builtin_fputs (loc, arg0, arg1, ignore, false, NULL_TREE);
10223
10224     case BUILT_IN_FPUTS_UNLOCKED:
10225       return fold_builtin_fputs (loc, arg0, arg1, ignore, true, NULL_TREE);
10226
10227     case BUILT_IN_STRSTR:
10228       return fold_builtin_strstr (loc, arg0, arg1, type);
10229
10230     case BUILT_IN_STRCAT:
10231       return fold_builtin_strcat (loc, arg0, arg1);
10232
10233     case BUILT_IN_STRSPN:
10234       return fold_builtin_strspn (loc, arg0, arg1);
10235
10236     case BUILT_IN_STRCSPN:
10237       return fold_builtin_strcspn (loc, arg0, arg1);
10238
10239     case BUILT_IN_STRCHR:
10240     case BUILT_IN_INDEX:
10241       return fold_builtin_strchr (loc, arg0, arg1, type);
10242
10243     case BUILT_IN_STRRCHR:
10244     case BUILT_IN_RINDEX:
10245       return fold_builtin_strrchr (loc, arg0, arg1, type);
10246
10247     case BUILT_IN_STRCPY:
10248       return fold_builtin_strcpy (loc, fndecl, arg0, arg1, NULL_TREE);
10249
10250     case BUILT_IN_STPCPY:
10251       if (ignore)
10252         {
10253           tree fn = implicit_built_in_decls[BUILT_IN_STRCPY];
10254           if (!fn)
10255             break;
10256
10257           return build_call_expr_loc (loc, fn, 2, arg0, arg1);
10258         }
10259       else
10260         return fold_builtin_stpcpy (loc, fndecl, arg0, arg1);
10261       break;
10262
10263     case BUILT_IN_STRCMP:
10264       return fold_builtin_strcmp (loc, arg0, arg1);
10265
10266     case BUILT_IN_STRPBRK:
10267       return fold_builtin_strpbrk (loc, arg0, arg1, type);
10268
10269     case BUILT_IN_EXPECT:
10270       return fold_builtin_expect (loc, arg0, arg1);
10271
10272     CASE_FLT_FN (BUILT_IN_POW):
10273       return fold_builtin_pow (loc, fndecl, arg0, arg1, type);
10274
10275     CASE_FLT_FN (BUILT_IN_POWI):
10276       return fold_builtin_powi (loc, fndecl, arg0, arg1, type);
10277
10278     CASE_FLT_FN (BUILT_IN_COPYSIGN):
10279       return fold_builtin_copysign (loc, fndecl, arg0, arg1, type);
10280
10281     CASE_FLT_FN (BUILT_IN_FMIN):
10282       return fold_builtin_fmin_fmax (loc, arg0, arg1, type, /*max=*/false);
10283
10284     CASE_FLT_FN (BUILT_IN_FMAX):
10285       return fold_builtin_fmin_fmax (loc, arg0, arg1, type, /*max=*/true);
10286
10287     case BUILT_IN_ISGREATER:
10288       return fold_builtin_unordered_cmp (loc, fndecl,
10289                                          arg0, arg1, UNLE_EXPR, LE_EXPR);
10290     case BUILT_IN_ISGREATEREQUAL:
10291       return fold_builtin_unordered_cmp (loc, fndecl,
10292                                          arg0, arg1, UNLT_EXPR, LT_EXPR);
10293     case BUILT_IN_ISLESS:
10294       return fold_builtin_unordered_cmp (loc, fndecl,
10295                                          arg0, arg1, UNGE_EXPR, GE_EXPR);
10296     case BUILT_IN_ISLESSEQUAL:
10297       return fold_builtin_unordered_cmp (loc, fndecl,
10298                                          arg0, arg1, UNGT_EXPR, GT_EXPR);
10299     case BUILT_IN_ISLESSGREATER:
10300       return fold_builtin_unordered_cmp (loc, fndecl,
10301                                          arg0, arg1, UNEQ_EXPR, EQ_EXPR);
10302     case BUILT_IN_ISUNORDERED:
10303       return fold_builtin_unordered_cmp (loc, fndecl,
10304                                          arg0, arg1, UNORDERED_EXPR,
10305                                          NOP_EXPR);
10306
10307       /* We do the folding for va_start in the expander.  */
10308     case BUILT_IN_VA_START:
10309       break;
10310
10311     case BUILT_IN_SPRINTF:
10312       return fold_builtin_sprintf (loc, arg0, arg1, NULL_TREE, ignore);
10313
10314     case BUILT_IN_OBJECT_SIZE:
10315       return fold_builtin_object_size (arg0, arg1);
10316
10317     case BUILT_IN_PRINTF:
10318     case BUILT_IN_PRINTF_UNLOCKED:
10319     case BUILT_IN_VPRINTF:
10320       return fold_builtin_printf (loc, fndecl, arg0, arg1, ignore, fcode);
10321
10322     case BUILT_IN_PRINTF_CHK:
10323     case BUILT_IN_VPRINTF_CHK:
10324       if (!validate_arg (arg0, INTEGER_TYPE)
10325           || TREE_SIDE_EFFECTS (arg0))
10326         return NULL_TREE;
10327       else
10328         return fold_builtin_printf (loc, fndecl,
10329                                     arg1, NULL_TREE, ignore, fcode);
10330     break;
10331
10332     case BUILT_IN_FPRINTF:
10333     case BUILT_IN_FPRINTF_UNLOCKED:
10334     case BUILT_IN_VFPRINTF:
10335       return fold_builtin_fprintf (loc, fndecl, arg0, arg1, NULL_TREE,
10336                                    ignore, fcode);
10337
10338     default:
10339       break;
10340     }
10341   return NULL_TREE;
10342 }
10343
10344 /* Fold a call to built-in function FNDECL with 3 arguments, ARG0, ARG1,
10345    and ARG2.  IGNORE is true if the result of the function call is ignored.
10346    This function returns NULL_TREE if no simplification was possible.  */
10347
10348 static tree
10349 fold_builtin_3 (location_t loc, tree fndecl,
10350                 tree arg0, tree arg1, tree arg2, bool ignore)
10351 {
10352   tree type = TREE_TYPE (TREE_TYPE (fndecl));
10353   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
10354   switch (fcode)
10355     {
10356
10357     CASE_FLT_FN (BUILT_IN_SINCOS):
10358       return fold_builtin_sincos (loc, arg0, arg1, arg2);
10359
10360     CASE_FLT_FN (BUILT_IN_FMA):
10361       if (validate_arg (arg0, REAL_TYPE)
10362           && validate_arg(arg1, REAL_TYPE)
10363           && validate_arg(arg2, REAL_TYPE))
10364         return do_mpfr_arg3 (arg0, arg1, arg2, type, mpfr_fma);
10365     break;
10366
10367     CASE_FLT_FN (BUILT_IN_REMQUO):
10368       if (validate_arg (arg0, REAL_TYPE)
10369           && validate_arg(arg1, REAL_TYPE)
10370           && validate_arg(arg2, POINTER_TYPE))
10371         return do_mpfr_remquo (arg0, arg1, arg2);
10372     break;
10373
10374     case BUILT_IN_MEMSET:
10375       return fold_builtin_memset (loc, arg0, arg1, arg2, type, ignore);
10376
10377     case BUILT_IN_BCOPY:
10378       return fold_builtin_memory_op (loc, arg1, arg0, arg2,
10379                                      void_type_node, true, /*endp=*/3);
10380
10381     case BUILT_IN_MEMCPY:
10382       return fold_builtin_memory_op (loc, arg0, arg1, arg2,
10383                                      type, ignore, /*endp=*/0);
10384
10385     case BUILT_IN_MEMPCPY:
10386       return fold_builtin_memory_op (loc, arg0, arg1, arg2,
10387                                      type, ignore, /*endp=*/1);
10388
10389     case BUILT_IN_MEMMOVE:
10390       return fold_builtin_memory_op (loc, arg0, arg1, arg2,
10391                                      type, ignore, /*endp=*/3);
10392
10393     case BUILT_IN_STRNCAT:
10394       return fold_builtin_strncat (loc, arg0, arg1, arg2);
10395
10396     case BUILT_IN_STRNCPY:
10397       return fold_builtin_strncpy (loc, fndecl, arg0, arg1, arg2, NULL_TREE);
10398
10399     case BUILT_IN_STRNCMP:
10400       return fold_builtin_strncmp (loc, arg0, arg1, arg2);
10401
10402     case BUILT_IN_MEMCHR:
10403       return fold_builtin_memchr (loc, arg0, arg1, arg2, type);
10404
10405     case BUILT_IN_BCMP:
10406     case BUILT_IN_MEMCMP:
10407       return fold_builtin_memcmp (loc, arg0, arg1, arg2);;
10408
10409     case BUILT_IN_SPRINTF:
10410       return fold_builtin_sprintf (loc, arg0, arg1, arg2, ignore);
10411
10412     case BUILT_IN_STRCPY_CHK:
10413     case BUILT_IN_STPCPY_CHK:
10414       return fold_builtin_stxcpy_chk (loc, fndecl, arg0, arg1, arg2, NULL_TREE,
10415                                       ignore, fcode);
10416
10417     case BUILT_IN_STRCAT_CHK:
10418       return fold_builtin_strcat_chk (loc, fndecl, arg0, arg1, arg2);
10419
10420     case BUILT_IN_PRINTF_CHK:
10421     case BUILT_IN_VPRINTF_CHK:
10422       if (!validate_arg (arg0, INTEGER_TYPE)
10423           || TREE_SIDE_EFFECTS (arg0))
10424         return NULL_TREE;
10425       else
10426         return fold_builtin_printf (loc, fndecl, arg1, arg2, ignore, fcode);
10427     break;
10428
10429     case BUILT_IN_FPRINTF:
10430     case BUILT_IN_FPRINTF_UNLOCKED:
10431     case BUILT_IN_VFPRINTF:
10432       return fold_builtin_fprintf (loc, fndecl, arg0, arg1, arg2,
10433                                    ignore, fcode);
10434
10435     case BUILT_IN_FPRINTF_CHK:
10436     case BUILT_IN_VFPRINTF_CHK:
10437       if (!validate_arg (arg1, INTEGER_TYPE)
10438           || TREE_SIDE_EFFECTS (arg1))
10439         return NULL_TREE;
10440       else
10441         return fold_builtin_fprintf (loc, fndecl, arg0, arg2, NULL_TREE,
10442                                      ignore, fcode);
10443
10444     default:
10445       break;
10446     }
10447   return NULL_TREE;
10448 }
10449
10450 /* Fold a call to built-in function FNDECL with 4 arguments, ARG0, ARG1,
10451    ARG2, and ARG3.  IGNORE is true if the result of the function call is
10452    ignored.  This function returns NULL_TREE if no simplification was
10453    possible.  */
10454
10455 static tree
10456 fold_builtin_4 (location_t loc, tree fndecl,
10457                 tree arg0, tree arg1, tree arg2, tree arg3, bool ignore)
10458 {
10459   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
10460
10461   switch (fcode)
10462     {
10463     case BUILT_IN_MEMCPY_CHK:
10464     case BUILT_IN_MEMPCPY_CHK:
10465     case BUILT_IN_MEMMOVE_CHK:
10466     case BUILT_IN_MEMSET_CHK:
10467       return fold_builtin_memory_chk (loc, fndecl, arg0, arg1, arg2, arg3,
10468                                       NULL_TREE, ignore,
10469                                       DECL_FUNCTION_CODE (fndecl));
10470
10471     case BUILT_IN_STRNCPY_CHK:
10472       return fold_builtin_strncpy_chk (loc, arg0, arg1, arg2, arg3, NULL_TREE);
10473
10474     case BUILT_IN_STRNCAT_CHK:
10475       return fold_builtin_strncat_chk (loc, fndecl, arg0, arg1, arg2, arg3);
10476
10477     case BUILT_IN_FPRINTF_CHK:
10478     case BUILT_IN_VFPRINTF_CHK:
10479       if (!validate_arg (arg1, INTEGER_TYPE)
10480           || TREE_SIDE_EFFECTS (arg1))
10481         return NULL_TREE;
10482       else
10483         return fold_builtin_fprintf (loc, fndecl, arg0, arg2, arg3,
10484                                      ignore, fcode);
10485     break;
10486
10487     default:
10488       break;
10489     }
10490   return NULL_TREE;
10491 }
10492
10493 /* Fold a call to built-in function FNDECL.  ARGS is an array of NARGS
10494     arguments, where NARGS <= 4.  IGNORE is true if the result of the
10495     function call is ignored.  This function returns NULL_TREE if no
10496     simplification was possible.  Note that this only folds builtins with
10497     fixed argument patterns.  Foldings that do varargs-to-varargs
10498     transformations, or that match calls with more than 4 arguments,
10499     need to be handled with fold_builtin_varargs instead.  */
10500
10501 #define MAX_ARGS_TO_FOLD_BUILTIN 4
10502
10503 static tree
10504 fold_builtin_n (location_t loc, tree fndecl, tree *args, int nargs, bool ignore)
10505 {
10506   tree ret = NULL_TREE;
10507
10508   switch (nargs)
10509     {
10510     case 0:
10511       ret = fold_builtin_0 (loc, fndecl, ignore);
10512       break;
10513     case 1:
10514       ret = fold_builtin_1 (loc, fndecl, args[0], ignore);
10515       break;
10516     case 2:
10517       ret = fold_builtin_2 (loc, fndecl, args[0], args[1], ignore);
10518       break;
10519     case 3:
10520       ret = fold_builtin_3 (loc, fndecl, args[0], args[1], args[2], ignore);
10521       break;
10522     case 4:
10523       ret = fold_builtin_4 (loc, fndecl, args[0], args[1], args[2], args[3],
10524                             ignore);
10525       break;
10526     default:
10527       break;
10528     }
10529   if (ret)
10530     {
10531       ret = build1 (NOP_EXPR, TREE_TYPE (ret), ret);
10532       SET_EXPR_LOCATION (ret, loc);
10533       TREE_NO_WARNING (ret) = 1;
10534       return ret;
10535     }
10536   return NULL_TREE;
10537 }
10538
10539 /* Builtins with folding operations that operate on "..." arguments
10540    need special handling; we need to store the arguments in a convenient
10541    data structure before attempting any folding.  Fortunately there are
10542    only a few builtins that fall into this category.  FNDECL is the
10543    function, EXP is the CALL_EXPR for the call, and IGNORE is true if the
10544    result of the function call is ignored.  */
10545
10546 static tree
10547 fold_builtin_varargs (location_t loc, tree fndecl, tree exp,
10548                       bool ignore ATTRIBUTE_UNUSED)
10549 {
10550   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
10551   tree ret = NULL_TREE;
10552
10553   switch (fcode)
10554     {
10555     case BUILT_IN_SPRINTF_CHK:
10556     case BUILT_IN_VSPRINTF_CHK:
10557       ret = fold_builtin_sprintf_chk (loc, exp, fcode);
10558       break;
10559
10560     case BUILT_IN_SNPRINTF_CHK:
10561     case BUILT_IN_VSNPRINTF_CHK:
10562       ret = fold_builtin_snprintf_chk (loc, exp, NULL_TREE, fcode);
10563       break;
10564
10565     case BUILT_IN_FPCLASSIFY:
10566       ret = fold_builtin_fpclassify (loc, exp);
10567       break;
10568
10569     default:
10570       break;
10571     }
10572   if (ret)
10573     {
10574       ret = build1 (NOP_EXPR, TREE_TYPE (ret), ret);
10575       SET_EXPR_LOCATION (ret, loc);
10576       TREE_NO_WARNING (ret) = 1;
10577       return ret;
10578     }
10579   return NULL_TREE;
10580 }
10581
10582 /* Return true if FNDECL shouldn't be folded right now.
10583    If a built-in function has an inline attribute always_inline
10584    wrapper, defer folding it after always_inline functions have
10585    been inlined, otherwise e.g. -D_FORTIFY_SOURCE checking
10586    might not be performed.  */
10587
10588 static bool
10589 avoid_folding_inline_builtin (tree fndecl)
10590 {
10591   return (DECL_DECLARED_INLINE_P (fndecl)
10592           && DECL_DISREGARD_INLINE_LIMITS (fndecl)
10593           && cfun
10594           && !cfun->always_inline_functions_inlined
10595           && lookup_attribute ("always_inline", DECL_ATTRIBUTES (fndecl)));
10596 }
10597
10598 /* A wrapper function for builtin folding that prevents warnings for
10599    "statement without effect" and the like, caused by removing the
10600    call node earlier than the warning is generated.  */
10601
10602 tree
10603 fold_call_expr (location_t loc, tree exp, bool ignore)
10604 {
10605   tree ret = NULL_TREE;
10606   tree fndecl = get_callee_fndecl (exp);
10607   if (fndecl
10608       && TREE_CODE (fndecl) == FUNCTION_DECL
10609       && DECL_BUILT_IN (fndecl)
10610       /* If CALL_EXPR_VA_ARG_PACK is set, the arguments aren't finalized
10611          yet.  Defer folding until we see all the arguments
10612          (after inlining).  */
10613       && !CALL_EXPR_VA_ARG_PACK (exp))
10614     {
10615       int nargs = call_expr_nargs (exp);
10616
10617       /* Before gimplification CALL_EXPR_VA_ARG_PACK is not set, but
10618          instead last argument is __builtin_va_arg_pack ().  Defer folding
10619          even in that case, until arguments are finalized.  */
10620       if (nargs && TREE_CODE (CALL_EXPR_ARG (exp, nargs - 1)) == CALL_EXPR)
10621         {
10622           tree fndecl2 = get_callee_fndecl (CALL_EXPR_ARG (exp, nargs - 1));
10623           if (fndecl2
10624               && TREE_CODE (fndecl2) == FUNCTION_DECL
10625               && DECL_BUILT_IN_CLASS (fndecl2) == BUILT_IN_NORMAL
10626               && DECL_FUNCTION_CODE (fndecl2) == BUILT_IN_VA_ARG_PACK)
10627             return NULL_TREE;
10628         }
10629
10630       if (avoid_folding_inline_builtin (fndecl))
10631         return NULL_TREE;
10632
10633       if (DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_MD)
10634         return targetm.fold_builtin (fndecl, call_expr_nargs (exp),
10635                                      CALL_EXPR_ARGP (exp), ignore);
10636       else
10637         {
10638           if (nargs <= MAX_ARGS_TO_FOLD_BUILTIN)
10639             {
10640               tree *args = CALL_EXPR_ARGP (exp);
10641               ret = fold_builtin_n (loc, fndecl, args, nargs, ignore);
10642             }
10643           if (!ret)
10644             ret = fold_builtin_varargs (loc, fndecl, exp, ignore);
10645           if (ret)
10646             return ret;
10647         }
10648     }
10649   return NULL_TREE;
10650 }
10651
10652 /* Conveniently construct a function call expression.  FNDECL names the
10653    function to be called and N arguments are passed in the array
10654    ARGARRAY.  */
10655
10656 tree
10657 build_call_expr_loc_array (location_t loc, tree fndecl, int n, tree *argarray)
10658 {
10659   tree fntype = TREE_TYPE (fndecl);
10660   tree fn = build1 (ADDR_EXPR, build_pointer_type (fntype), fndecl);
10661  
10662   return fold_builtin_call_array (loc, TREE_TYPE (fntype), fn, n, argarray);
10663 }
10664
10665 /* Conveniently construct a function call expression.  FNDECL names the
10666    function to be called and the arguments are passed in the vector
10667    VEC.  */
10668
10669 tree
10670 build_call_expr_loc_vec (location_t loc, tree fndecl, VEC(tree,gc) *vec)
10671 {
10672   return build_call_expr_loc_array (loc, fndecl, VEC_length (tree, vec),
10673                                     VEC_address (tree, vec));
10674 }
10675
10676
10677 /* Conveniently construct a function call expression.  FNDECL names the
10678    function to be called, N is the number of arguments, and the "..."
10679    parameters are the argument expressions.  */
10680
10681 tree
10682 build_call_expr_loc (location_t loc, tree fndecl, int n, ...)
10683 {
10684   va_list ap;
10685   tree *argarray = XALLOCAVEC (tree, n);
10686   int i;
10687
10688   va_start (ap, n);
10689   for (i = 0; i < n; i++)
10690     argarray[i] = va_arg (ap, tree);
10691   va_end (ap);
10692   return build_call_expr_loc_array (loc, fndecl, n, argarray);
10693 }
10694
10695 /* Like build_call_expr_loc (UNKNOWN_LOCATION, ...).  Duplicated because
10696    varargs macros aren't supported by all bootstrap compilers.  */
10697
10698 tree
10699 build_call_expr (tree fndecl, int n, ...)
10700 {
10701   va_list ap;
10702   tree *argarray = XALLOCAVEC (tree, n);
10703   int i;
10704
10705   va_start (ap, n);
10706   for (i = 0; i < n; i++)
10707     argarray[i] = va_arg (ap, tree);
10708   va_end (ap);
10709   return build_call_expr_loc_array (UNKNOWN_LOCATION, fndecl, n, argarray);
10710 }
10711
10712 /* Construct a CALL_EXPR with type TYPE with FN as the function expression.
10713    N arguments are passed in the array ARGARRAY.  */
10714
10715 tree
10716 fold_builtin_call_array (location_t loc, tree type,
10717                          tree fn,
10718                          int n,
10719                          tree *argarray)
10720 {
10721   tree ret = NULL_TREE;
10722    tree exp;
10723
10724   if (TREE_CODE (fn) == ADDR_EXPR)
10725   {
10726     tree fndecl = TREE_OPERAND (fn, 0);
10727     if (TREE_CODE (fndecl) == FUNCTION_DECL
10728         && DECL_BUILT_IN (fndecl))
10729       {
10730         /* If last argument is __builtin_va_arg_pack (), arguments to this
10731            function are not finalized yet.  Defer folding until they are.  */
10732         if (n && TREE_CODE (argarray[n - 1]) == CALL_EXPR)
10733           {
10734             tree fndecl2 = get_callee_fndecl (argarray[n - 1]);
10735             if (fndecl2
10736                 && TREE_CODE (fndecl2) == FUNCTION_DECL
10737                 && DECL_BUILT_IN_CLASS (fndecl2) == BUILT_IN_NORMAL
10738                 && DECL_FUNCTION_CODE (fndecl2) == BUILT_IN_VA_ARG_PACK)
10739               return build_call_array_loc (loc, type, fn, n, argarray);
10740           }
10741         if (avoid_folding_inline_builtin (fndecl))
10742           return build_call_array_loc (loc, type, fn, n, argarray);
10743         if (DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_MD)
10744           {
10745             ret = targetm.fold_builtin (fndecl, n, argarray, false);
10746             if (ret)
10747               return ret;
10748
10749             return build_call_array_loc (loc, type, fn, n, argarray);
10750           }
10751         else if (n <= MAX_ARGS_TO_FOLD_BUILTIN)
10752           {
10753             /* First try the transformations that don't require consing up
10754                an exp.  */
10755             ret = fold_builtin_n (loc, fndecl, argarray, n, false);
10756             if (ret)
10757               return ret;
10758           }
10759
10760         /* If we got this far, we need to build an exp.  */
10761         exp = build_call_array_loc (loc, type, fn, n, argarray);
10762         ret = fold_builtin_varargs (loc, fndecl, exp, false);
10763         return ret ? ret : exp;
10764       }
10765   }
10766
10767   return build_call_array_loc (loc, type, fn, n, argarray);
10768 }
10769
10770 /* Construct a new CALL_EXPR using the tail of the argument list of EXP
10771    along with N new arguments specified as the "..." parameters.  SKIP
10772    is the number of arguments in EXP to be omitted.  This function is used
10773    to do varargs-to-varargs transformations.  */
10774
10775 static tree
10776 rewrite_call_expr (location_t loc, tree exp, int skip, tree fndecl, int n, ...)
10777 {
10778   int oldnargs = call_expr_nargs (exp);
10779   int nargs = oldnargs - skip + n;
10780   tree fntype = TREE_TYPE (fndecl);
10781   tree fn = build1 (ADDR_EXPR, build_pointer_type (fntype), fndecl);
10782   tree *buffer;
10783
10784   if (n > 0)
10785     {
10786       int i, j;
10787       va_list ap;
10788
10789       buffer = XALLOCAVEC (tree, nargs);
10790       va_start (ap, n);
10791       for (i = 0; i < n; i++)
10792         buffer[i] = va_arg (ap, tree);
10793       va_end (ap);
10794       for (j = skip; j < oldnargs; j++, i++)
10795         buffer[i] = CALL_EXPR_ARG (exp, j);
10796     }
10797   else
10798     buffer = CALL_EXPR_ARGP (exp) + skip;
10799
10800   return fold (build_call_array_loc (loc, TREE_TYPE (exp), fn, nargs, buffer));
10801 }
10802
10803 /* Validate a single argument ARG against a tree code CODE representing
10804    a type.  */
10805
10806 static bool
10807 validate_arg (const_tree arg, enum tree_code code)
10808 {
10809   if (!arg)
10810     return false;
10811   else if (code == POINTER_TYPE)
10812     return POINTER_TYPE_P (TREE_TYPE (arg));
10813   else if (code == INTEGER_TYPE)
10814     return INTEGRAL_TYPE_P (TREE_TYPE (arg));
10815   return code == TREE_CODE (TREE_TYPE (arg));
10816 }
10817
10818 /* This function validates the types of a function call argument list
10819    against a specified list of tree_codes.  If the last specifier is a 0,
10820    that represents an ellipses, otherwise the last specifier must be a
10821    VOID_TYPE.
10822
10823    This is the GIMPLE version of validate_arglist.  Eventually we want to
10824    completely convert builtins.c to work from GIMPLEs and the tree based
10825    validate_arglist will then be removed.  */
10826
10827 bool
10828 validate_gimple_arglist (const_gimple call, ...)
10829 {
10830   enum tree_code code;
10831   bool res = 0;
10832   va_list ap;
10833   const_tree arg;
10834   size_t i;
10835
10836   va_start (ap, call);
10837   i = 0;
10838
10839   do
10840     {
10841       code = (enum tree_code) va_arg (ap, int);
10842       switch (code)
10843         {
10844         case 0:
10845           /* This signifies an ellipses, any further arguments are all ok.  */
10846           res = true;
10847           goto end;
10848         case VOID_TYPE:
10849           /* This signifies an endlink, if no arguments remain, return
10850              true, otherwise return false.  */
10851           res = (i == gimple_call_num_args (call));
10852           goto end;
10853         default:
10854           /* If no parameters remain or the parameter's code does not
10855              match the specified code, return false.  Otherwise continue
10856              checking any remaining arguments.  */
10857           arg = gimple_call_arg (call, i++);
10858           if (!validate_arg (arg, code))
10859             goto end;
10860           break;
10861         }
10862     }
10863   while (1);
10864
10865   /* We need gotos here since we can only have one VA_CLOSE in a
10866      function.  */
10867  end: ;
10868   va_end (ap);
10869
10870   return res;
10871 }
10872
10873 /* This function validates the types of a function call argument list
10874    against a specified list of tree_codes.  If the last specifier is a 0,
10875    that represents an ellipses, otherwise the last specifier must be a
10876    VOID_TYPE.  */
10877
10878 bool
10879 validate_arglist (const_tree callexpr, ...)
10880 {
10881   enum tree_code code;
10882   bool res = 0;
10883   va_list ap;
10884   const_call_expr_arg_iterator iter;
10885   const_tree arg;
10886
10887   va_start (ap, callexpr);
10888   init_const_call_expr_arg_iterator (callexpr, &iter);
10889
10890   do
10891     {
10892       code = (enum tree_code) va_arg (ap, int);
10893       switch (code)
10894         {
10895         case 0:
10896           /* This signifies an ellipses, any further arguments are all ok.  */
10897           res = true;
10898           goto end;
10899         case VOID_TYPE:
10900           /* This signifies an endlink, if no arguments remain, return
10901              true, otherwise return false.  */
10902           res = !more_const_call_expr_args_p (&iter);
10903           goto end;
10904         default:
10905           /* If no parameters remain or the parameter's code does not
10906              match the specified code, return false.  Otherwise continue
10907              checking any remaining arguments.  */
10908           arg = next_const_call_expr_arg (&iter);
10909           if (!validate_arg (arg, code))
10910             goto end;
10911           break;
10912         }
10913     }
10914   while (1);
10915
10916   /* We need gotos here since we can only have one VA_CLOSE in a
10917      function.  */
10918  end: ;
10919   va_end (ap);
10920
10921   return res;
10922 }
10923
10924 /* Default target-specific builtin expander that does nothing.  */
10925
10926 rtx
10927 default_expand_builtin (tree exp ATTRIBUTE_UNUSED,
10928                         rtx target ATTRIBUTE_UNUSED,
10929                         rtx subtarget ATTRIBUTE_UNUSED,
10930                         enum machine_mode mode ATTRIBUTE_UNUSED,
10931                         int ignore ATTRIBUTE_UNUSED)
10932 {
10933   return NULL_RTX;
10934 }
10935
10936 /* Returns true is EXP represents data that would potentially reside
10937    in a readonly section.  */
10938
10939 static bool
10940 readonly_data_expr (tree exp)
10941 {
10942   STRIP_NOPS (exp);
10943
10944   if (TREE_CODE (exp) != ADDR_EXPR)
10945     return false;
10946
10947   exp = get_base_address (TREE_OPERAND (exp, 0));
10948   if (!exp)
10949     return false;
10950
10951   /* Make sure we call decl_readonly_section only for trees it
10952      can handle (since it returns true for everything it doesn't
10953      understand).  */
10954   if (TREE_CODE (exp) == STRING_CST
10955       || TREE_CODE (exp) == CONSTRUCTOR
10956       || (TREE_CODE (exp) == VAR_DECL && TREE_STATIC (exp)))
10957     return decl_readonly_section (exp, 0);
10958   else
10959     return false;
10960 }
10961
10962 /* Simplify a call to the strstr builtin.  S1 and S2 are the arguments
10963    to the call, and TYPE is its return type.
10964
10965    Return NULL_TREE if no simplification was possible, otherwise return the
10966    simplified form of the call as a tree.
10967
10968    The simplified form may be a constant or other expression which
10969    computes the same value, but in a more efficient manner (including
10970    calls to other builtin functions).
10971
10972    The call may contain arguments which need to be evaluated, but
10973    which are not useful to determine the result of the call.  In
10974    this case we return a chain of COMPOUND_EXPRs.  The LHS of each
10975    COMPOUND_EXPR will be an argument which must be evaluated.
10976    COMPOUND_EXPRs are chained through their RHS.  The RHS of the last
10977    COMPOUND_EXPR in the chain will contain the tree for the simplified
10978    form of the builtin function call.  */
10979
10980 static tree
10981 fold_builtin_strstr (location_t loc, tree s1, tree s2, tree type)
10982 {
10983   if (!validate_arg (s1, POINTER_TYPE)
10984       || !validate_arg (s2, POINTER_TYPE))
10985     return NULL_TREE;
10986   else
10987     {
10988       tree fn;
10989       const char *p1, *p2;
10990
10991       p2 = c_getstr (s2);
10992       if (p2 == NULL)
10993         return NULL_TREE;
10994
10995       p1 = c_getstr (s1);
10996       if (p1 != NULL)
10997         {
10998           const char *r = strstr (p1, p2);
10999           tree tem;
11000
11001           if (r == NULL)
11002             return build_int_cst (TREE_TYPE (s1), 0);
11003
11004           /* Return an offset into the constant string argument.  */
11005           tem = fold_build2_loc (loc, POINTER_PLUS_EXPR, TREE_TYPE (s1),
11006                              s1, size_int (r - p1));
11007           return fold_convert_loc (loc, type, tem);
11008         }
11009
11010       /* The argument is const char *, and the result is char *, so we need
11011          a type conversion here to avoid a warning.  */
11012       if (p2[0] == '\0')
11013         return fold_convert_loc (loc, type, s1);
11014
11015       if (p2[1] != '\0')
11016         return NULL_TREE;
11017
11018       fn = implicit_built_in_decls[BUILT_IN_STRCHR];
11019       if (!fn)
11020         return NULL_TREE;
11021
11022       /* New argument list transforming strstr(s1, s2) to
11023          strchr(s1, s2[0]).  */
11024       return build_call_expr_loc (loc, fn, 2, s1, build_int_cst (NULL_TREE, p2[0]));
11025     }
11026 }
11027
11028 /* Simplify a call to the strchr builtin.  S1 and S2 are the arguments to
11029    the call, and TYPE is its return type.
11030
11031    Return NULL_TREE if no simplification was possible, otherwise return the
11032    simplified form of the call as a tree.
11033
11034    The simplified form may be a constant or other expression which
11035    computes the same value, but in a more efficient manner (including
11036    calls to other builtin functions).
11037
11038    The call may contain arguments which need to be evaluated, but
11039    which are not useful to determine the result of the call.  In
11040    this case we return a chain of COMPOUND_EXPRs.  The LHS of each
11041    COMPOUND_EXPR will be an argument which must be evaluated.
11042    COMPOUND_EXPRs are chained through their RHS.  The RHS of the last
11043    COMPOUND_EXPR in the chain will contain the tree for the simplified
11044    form of the builtin function call.  */
11045
11046 static tree
11047 fold_builtin_strchr (location_t loc, tree s1, tree s2, tree type)
11048 {
11049   if (!validate_arg (s1, POINTER_TYPE)
11050       || !validate_arg (s2, INTEGER_TYPE))
11051     return NULL_TREE;
11052   else
11053     {
11054       const char *p1;
11055
11056       if (TREE_CODE (s2) != INTEGER_CST)
11057         return NULL_TREE;
11058
11059       p1 = c_getstr (s1);
11060       if (p1 != NULL)
11061         {
11062           char c;
11063           const char *r;
11064           tree tem;
11065
11066           if (target_char_cast (s2, &c))
11067             return NULL_TREE;
11068
11069           r = strchr (p1, c);
11070
11071           if (r == NULL)
11072             return build_int_cst (TREE_TYPE (s1), 0);
11073
11074           /* Return an offset into the constant string argument.  */
11075           tem = fold_build2_loc (loc, POINTER_PLUS_EXPR, TREE_TYPE (s1),
11076                              s1, size_int (r - p1));
11077           return fold_convert_loc (loc, type, tem);
11078         }
11079       return NULL_TREE;
11080     }
11081 }
11082
11083 /* Simplify a call to the strrchr builtin.  S1 and S2 are the arguments to
11084    the call, and TYPE is its return type.
11085
11086    Return NULL_TREE if no simplification was possible, otherwise return the
11087    simplified form of the call as a tree.
11088
11089    The simplified form may be a constant or other expression which
11090    computes the same value, but in a more efficient manner (including
11091    calls to other builtin functions).
11092
11093    The call may contain arguments which need to be evaluated, but
11094    which are not useful to determine the result of the call.  In
11095    this case we return a chain of COMPOUND_EXPRs.  The LHS of each
11096    COMPOUND_EXPR will be an argument which must be evaluated.
11097    COMPOUND_EXPRs are chained through their RHS.  The RHS of the last
11098    COMPOUND_EXPR in the chain will contain the tree for the simplified
11099    form of the builtin function call.  */
11100
11101 static tree
11102 fold_builtin_strrchr (location_t loc, tree s1, tree s2, tree type)
11103 {
11104   if (!validate_arg (s1, POINTER_TYPE)
11105       || !validate_arg (s2, INTEGER_TYPE))
11106     return NULL_TREE;
11107   else
11108     {
11109       tree fn;
11110       const char *p1;
11111
11112       if (TREE_CODE (s2) != INTEGER_CST)
11113         return NULL_TREE;
11114
11115       p1 = c_getstr (s1);
11116       if (p1 != NULL)
11117         {
11118           char c;
11119           const char *r;
11120           tree tem;
11121
11122           if (target_char_cast (s2, &c))
11123             return NULL_TREE;
11124
11125           r = strrchr (p1, c);
11126
11127           if (r == NULL)
11128             return build_int_cst (TREE_TYPE (s1), 0);
11129
11130           /* Return an offset into the constant string argument.  */
11131           tem = fold_build2_loc (loc, POINTER_PLUS_EXPR, TREE_TYPE (s1),
11132                              s1, size_int (r - p1));
11133           return fold_convert_loc (loc, type, tem);
11134         }
11135
11136       if (! integer_zerop (s2))
11137         return NULL_TREE;
11138
11139       fn = implicit_built_in_decls[BUILT_IN_STRCHR];
11140       if (!fn)
11141         return NULL_TREE;
11142
11143       /* Transform strrchr(s1, '\0') to strchr(s1, '\0').  */
11144       return build_call_expr_loc (loc, fn, 2, s1, s2);
11145     }
11146 }
11147
11148 /* Simplify a call to the strpbrk builtin.  S1 and S2 are the arguments
11149    to the call, and TYPE is its return type.
11150
11151    Return NULL_TREE if no simplification was possible, otherwise return the
11152    simplified form of the call as a tree.
11153
11154    The simplified form may be a constant or other expression which
11155    computes the same value, but in a more efficient manner (including
11156    calls to other builtin functions).
11157
11158    The call may contain arguments which need to be evaluated, but
11159    which are not useful to determine the result of the call.  In
11160    this case we return a chain of COMPOUND_EXPRs.  The LHS of each
11161    COMPOUND_EXPR will be an argument which must be evaluated.
11162    COMPOUND_EXPRs are chained through their RHS.  The RHS of the last
11163    COMPOUND_EXPR in the chain will contain the tree for the simplified
11164    form of the builtin function call.  */
11165
11166 static tree
11167 fold_builtin_strpbrk (location_t loc, tree s1, tree s2, tree type)
11168 {
11169   if (!validate_arg (s1, POINTER_TYPE)
11170       || !validate_arg (s2, POINTER_TYPE))
11171     return NULL_TREE;
11172   else
11173     {
11174       tree fn;
11175       const char *p1, *p2;
11176
11177       p2 = c_getstr (s2);
11178       if (p2 == NULL)
11179         return NULL_TREE;
11180
11181       p1 = c_getstr (s1);
11182       if (p1 != NULL)
11183         {
11184           const char *r = strpbrk (p1, p2);
11185           tree tem;
11186
11187           if (r == NULL)
11188             return build_int_cst (TREE_TYPE (s1), 0);
11189
11190           /* Return an offset into the constant string argument.  */
11191           tem = fold_build2_loc (loc, POINTER_PLUS_EXPR, TREE_TYPE (s1),
11192                              s1, size_int (r - p1));
11193           return fold_convert_loc (loc, type, tem);
11194         }
11195
11196       if (p2[0] == '\0')
11197         /* strpbrk(x, "") == NULL.
11198            Evaluate and ignore s1 in case it had side-effects.  */
11199         return omit_one_operand_loc (loc, TREE_TYPE (s1), integer_zero_node, s1);
11200
11201       if (p2[1] != '\0')
11202         return NULL_TREE;  /* Really call strpbrk.  */
11203
11204       fn = implicit_built_in_decls[BUILT_IN_STRCHR];
11205       if (!fn)
11206         return NULL_TREE;
11207
11208       /* New argument list transforming strpbrk(s1, s2) to
11209          strchr(s1, s2[0]).  */
11210       return build_call_expr_loc (loc, fn, 2, s1, build_int_cst (NULL_TREE, p2[0]));
11211     }
11212 }
11213
11214 /* Simplify a call to the strcat builtin.  DST and SRC are the arguments
11215    to the call.
11216
11217    Return NULL_TREE if no simplification was possible, otherwise return the
11218    simplified form of the call as a tree.
11219
11220    The simplified form may be a constant or other expression which
11221    computes the same value, but in a more efficient manner (including
11222    calls to other builtin functions).
11223
11224    The call may contain arguments which need to be evaluated, but
11225    which are not useful to determine the result of the call.  In
11226    this case we return a chain of COMPOUND_EXPRs.  The LHS of each
11227    COMPOUND_EXPR will be an argument which must be evaluated.
11228    COMPOUND_EXPRs are chained through their RHS.  The RHS of the last
11229    COMPOUND_EXPR in the chain will contain the tree for the simplified
11230    form of the builtin function call.  */
11231
11232 static tree
11233 fold_builtin_strcat (location_t loc ATTRIBUTE_UNUSED, tree dst, tree src)
11234 {
11235   if (!validate_arg (dst, POINTER_TYPE)
11236       || !validate_arg (src, POINTER_TYPE))
11237     return NULL_TREE;
11238   else
11239     {
11240       const char *p = c_getstr (src);
11241
11242       /* If the string length is zero, return the dst parameter.  */
11243       if (p && *p == '\0')
11244         return dst;
11245
11246       if (optimize_insn_for_speed_p ())
11247         {
11248           /* See if we can store by pieces into (dst + strlen(dst)).  */
11249           tree newdst, call;
11250           tree strlen_fn = implicit_built_in_decls[BUILT_IN_STRLEN];
11251           tree strcpy_fn = implicit_built_in_decls[BUILT_IN_STRCPY];
11252
11253           if (!strlen_fn || !strcpy_fn)
11254             return NULL_TREE;
11255
11256           /* If we don't have a movstr we don't want to emit an strcpy
11257              call.  We have to do that if the length of the source string
11258              isn't computable (in that case we can use memcpy probably
11259              later expanding to a sequence of mov instructions).  If we
11260              have movstr instructions we can emit strcpy calls.  */
11261           if (!HAVE_movstr)
11262             {
11263               tree len = c_strlen (src, 1);
11264               if (! len || TREE_SIDE_EFFECTS (len))
11265                 return NULL_TREE;
11266             }
11267
11268           /* Stabilize the argument list.  */
11269           dst = builtin_save_expr (dst);
11270
11271           /* Create strlen (dst).  */
11272           newdst = build_call_expr_loc (loc, strlen_fn, 1, dst);
11273           /* Create (dst p+ strlen (dst)).  */
11274
11275           newdst = fold_build2_loc (loc, POINTER_PLUS_EXPR,
11276                                 TREE_TYPE (dst), dst, newdst);
11277           newdst = builtin_save_expr (newdst);
11278
11279           call = build_call_expr_loc (loc, strcpy_fn, 2, newdst, src);
11280           return build2 (COMPOUND_EXPR, TREE_TYPE (dst), call, dst);
11281         }
11282       return NULL_TREE;
11283     }
11284 }
11285
11286 /* Simplify a call to the strncat builtin.  DST, SRC, and LEN are the
11287    arguments to the call.
11288
11289    Return NULL_TREE if no simplification was possible, otherwise return the
11290    simplified form of the call as a tree.
11291
11292    The simplified form may be a constant or other expression which
11293    computes the same value, but in a more efficient manner (including
11294    calls to other builtin functions).
11295
11296    The call may contain arguments which need to be evaluated, but
11297    which are not useful to determine the result of the call.  In
11298    this case we return a chain of COMPOUND_EXPRs.  The LHS of each
11299    COMPOUND_EXPR will be an argument which must be evaluated.
11300    COMPOUND_EXPRs are chained through their RHS.  The RHS of the last
11301    COMPOUND_EXPR in the chain will contain the tree for the simplified
11302    form of the builtin function call.  */
11303
11304 static tree
11305 fold_builtin_strncat (location_t loc, tree dst, tree src, tree len)
11306 {
11307   if (!validate_arg (dst, POINTER_TYPE)
11308       || !validate_arg (src, POINTER_TYPE)
11309       || !validate_arg (len, INTEGER_TYPE))
11310     return NULL_TREE;
11311   else
11312     {
11313       const char *p = c_getstr (src);
11314
11315       /* If the requested length is zero, or the src parameter string
11316          length is zero, return the dst parameter.  */
11317       if (integer_zerop (len) || (p && *p == '\0'))
11318         return omit_two_operands_loc (loc, TREE_TYPE (dst), dst, src, len);
11319
11320       /* If the requested len is greater than or equal to the string
11321          length, call strcat.  */
11322       if (TREE_CODE (len) == INTEGER_CST && p
11323           && compare_tree_int (len, strlen (p)) >= 0)
11324         {
11325           tree fn = implicit_built_in_decls[BUILT_IN_STRCAT];
11326
11327           /* If the replacement _DECL isn't initialized, don't do the
11328              transformation.  */
11329           if (!fn)
11330             return NULL_TREE;
11331
11332           return build_call_expr_loc (loc, fn, 2, dst, src);
11333         }
11334       return NULL_TREE;
11335     }
11336 }
11337
11338 /* Simplify a call to the strspn builtin.  S1 and S2 are the arguments
11339    to the call.
11340
11341    Return NULL_TREE if no simplification was possible, otherwise return the
11342    simplified form of the call as a tree.
11343
11344    The simplified form may be a constant or other expression which
11345    computes the same value, but in a more efficient manner (including
11346    calls to other builtin functions).
11347
11348    The call may contain arguments which need to be evaluated, but
11349    which are not useful to determine the result of the call.  In
11350    this case we return a chain of COMPOUND_EXPRs.  The LHS of each
11351    COMPOUND_EXPR will be an argument which must be evaluated.
11352    COMPOUND_EXPRs are chained through their RHS.  The RHS of the last
11353    COMPOUND_EXPR in the chain will contain the tree for the simplified
11354    form of the builtin function call.  */
11355
11356 static tree
11357 fold_builtin_strspn (location_t loc, tree s1, tree s2)
11358 {
11359   if (!validate_arg (s1, POINTER_TYPE)
11360       || !validate_arg (s2, POINTER_TYPE))
11361     return NULL_TREE;
11362   else
11363     {
11364       const char *p1 = c_getstr (s1), *p2 = c_getstr (s2);
11365
11366       /* If both arguments are constants, evaluate at compile-time.  */
11367       if (p1 && p2)
11368         {
11369           const size_t r = strspn (p1, p2);
11370           return size_int (r);
11371         }
11372
11373       /* If either argument is "", return NULL_TREE.  */
11374       if ((p1 && *p1 == '\0') || (p2 && *p2 == '\0'))
11375         /* Evaluate and ignore both arguments in case either one has
11376            side-effects.  */
11377         return omit_two_operands_loc (loc, size_type_node, size_zero_node,
11378                                   s1, s2);
11379       return NULL_TREE;
11380     }
11381 }
11382
11383 /* Simplify a call to the strcspn builtin.  S1 and S2 are the arguments
11384    to the call.
11385
11386    Return NULL_TREE if no simplification was possible, otherwise return the
11387    simplified form of the call as a tree.
11388
11389    The simplified form may be a constant or other expression which
11390    computes the same value, but in a more efficient manner (including
11391    calls to other builtin functions).
11392
11393    The call may contain arguments which need to be evaluated, but
11394    which are not useful to determine the result of the call.  In
11395    this case we return a chain of COMPOUND_EXPRs.  The LHS of each
11396    COMPOUND_EXPR will be an argument which must be evaluated.
11397    COMPOUND_EXPRs are chained through their RHS.  The RHS of the last
11398    COMPOUND_EXPR in the chain will contain the tree for the simplified
11399    form of the builtin function call.  */
11400
11401 static tree
11402 fold_builtin_strcspn (location_t loc, tree s1, tree s2)
11403 {
11404   if (!validate_arg (s1, POINTER_TYPE)
11405       || !validate_arg (s2, POINTER_TYPE))
11406     return NULL_TREE;
11407   else
11408     {
11409       const char *p1 = c_getstr (s1), *p2 = c_getstr (s2);
11410
11411       /* If both arguments are constants, evaluate at compile-time.  */
11412       if (p1 && p2)
11413         {
11414           const size_t r = strcspn (p1, p2);
11415           return size_int (r);
11416         }
11417
11418       /* If the first argument is "", return NULL_TREE.  */
11419       if (p1 && *p1 == '\0')
11420         {
11421           /* Evaluate and ignore argument s2 in case it has
11422              side-effects.  */
11423           return omit_one_operand_loc (loc, size_type_node,
11424                                    size_zero_node, s2);
11425         }
11426
11427       /* If the second argument is "", return __builtin_strlen(s1).  */
11428       if (p2 && *p2 == '\0')
11429         {
11430           tree fn = implicit_built_in_decls[BUILT_IN_STRLEN];
11431
11432           /* If the replacement _DECL isn't initialized, don't do the
11433              transformation.  */
11434           if (!fn)
11435             return NULL_TREE;
11436
11437           return build_call_expr_loc (loc, fn, 1, s1);
11438         }
11439       return NULL_TREE;
11440     }
11441 }
11442
11443 /* Fold a call to the fputs builtin.  ARG0 and ARG1 are the arguments
11444    to the call.  IGNORE is true if the value returned
11445    by the builtin will be ignored.  UNLOCKED is true is true if this
11446    actually a call to fputs_unlocked.  If LEN in non-NULL, it represents
11447    the known length of the string.  Return NULL_TREE if no simplification
11448    was possible.  */
11449
11450 tree
11451 fold_builtin_fputs (location_t loc, tree arg0, tree arg1,
11452                     bool ignore, bool unlocked, tree len)
11453 {
11454   /* If we're using an unlocked function, assume the other unlocked
11455      functions exist explicitly.  */
11456   tree const fn_fputc = unlocked ? built_in_decls[BUILT_IN_FPUTC_UNLOCKED]
11457     : implicit_built_in_decls[BUILT_IN_FPUTC];
11458   tree const fn_fwrite = unlocked ? built_in_decls[BUILT_IN_FWRITE_UNLOCKED]
11459     : implicit_built_in_decls[BUILT_IN_FWRITE];
11460
11461   /* If the return value is used, don't do the transformation.  */
11462   if (!ignore)
11463     return NULL_TREE;
11464
11465   /* Verify the arguments in the original call.  */
11466   if (!validate_arg (arg0, POINTER_TYPE)
11467       || !validate_arg (arg1, POINTER_TYPE))
11468     return NULL_TREE;
11469
11470   if (! len)
11471     len = c_strlen (arg0, 0);
11472
11473   /* Get the length of the string passed to fputs.  If the length
11474      can't be determined, punt.  */
11475   if (!len
11476       || TREE_CODE (len) != INTEGER_CST)
11477     return NULL_TREE;
11478
11479   switch (compare_tree_int (len, 1))
11480     {
11481     case -1: /* length is 0, delete the call entirely .  */
11482       return omit_one_operand_loc (loc, integer_type_node,
11483                                integer_zero_node, arg1);;
11484
11485     case 0: /* length is 1, call fputc.  */
11486       {
11487         const char *p = c_getstr (arg0);
11488
11489         if (p != NULL)
11490           {
11491             if (fn_fputc)
11492               return build_call_expr_loc (loc, fn_fputc, 2,
11493                                       build_int_cst (NULL_TREE, p[0]), arg1);
11494             else
11495               return NULL_TREE;
11496           }
11497       }
11498       /* FALLTHROUGH */
11499     case 1: /* length is greater than 1, call fwrite.  */
11500       {
11501         /* If optimizing for size keep fputs.  */
11502         if (optimize_function_for_size_p (cfun))
11503           return NULL_TREE;
11504         /* New argument list transforming fputs(string, stream) to
11505            fwrite(string, 1, len, stream).  */
11506         if (fn_fwrite)
11507           return build_call_expr_loc (loc, fn_fwrite, 4, arg0,
11508                                   size_one_node, len, arg1);
11509         else
11510           return NULL_TREE;
11511       }
11512     default:
11513       gcc_unreachable ();
11514     }
11515   return NULL_TREE;
11516 }
11517
11518 /* Fold the next_arg or va_start call EXP. Returns true if there was an error
11519    produced.  False otherwise.  This is done so that we don't output the error
11520    or warning twice or three times.  */
11521
11522 bool
11523 fold_builtin_next_arg (tree exp, bool va_start_p)
11524 {
11525   tree fntype = TREE_TYPE (current_function_decl);
11526   int nargs = call_expr_nargs (exp);
11527   tree arg;
11528
11529   if (TYPE_ARG_TYPES (fntype) == 0
11530       || (TREE_VALUE (tree_last (TYPE_ARG_TYPES (fntype)))
11531           == void_type_node))
11532     {
11533       error ("%<va_start%> used in function with fixed args");
11534       return true;
11535     }
11536
11537   if (va_start_p)
11538     {
11539       if (va_start_p && (nargs != 2))
11540         {
11541           error ("wrong number of arguments to function %<va_start%>");
11542           return true;
11543         }
11544       arg = CALL_EXPR_ARG (exp, 1);
11545     }
11546   /* We use __builtin_va_start (ap, 0, 0) or __builtin_next_arg (0, 0)
11547      when we checked the arguments and if needed issued a warning.  */
11548   else
11549     {
11550       if (nargs == 0)
11551         {
11552           /* Evidently an out of date version of <stdarg.h>; can't validate
11553              va_start's second argument, but can still work as intended.  */
11554           warning (0, "%<__builtin_next_arg%> called without an argument");
11555           return true;
11556         }
11557       else if (nargs > 1)
11558         {
11559           error ("wrong number of arguments to function %<__builtin_next_arg%>");
11560           return true;
11561         }
11562       arg = CALL_EXPR_ARG (exp, 0);
11563     }
11564
11565   if (TREE_CODE (arg) == SSA_NAME)
11566     arg = SSA_NAME_VAR (arg);
11567
11568   /* We destructively modify the call to be __builtin_va_start (ap, 0)
11569      or __builtin_next_arg (0) the first time we see it, after checking
11570      the arguments and if needed issuing a warning.  */
11571   if (!integer_zerop (arg))
11572     {
11573       tree last_parm = tree_last (DECL_ARGUMENTS (current_function_decl));
11574
11575       /* Strip off all nops for the sake of the comparison.  This
11576          is not quite the same as STRIP_NOPS.  It does more.
11577          We must also strip off INDIRECT_EXPR for C++ reference
11578          parameters.  */
11579       while (CONVERT_EXPR_P (arg)
11580              || TREE_CODE (arg) == INDIRECT_REF)
11581         arg = TREE_OPERAND (arg, 0);
11582       if (arg != last_parm)
11583         {
11584           /* FIXME: Sometimes with the tree optimizers we can get the
11585              not the last argument even though the user used the last
11586              argument.  We just warn and set the arg to be the last
11587              argument so that we will get wrong-code because of
11588              it.  */
11589           warning (0, "second parameter of %<va_start%> not last named argument");
11590         }
11591
11592       /* Undefined by C99 7.15.1.4p4 (va_start):
11593          "If the parameter parmN is declared with the register storage
11594          class, with a function or array type, or with a type that is
11595          not compatible with the type that results after application of
11596          the default argument promotions, the behavior is undefined."
11597       */
11598       else if (DECL_REGISTER (arg))
11599         warning (0, "undefined behaviour when second parameter of "
11600                  "%<va_start%> is declared with %<register%> storage");
11601
11602       /* We want to verify the second parameter just once before the tree
11603          optimizers are run and then avoid keeping it in the tree,
11604          as otherwise we could warn even for correct code like:
11605          void foo (int i, ...)
11606          { va_list ap; i++; va_start (ap, i); va_end (ap); }  */
11607       if (va_start_p)
11608         CALL_EXPR_ARG (exp, 1) = integer_zero_node;
11609       else
11610         CALL_EXPR_ARG (exp, 0) = integer_zero_node;
11611     }
11612   return false;
11613 }
11614
11615
11616 /* Simplify a call to the sprintf builtin with arguments DEST, FMT, and ORIG.
11617    ORIG may be null if this is a 2-argument call.  We don't attempt to
11618    simplify calls with more than 3 arguments.
11619
11620    Return NULL_TREE if no simplification was possible, otherwise return the
11621    simplified form of the call as a tree.  If IGNORED is true, it means that
11622    the caller does not use the returned value of the function.  */
11623
11624 static tree
11625 fold_builtin_sprintf (location_t loc, tree dest, tree fmt,
11626                       tree orig, int ignored)
11627 {
11628   tree call, retval;
11629   const char *fmt_str = NULL;
11630
11631   /* Verify the required arguments in the original call.  We deal with two
11632      types of sprintf() calls: 'sprintf (str, fmt)' and
11633      'sprintf (dest, "%s", orig)'.  */
11634   if (!validate_arg (dest, POINTER_TYPE)
11635       || !validate_arg (fmt, POINTER_TYPE))
11636     return NULL_TREE;
11637   if (orig && !validate_arg (orig, POINTER_TYPE))
11638     return NULL_TREE;
11639
11640   /* Check whether the format is a literal string constant.  */
11641   fmt_str = c_getstr (fmt);
11642   if (fmt_str == NULL)
11643     return NULL_TREE;
11644
11645   call = NULL_TREE;
11646   retval = NULL_TREE;
11647
11648   if (!init_target_chars ())
11649     return NULL_TREE;
11650
11651   /* If the format doesn't contain % args or %%, use strcpy.  */
11652   if (strchr (fmt_str, target_percent) == NULL)
11653     {
11654       tree fn = implicit_built_in_decls[BUILT_IN_STRCPY];
11655
11656       if (!fn)
11657         return NULL_TREE;
11658
11659       /* Don't optimize sprintf (buf, "abc", ptr++).  */
11660       if (orig)
11661         return NULL_TREE;
11662
11663       /* Convert sprintf (str, fmt) into strcpy (str, fmt) when
11664          'format' is known to contain no % formats.  */
11665       call = build_call_expr_loc (loc, fn, 2, dest, fmt);
11666       if (!ignored)
11667         retval = build_int_cst (NULL_TREE, strlen (fmt_str));
11668     }
11669
11670   /* If the format is "%s", use strcpy if the result isn't used.  */
11671   else if (fmt_str && strcmp (fmt_str, target_percent_s) == 0)
11672     {
11673       tree fn;
11674       fn = implicit_built_in_decls[BUILT_IN_STRCPY];
11675
11676       if (!fn)
11677         return NULL_TREE;
11678
11679       /* Don't crash on sprintf (str1, "%s").  */
11680       if (!orig)
11681         return NULL_TREE;
11682
11683       /* Convert sprintf (str1, "%s", str2) into strcpy (str1, str2).  */
11684       if (!ignored)
11685         {
11686           retval = c_strlen (orig, 1);
11687           if (!retval || TREE_CODE (retval) != INTEGER_CST)
11688             return NULL_TREE;
11689         }
11690       call = build_call_expr_loc (loc, fn, 2, dest, orig);
11691     }
11692
11693   if (call && retval)
11694     {
11695       retval = fold_convert_loc
11696         (loc, TREE_TYPE (TREE_TYPE (implicit_built_in_decls[BUILT_IN_SPRINTF])),
11697          retval);
11698       return build2 (COMPOUND_EXPR, TREE_TYPE (retval), call, retval);
11699     }
11700   else
11701     return call;
11702 }
11703
11704 /* Expand a call EXP to __builtin_object_size.  */
11705
11706 rtx
11707 expand_builtin_object_size (tree exp)
11708 {
11709   tree ost;
11710   int object_size_type;
11711   tree fndecl = get_callee_fndecl (exp);
11712
11713   if (!validate_arglist (exp, POINTER_TYPE, INTEGER_TYPE, VOID_TYPE))
11714     {
11715       error ("%Kfirst argument of %D must be a pointer, second integer constant",
11716              exp, fndecl);
11717       expand_builtin_trap ();
11718       return const0_rtx;
11719     }
11720
11721   ost = CALL_EXPR_ARG (exp, 1);
11722   STRIP_NOPS (ost);
11723
11724   if (TREE_CODE (ost) != INTEGER_CST
11725       || tree_int_cst_sgn (ost) < 0
11726       || compare_tree_int (ost, 3) > 0)
11727     {
11728       error ("%Klast argument of %D is not integer constant between 0 and 3",
11729              exp, fndecl);
11730       expand_builtin_trap ();
11731       return const0_rtx;
11732     }
11733
11734   object_size_type = tree_low_cst (ost, 0);
11735
11736   return object_size_type < 2 ? constm1_rtx : const0_rtx;
11737 }
11738
11739 /* Expand EXP, a call to the __mem{cpy,pcpy,move,set}_chk builtin.
11740    FCODE is the BUILT_IN_* to use.
11741    Return NULL_RTX if we failed; the caller should emit a normal call,
11742    otherwise try to get the result in TARGET, if convenient (and in
11743    mode MODE if that's convenient).  */
11744
11745 static rtx
11746 expand_builtin_memory_chk (tree exp, rtx target, enum machine_mode mode,
11747                            enum built_in_function fcode)
11748 {
11749   tree dest, src, len, size;
11750
11751   if (!validate_arglist (exp,
11752                          POINTER_TYPE,
11753                          fcode == BUILT_IN_MEMSET_CHK
11754                          ? INTEGER_TYPE : POINTER_TYPE,
11755                          INTEGER_TYPE, INTEGER_TYPE, VOID_TYPE))
11756     return NULL_RTX;
11757
11758   dest = CALL_EXPR_ARG (exp, 0);
11759   src = CALL_EXPR_ARG (exp, 1);
11760   len = CALL_EXPR_ARG (exp, 2);
11761   size = CALL_EXPR_ARG (exp, 3);
11762
11763   if (! host_integerp (size, 1))
11764     return NULL_RTX;
11765
11766   if (host_integerp (len, 1) || integer_all_onesp (size))
11767     {
11768       tree fn;
11769
11770       if (! integer_all_onesp (size) && tree_int_cst_lt (size, len))
11771         {
11772           warning_at (tree_nonartificial_location (exp),
11773                       0, "%Kcall to %D will always overflow destination buffer",
11774                       exp, get_callee_fndecl (exp));
11775           return NULL_RTX;
11776         }
11777
11778       fn = NULL_TREE;
11779       /* If __builtin_mem{cpy,pcpy,move,set}_chk is used, assume
11780          mem{cpy,pcpy,move,set} is available.  */
11781       switch (fcode)
11782         {
11783         case BUILT_IN_MEMCPY_CHK:
11784           fn = built_in_decls[BUILT_IN_MEMCPY];
11785           break;
11786         case BUILT_IN_MEMPCPY_CHK:
11787           fn = built_in_decls[BUILT_IN_MEMPCPY];
11788           break;
11789         case BUILT_IN_MEMMOVE_CHK:
11790           fn = built_in_decls[BUILT_IN_MEMMOVE];
11791           break;
11792         case BUILT_IN_MEMSET_CHK:
11793           fn = built_in_decls[BUILT_IN_MEMSET];
11794           break;
11795         default:
11796           break;
11797         }
11798
11799       if (! fn)
11800         return NULL_RTX;
11801
11802       fn = build_call_nofold_loc (EXPR_LOCATION (exp), fn, 3, dest, src, len);
11803       gcc_assert (TREE_CODE (fn) == CALL_EXPR);
11804       CALL_EXPR_TAILCALL (fn) = CALL_EXPR_TAILCALL (exp);
11805       return expand_expr (fn, target, mode, EXPAND_NORMAL);
11806     }
11807   else if (fcode == BUILT_IN_MEMSET_CHK)
11808     return NULL_RTX;
11809   else
11810     {
11811       unsigned int dest_align
11812         = get_pointer_alignment (dest, BIGGEST_ALIGNMENT);
11813
11814       /* If DEST is not a pointer type, call the normal function.  */
11815       if (dest_align == 0)
11816         return NULL_RTX;
11817
11818       /* If SRC and DEST are the same (and not volatile), do nothing.  */
11819       if (operand_equal_p (src, dest, 0))
11820         {
11821           tree expr;
11822
11823           if (fcode != BUILT_IN_MEMPCPY_CHK)
11824             {
11825               /* Evaluate and ignore LEN in case it has side-effects.  */
11826               expand_expr (len, const0_rtx, VOIDmode, EXPAND_NORMAL);
11827               return expand_expr (dest, target, mode, EXPAND_NORMAL);
11828             }
11829
11830           expr = fold_build2 (POINTER_PLUS_EXPR, TREE_TYPE (dest), dest, len);
11831           return expand_expr (expr, target, mode, EXPAND_NORMAL);
11832         }
11833
11834       /* __memmove_chk special case.  */
11835       if (fcode == BUILT_IN_MEMMOVE_CHK)
11836         {
11837           unsigned int src_align
11838             = get_pointer_alignment (src, BIGGEST_ALIGNMENT);
11839
11840           if (src_align == 0)
11841             return NULL_RTX;
11842
11843           /* If src is categorized for a readonly section we can use
11844              normal __memcpy_chk.  */
11845           if (readonly_data_expr (src))
11846             {
11847               tree fn = built_in_decls[BUILT_IN_MEMCPY_CHK];
11848               if (!fn)
11849                 return NULL_RTX;
11850               fn = build_call_nofold_loc (EXPR_LOCATION (exp), fn, 4,
11851                                           dest, src, len, size);
11852               gcc_assert (TREE_CODE (fn) == CALL_EXPR);
11853               CALL_EXPR_TAILCALL (fn) = CALL_EXPR_TAILCALL (exp);
11854               return expand_expr (fn, target, mode, EXPAND_NORMAL);
11855             }
11856         }
11857       return NULL_RTX;
11858     }
11859 }
11860
11861 /* Emit warning if a buffer overflow is detected at compile time.  */
11862
11863 static void
11864 maybe_emit_chk_warning (tree exp, enum built_in_function fcode)
11865 {
11866   int is_strlen = 0;
11867   tree len, size;
11868   location_t loc = tree_nonartificial_location (exp);
11869
11870   switch (fcode)
11871     {
11872     case BUILT_IN_STRCPY_CHK:
11873     case BUILT_IN_STPCPY_CHK:
11874     /* For __strcat_chk the warning will be emitted only if overflowing
11875        by at least strlen (dest) + 1 bytes.  */
11876     case BUILT_IN_STRCAT_CHK:
11877       len = CALL_EXPR_ARG (exp, 1);
11878       size = CALL_EXPR_ARG (exp, 2);
11879       is_strlen = 1;
11880       break;
11881     case BUILT_IN_STRNCAT_CHK:
11882     case BUILT_IN_STRNCPY_CHK:
11883       len = CALL_EXPR_ARG (exp, 2);
11884       size = CALL_EXPR_ARG (exp, 3);
11885       break;
11886     case BUILT_IN_SNPRINTF_CHK:
11887     case BUILT_IN_VSNPRINTF_CHK:
11888       len = CALL_EXPR_ARG (exp, 1);
11889       size = CALL_EXPR_ARG (exp, 3);
11890       break;
11891     default:
11892       gcc_unreachable ();
11893     }
11894
11895   if (!len || !size)
11896     return;
11897
11898   if (! host_integerp (size, 1) || integer_all_onesp (size))
11899     return;
11900
11901   if (is_strlen)
11902     {
11903       len = c_strlen (len, 1);
11904       if (! len || ! host_integerp (len, 1) || tree_int_cst_lt (len, size))
11905         return;
11906     }
11907   else if (fcode == BUILT_IN_STRNCAT_CHK)
11908     {
11909       tree src = CALL_EXPR_ARG (exp, 1);
11910       if (! src || ! host_integerp (len, 1) || tree_int_cst_lt (len, size))
11911         return;
11912       src = c_strlen (src, 1);
11913       if (! src || ! host_integerp (src, 1))
11914         {
11915           warning_at (loc, 0, "%Kcall to %D might overflow destination buffer",
11916                       exp, get_callee_fndecl (exp));
11917           return;
11918         }
11919       else if (tree_int_cst_lt (src, size))
11920         return;
11921     }
11922   else if (! host_integerp (len, 1) || ! tree_int_cst_lt (size, len))
11923     return;
11924
11925   warning_at (loc, 0, "%Kcall to %D will always overflow destination buffer",
11926               exp, get_callee_fndecl (exp));
11927 }
11928
11929 /* Emit warning if a buffer overflow is detected at compile time
11930    in __sprintf_chk/__vsprintf_chk calls.  */
11931
11932 static void
11933 maybe_emit_sprintf_chk_warning (tree exp, enum built_in_function fcode)
11934 {
11935   tree size, len, fmt;
11936   const char *fmt_str;
11937   int nargs = call_expr_nargs (exp);
11938
11939   /* Verify the required arguments in the original call.  */
11940
11941   if (nargs < 4)
11942     return;
11943   size = CALL_EXPR_ARG (exp, 2);
11944   fmt = CALL_EXPR_ARG (exp, 3);
11945
11946   if (! host_integerp (size, 1) || integer_all_onesp (size))
11947     return;
11948
11949   /* Check whether the format is a literal string constant.  */
11950   fmt_str = c_getstr (fmt);
11951   if (fmt_str == NULL)
11952     return;
11953
11954   if (!init_target_chars ())
11955     return;
11956
11957   /* If the format doesn't contain % args or %%, we know its size.  */
11958   if (strchr (fmt_str, target_percent) == 0)
11959     len = build_int_cstu (size_type_node, strlen (fmt_str));
11960   /* If the format is "%s" and first ... argument is a string literal,
11961      we know it too.  */
11962   else if (fcode == BUILT_IN_SPRINTF_CHK
11963            && strcmp (fmt_str, target_percent_s) == 0)
11964     {
11965       tree arg;
11966
11967       if (nargs < 5)
11968         return;
11969       arg = CALL_EXPR_ARG (exp, 4);
11970       if (! POINTER_TYPE_P (TREE_TYPE (arg)))
11971         return;
11972
11973       len = c_strlen (arg, 1);
11974       if (!len || ! host_integerp (len, 1))
11975         return;
11976     }
11977   else
11978     return;
11979
11980   if (! tree_int_cst_lt (len, size))
11981     warning_at (tree_nonartificial_location (exp),
11982                 0, "%Kcall to %D will always overflow destination buffer",
11983                 exp, get_callee_fndecl (exp));
11984 }
11985
11986 /* Emit warning if a free is called with address of a variable.  */
11987
11988 static void
11989 maybe_emit_free_warning (tree exp)
11990 {
11991   tree arg = CALL_EXPR_ARG (exp, 0);
11992
11993   STRIP_NOPS (arg);
11994   if (TREE_CODE (arg) != ADDR_EXPR)
11995     return;
11996
11997   arg = get_base_address (TREE_OPERAND (arg, 0));
11998   if (arg == NULL || INDIRECT_REF_P (arg) || TREE_CODE (arg) == MEM_REF)
11999     return;
12000
12001   if (SSA_VAR_P (arg))
12002     warning_at (tree_nonartificial_location (exp),
12003                 0, "%Kattempt to free a non-heap object %qD", exp, arg);
12004   else
12005     warning_at (tree_nonartificial_location (exp),
12006                 0, "%Kattempt to free a non-heap object", exp);
12007 }
12008
12009 /* Fold a call to __builtin_object_size with arguments PTR and OST,
12010    if possible.  */
12011
12012 tree
12013 fold_builtin_object_size (tree ptr, tree ost)
12014 {
12015   unsigned HOST_WIDE_INT bytes;
12016   int object_size_type;
12017
12018   if (!validate_arg (ptr, POINTER_TYPE)
12019       || !validate_arg (ost, INTEGER_TYPE))
12020     return NULL_TREE;
12021
12022   STRIP_NOPS (ost);
12023
12024   if (TREE_CODE (ost) != INTEGER_CST
12025       || tree_int_cst_sgn (ost) < 0
12026       || compare_tree_int (ost, 3) > 0)
12027     return NULL_TREE;
12028
12029   object_size_type = tree_low_cst (ost, 0);
12030
12031   /* __builtin_object_size doesn't evaluate side-effects in its arguments;
12032      if there are any side-effects, it returns (size_t) -1 for types 0 and 1
12033      and (size_t) 0 for types 2 and 3.  */
12034   if (TREE_SIDE_EFFECTS (ptr))
12035     return build_int_cst_type (size_type_node, object_size_type < 2 ? -1 : 0);
12036
12037   if (TREE_CODE (ptr) == ADDR_EXPR)
12038     {
12039       bytes = compute_builtin_object_size (ptr, object_size_type);
12040       if (double_int_fits_to_tree_p (size_type_node,
12041                                      uhwi_to_double_int (bytes)))
12042         return build_int_cstu (size_type_node, bytes);
12043     }
12044   else if (TREE_CODE (ptr) == SSA_NAME)
12045     {
12046       /* If object size is not known yet, delay folding until
12047        later.  Maybe subsequent passes will help determining
12048        it.  */
12049       bytes = compute_builtin_object_size (ptr, object_size_type);
12050       if (bytes != (unsigned HOST_WIDE_INT) (object_size_type < 2 ? -1 : 0)
12051           && double_int_fits_to_tree_p (size_type_node,
12052                                         uhwi_to_double_int (bytes)))
12053         return build_int_cstu (size_type_node, bytes);
12054     }
12055
12056   return NULL_TREE;
12057 }
12058
12059 /* Fold a call to the __mem{cpy,pcpy,move,set}_chk builtin.
12060    DEST, SRC, LEN, and SIZE are the arguments to the call.
12061    IGNORE is true, if return value can be ignored.  FCODE is the BUILT_IN_*
12062    code of the builtin.  If MAXLEN is not NULL, it is maximum length
12063    passed as third argument.  */
12064
12065 tree
12066 fold_builtin_memory_chk (location_t loc, tree fndecl,
12067                          tree dest, tree src, tree len, tree size,
12068                          tree maxlen, bool ignore,
12069                          enum built_in_function fcode)
12070 {
12071   tree fn;
12072
12073   if (!validate_arg (dest, POINTER_TYPE)
12074       || !validate_arg (src,
12075                         (fcode == BUILT_IN_MEMSET_CHK
12076                          ? INTEGER_TYPE : POINTER_TYPE))
12077       || !validate_arg (len, INTEGER_TYPE)
12078       || !validate_arg (size, INTEGER_TYPE))
12079     return NULL_TREE;
12080
12081   /* If SRC and DEST are the same (and not volatile), return DEST
12082      (resp. DEST+LEN for __mempcpy_chk).  */
12083   if (fcode != BUILT_IN_MEMSET_CHK && operand_equal_p (src, dest, 0))
12084     {
12085       if (fcode != BUILT_IN_MEMPCPY_CHK)
12086         return omit_one_operand_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)),
12087                                  dest, len);
12088       else
12089         {
12090           tree temp = fold_build2_loc (loc, POINTER_PLUS_EXPR, TREE_TYPE (dest),
12091                                    dest, len);
12092           return fold_convert_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)), temp);
12093         }
12094     }
12095
12096   if (! host_integerp (size, 1))
12097     return NULL_TREE;
12098
12099   if (! integer_all_onesp (size))
12100     {
12101       if (! host_integerp (len, 1))
12102         {
12103           /* If LEN is not constant, try MAXLEN too.
12104              For MAXLEN only allow optimizing into non-_ocs function
12105              if SIZE is >= MAXLEN, never convert to __ocs_fail ().  */
12106           if (maxlen == NULL_TREE || ! host_integerp (maxlen, 1))
12107             {
12108               if (fcode == BUILT_IN_MEMPCPY_CHK && ignore)
12109                 {
12110                   /* (void) __mempcpy_chk () can be optimized into
12111                      (void) __memcpy_chk ().  */
12112                   fn = built_in_decls[BUILT_IN_MEMCPY_CHK];
12113                   if (!fn)
12114                     return NULL_TREE;
12115
12116                   return build_call_expr_loc (loc, fn, 4, dest, src, len, size);
12117                 }
12118               return NULL_TREE;
12119             }
12120         }
12121       else
12122         maxlen = len;
12123
12124       if (tree_int_cst_lt (size, maxlen))
12125         return NULL_TREE;
12126     }
12127
12128   fn = NULL_TREE;
12129   /* If __builtin_mem{cpy,pcpy,move,set}_chk is used, assume
12130      mem{cpy,pcpy,move,set} is available.  */
12131   switch (fcode)
12132     {
12133     case BUILT_IN_MEMCPY_CHK:
12134       fn = built_in_decls[BUILT_IN_MEMCPY];
12135       break;
12136     case BUILT_IN_MEMPCPY_CHK:
12137       fn = built_in_decls[BUILT_IN_MEMPCPY];
12138       break;
12139     case BUILT_IN_MEMMOVE_CHK:
12140       fn = built_in_decls[BUILT_IN_MEMMOVE];
12141       break;
12142     case BUILT_IN_MEMSET_CHK:
12143       fn = built_in_decls[BUILT_IN_MEMSET];
12144       break;
12145     default:
12146       break;
12147     }
12148
12149   if (!fn)
12150     return NULL_TREE;
12151
12152   return build_call_expr_loc (loc, fn, 3, dest, src, len);
12153 }
12154
12155 /* Fold a call to the __st[rp]cpy_chk builtin.
12156    DEST, SRC, and SIZE are the arguments to the call.
12157    IGNORE is true if return value can be ignored.  FCODE is the BUILT_IN_*
12158    code of the builtin.  If MAXLEN is not NULL, it is maximum length of
12159    strings passed as second argument.  */
12160
12161 tree
12162 fold_builtin_stxcpy_chk (location_t loc, tree fndecl, tree dest,
12163                          tree src, tree size,
12164                          tree maxlen, bool ignore,
12165                          enum built_in_function fcode)
12166 {
12167   tree len, fn;
12168
12169   if (!validate_arg (dest, POINTER_TYPE)
12170       || !validate_arg (src, POINTER_TYPE)
12171       || !validate_arg (size, INTEGER_TYPE))
12172     return NULL_TREE;
12173
12174   /* If SRC and DEST are the same (and not volatile), return DEST.  */
12175   if (fcode == BUILT_IN_STRCPY_CHK && operand_equal_p (src, dest, 0))
12176     return fold_convert_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)), dest);
12177
12178   if (! host_integerp (size, 1))
12179     return NULL_TREE;
12180
12181   if (! integer_all_onesp (size))
12182     {
12183       len = c_strlen (src, 1);
12184       if (! len || ! host_integerp (len, 1))
12185         {
12186           /* If LEN is not constant, try MAXLEN too.
12187              For MAXLEN only allow optimizing into non-_ocs function
12188              if SIZE is >= MAXLEN, never convert to __ocs_fail ().  */
12189           if (maxlen == NULL_TREE || ! host_integerp (maxlen, 1))
12190             {
12191               if (fcode == BUILT_IN_STPCPY_CHK)
12192                 {
12193                   if (! ignore)
12194                     return NULL_TREE;
12195
12196                   /* If return value of __stpcpy_chk is ignored,
12197                      optimize into __strcpy_chk.  */
12198                   fn = built_in_decls[BUILT_IN_STRCPY_CHK];
12199                   if (!fn)
12200                     return NULL_TREE;
12201
12202                   return build_call_expr_loc (loc, fn, 3, dest, src, size);
12203                 }
12204
12205               if (! len || TREE_SIDE_EFFECTS (len))
12206                 return NULL_TREE;
12207
12208               /* If c_strlen returned something, but not a constant,
12209                  transform __strcpy_chk into __memcpy_chk.  */
12210               fn = built_in_decls[BUILT_IN_MEMCPY_CHK];
12211               if (!fn)
12212                 return NULL_TREE;
12213
12214               len = size_binop_loc (loc, PLUS_EXPR, len, ssize_int (1));
12215               return fold_convert_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)),
12216                                        build_call_expr_loc (loc, fn, 4,
12217                                                         dest, src, len, size));
12218             }
12219         }
12220       else
12221         maxlen = len;
12222
12223       if (! tree_int_cst_lt (maxlen, size))
12224         return NULL_TREE;
12225     }
12226
12227   /* If __builtin_st{r,p}cpy_chk is used, assume st{r,p}cpy is available.  */
12228   fn = built_in_decls[fcode == BUILT_IN_STPCPY_CHK
12229                       ? BUILT_IN_STPCPY : BUILT_IN_STRCPY];
12230   if (!fn)
12231     return NULL_TREE;
12232
12233   return build_call_expr_loc (loc, fn, 2, dest, src);
12234 }
12235
12236 /* Fold a call to the __strncpy_chk builtin.  DEST, SRC, LEN, and SIZE
12237    are the arguments to the call.  If MAXLEN is not NULL, it is maximum
12238    length passed as third argument.  */
12239
12240 tree
12241 fold_builtin_strncpy_chk (location_t loc, tree dest, tree src,
12242                           tree len, tree size, tree maxlen)
12243 {
12244   tree fn;
12245
12246   if (!validate_arg (dest, POINTER_TYPE)
12247       || !validate_arg (src, POINTER_TYPE)
12248       || !validate_arg (len, INTEGER_TYPE)
12249       || !validate_arg (size, INTEGER_TYPE))
12250     return NULL_TREE;
12251
12252   if (! host_integerp (size, 1))
12253     return NULL_TREE;
12254
12255   if (! integer_all_onesp (size))
12256     {
12257       if (! host_integerp (len, 1))
12258         {
12259           /* If LEN is not constant, try MAXLEN too.
12260              For MAXLEN only allow optimizing into non-_ocs function
12261              if SIZE is >= MAXLEN, never convert to __ocs_fail ().  */
12262           if (maxlen == NULL_TREE || ! host_integerp (maxlen, 1))
12263             return NULL_TREE;
12264         }
12265       else
12266         maxlen = len;
12267
12268       if (tree_int_cst_lt (size, maxlen))
12269         return NULL_TREE;
12270     }
12271
12272   /* If __builtin_strncpy_chk is used, assume strncpy is available.  */
12273   fn = built_in_decls[BUILT_IN_STRNCPY];
12274   if (!fn)
12275     return NULL_TREE;
12276
12277   return build_call_expr_loc (loc, fn, 3, dest, src, len);
12278 }
12279
12280 /* Fold a call to the __strcat_chk builtin FNDECL.  DEST, SRC, and SIZE
12281    are the arguments to the call.  */
12282
12283 static tree
12284 fold_builtin_strcat_chk (location_t loc, tree fndecl, tree dest,
12285                          tree src, tree size)
12286 {
12287   tree fn;
12288   const char *p;
12289
12290   if (!validate_arg (dest, POINTER_TYPE)
12291       || !validate_arg (src, POINTER_TYPE)
12292       || !validate_arg (size, INTEGER_TYPE))
12293     return NULL_TREE;
12294
12295   p = c_getstr (src);
12296   /* If the SRC parameter is "", return DEST.  */
12297   if (p && *p == '\0')
12298     return omit_one_operand_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)), dest, src);
12299
12300   if (! host_integerp (size, 1) || ! integer_all_onesp (size))
12301     return NULL_TREE;
12302
12303   /* If __builtin_strcat_chk is used, assume strcat is available.  */
12304   fn = built_in_decls[BUILT_IN_STRCAT];
12305   if (!fn)
12306     return NULL_TREE;
12307
12308   return build_call_expr_loc (loc, fn, 2, dest, src);
12309 }
12310
12311 /* Fold a call to the __strncat_chk builtin with arguments DEST, SRC,
12312    LEN, and SIZE.  */
12313
12314 static tree
12315 fold_builtin_strncat_chk (location_t loc, tree fndecl,
12316                           tree dest, tree src, tree len, tree size)
12317 {
12318   tree fn;
12319   const char *p;
12320
12321   if (!validate_arg (dest, POINTER_TYPE)
12322       || !validate_arg (src, POINTER_TYPE)
12323       || !validate_arg (size, INTEGER_TYPE)
12324       || !validate_arg (size, INTEGER_TYPE))
12325     return NULL_TREE;
12326
12327   p = c_getstr (src);
12328   /* If the SRC parameter is "" or if LEN is 0, return DEST.  */
12329   if (p && *p == '\0')
12330     return omit_one_operand_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)), dest, len);
12331   else if (integer_zerop (len))
12332     return omit_one_operand_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)), dest, src);
12333
12334   if (! host_integerp (size, 1))
12335     return NULL_TREE;
12336
12337   if (! integer_all_onesp (size))
12338     {
12339       tree src_len = c_strlen (src, 1);
12340       if (src_len
12341           && host_integerp (src_len, 1)
12342           && host_integerp (len, 1)
12343           && ! tree_int_cst_lt (len, src_len))
12344         {
12345           /* If LEN >= strlen (SRC), optimize into __strcat_chk.  */
12346           fn = built_in_decls[BUILT_IN_STRCAT_CHK];
12347           if (!fn)
12348             return NULL_TREE;
12349
12350           return build_call_expr_loc (loc, fn, 3, dest, src, size);
12351         }
12352       return NULL_TREE;
12353     }
12354
12355   /* If __builtin_strncat_chk is used, assume strncat is available.  */
12356   fn = built_in_decls[BUILT_IN_STRNCAT];
12357   if (!fn)
12358     return NULL_TREE;
12359
12360   return build_call_expr_loc (loc, fn, 3, dest, src, len);
12361 }
12362
12363 /* Fold a call EXP to __{,v}sprintf_chk.  Return NULL_TREE if
12364    a normal call should be emitted rather than expanding the function
12365    inline.  FCODE is either BUILT_IN_SPRINTF_CHK or BUILT_IN_VSPRINTF_CHK.  */
12366
12367 static tree
12368 fold_builtin_sprintf_chk (location_t loc, tree exp,
12369                           enum built_in_function fcode)
12370 {
12371   tree dest, size, len, fn, fmt, flag;
12372   const char *fmt_str;
12373   int nargs = call_expr_nargs (exp);
12374
12375   /* Verify the required arguments in the original call.  */
12376   if (nargs < 4)
12377     return NULL_TREE;
12378   dest = CALL_EXPR_ARG (exp, 0);
12379   if (!validate_arg (dest, POINTER_TYPE))
12380     return NULL_TREE;
12381   flag = CALL_EXPR_ARG (exp, 1);
12382   if (!validate_arg (flag, INTEGER_TYPE))
12383     return NULL_TREE;
12384   size = CALL_EXPR_ARG (exp, 2);
12385   if (!validate_arg (size, INTEGER_TYPE))
12386     return NULL_TREE;
12387   fmt = CALL_EXPR_ARG (exp, 3);
12388   if (!validate_arg (fmt, POINTER_TYPE))
12389     return NULL_TREE;
12390
12391   if (! host_integerp (size, 1))
12392     return NULL_TREE;
12393
12394   len = NULL_TREE;
12395
12396   if (!init_target_chars ())
12397     return NULL_TREE;
12398
12399   /* Check whether the format is a literal string constant.  */
12400   fmt_str = c_getstr (fmt);
12401   if (fmt_str != NULL)
12402     {
12403       /* If the format doesn't contain % args or %%, we know the size.  */
12404       if (strchr (fmt_str, target_percent) == 0)
12405         {
12406           if (fcode != BUILT_IN_SPRINTF_CHK || nargs == 4)
12407             len = build_int_cstu (size_type_node, strlen (fmt_str));
12408         }
12409       /* If the format is "%s" and first ... argument is a string literal,
12410          we know the size too.  */
12411       else if (fcode == BUILT_IN_SPRINTF_CHK
12412                && strcmp (fmt_str, target_percent_s) == 0)
12413         {
12414           tree arg;
12415
12416           if (nargs == 5)
12417             {
12418               arg = CALL_EXPR_ARG (exp, 4);
12419               if (validate_arg (arg, POINTER_TYPE))
12420                 {
12421                   len = c_strlen (arg, 1);
12422                   if (! len || ! host_integerp (len, 1))
12423                     len = NULL_TREE;
12424                 }
12425             }
12426         }
12427     }
12428
12429   if (! integer_all_onesp (size))
12430     {
12431       if (! len || ! tree_int_cst_lt (len, size))
12432         return NULL_TREE;
12433     }
12434
12435   /* Only convert __{,v}sprintf_chk to {,v}sprintf if flag is 0
12436      or if format doesn't contain % chars or is "%s".  */
12437   if (! integer_zerop (flag))
12438     {
12439       if (fmt_str == NULL)
12440         return NULL_TREE;
12441       if (strchr (fmt_str, target_percent) != NULL
12442           && strcmp (fmt_str, target_percent_s))
12443         return NULL_TREE;
12444     }
12445
12446   /* If __builtin_{,v}sprintf_chk is used, assume {,v}sprintf is available.  */
12447   fn = built_in_decls[fcode == BUILT_IN_VSPRINTF_CHK
12448                       ? BUILT_IN_VSPRINTF : BUILT_IN_SPRINTF];
12449   if (!fn)
12450     return NULL_TREE;
12451
12452   return rewrite_call_expr (loc, exp, 4, fn, 2, dest, fmt);
12453 }
12454
12455 /* Fold a call EXP to {,v}snprintf.  Return NULL_TREE if
12456    a normal call should be emitted rather than expanding the function
12457    inline.  FCODE is either BUILT_IN_SNPRINTF_CHK or
12458    BUILT_IN_VSNPRINTF_CHK.  If MAXLEN is not NULL, it is maximum length
12459    passed as second argument.  */
12460
12461 tree
12462 fold_builtin_snprintf_chk (location_t loc, tree exp, tree maxlen,
12463                            enum built_in_function fcode)
12464 {
12465   tree dest, size, len, fn, fmt, flag;
12466   const char *fmt_str;
12467
12468   /* Verify the required arguments in the original call.  */
12469   if (call_expr_nargs (exp) < 5)
12470     return NULL_TREE;
12471   dest = CALL_EXPR_ARG (exp, 0);
12472   if (!validate_arg (dest, POINTER_TYPE))
12473     return NULL_TREE;
12474   len = CALL_EXPR_ARG (exp, 1);
12475   if (!validate_arg (len, INTEGER_TYPE))
12476     return NULL_TREE;
12477   flag = CALL_EXPR_ARG (exp, 2);
12478   if (!validate_arg (flag, INTEGER_TYPE))
12479     return NULL_TREE;
12480   size = CALL_EXPR_ARG (exp, 3);
12481   if (!validate_arg (size, INTEGER_TYPE))
12482     return NULL_TREE;
12483   fmt = CALL_EXPR_ARG (exp, 4);
12484   if (!validate_arg (fmt, POINTER_TYPE))
12485     return NULL_TREE;
12486
12487   if (! host_integerp (size, 1))
12488     return NULL_TREE;
12489
12490   if (! integer_all_onesp (size))
12491     {
12492       if (! host_integerp (len, 1))
12493         {
12494           /* If LEN is not constant, try MAXLEN too.
12495              For MAXLEN only allow optimizing into non-_ocs function
12496              if SIZE is >= MAXLEN, never convert to __ocs_fail ().  */
12497           if (maxlen == NULL_TREE || ! host_integerp (maxlen, 1))
12498             return NULL_TREE;
12499         }
12500       else
12501         maxlen = len;
12502
12503       if (tree_int_cst_lt (size, maxlen))
12504         return NULL_TREE;
12505     }
12506
12507   if (!init_target_chars ())
12508     return NULL_TREE;
12509
12510   /* Only convert __{,v}snprintf_chk to {,v}snprintf if flag is 0
12511      or if format doesn't contain % chars or is "%s".  */
12512   if (! integer_zerop (flag))
12513     {
12514       fmt_str = c_getstr (fmt);
12515       if (fmt_str == NULL)
12516         return NULL_TREE;
12517       if (strchr (fmt_str, target_percent) != NULL
12518           && strcmp (fmt_str, target_percent_s))
12519         return NULL_TREE;
12520     }
12521
12522   /* If __builtin_{,v}snprintf_chk is used, assume {,v}snprintf is
12523      available.  */
12524   fn = built_in_decls[fcode == BUILT_IN_VSNPRINTF_CHK
12525                       ? BUILT_IN_VSNPRINTF : BUILT_IN_SNPRINTF];
12526   if (!fn)
12527     return NULL_TREE;
12528
12529   return rewrite_call_expr (loc, exp, 5, fn, 3, dest, len, fmt);
12530 }
12531
12532 /* Fold a call to the {,v}printf{,_unlocked} and __{,v}printf_chk builtins.
12533    FMT and ARG are the arguments to the call; we don't fold cases with
12534    more than 2 arguments, and ARG may be null if this is a 1-argument case.
12535
12536    Return NULL_TREE if no simplification was possible, otherwise return the
12537    simplified form of the call as a tree.  FCODE is the BUILT_IN_*
12538    code of the function to be simplified.  */
12539
12540 static tree
12541 fold_builtin_printf (location_t loc, tree fndecl, tree fmt,
12542                      tree arg, bool ignore,
12543                      enum built_in_function fcode)
12544 {
12545   tree fn_putchar, fn_puts, newarg, call = NULL_TREE;
12546   const char *fmt_str = NULL;
12547
12548   /* If the return value is used, don't do the transformation.  */
12549   if (! ignore)
12550     return NULL_TREE;
12551
12552   /* Verify the required arguments in the original call.  */
12553   if (!validate_arg (fmt, POINTER_TYPE))
12554     return NULL_TREE;
12555
12556   /* Check whether the format is a literal string constant.  */
12557   fmt_str = c_getstr (fmt);
12558   if (fmt_str == NULL)
12559     return NULL_TREE;
12560
12561   if (fcode == BUILT_IN_PRINTF_UNLOCKED)
12562     {
12563       /* If we're using an unlocked function, assume the other
12564          unlocked functions exist explicitly.  */
12565       fn_putchar = built_in_decls[BUILT_IN_PUTCHAR_UNLOCKED];
12566       fn_puts = built_in_decls[BUILT_IN_PUTS_UNLOCKED];
12567     }
12568   else
12569     {
12570       fn_putchar = implicit_built_in_decls[BUILT_IN_PUTCHAR];
12571       fn_puts = implicit_built_in_decls[BUILT_IN_PUTS];
12572     }
12573
12574   if (!init_target_chars ())
12575     return NULL_TREE;
12576
12577   if (strcmp (fmt_str, target_percent_s) == 0
12578       || strchr (fmt_str, target_percent) == NULL)
12579     {
12580       const char *str;
12581
12582       if (strcmp (fmt_str, target_percent_s) == 0)
12583         {
12584           if (fcode == BUILT_IN_VPRINTF || fcode == BUILT_IN_VPRINTF_CHK)
12585             return NULL_TREE;
12586
12587           if (!arg || !validate_arg (arg, POINTER_TYPE))
12588             return NULL_TREE;
12589
12590           str = c_getstr (arg);
12591           if (str == NULL)
12592             return NULL_TREE;
12593         }
12594       else
12595         {
12596           /* The format specifier doesn't contain any '%' characters.  */
12597           if (fcode != BUILT_IN_VPRINTF && fcode != BUILT_IN_VPRINTF_CHK
12598               && arg)
12599             return NULL_TREE;
12600           str = fmt_str;
12601         }
12602
12603       /* If the string was "", printf does nothing.  */
12604       if (str[0] == '\0')
12605         return build_int_cst (TREE_TYPE (TREE_TYPE (fndecl)), 0);
12606
12607       /* If the string has length of 1, call putchar.  */
12608       if (str[1] == '\0')
12609         {
12610           /* Given printf("c"), (where c is any one character,)
12611              convert "c"[0] to an int and pass that to the replacement
12612              function.  */
12613           newarg = build_int_cst (NULL_TREE, str[0]);
12614           if (fn_putchar)
12615             call = build_call_expr_loc (loc, fn_putchar, 1, newarg);
12616         }
12617       else
12618         {
12619           /* If the string was "string\n", call puts("string").  */
12620           size_t len = strlen (str);
12621           if ((unsigned char)str[len - 1] == target_newline)
12622             {
12623               /* Create a NUL-terminated string that's one char shorter
12624                  than the original, stripping off the trailing '\n'.  */
12625               char *newstr = XALLOCAVEC (char, len);
12626               memcpy (newstr, str, len - 1);
12627               newstr[len - 1] = 0;
12628
12629               newarg = build_string_literal (len, newstr);
12630               if (fn_puts)
12631                 call = build_call_expr_loc (loc, fn_puts, 1, newarg);
12632             }
12633           else
12634             /* We'd like to arrange to call fputs(string,stdout) here,
12635                but we need stdout and don't have a way to get it yet.  */
12636             return NULL_TREE;
12637         }
12638     }
12639
12640   /* The other optimizations can be done only on the non-va_list variants.  */
12641   else if (fcode == BUILT_IN_VPRINTF || fcode == BUILT_IN_VPRINTF_CHK)
12642     return NULL_TREE;
12643
12644   /* If the format specifier was "%s\n", call __builtin_puts(arg).  */
12645   else if (strcmp (fmt_str, target_percent_s_newline) == 0)
12646     {
12647       if (!arg || !validate_arg (arg, POINTER_TYPE))
12648         return NULL_TREE;
12649       if (fn_puts)
12650         call = build_call_expr_loc (loc, fn_puts, 1, arg);
12651     }
12652
12653   /* If the format specifier was "%c", call __builtin_putchar(arg).  */
12654   else if (strcmp (fmt_str, target_percent_c) == 0)
12655     {
12656       if (!arg || !validate_arg (arg, INTEGER_TYPE))
12657         return NULL_TREE;
12658       if (fn_putchar)
12659         call = build_call_expr_loc (loc, fn_putchar, 1, arg);
12660     }
12661
12662   if (!call)
12663     return NULL_TREE;
12664
12665   return fold_convert_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)), call);
12666 }
12667
12668 /* Fold a call to the {,v}fprintf{,_unlocked} and __{,v}printf_chk builtins.
12669    FP, FMT, and ARG are the arguments to the call.  We don't fold calls with
12670    more than 3 arguments, and ARG may be null in the 2-argument case.
12671
12672    Return NULL_TREE if no simplification was possible, otherwise return the
12673    simplified form of the call as a tree.  FCODE is the BUILT_IN_*
12674    code of the function to be simplified.  */
12675
12676 static tree
12677 fold_builtin_fprintf (location_t loc, tree fndecl, tree fp,
12678                       tree fmt, tree arg, bool ignore,
12679                       enum built_in_function fcode)
12680 {
12681   tree fn_fputc, fn_fputs, call = NULL_TREE;
12682   const char *fmt_str = NULL;
12683
12684   /* If the return value is used, don't do the transformation.  */
12685   if (! ignore)
12686     return NULL_TREE;
12687
12688   /* Verify the required arguments in the original call.  */
12689   if (!validate_arg (fp, POINTER_TYPE))
12690     return NULL_TREE;
12691   if (!validate_arg (fmt, POINTER_TYPE))
12692     return NULL_TREE;
12693
12694   /* Check whether the format is a literal string constant.  */
12695   fmt_str = c_getstr (fmt);
12696   if (fmt_str == NULL)
12697     return NULL_TREE;
12698
12699   if (fcode == BUILT_IN_FPRINTF_UNLOCKED)
12700     {
12701       /* If we're using an unlocked function, assume the other
12702          unlocked functions exist explicitly.  */
12703       fn_fputc = built_in_decls[BUILT_IN_FPUTC_UNLOCKED];
12704       fn_fputs = built_in_decls[BUILT_IN_FPUTS_UNLOCKED];
12705     }
12706   else
12707     {
12708       fn_fputc = implicit_built_in_decls[BUILT_IN_FPUTC];
12709       fn_fputs = implicit_built_in_decls[BUILT_IN_FPUTS];
12710     }
12711
12712   if (!init_target_chars ())
12713     return NULL_TREE;
12714
12715   /* If the format doesn't contain % args or %%, use strcpy.  */
12716   if (strchr (fmt_str, target_percent) == NULL)
12717     {
12718       if (fcode != BUILT_IN_VFPRINTF && fcode != BUILT_IN_VFPRINTF_CHK
12719           && arg)
12720         return NULL_TREE;
12721
12722       /* If the format specifier was "", fprintf does nothing.  */
12723       if (fmt_str[0] == '\0')
12724         {
12725           /* If FP has side-effects, just wait until gimplification is
12726              done.  */
12727           if (TREE_SIDE_EFFECTS (fp))
12728             return NULL_TREE;
12729
12730           return build_int_cst (TREE_TYPE (TREE_TYPE (fndecl)), 0);
12731         }
12732
12733       /* When "string" doesn't contain %, replace all cases of
12734          fprintf (fp, string) with fputs (string, fp).  The fputs
12735          builtin will take care of special cases like length == 1.  */
12736       if (fn_fputs)
12737         call = build_call_expr_loc (loc, fn_fputs, 2, fmt, fp);
12738     }
12739
12740   /* The other optimizations can be done only on the non-va_list variants.  */
12741   else if (fcode == BUILT_IN_VFPRINTF || fcode == BUILT_IN_VFPRINTF_CHK)
12742     return NULL_TREE;
12743
12744   /* If the format specifier was "%s", call __builtin_fputs (arg, fp).  */
12745   else if (strcmp (fmt_str, target_percent_s) == 0)
12746     {
12747       if (!arg || !validate_arg (arg, POINTER_TYPE))
12748         return NULL_TREE;
12749       if (fn_fputs)
12750         call = build_call_expr_loc (loc, fn_fputs, 2, arg, fp);
12751     }
12752
12753   /* If the format specifier was "%c", call __builtin_fputc (arg, fp).  */
12754   else if (strcmp (fmt_str, target_percent_c) == 0)
12755     {
12756       if (!arg || !validate_arg (arg, INTEGER_TYPE))
12757         return NULL_TREE;
12758       if (fn_fputc)
12759         call = build_call_expr_loc (loc, fn_fputc, 2, arg, fp);
12760     }
12761
12762   if (!call)
12763     return NULL_TREE;
12764   return fold_convert_loc (loc, TREE_TYPE (TREE_TYPE (fndecl)), call);
12765 }
12766
12767 /* Initialize format string characters in the target charset.  */
12768
12769 static bool
12770 init_target_chars (void)
12771 {
12772   static bool init;
12773   if (!init)
12774     {
12775       target_newline = lang_hooks.to_target_charset ('\n');
12776       target_percent = lang_hooks.to_target_charset ('%');
12777       target_c = lang_hooks.to_target_charset ('c');
12778       target_s = lang_hooks.to_target_charset ('s');
12779       if (target_newline == 0 || target_percent == 0 || target_c == 0
12780           || target_s == 0)
12781         return false;
12782
12783       target_percent_c[0] = target_percent;
12784       target_percent_c[1] = target_c;
12785       target_percent_c[2] = '\0';
12786
12787       target_percent_s[0] = target_percent;
12788       target_percent_s[1] = target_s;
12789       target_percent_s[2] = '\0';
12790
12791       target_percent_s_newline[0] = target_percent;
12792       target_percent_s_newline[1] = target_s;
12793       target_percent_s_newline[2] = target_newline;
12794       target_percent_s_newline[3] = '\0';
12795
12796       init = true;
12797     }
12798   return true;
12799 }
12800
12801 /* Helper function for do_mpfr_arg*().  Ensure M is a normal number
12802    and no overflow/underflow occurred.  INEXACT is true if M was not
12803    exactly calculated.  TYPE is the tree type for the result.  This
12804    function assumes that you cleared the MPFR flags and then
12805    calculated M to see if anything subsequently set a flag prior to
12806    entering this function.  Return NULL_TREE if any checks fail.  */
12807
12808 static tree
12809 do_mpfr_ckconv (mpfr_srcptr m, tree type, int inexact)
12810 {
12811   /* Proceed iff we get a normal number, i.e. not NaN or Inf and no
12812      overflow/underflow occurred.  If -frounding-math, proceed iff the
12813      result of calling FUNC was exact.  */
12814   if (mpfr_number_p (m) && !mpfr_overflow_p () && !mpfr_underflow_p ()
12815       && (!flag_rounding_math || !inexact))
12816     {
12817       REAL_VALUE_TYPE rr;
12818
12819       real_from_mpfr (&rr, m, type, GMP_RNDN);
12820       /* Proceed iff GCC's REAL_VALUE_TYPE can hold the MPFR value,
12821          check for overflow/underflow.  If the REAL_VALUE_TYPE is zero
12822          but the mpft_t is not, then we underflowed in the
12823          conversion.  */
12824       if (real_isfinite (&rr)
12825           && (rr.cl == rvc_zero) == (mpfr_zero_p (m) != 0))
12826         {
12827           REAL_VALUE_TYPE rmode;
12828
12829           real_convert (&rmode, TYPE_MODE (type), &rr);
12830           /* Proceed iff the specified mode can hold the value.  */
12831           if (real_identical (&rmode, &rr))
12832             return build_real (type, rmode);
12833         }
12834     }
12835   return NULL_TREE;
12836 }
12837
12838 /* Helper function for do_mpc_arg*().  Ensure M is a normal complex
12839    number and no overflow/underflow occurred.  INEXACT is true if M
12840    was not exactly calculated.  TYPE is the tree type for the result.
12841    This function assumes that you cleared the MPFR flags and then
12842    calculated M to see if anything subsequently set a flag prior to
12843    entering this function.  Return NULL_TREE if any checks fail, if
12844    FORCE_CONVERT is true, then bypass the checks.  */
12845
12846 static tree
12847 do_mpc_ckconv (mpc_srcptr m, tree type, int inexact, int force_convert)
12848 {
12849   /* Proceed iff we get a normal number, i.e. not NaN or Inf and no
12850      overflow/underflow occurred.  If -frounding-math, proceed iff the
12851      result of calling FUNC was exact.  */
12852   if (force_convert
12853       || (mpfr_number_p (mpc_realref (m)) && mpfr_number_p (mpc_imagref (m))
12854           && !mpfr_overflow_p () && !mpfr_underflow_p ()
12855           && (!flag_rounding_math || !inexact)))
12856     {
12857       REAL_VALUE_TYPE re, im;
12858
12859       real_from_mpfr (&re, mpc_realref (m), TREE_TYPE (type), GMP_RNDN);
12860       real_from_mpfr (&im, mpc_imagref (m), TREE_TYPE (type), GMP_RNDN);
12861       /* Proceed iff GCC's REAL_VALUE_TYPE can hold the MPFR values,
12862          check for overflow/underflow.  If the REAL_VALUE_TYPE is zero
12863          but the mpft_t is not, then we underflowed in the
12864          conversion.  */
12865       if (force_convert
12866           || (real_isfinite (&re) && real_isfinite (&im)
12867               && (re.cl == rvc_zero) == (mpfr_zero_p (mpc_realref (m)) != 0)
12868               && (im.cl == rvc_zero) == (mpfr_zero_p (mpc_imagref (m)) != 0)))
12869         {
12870           REAL_VALUE_TYPE re_mode, im_mode;
12871
12872           real_convert (&re_mode, TYPE_MODE (TREE_TYPE (type)), &re);
12873           real_convert (&im_mode, TYPE_MODE (TREE_TYPE (type)), &im);
12874           /* Proceed iff the specified mode can hold the value.  */
12875           if (force_convert
12876               || (real_identical (&re_mode, &re)
12877                   && real_identical (&im_mode, &im)))
12878             return build_complex (type, build_real (TREE_TYPE (type), re_mode),
12879                                   build_real (TREE_TYPE (type), im_mode));
12880         }
12881     }
12882   return NULL_TREE;
12883 }
12884
12885 /* If argument ARG is a REAL_CST, call the one-argument mpfr function
12886    FUNC on it and return the resulting value as a tree with type TYPE.
12887    If MIN and/or MAX are not NULL, then the supplied ARG must be
12888    within those bounds.  If INCLUSIVE is true, then MIN/MAX are
12889    acceptable values, otherwise they are not.  The mpfr precision is
12890    set to the precision of TYPE.  We assume that function FUNC returns
12891    zero if the result could be calculated exactly within the requested
12892    precision.  */
12893
12894 static tree
12895 do_mpfr_arg1 (tree arg, tree type, int (*func)(mpfr_ptr, mpfr_srcptr, mp_rnd_t),
12896               const REAL_VALUE_TYPE *min, const REAL_VALUE_TYPE *max,
12897               bool inclusive)
12898 {
12899   tree result = NULL_TREE;
12900
12901   STRIP_NOPS (arg);
12902
12903   /* To proceed, MPFR must exactly represent the target floating point
12904      format, which only happens when the target base equals two.  */
12905   if (REAL_MODE_FORMAT (TYPE_MODE (type))->b == 2
12906       && TREE_CODE (arg) == REAL_CST && !TREE_OVERFLOW (arg))
12907     {
12908       const REAL_VALUE_TYPE *const ra = &TREE_REAL_CST (arg);
12909
12910       if (real_isfinite (ra)
12911           && (!min || real_compare (inclusive ? GE_EXPR: GT_EXPR , ra, min))
12912           && (!max || real_compare (inclusive ? LE_EXPR: LT_EXPR , ra, max)))
12913         {
12914           const struct real_format *fmt = REAL_MODE_FORMAT (TYPE_MODE (type));
12915           const int prec = fmt->p;
12916           const mp_rnd_t rnd = fmt->round_towards_zero? GMP_RNDZ : GMP_RNDN;
12917           int inexact;
12918           mpfr_t m;
12919
12920           mpfr_init2 (m, prec);
12921           mpfr_from_real (m, ra, GMP_RNDN);
12922           mpfr_clear_flags ();
12923           inexact = func (m, m, rnd);
12924           result = do_mpfr_ckconv (m, type, inexact);
12925           mpfr_clear (m);
12926         }
12927     }
12928
12929   return result;
12930 }
12931
12932 /* If argument ARG is a REAL_CST, call the two-argument mpfr function
12933    FUNC on it and return the resulting value as a tree with type TYPE.
12934    The mpfr precision is set to the precision of TYPE.  We assume that
12935    function FUNC returns zero if the result could be calculated
12936    exactly within the requested precision.  */
12937
12938 static tree
12939 do_mpfr_arg2 (tree arg1, tree arg2, tree type,
12940               int (*func)(mpfr_ptr, mpfr_srcptr, mpfr_srcptr, mp_rnd_t))
12941 {
12942   tree result = NULL_TREE;
12943
12944   STRIP_NOPS (arg1);
12945   STRIP_NOPS (arg2);
12946
12947   /* To proceed, MPFR must exactly represent the target floating point
12948      format, which only happens when the target base equals two.  */
12949   if (REAL_MODE_FORMAT (TYPE_MODE (type))->b == 2
12950       && TREE_CODE (arg1) == REAL_CST && !TREE_OVERFLOW (arg1)
12951       && TREE_CODE (arg2) == REAL_CST && !TREE_OVERFLOW (arg2))
12952     {
12953       const REAL_VALUE_TYPE *const ra1 = &TREE_REAL_CST (arg1);
12954       const REAL_VALUE_TYPE *const ra2 = &TREE_REAL_CST (arg2);
12955
12956       if (real_isfinite (ra1) && real_isfinite (ra2))
12957         {
12958           const struct real_format *fmt = REAL_MODE_FORMAT (TYPE_MODE (type));
12959           const int prec = fmt->p;
12960           const mp_rnd_t rnd = fmt->round_towards_zero? GMP_RNDZ : GMP_RNDN;
12961           int inexact;
12962           mpfr_t m1, m2;
12963
12964           mpfr_inits2 (prec, m1, m2, NULL);
12965           mpfr_from_real (m1, ra1, GMP_RNDN);
12966           mpfr_from_real (m2, ra2, GMP_RNDN);
12967           mpfr_clear_flags ();
12968           inexact = func (m1, m1, m2, rnd);
12969           result = do_mpfr_ckconv (m1, type, inexact);
12970           mpfr_clears (m1, m2, NULL);
12971         }
12972     }
12973
12974   return result;
12975 }
12976
12977 /* If argument ARG is a REAL_CST, call the three-argument mpfr function
12978    FUNC on it and return the resulting value as a tree with type TYPE.
12979    The mpfr precision is set to the precision of TYPE.  We assume that
12980    function FUNC returns zero if the result could be calculated
12981    exactly within the requested precision.  */
12982
12983 static tree
12984 do_mpfr_arg3 (tree arg1, tree arg2, tree arg3, tree type,
12985               int (*func)(mpfr_ptr, mpfr_srcptr, mpfr_srcptr, mpfr_srcptr, mp_rnd_t))
12986 {
12987   tree result = NULL_TREE;
12988
12989   STRIP_NOPS (arg1);
12990   STRIP_NOPS (arg2);
12991   STRIP_NOPS (arg3);
12992
12993   /* To proceed, MPFR must exactly represent the target floating point
12994      format, which only happens when the target base equals two.  */
12995   if (REAL_MODE_FORMAT (TYPE_MODE (type))->b == 2
12996       && TREE_CODE (arg1) == REAL_CST && !TREE_OVERFLOW (arg1)
12997       && TREE_CODE (arg2) == REAL_CST && !TREE_OVERFLOW (arg2)
12998       && TREE_CODE (arg3) == REAL_CST && !TREE_OVERFLOW (arg3))
12999     {
13000       const REAL_VALUE_TYPE *const ra1 = &TREE_REAL_CST (arg1);
13001       const REAL_VALUE_TYPE *const ra2 = &TREE_REAL_CST (arg2);
13002       const REAL_VALUE_TYPE *const ra3 = &TREE_REAL_CST (arg3);
13003
13004       if (real_isfinite (ra1) && real_isfinite (ra2) && real_isfinite (ra3))
13005         {
13006           const struct real_format *fmt = REAL_MODE_FORMAT (TYPE_MODE (type));
13007           const int prec = fmt->p;
13008           const mp_rnd_t rnd = fmt->round_towards_zero? GMP_RNDZ : GMP_RNDN;
13009           int inexact;
13010           mpfr_t m1, m2, m3;
13011
13012           mpfr_inits2 (prec, m1, m2, m3, NULL);
13013           mpfr_from_real (m1, ra1, GMP_RNDN);
13014           mpfr_from_real (m2, ra2, GMP_RNDN);
13015           mpfr_from_real (m3, ra3, GMP_RNDN);
13016           mpfr_clear_flags ();
13017           inexact = func (m1, m1, m2, m3, rnd);
13018           result = do_mpfr_ckconv (m1, type, inexact);
13019           mpfr_clears (m1, m2, m3, NULL);
13020         }
13021     }
13022
13023   return result;
13024 }
13025
13026 /* If argument ARG is a REAL_CST, call mpfr_sin_cos() on it and set
13027    the pointers *(ARG_SINP) and *(ARG_COSP) to the resulting values.
13028    If ARG_SINP and ARG_COSP are NULL then the result is returned
13029    as a complex value.
13030    The type is taken from the type of ARG and is used for setting the
13031    precision of the calculation and results.  */
13032
13033 static tree
13034 do_mpfr_sincos (tree arg, tree arg_sinp, tree arg_cosp)
13035 {
13036   tree const type = TREE_TYPE (arg);
13037   tree result = NULL_TREE;
13038
13039   STRIP_NOPS (arg);
13040
13041   /* To proceed, MPFR must exactly represent the target floating point
13042      format, which only happens when the target base equals two.  */
13043   if (REAL_MODE_FORMAT (TYPE_MODE (type))->b == 2
13044       && TREE_CODE (arg) == REAL_CST
13045       && !TREE_OVERFLOW (arg))
13046     {
13047       const REAL_VALUE_TYPE *const ra = &TREE_REAL_CST (arg);
13048
13049       if (real_isfinite (ra))
13050         {
13051           const struct real_format *fmt = REAL_MODE_FORMAT (TYPE_MODE (type));
13052           const int prec = fmt->p;
13053           const mp_rnd_t rnd = fmt->round_towards_zero? GMP_RNDZ : GMP_RNDN;
13054           tree result_s, result_c;
13055           int inexact;
13056           mpfr_t m, ms, mc;
13057
13058           mpfr_inits2 (prec, m, ms, mc, NULL);
13059           mpfr_from_real (m, ra, GMP_RNDN);
13060           mpfr_clear_flags ();
13061           inexact = mpfr_sin_cos (ms, mc, m, rnd);
13062           result_s = do_mpfr_ckconv (ms, type, inexact);
13063           result_c = do_mpfr_ckconv (mc, type, inexact);
13064           mpfr_clears (m, ms, mc, NULL);
13065           if (result_s && result_c)
13066             {
13067               /* If we are to return in a complex value do so.  */
13068               if (!arg_sinp && !arg_cosp)
13069                 return build_complex (build_complex_type (type),
13070                                       result_c, result_s);
13071
13072               /* Dereference the sin/cos pointer arguments.  */
13073               arg_sinp = build_fold_indirect_ref (arg_sinp);
13074               arg_cosp = build_fold_indirect_ref (arg_cosp);
13075               /* Proceed if valid pointer type were passed in.  */
13076               if (TYPE_MAIN_VARIANT (TREE_TYPE (arg_sinp)) == TYPE_MAIN_VARIANT (type)
13077                   && TYPE_MAIN_VARIANT (TREE_TYPE (arg_cosp)) == TYPE_MAIN_VARIANT (type))
13078                 {
13079                   /* Set the values. */
13080                   result_s = fold_build2 (MODIFY_EXPR, type, arg_sinp,
13081                                           result_s);
13082                   TREE_SIDE_EFFECTS (result_s) = 1;
13083                   result_c = fold_build2 (MODIFY_EXPR, type, arg_cosp,
13084                                           result_c);
13085                   TREE_SIDE_EFFECTS (result_c) = 1;
13086                   /* Combine the assignments into a compound expr.  */
13087                   result = non_lvalue (fold_build2 (COMPOUND_EXPR, type,
13088                                                     result_s, result_c));
13089                 }
13090             }
13091         }
13092     }
13093   return result;
13094 }
13095
13096 /* If argument ARG1 is an INTEGER_CST and ARG2 is a REAL_CST, call the
13097    two-argument mpfr order N Bessel function FUNC on them and return
13098    the resulting value as a tree with type TYPE.  The mpfr precision
13099    is set to the precision of TYPE.  We assume that function FUNC
13100    returns zero if the result could be calculated exactly within the
13101    requested precision.  */
13102 static tree
13103 do_mpfr_bessel_n (tree arg1, tree arg2, tree type,
13104                   int (*func)(mpfr_ptr, long, mpfr_srcptr, mp_rnd_t),
13105                   const REAL_VALUE_TYPE *min, bool inclusive)
13106 {
13107   tree result = NULL_TREE;
13108
13109   STRIP_NOPS (arg1);
13110   STRIP_NOPS (arg2);
13111
13112   /* To proceed, MPFR must exactly represent the target floating point
13113      format, which only happens when the target base equals two.  */
13114   if (REAL_MODE_FORMAT (TYPE_MODE (type))->b == 2
13115       && host_integerp (arg1, 0)
13116       && TREE_CODE (arg2) == REAL_CST && !TREE_OVERFLOW (arg2))
13117     {
13118       const HOST_WIDE_INT n = tree_low_cst(arg1, 0);
13119       const REAL_VALUE_TYPE *const ra = &TREE_REAL_CST (arg2);
13120
13121       if (n == (long)n
13122           && real_isfinite (ra)
13123           && (!min || real_compare (inclusive ? GE_EXPR: GT_EXPR , ra, min)))
13124         {
13125           const struct real_format *fmt = REAL_MODE_FORMAT (TYPE_MODE (type));
13126           const int prec = fmt->p;
13127           const mp_rnd_t rnd = fmt->round_towards_zero? GMP_RNDZ : GMP_RNDN;
13128           int inexact;
13129           mpfr_t m;
13130
13131           mpfr_init2 (m, prec);
13132           mpfr_from_real (m, ra, GMP_RNDN);
13133           mpfr_clear_flags ();
13134           inexact = func (m, n, m, rnd);
13135           result = do_mpfr_ckconv (m, type, inexact);
13136           mpfr_clear (m);
13137         }
13138     }
13139
13140   return result;
13141 }
13142
13143 /* If arguments ARG0 and ARG1 are REAL_CSTs, call mpfr_remquo() to set
13144    the pointer *(ARG_QUO) and return the result.  The type is taken
13145    from the type of ARG0 and is used for setting the precision of the
13146    calculation and results.  */
13147
13148 static tree
13149 do_mpfr_remquo (tree arg0, tree arg1, tree arg_quo)
13150 {
13151   tree const type = TREE_TYPE (arg0);
13152   tree result = NULL_TREE;
13153
13154   STRIP_NOPS (arg0);
13155   STRIP_NOPS (arg1);
13156
13157   /* To proceed, MPFR must exactly represent the target floating point
13158      format, which only happens when the target base equals two.  */
13159   if (REAL_MODE_FORMAT (TYPE_MODE (type))->b == 2
13160       && TREE_CODE (arg0) == REAL_CST && !TREE_OVERFLOW (arg0)
13161       && TREE_CODE (arg1) == REAL_CST && !TREE_OVERFLOW (arg1))
13162     {
13163       const REAL_VALUE_TYPE *const ra0 = TREE_REAL_CST_PTR (arg0);
13164       const REAL_VALUE_TYPE *const ra1 = TREE_REAL_CST_PTR (arg1);
13165
13166       if (real_isfinite (ra0) && real_isfinite (ra1))
13167         {
13168           const struct real_format *fmt = REAL_MODE_FORMAT (TYPE_MODE (type));
13169           const int prec = fmt->p;
13170           const mp_rnd_t rnd = fmt->round_towards_zero? GMP_RNDZ : GMP_RNDN;
13171           tree result_rem;
13172           long integer_quo;
13173           mpfr_t m0, m1;
13174
13175           mpfr_inits2 (prec, m0, m1, NULL);
13176           mpfr_from_real (m0, ra0, GMP_RNDN);
13177           mpfr_from_real (m1, ra1, GMP_RNDN);
13178           mpfr_clear_flags ();
13179           mpfr_remquo (m0, &integer_quo, m0, m1, rnd);
13180           /* Remquo is independent of the rounding mode, so pass
13181              inexact=0 to do_mpfr_ckconv().  */
13182           result_rem = do_mpfr_ckconv (m0, type, /*inexact=*/ 0);
13183           mpfr_clears (m0, m1, NULL);
13184           if (result_rem)
13185             {
13186               /* MPFR calculates quo in the host's long so it may
13187                  return more bits in quo than the target int can hold
13188                  if sizeof(host long) > sizeof(target int).  This can
13189                  happen even for native compilers in LP64 mode.  In
13190                  these cases, modulo the quo value with the largest
13191                  number that the target int can hold while leaving one
13192                  bit for the sign.  */
13193               if (sizeof (integer_quo) * CHAR_BIT > INT_TYPE_SIZE)
13194                 integer_quo %= (long)(1UL << (INT_TYPE_SIZE - 1));
13195
13196               /* Dereference the quo pointer argument.  */
13197               arg_quo = build_fold_indirect_ref (arg_quo);
13198               /* Proceed iff a valid pointer type was passed in.  */
13199               if (TYPE_MAIN_VARIANT (TREE_TYPE (arg_quo)) == integer_type_node)
13200                 {
13201                   /* Set the value. */
13202                   tree result_quo = fold_build2 (MODIFY_EXPR,
13203                                                  TREE_TYPE (arg_quo), arg_quo,
13204                                                  build_int_cst (NULL, integer_quo));
13205                   TREE_SIDE_EFFECTS (result_quo) = 1;
13206                   /* Combine the quo assignment with the rem.  */
13207                   result = non_lvalue (fold_build2 (COMPOUND_EXPR, type,
13208                                                     result_quo, result_rem));
13209                 }
13210             }
13211         }
13212     }
13213   return result;
13214 }
13215
13216 /* If ARG is a REAL_CST, call mpfr_lgamma() on it and return the
13217    resulting value as a tree with type TYPE.  The mpfr precision is
13218    set to the precision of TYPE.  We assume that this mpfr function
13219    returns zero if the result could be calculated exactly within the
13220    requested precision.  In addition, the integer pointer represented
13221    by ARG_SG will be dereferenced and set to the appropriate signgam
13222    (-1,1) value.  */
13223
13224 static tree
13225 do_mpfr_lgamma_r (tree arg, tree arg_sg, tree type)
13226 {
13227   tree result = NULL_TREE;
13228
13229   STRIP_NOPS (arg);
13230
13231   /* To proceed, MPFR must exactly represent the target floating point
13232      format, which only happens when the target base equals two.  Also
13233      verify ARG is a constant and that ARG_SG is an int pointer.  */
13234   if (REAL_MODE_FORMAT (TYPE_MODE (type))->b == 2
13235       && TREE_CODE (arg) == REAL_CST && !TREE_OVERFLOW (arg)
13236       && TREE_CODE (TREE_TYPE (arg_sg)) == POINTER_TYPE
13237       && TYPE_MAIN_VARIANT (TREE_TYPE (TREE_TYPE (arg_sg))) == integer_type_node)
13238     {
13239       const REAL_VALUE_TYPE *const ra = TREE_REAL_CST_PTR (arg);
13240
13241       /* In addition to NaN and Inf, the argument cannot be zero or a
13242          negative integer.  */
13243       if (real_isfinite (ra)
13244           && ra->cl != rvc_zero
13245           && !(real_isneg(ra) && real_isinteger(ra, TYPE_MODE (type))))
13246         {
13247           const struct real_format *fmt = REAL_MODE_FORMAT (TYPE_MODE (type));
13248           const int prec = fmt->p;
13249           const mp_rnd_t rnd = fmt->round_towards_zero? GMP_RNDZ : GMP_RNDN;
13250           int inexact, sg;
13251           mpfr_t m;
13252           tree result_lg;
13253
13254           mpfr_init2 (m, prec);
13255           mpfr_from_real (m, ra, GMP_RNDN);
13256           mpfr_clear_flags ();
13257           inexact = mpfr_lgamma (m, &sg, m, rnd);
13258           result_lg = do_mpfr_ckconv (m, type, inexact);
13259           mpfr_clear (m);
13260           if (result_lg)
13261             {
13262               tree result_sg;
13263
13264               /* Dereference the arg_sg pointer argument.  */
13265               arg_sg = build_fold_indirect_ref (arg_sg);
13266               /* Assign the signgam value into *arg_sg. */
13267               result_sg = fold_build2 (MODIFY_EXPR,
13268                                        TREE_TYPE (arg_sg), arg_sg,
13269                                        build_int_cst (NULL, sg));
13270               TREE_SIDE_EFFECTS (result_sg) = 1;
13271               /* Combine the signgam assignment with the lgamma result.  */
13272               result = non_lvalue (fold_build2 (COMPOUND_EXPR, type,
13273                                                 result_sg, result_lg));
13274             }
13275         }
13276     }
13277
13278   return result;
13279 }
13280
13281 /* If argument ARG is a COMPLEX_CST, call the one-argument mpc
13282    function FUNC on it and return the resulting value as a tree with
13283    type TYPE.  The mpfr precision is set to the precision of TYPE.  We
13284    assume that function FUNC returns zero if the result could be
13285    calculated exactly within the requested precision.  */
13286
13287 static tree
13288 do_mpc_arg1 (tree arg, tree type, int (*func)(mpc_ptr, mpc_srcptr, mpc_rnd_t))
13289 {
13290   tree result = NULL_TREE;
13291
13292   STRIP_NOPS (arg);
13293
13294   /* To proceed, MPFR must exactly represent the target floating point
13295      format, which only happens when the target base equals two.  */
13296   if (TREE_CODE (arg) == COMPLEX_CST && !TREE_OVERFLOW (arg)
13297       && TREE_CODE (TREE_TYPE (TREE_TYPE (arg))) == REAL_TYPE
13298       && REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (TREE_TYPE (arg))))->b == 2)
13299     {
13300       const REAL_VALUE_TYPE *const re = TREE_REAL_CST_PTR (TREE_REALPART (arg));
13301       const REAL_VALUE_TYPE *const im = TREE_REAL_CST_PTR (TREE_IMAGPART (arg));
13302
13303       if (real_isfinite (re) && real_isfinite (im))
13304         {
13305           const struct real_format *const fmt =
13306             REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (type)));
13307           const int prec = fmt->p;
13308           const mp_rnd_t rnd = fmt->round_towards_zero ? GMP_RNDZ : GMP_RNDN;
13309           const mpc_rnd_t crnd = fmt->round_towards_zero ? MPC_RNDZZ : MPC_RNDNN;
13310           int inexact;
13311           mpc_t m;
13312
13313           mpc_init2 (m, prec);
13314           mpfr_from_real (mpc_realref(m), re, rnd);
13315           mpfr_from_real (mpc_imagref(m), im, rnd);
13316           mpfr_clear_flags ();
13317           inexact = func (m, m, crnd);
13318           result = do_mpc_ckconv (m, type, inexact, /*force_convert=*/ 0);
13319           mpc_clear (m);
13320         }
13321     }
13322
13323   return result;
13324 }
13325
13326 /* If arguments ARG0 and ARG1 are a COMPLEX_CST, call the two-argument
13327    mpc function FUNC on it and return the resulting value as a tree
13328    with type TYPE.  The mpfr precision is set to the precision of
13329    TYPE.  We assume that function FUNC returns zero if the result
13330    could be calculated exactly within the requested precision.  If
13331    DO_NONFINITE is true, then fold expressions containing Inf or NaN
13332    in the arguments and/or results.  */
13333
13334 tree
13335 do_mpc_arg2 (tree arg0, tree arg1, tree type, int do_nonfinite,
13336              int (*func)(mpc_ptr, mpc_srcptr, mpc_srcptr, mpc_rnd_t))
13337 {
13338   tree result = NULL_TREE;
13339
13340   STRIP_NOPS (arg0);
13341   STRIP_NOPS (arg1);
13342
13343   /* To proceed, MPFR must exactly represent the target floating point
13344      format, which only happens when the target base equals two.  */
13345   if (TREE_CODE (arg0) == COMPLEX_CST && !TREE_OVERFLOW (arg0)
13346       && TREE_CODE (TREE_TYPE (TREE_TYPE (arg0))) == REAL_TYPE
13347       && TREE_CODE (arg1) == COMPLEX_CST && !TREE_OVERFLOW (arg1)
13348       && TREE_CODE (TREE_TYPE (TREE_TYPE (arg1))) == REAL_TYPE
13349       && REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (TREE_TYPE (arg0))))->b == 2)
13350     {
13351       const REAL_VALUE_TYPE *const re0 = TREE_REAL_CST_PTR (TREE_REALPART (arg0));
13352       const REAL_VALUE_TYPE *const im0 = TREE_REAL_CST_PTR (TREE_IMAGPART (arg0));
13353       const REAL_VALUE_TYPE *const re1 = TREE_REAL_CST_PTR (TREE_REALPART (arg1));
13354       const REAL_VALUE_TYPE *const im1 = TREE_REAL_CST_PTR (TREE_IMAGPART (arg1));
13355
13356       if (do_nonfinite
13357           || (real_isfinite (re0) && real_isfinite (im0)
13358               && real_isfinite (re1) && real_isfinite (im1)))
13359         {
13360           const struct real_format *const fmt =
13361             REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (type)));
13362           const int prec = fmt->p;
13363           const mp_rnd_t rnd = fmt->round_towards_zero ? GMP_RNDZ : GMP_RNDN;
13364           const mpc_rnd_t crnd = fmt->round_towards_zero ? MPC_RNDZZ : MPC_RNDNN;
13365           int inexact;
13366           mpc_t m0, m1;
13367
13368           mpc_init2 (m0, prec);
13369           mpc_init2 (m1, prec);
13370           mpfr_from_real (mpc_realref(m0), re0, rnd);
13371           mpfr_from_real (mpc_imagref(m0), im0, rnd);
13372           mpfr_from_real (mpc_realref(m1), re1, rnd);
13373           mpfr_from_real (mpc_imagref(m1), im1, rnd);
13374           mpfr_clear_flags ();
13375           inexact = func (m0, m0, m1, crnd);
13376           result = do_mpc_ckconv (m0, type, inexact, do_nonfinite);
13377           mpc_clear (m0);
13378           mpc_clear (m1);
13379         }
13380     }
13381
13382   return result;
13383 }
13384
13385 /* FIXME tuples.
13386    The functions below provide an alternate interface for folding
13387    builtin function calls presented as GIMPLE_CALL statements rather
13388    than as CALL_EXPRs.  The folded result is still expressed as a
13389    tree.  There is too much code duplication in the handling of
13390    varargs functions, and a more intrusive re-factoring would permit
13391    better sharing of code between the tree and statement-based
13392    versions of these functions.  */
13393
13394 /* Construct a new CALL_EXPR using the tail of the argument list of STMT
13395    along with N new arguments specified as the "..." parameters.  SKIP
13396    is the number of arguments in STMT to be omitted.  This function is used
13397    to do varargs-to-varargs transformations.  */
13398
13399 static tree
13400 gimple_rewrite_call_expr (gimple stmt, int skip, tree fndecl, int n, ...)
13401 {
13402   int oldnargs = gimple_call_num_args (stmt);
13403   int nargs = oldnargs - skip + n;
13404   tree fntype = TREE_TYPE (fndecl);
13405   tree fn = build1 (ADDR_EXPR, build_pointer_type (fntype), fndecl);
13406   tree *buffer;
13407   int i, j;
13408   va_list ap;
13409   location_t loc = gimple_location (stmt);
13410
13411   buffer = XALLOCAVEC (tree, nargs);
13412   va_start (ap, n);
13413   for (i = 0; i < n; i++)
13414     buffer[i] = va_arg (ap, tree);
13415   va_end (ap);
13416   for (j = skip; j < oldnargs; j++, i++)
13417     buffer[i] = gimple_call_arg (stmt, j);
13418
13419   return fold (build_call_array_loc (loc, TREE_TYPE (fntype), fn, nargs, buffer));
13420 }
13421
13422 /* Fold a call STMT to __{,v}sprintf_chk.  Return NULL_TREE if
13423    a normal call should be emitted rather than expanding the function
13424    inline.  FCODE is either BUILT_IN_SPRINTF_CHK or BUILT_IN_VSPRINTF_CHK.  */
13425
13426 static tree
13427 gimple_fold_builtin_sprintf_chk (gimple stmt, enum built_in_function fcode)
13428 {
13429   tree dest, size, len, fn, fmt, flag;
13430   const char *fmt_str;
13431   int nargs = gimple_call_num_args (stmt);
13432
13433   /* Verify the required arguments in the original call.  */
13434   if (nargs < 4)
13435     return NULL_TREE;
13436   dest = gimple_call_arg (stmt, 0);
13437   if (!validate_arg (dest, POINTER_TYPE))
13438     return NULL_TREE;
13439   flag = gimple_call_arg (stmt, 1);
13440   if (!validate_arg (flag, INTEGER_TYPE))
13441     return NULL_TREE;
13442   size = gimple_call_arg (stmt, 2);
13443   if (!validate_arg (size, INTEGER_TYPE))
13444     return NULL_TREE;
13445   fmt = gimple_call_arg (stmt, 3);
13446   if (!validate_arg (fmt, POINTER_TYPE))
13447     return NULL_TREE;
13448
13449   if (! host_integerp (size, 1))
13450     return NULL_TREE;
13451
13452   len = NULL_TREE;
13453
13454   if (!init_target_chars ())
13455     return NULL_TREE;
13456
13457   /* Check whether the format is a literal string constant.  */
13458   fmt_str = c_getstr (fmt);
13459   if (fmt_str != NULL)
13460     {
13461       /* If the format doesn't contain % args or %%, we know the size.  */
13462       if (strchr (fmt_str, target_percent) == 0)
13463         {
13464           if (fcode != BUILT_IN_SPRINTF_CHK || nargs == 4)
13465             len = build_int_cstu (size_type_node, strlen (fmt_str));
13466         }
13467       /* If the format is "%s" and first ... argument is a string literal,
13468          we know the size too.  */
13469       else if (fcode == BUILT_IN_SPRINTF_CHK
13470                && strcmp (fmt_str, target_percent_s) == 0)
13471         {
13472           tree arg;
13473
13474           if (nargs == 5)
13475             {
13476               arg = gimple_call_arg (stmt, 4);
13477               if (validate_arg (arg, POINTER_TYPE))
13478                 {
13479                   len = c_strlen (arg, 1);
13480                   if (! len || ! host_integerp (len, 1))
13481                     len = NULL_TREE;
13482                 }
13483             }
13484         }
13485     }
13486
13487   if (! integer_all_onesp (size))
13488     {
13489       if (! len || ! tree_int_cst_lt (len, size))
13490         return NULL_TREE;
13491     }
13492
13493   /* Only convert __{,v}sprintf_chk to {,v}sprintf if flag is 0
13494      or if format doesn't contain % chars or is "%s".  */
13495   if (! integer_zerop (flag))
13496     {
13497       if (fmt_str == NULL)
13498         return NULL_TREE;
13499       if (strchr (fmt_str, target_percent) != NULL
13500           && strcmp (fmt_str, target_percent_s))
13501         return NULL_TREE;
13502     }
13503
13504   /* If __builtin_{,v}sprintf_chk is used, assume {,v}sprintf is available.  */
13505   fn = built_in_decls[fcode == BUILT_IN_VSPRINTF_CHK
13506                       ? BUILT_IN_VSPRINTF : BUILT_IN_SPRINTF];
13507   if (!fn)
13508     return NULL_TREE;
13509
13510   return gimple_rewrite_call_expr (stmt, 4, fn, 2, dest, fmt);
13511 }
13512
13513 /* Fold a call STMT to {,v}snprintf.  Return NULL_TREE if
13514    a normal call should be emitted rather than expanding the function
13515    inline.  FCODE is either BUILT_IN_SNPRINTF_CHK or
13516    BUILT_IN_VSNPRINTF_CHK.  If MAXLEN is not NULL, it is maximum length
13517    passed as second argument.  */
13518
13519 tree
13520 gimple_fold_builtin_snprintf_chk (gimple stmt, tree maxlen,
13521                                   enum built_in_function fcode)
13522 {
13523   tree dest, size, len, fn, fmt, flag;
13524   const char *fmt_str;
13525
13526   /* Verify the required arguments in the original call.  */
13527   if (gimple_call_num_args (stmt) < 5)
13528     return NULL_TREE;
13529   dest = gimple_call_arg (stmt, 0);
13530   if (!validate_arg (dest, POINTER_TYPE))
13531     return NULL_TREE;
13532   len = gimple_call_arg (stmt, 1);
13533   if (!validate_arg (len, INTEGER_TYPE))
13534     return NULL_TREE;
13535   flag = gimple_call_arg (stmt, 2);
13536   if (!validate_arg (flag, INTEGER_TYPE))
13537     return NULL_TREE;
13538   size = gimple_call_arg (stmt, 3);
13539   if (!validate_arg (size, INTEGER_TYPE))
13540     return NULL_TREE;
13541   fmt = gimple_call_arg (stmt, 4);
13542   if (!validate_arg (fmt, POINTER_TYPE))
13543     return NULL_TREE;
13544
13545   if (! host_integerp (size, 1))
13546     return NULL_TREE;
13547
13548   if (! integer_all_onesp (size))
13549     {
13550       if (! host_integerp (len, 1))
13551         {
13552           /* If LEN is not constant, try MAXLEN too.
13553              For MAXLEN only allow optimizing into non-_ocs function
13554              if SIZE is >= MAXLEN, never convert to __ocs_fail ().  */
13555           if (maxlen == NULL_TREE || ! host_integerp (maxlen, 1))
13556             return NULL_TREE;
13557         }
13558       else
13559         maxlen = len;
13560
13561       if (tree_int_cst_lt (size, maxlen))
13562         return NULL_TREE;
13563     }
13564
13565   if (!init_target_chars ())
13566     return NULL_TREE;
13567
13568   /* Only convert __{,v}snprintf_chk to {,v}snprintf if flag is 0
13569      or if format doesn't contain % chars or is "%s".  */
13570   if (! integer_zerop (flag))
13571     {
13572       fmt_str = c_getstr (fmt);
13573       if (fmt_str == NULL)
13574         return NULL_TREE;
13575       if (strchr (fmt_str, target_percent) != NULL
13576           && strcmp (fmt_str, target_percent_s))
13577         return NULL_TREE;
13578     }
13579
13580   /* If __builtin_{,v}snprintf_chk is used, assume {,v}snprintf is
13581      available.  */
13582   fn = built_in_decls[fcode == BUILT_IN_VSNPRINTF_CHK
13583                       ? BUILT_IN_VSNPRINTF : BUILT_IN_SNPRINTF];
13584   if (!fn)
13585     return NULL_TREE;
13586
13587   return gimple_rewrite_call_expr (stmt, 5, fn, 3, dest, len, fmt);
13588 }
13589
13590 /* Builtins with folding operations that operate on "..." arguments
13591    need special handling; we need to store the arguments in a convenient
13592    data structure before attempting any folding.  Fortunately there are
13593    only a few builtins that fall into this category.  FNDECL is the
13594    function, EXP is the CALL_EXPR for the call, and IGNORE is true if the
13595    result of the function call is ignored.  */
13596
13597 static tree
13598 gimple_fold_builtin_varargs (tree fndecl, gimple stmt,
13599                              bool ignore ATTRIBUTE_UNUSED)
13600 {
13601   enum built_in_function fcode = DECL_FUNCTION_CODE (fndecl);
13602   tree ret = NULL_TREE;
13603
13604   switch (fcode)
13605     {
13606     case BUILT_IN_SPRINTF_CHK:
13607     case BUILT_IN_VSPRINTF_CHK:
13608       ret = gimple_fold_builtin_sprintf_chk (stmt, fcode);
13609       break;
13610
13611     case BUILT_IN_SNPRINTF_CHK:
13612     case BUILT_IN_VSNPRINTF_CHK:
13613       ret = gimple_fold_builtin_snprintf_chk (stmt, NULL_TREE, fcode);
13614
13615     default:
13616       break;
13617     }
13618   if (ret)
13619     {
13620       ret = build1 (NOP_EXPR, TREE_TYPE (ret), ret);
13621       TREE_NO_WARNING (ret) = 1;
13622       return ret;
13623     }
13624   return NULL_TREE;
13625 }
13626
13627 /* A wrapper function for builtin folding that prevents warnings for
13628    "statement without effect" and the like, caused by removing the
13629    call node earlier than the warning is generated.  */
13630
13631 tree
13632 fold_call_stmt (gimple stmt, bool ignore)
13633 {
13634   tree ret = NULL_TREE;
13635   tree fndecl = gimple_call_fndecl (stmt);
13636   location_t loc = gimple_location (stmt);
13637   if (fndecl
13638       && TREE_CODE (fndecl) == FUNCTION_DECL
13639       && DECL_BUILT_IN (fndecl)
13640       && !gimple_call_va_arg_pack_p (stmt))
13641     {
13642       int nargs = gimple_call_num_args (stmt);
13643
13644       if (avoid_folding_inline_builtin (fndecl))
13645         return NULL_TREE;
13646       if (DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_MD)
13647         {
13648           return targetm.fold_builtin (fndecl, nargs,
13649                                        (nargs > 0
13650                                         ? gimple_call_arg_ptr (stmt, 0)
13651                                         : &error_mark_node), ignore);
13652         }
13653       else
13654         {
13655           if (nargs <= MAX_ARGS_TO_FOLD_BUILTIN)
13656             {
13657               tree args[MAX_ARGS_TO_FOLD_BUILTIN];
13658               int i;
13659               for (i = 0; i < nargs; i++)
13660                 args[i] = gimple_call_arg (stmt, i);
13661               ret = fold_builtin_n (loc, fndecl, args, nargs, ignore);
13662             }
13663           if (!ret)
13664             ret = gimple_fold_builtin_varargs (fndecl, stmt, ignore);
13665           if (ret)
13666             {
13667               /* Propagate location information from original call to
13668                  expansion of builtin.  Otherwise things like
13669                  maybe_emit_chk_warning, that operate on the expansion
13670                  of a builtin, will use the wrong location information.  */
13671               if (gimple_has_location (stmt))
13672                 {
13673                   tree realret = ret;
13674                   if (TREE_CODE (ret) == NOP_EXPR)
13675                     realret = TREE_OPERAND (ret, 0);
13676                   if (CAN_HAVE_LOCATION_P (realret)
13677                       && !EXPR_HAS_LOCATION (realret))
13678                     SET_EXPR_LOCATION (realret, loc);
13679                   return realret;
13680                 }
13681               return ret;
13682             }
13683         }
13684     }
13685   return NULL_TREE;
13686 }
13687
13688 /* Look up the function in built_in_decls that corresponds to DECL
13689    and set ASMSPEC as its user assembler name.  DECL must be a
13690    function decl that declares a builtin.  */
13691
13692 void
13693 set_builtin_user_assembler_name (tree decl, const char *asmspec)
13694 {
13695   tree builtin;
13696   gcc_assert (TREE_CODE (decl) == FUNCTION_DECL
13697               && DECL_BUILT_IN_CLASS (decl) == BUILT_IN_NORMAL
13698               && asmspec != 0);
13699
13700   builtin = built_in_decls [DECL_FUNCTION_CODE (decl)];
13701   set_user_assembler_name (builtin, asmspec);
13702   switch (DECL_FUNCTION_CODE (decl))
13703     {
13704     case BUILT_IN_MEMCPY:
13705       init_block_move_fn (asmspec);
13706       memcpy_libfunc = set_user_assembler_libfunc ("memcpy", asmspec);
13707       break;
13708     case BUILT_IN_MEMSET:
13709       init_block_clear_fn (asmspec);
13710       memset_libfunc = set_user_assembler_libfunc ("memset", asmspec);
13711       break;
13712     case BUILT_IN_MEMMOVE:
13713       memmove_libfunc = set_user_assembler_libfunc ("memmove", asmspec);
13714       break;
13715     case BUILT_IN_MEMCMP:
13716       memcmp_libfunc = set_user_assembler_libfunc ("memcmp", asmspec);
13717       break;
13718     case BUILT_IN_ABORT:
13719       abort_libfunc = set_user_assembler_libfunc ("abort", asmspec);
13720       break;
13721     case BUILT_IN_FFS:
13722       if (INT_TYPE_SIZE < BITS_PER_WORD)
13723         {
13724           set_user_assembler_libfunc ("ffs", asmspec);
13725           set_optab_libfunc (ffs_optab, mode_for_size (INT_TYPE_SIZE,
13726                                                        MODE_INT, 0), "ffs");
13727         }
13728       break;
13729     default:
13730       break;
13731     }
13732 }
13733
13734 /* Return true if DECL is a builtin that expands to a constant or similarly
13735    simple code.  */
13736 bool
13737 is_simple_builtin (tree decl)
13738 {
13739   if (decl && DECL_BUILT_IN_CLASS (decl) == BUILT_IN_NORMAL)
13740     switch (DECL_FUNCTION_CODE (decl))
13741       {
13742         /* Builtins that expand to constants.  */
13743       case BUILT_IN_CONSTANT_P:
13744       case BUILT_IN_EXPECT:
13745       case BUILT_IN_OBJECT_SIZE:
13746       case BUILT_IN_UNREACHABLE:
13747         /* Simple register moves or loads from stack.  */
13748       case BUILT_IN_RETURN_ADDRESS:
13749       case BUILT_IN_EXTRACT_RETURN_ADDR:
13750       case BUILT_IN_FROB_RETURN_ADDR:
13751       case BUILT_IN_RETURN:
13752       case BUILT_IN_AGGREGATE_INCOMING_ADDRESS:
13753       case BUILT_IN_FRAME_ADDRESS:
13754       case BUILT_IN_VA_END:
13755       case BUILT_IN_STACK_SAVE:
13756       case BUILT_IN_STACK_RESTORE:
13757         /* Exception state returns or moves registers around.  */
13758       case BUILT_IN_EH_FILTER:
13759       case BUILT_IN_EH_POINTER:
13760       case BUILT_IN_EH_COPY_VALUES:
13761         return true;
13762
13763       default:
13764         return false;
13765       }
13766
13767   return false;
13768 }
13769
13770 /* Return true if DECL is a builtin that is not expensive, i.e., they are
13771    most probably expanded inline into reasonably simple code.  This is a
13772    superset of is_simple_builtin.  */
13773 bool
13774 is_inexpensive_builtin (tree decl)
13775 {
13776   if (!decl)
13777     return false;
13778   else if (DECL_BUILT_IN_CLASS (decl) == BUILT_IN_MD)
13779     return true;
13780   else if (DECL_BUILT_IN_CLASS (decl) == BUILT_IN_NORMAL)
13781     switch (DECL_FUNCTION_CODE (decl))
13782       {
13783       case BUILT_IN_ABS:
13784       case BUILT_IN_ALLOCA:
13785       case BUILT_IN_BSWAP32:
13786       case BUILT_IN_BSWAP64:
13787       case BUILT_IN_CLZ:
13788       case BUILT_IN_CLZIMAX:
13789       case BUILT_IN_CLZL:
13790       case BUILT_IN_CLZLL:
13791       case BUILT_IN_CTZ:
13792       case BUILT_IN_CTZIMAX:
13793       case BUILT_IN_CTZL:
13794       case BUILT_IN_CTZLL:
13795       case BUILT_IN_FFS:
13796       case BUILT_IN_FFSIMAX:
13797       case BUILT_IN_FFSL:
13798       case BUILT_IN_FFSLL:
13799       case BUILT_IN_IMAXABS:
13800       case BUILT_IN_FINITE:
13801       case BUILT_IN_FINITEF:
13802       case BUILT_IN_FINITEL:
13803       case BUILT_IN_FINITED32:
13804       case BUILT_IN_FINITED64:
13805       case BUILT_IN_FINITED128:
13806       case BUILT_IN_FPCLASSIFY:
13807       case BUILT_IN_ISFINITE:
13808       case BUILT_IN_ISINF_SIGN:
13809       case BUILT_IN_ISINF:
13810       case BUILT_IN_ISINFF:
13811       case BUILT_IN_ISINFL:
13812       case BUILT_IN_ISINFD32:
13813       case BUILT_IN_ISINFD64:
13814       case BUILT_IN_ISINFD128:
13815       case BUILT_IN_ISNAN:
13816       case BUILT_IN_ISNANF:
13817       case BUILT_IN_ISNANL:
13818       case BUILT_IN_ISNAND32:
13819       case BUILT_IN_ISNAND64:
13820       case BUILT_IN_ISNAND128:
13821       case BUILT_IN_ISNORMAL:
13822       case BUILT_IN_ISGREATER:
13823       case BUILT_IN_ISGREATEREQUAL:
13824       case BUILT_IN_ISLESS:
13825       case BUILT_IN_ISLESSEQUAL:
13826       case BUILT_IN_ISLESSGREATER:
13827       case BUILT_IN_ISUNORDERED:
13828       case BUILT_IN_VA_ARG_PACK:
13829       case BUILT_IN_VA_ARG_PACK_LEN:
13830       case BUILT_IN_VA_COPY:
13831       case BUILT_IN_TRAP:
13832       case BUILT_IN_SAVEREGS:
13833       case BUILT_IN_POPCOUNTL:
13834       case BUILT_IN_POPCOUNTLL:
13835       case BUILT_IN_POPCOUNTIMAX:
13836       case BUILT_IN_POPCOUNT:
13837       case BUILT_IN_PARITYL:
13838       case BUILT_IN_PARITYLL:
13839       case BUILT_IN_PARITYIMAX:
13840       case BUILT_IN_PARITY:
13841       case BUILT_IN_LABS:
13842       case BUILT_IN_LLABS:
13843       case BUILT_IN_PREFETCH:
13844         return true;
13845
13846       default:
13847         return is_simple_builtin (decl);
13848       }
13849
13850   return false;
13851 }
13852