fold-const.c (tree_swap_operands_p): Remove unused arg.
[platform/upstream/gcc.git] / gcc / gimple-fold.c
1 /* Statement simplification on GIMPLE.
2    Copyright (C) 2010-2016 Free Software Foundation, Inc.
3    Split out from tree-ssa-ccp.c.
4
5 This file is part of GCC.
6
7 GCC is free software; you can redistribute it and/or modify it
8 under the terms of the GNU General Public License as published by the
9 Free Software Foundation; either version 3, or (at your option) any
10 later version.
11
12 GCC is distributed in the hope that it will be useful, but WITHOUT
13 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
15 for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING3.  If not see
19 <http://www.gnu.org/licenses/>.  */
20
21 #include "config.h"
22 #include "system.h"
23 #include "coretypes.h"
24 #include "backend.h"
25 #include "target.h"
26 #include "rtl.h"
27 #include "tree.h"
28 #include "gimple.h"
29 #include "predict.h"
30 #include "ssa.h"
31 #include "cgraph.h"
32 #include "gimple-pretty-print.h"
33 #include "fold-const.h"
34 #include "stmt.h"
35 #include "expr.h"
36 #include "stor-layout.h"
37 #include "dumpfile.h"
38 #include "gimple-fold.h"
39 #include "gimplify.h"
40 #include "gimple-iterator.h"
41 #include "tree-into-ssa.h"
42 #include "tree-dfa.h"
43 #include "tree-ssa.h"
44 #include "tree-ssa-propagate.h"
45 #include "ipa-utils.h"
46 #include "tree-ssa-address.h"
47 #include "langhooks.h"
48 #include "gimplify-me.h"
49 #include "dbgcnt.h"
50 #include "builtins.h"
51 #include "tree-eh.h"
52 #include "gimple-match.h"
53 #include "gomp-constants.h"
54 #include "optabs-query.h"
55 #include "omp-low.h"
56 #include "ipa-chkp.h"
57 #include "tree-cfg.h"
58 #include "fold-const-call.h"
59
60 /* Return true when DECL can be referenced from current unit.
61    FROM_DECL (if non-null) specify constructor of variable DECL was taken from.
62    We can get declarations that are not possible to reference for various
63    reasons:
64
65      1) When analyzing C++ virtual tables.
66         C++ virtual tables do have known constructors even
67         when they are keyed to other compilation unit.
68         Those tables can contain pointers to methods and vars
69         in other units.  Those methods have both STATIC and EXTERNAL
70         set.
71      2) In WHOPR mode devirtualization might lead to reference
72         to method that was partitioned elsehwere.
73         In this case we have static VAR_DECL or FUNCTION_DECL
74         that has no corresponding callgraph/varpool node
75         declaring the body.  
76      3) COMDAT functions referred by external vtables that
77         we devirtualize only during final compilation stage.
78         At this time we already decided that we will not output
79         the function body and thus we can't reference the symbol
80         directly.  */
81
82 static bool
83 can_refer_decl_in_current_unit_p (tree decl, tree from_decl)
84 {
85   varpool_node *vnode;
86   struct cgraph_node *node;
87   symtab_node *snode;
88
89   if (DECL_ABSTRACT_P (decl))
90     return false;
91
92   /* We are concerned only about static/external vars and functions.  */
93   if ((!TREE_STATIC (decl) && !DECL_EXTERNAL (decl))
94       || !VAR_OR_FUNCTION_DECL_P (decl))
95     return true;
96
97   /* Static objects can be referred only if they was not optimized out yet.  */
98   if (!TREE_PUBLIC (decl) && !DECL_EXTERNAL (decl))
99     {
100       /* Before we start optimizing unreachable code we can be sure all
101          static objects are defined.  */
102       if (symtab->function_flags_ready)
103         return true;
104       snode = symtab_node::get (decl);
105       if (!snode || !snode->definition)
106         return false;
107       node = dyn_cast <cgraph_node *> (snode);
108       return !node || !node->global.inlined_to;
109     }
110
111   /* We will later output the initializer, so we can refer to it.
112      So we are concerned only when DECL comes from initializer of
113      external var or var that has been optimized out.  */
114   if (!from_decl
115       || !VAR_P (from_decl)
116       || (!DECL_EXTERNAL (from_decl)
117           && (vnode = varpool_node::get (from_decl)) != NULL
118           && vnode->definition)
119       || (flag_ltrans
120           && (vnode = varpool_node::get (from_decl)) != NULL
121           && vnode->in_other_partition))
122     return true;
123   /* We are folding reference from external vtable.  The vtable may reffer
124      to a symbol keyed to other compilation unit.  The other compilation
125      unit may be in separate DSO and the symbol may be hidden.  */
126   if (DECL_VISIBILITY_SPECIFIED (decl)
127       && DECL_EXTERNAL (decl)
128       && DECL_VISIBILITY (decl) != VISIBILITY_DEFAULT
129       && (!(snode = symtab_node::get (decl)) || !snode->in_other_partition))
130     return false;
131   /* When function is public, we always can introduce new reference.
132      Exception are the COMDAT functions where introducing a direct
133      reference imply need to include function body in the curren tunit.  */
134   if (TREE_PUBLIC (decl) && !DECL_COMDAT (decl))
135     return true;
136   /* We have COMDAT.  We are going to check if we still have definition
137      or if the definition is going to be output in other partition.
138      Bypass this when gimplifying; all needed functions will be produced.
139
140      As observed in PR20991 for already optimized out comdat virtual functions
141      it may be tempting to not necessarily give up because the copy will be
142      output elsewhere when corresponding vtable is output.  
143      This is however not possible - ABI specify that COMDATs are output in
144      units where they are used and when the other unit was compiled with LTO
145      it is possible that vtable was kept public while the function itself
146      was privatized. */
147   if (!symtab->function_flags_ready)
148     return true;
149
150   snode = symtab_node::get (decl);
151   if (!snode
152       || ((!snode->definition || DECL_EXTERNAL (decl))
153           && (!snode->in_other_partition
154               || (!snode->forced_by_abi && !snode->force_output))))
155     return false;
156   node = dyn_cast <cgraph_node *> (snode);
157   return !node || !node->global.inlined_to;
158 }
159
160 /* Create a temporary for TYPE for a statement STMT.  If the current function
161    is in SSA form, a SSA name is created.  Otherwise a temporary register
162    is made.  */
163
164 static tree
165 create_tmp_reg_or_ssa_name (tree type, gimple *stmt = NULL)
166 {
167   if (gimple_in_ssa_p (cfun))
168     return make_ssa_name (type, stmt);
169   else
170     return create_tmp_reg (type);
171 }
172
173 /* CVAL is value taken from DECL_INITIAL of variable.  Try to transform it into
174    acceptable form for is_gimple_min_invariant.
175    FROM_DECL (if non-NULL) specify variable whose constructor contains CVAL.  */
176
177 tree
178 canonicalize_constructor_val (tree cval, tree from_decl)
179 {
180   tree orig_cval = cval;
181   STRIP_NOPS (cval);
182   if (TREE_CODE (cval) == POINTER_PLUS_EXPR
183       && TREE_CODE (TREE_OPERAND (cval, 1)) == INTEGER_CST)
184     {
185       tree ptr = TREE_OPERAND (cval, 0);
186       if (is_gimple_min_invariant (ptr))
187         cval = build1_loc (EXPR_LOCATION (cval),
188                            ADDR_EXPR, TREE_TYPE (ptr),
189                            fold_build2 (MEM_REF, TREE_TYPE (TREE_TYPE (ptr)),
190                                         ptr,
191                                         fold_convert (ptr_type_node,
192                                                       TREE_OPERAND (cval, 1))));
193     }
194   if (TREE_CODE (cval) == ADDR_EXPR)
195     {
196       tree base = NULL_TREE;
197       if (TREE_CODE (TREE_OPERAND (cval, 0)) == COMPOUND_LITERAL_EXPR)
198         {
199           base = COMPOUND_LITERAL_EXPR_DECL (TREE_OPERAND (cval, 0));
200           if (base)
201             TREE_OPERAND (cval, 0) = base;
202         }
203       else
204         base = get_base_address (TREE_OPERAND (cval, 0));
205       if (!base)
206         return NULL_TREE;
207
208       if (VAR_OR_FUNCTION_DECL_P (base)
209           && !can_refer_decl_in_current_unit_p (base, from_decl))
210         return NULL_TREE;
211       if (TREE_TYPE (base) == error_mark_node)
212         return NULL_TREE;
213       if (VAR_P (base))
214         TREE_ADDRESSABLE (base) = 1;
215       else if (TREE_CODE (base) == FUNCTION_DECL)
216         {
217           /* Make sure we create a cgraph node for functions we'll reference.
218              They can be non-existent if the reference comes from an entry
219              of an external vtable for example.  */
220           cgraph_node::get_create (base);
221         }
222       /* Fixup types in global initializers.  */
223       if (TREE_TYPE (TREE_TYPE (cval)) != TREE_TYPE (TREE_OPERAND (cval, 0)))
224         cval = build_fold_addr_expr (TREE_OPERAND (cval, 0));
225
226       if (!useless_type_conversion_p (TREE_TYPE (orig_cval), TREE_TYPE (cval)))
227         cval = fold_convert (TREE_TYPE (orig_cval), cval);
228       return cval;
229     }
230   if (TREE_OVERFLOW_P (cval))
231     return drop_tree_overflow (cval);
232   return orig_cval;
233 }
234
235 /* If SYM is a constant variable with known value, return the value.
236    NULL_TREE is returned otherwise.  */
237
238 tree
239 get_symbol_constant_value (tree sym)
240 {
241   tree val = ctor_for_folding (sym);
242   if (val != error_mark_node)
243     {
244       if (val)
245         {
246           val = canonicalize_constructor_val (unshare_expr (val), sym);
247           if (val && is_gimple_min_invariant (val))
248             return val;
249           else
250             return NULL_TREE;
251         }
252       /* Variables declared 'const' without an initializer
253          have zero as the initializer if they may not be
254          overridden at link or run time.  */
255       if (!val
256           && is_gimple_reg_type (TREE_TYPE (sym)))
257         return build_zero_cst (TREE_TYPE (sym));
258     }
259
260   return NULL_TREE;
261 }
262
263
264
265 /* Subroutine of fold_stmt.  We perform several simplifications of the
266    memory reference tree EXPR and make sure to re-gimplify them properly
267    after propagation of constant addresses.  IS_LHS is true if the
268    reference is supposed to be an lvalue.  */
269
270 static tree
271 maybe_fold_reference (tree expr, bool is_lhs)
272 {
273   tree result;
274
275   if ((TREE_CODE (expr) == VIEW_CONVERT_EXPR
276        || TREE_CODE (expr) == REALPART_EXPR
277        || TREE_CODE (expr) == IMAGPART_EXPR)
278       && CONSTANT_CLASS_P (TREE_OPERAND (expr, 0)))
279     return fold_unary_loc (EXPR_LOCATION (expr),
280                            TREE_CODE (expr),
281                            TREE_TYPE (expr),
282                            TREE_OPERAND (expr, 0));
283   else if (TREE_CODE (expr) == BIT_FIELD_REF
284            && CONSTANT_CLASS_P (TREE_OPERAND (expr, 0)))
285     return fold_ternary_loc (EXPR_LOCATION (expr),
286                              TREE_CODE (expr),
287                              TREE_TYPE (expr),
288                              TREE_OPERAND (expr, 0),
289                              TREE_OPERAND (expr, 1),
290                              TREE_OPERAND (expr, 2));
291
292   if (!is_lhs
293       && (result = fold_const_aggregate_ref (expr))
294       && is_gimple_min_invariant (result))
295     return result;
296
297   return NULL_TREE;
298 }
299
300
301 /* Attempt to fold an assignment statement pointed-to by SI.  Returns a
302    replacement rhs for the statement or NULL_TREE if no simplification
303    could be made.  It is assumed that the operands have been previously
304    folded.  */
305
306 static tree
307 fold_gimple_assign (gimple_stmt_iterator *si)
308 {
309   gimple *stmt = gsi_stmt (*si);
310   enum tree_code subcode = gimple_assign_rhs_code (stmt);
311   location_t loc = gimple_location (stmt);
312
313   tree result = NULL_TREE;
314
315   switch (get_gimple_rhs_class (subcode))
316     {
317     case GIMPLE_SINGLE_RHS:
318       {
319         tree rhs = gimple_assign_rhs1 (stmt);
320
321         if (TREE_CLOBBER_P (rhs))
322           return NULL_TREE;
323
324         if (REFERENCE_CLASS_P (rhs))
325           return maybe_fold_reference (rhs, false);
326
327         else if (TREE_CODE (rhs) == OBJ_TYPE_REF)
328           {
329             tree val = OBJ_TYPE_REF_EXPR (rhs);
330             if (is_gimple_min_invariant (val))
331               return val;
332             else if (flag_devirtualize && virtual_method_call_p (rhs))
333               {
334                 bool final;
335                 vec <cgraph_node *>targets
336                   = possible_polymorphic_call_targets (rhs, stmt, &final);
337                 if (final && targets.length () <= 1 && dbg_cnt (devirt))
338                   {
339                     if (dump_enabled_p ())
340                       {
341                         location_t loc = gimple_location_safe (stmt);
342                         dump_printf_loc (MSG_OPTIMIZED_LOCATIONS, loc,
343                                          "resolving virtual function address "
344                                          "reference to function %s\n",
345                                          targets.length () == 1
346                                          ? targets[0]->name ()
347                                          : "NULL");
348                       }
349                     if (targets.length () == 1)
350                       {
351                         val = fold_convert (TREE_TYPE (val),
352                                             build_fold_addr_expr_loc
353                                               (loc, targets[0]->decl));
354                         STRIP_USELESS_TYPE_CONVERSION (val);
355                       }
356                     else
357                       /* We can not use __builtin_unreachable here because it
358                          can not have address taken.  */
359                       val = build_int_cst (TREE_TYPE (val), 0);
360                     return val;
361                   }
362               }
363           }
364
365         else if (TREE_CODE (rhs) == ADDR_EXPR)
366           {
367             tree ref = TREE_OPERAND (rhs, 0);
368             tree tem = maybe_fold_reference (ref, true);
369             if (tem
370                 && TREE_CODE (tem) == MEM_REF
371                 && integer_zerop (TREE_OPERAND (tem, 1)))
372               result = fold_convert (TREE_TYPE (rhs), TREE_OPERAND (tem, 0));
373             else if (tem)
374               result = fold_convert (TREE_TYPE (rhs),
375                                      build_fold_addr_expr_loc (loc, tem));
376             else if (TREE_CODE (ref) == MEM_REF
377                      && integer_zerop (TREE_OPERAND (ref, 1)))
378               result = fold_convert (TREE_TYPE (rhs), TREE_OPERAND (ref, 0));
379
380             if (result)
381               {
382                 /* Strip away useless type conversions.  Both the
383                    NON_LVALUE_EXPR that may have been added by fold, and
384                    "useless" type conversions that might now be apparent
385                    due to propagation.  */
386                 STRIP_USELESS_TYPE_CONVERSION (result);
387
388                 if (result != rhs && valid_gimple_rhs_p (result))
389                   return result;
390               }
391           }
392
393         else if (TREE_CODE (rhs) == CONSTRUCTOR
394                  && TREE_CODE (TREE_TYPE (rhs)) == VECTOR_TYPE)
395           {
396             /* Fold a constant vector CONSTRUCTOR to VECTOR_CST.  */
397             unsigned i;
398             tree val;
399
400             FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (rhs), i, val)
401               if (! CONSTANT_CLASS_P (val))
402                 return NULL_TREE;
403
404             return build_vector_from_ctor (TREE_TYPE (rhs),
405                                            CONSTRUCTOR_ELTS (rhs));
406           }
407
408         else if (DECL_P (rhs))
409           return get_symbol_constant_value (rhs);
410       }
411       break;
412
413     case GIMPLE_UNARY_RHS:
414       break;
415
416     case GIMPLE_BINARY_RHS:
417       break;
418
419     case GIMPLE_TERNARY_RHS:
420       result = fold_ternary_loc (loc, subcode,
421                                  TREE_TYPE (gimple_assign_lhs (stmt)),
422                                  gimple_assign_rhs1 (stmt),
423                                  gimple_assign_rhs2 (stmt),
424                                  gimple_assign_rhs3 (stmt));
425
426       if (result)
427         {
428           STRIP_USELESS_TYPE_CONVERSION (result);
429           if (valid_gimple_rhs_p (result))
430             return result;
431         }
432       break;
433
434     case GIMPLE_INVALID_RHS:
435       gcc_unreachable ();
436     }
437
438   return NULL_TREE;
439 }
440
441
442 /* Replace a statement at *SI_P with a sequence of statements in STMTS,
443    adjusting the replacement stmts location and virtual operands.
444    If the statement has a lhs the last stmt in the sequence is expected
445    to assign to that lhs.  */
446
447 static void
448 gsi_replace_with_seq_vops (gimple_stmt_iterator *si_p, gimple_seq stmts)
449 {
450   gimple *stmt = gsi_stmt (*si_p);
451
452   if (gimple_has_location (stmt))
453     annotate_all_with_location (stmts, gimple_location (stmt));
454
455   /* First iterate over the replacement statements backward, assigning
456      virtual operands to their defining statements.  */
457   gimple *laststore = NULL;
458   for (gimple_stmt_iterator i = gsi_last (stmts);
459        !gsi_end_p (i); gsi_prev (&i))
460     {
461       gimple *new_stmt = gsi_stmt (i);
462       if ((gimple_assign_single_p (new_stmt)
463            && !is_gimple_reg (gimple_assign_lhs (new_stmt)))
464           || (is_gimple_call (new_stmt)
465               && (gimple_call_flags (new_stmt)
466                   & (ECF_NOVOPS | ECF_PURE | ECF_CONST | ECF_NORETURN)) == 0))
467         {
468           tree vdef;
469           if (!laststore)
470             vdef = gimple_vdef (stmt);
471           else
472             vdef = make_ssa_name (gimple_vop (cfun), new_stmt);
473           gimple_set_vdef (new_stmt, vdef);
474           if (vdef && TREE_CODE (vdef) == SSA_NAME)
475             SSA_NAME_DEF_STMT (vdef) = new_stmt;
476           laststore = new_stmt;
477         }
478     }
479
480   /* Second iterate over the statements forward, assigning virtual
481      operands to their uses.  */
482   tree reaching_vuse = gimple_vuse (stmt);
483   for (gimple_stmt_iterator i = gsi_start (stmts);
484        !gsi_end_p (i); gsi_next (&i))
485     {
486       gimple *new_stmt = gsi_stmt (i);
487       /* If the new statement possibly has a VUSE, update it with exact SSA
488          name we know will reach this one.  */
489       if (gimple_has_mem_ops (new_stmt))
490         gimple_set_vuse (new_stmt, reaching_vuse);
491       gimple_set_modified (new_stmt, true);
492       if (gimple_vdef (new_stmt))
493         reaching_vuse = gimple_vdef (new_stmt);
494     }
495
496   /* If the new sequence does not do a store release the virtual
497      definition of the original statement.  */
498   if (reaching_vuse
499       && reaching_vuse == gimple_vuse (stmt))
500     {
501       tree vdef = gimple_vdef (stmt);
502       if (vdef
503           && TREE_CODE (vdef) == SSA_NAME)
504         {
505           unlink_stmt_vdef (stmt);
506           release_ssa_name (vdef);
507         }
508     }
509
510   /* Finally replace the original statement with the sequence.  */
511   gsi_replace_with_seq (si_p, stmts, false);
512 }
513
514 /* Convert EXPR into a GIMPLE value suitable for substitution on the
515    RHS of an assignment.  Insert the necessary statements before
516    iterator *SI_P.  The statement at *SI_P, which must be a GIMPLE_CALL
517    is replaced.  If the call is expected to produces a result, then it
518    is replaced by an assignment of the new RHS to the result variable.
519    If the result is to be ignored, then the call is replaced by a
520    GIMPLE_NOP.  A proper VDEF chain is retained by making the first
521    VUSE and the last VDEF of the whole sequence be the same as the replaced
522    statement and using new SSA names for stores in between.  */
523
524 void
525 gimplify_and_update_call_from_tree (gimple_stmt_iterator *si_p, tree expr)
526 {
527   tree lhs;
528   gimple *stmt, *new_stmt;
529   gimple_stmt_iterator i;
530   gimple_seq stmts = NULL;
531
532   stmt = gsi_stmt (*si_p);
533
534   gcc_assert (is_gimple_call (stmt));
535
536   push_gimplify_context (gimple_in_ssa_p (cfun));
537
538   lhs = gimple_call_lhs (stmt);
539   if (lhs == NULL_TREE)
540     {
541       gimplify_and_add (expr, &stmts);
542       /* We can end up with folding a memcpy of an empty class assignment
543          which gets optimized away by C++ gimplification.  */
544       if (gimple_seq_empty_p (stmts))
545         {
546           pop_gimplify_context (NULL);
547           if (gimple_in_ssa_p (cfun))
548             {
549               unlink_stmt_vdef (stmt);
550               release_defs (stmt);
551             }
552           gsi_replace (si_p, gimple_build_nop (), false);
553           return;
554         }
555     }
556   else
557     {
558       tree tmp = force_gimple_operand (expr, &stmts, false, NULL_TREE);
559       new_stmt = gimple_build_assign (lhs, tmp);
560       i = gsi_last (stmts);
561       gsi_insert_after_without_update (&i, new_stmt,
562                                        GSI_CONTINUE_LINKING);
563     }
564
565   pop_gimplify_context (NULL);
566
567   gsi_replace_with_seq_vops (si_p, stmts);
568 }
569
570
571 /* Replace the call at *GSI with the gimple value VAL.  */
572
573 static void
574 replace_call_with_value (gimple_stmt_iterator *gsi, tree val)
575 {
576   gimple *stmt = gsi_stmt (*gsi);
577   tree lhs = gimple_call_lhs (stmt);
578   gimple *repl;
579   if (lhs)
580     {
581       if (!useless_type_conversion_p (TREE_TYPE (lhs), TREE_TYPE (val)))
582         val = fold_convert (TREE_TYPE (lhs), val);
583       repl = gimple_build_assign (lhs, val);
584     }
585   else
586     repl = gimple_build_nop ();
587   tree vdef = gimple_vdef (stmt);
588   if (vdef && TREE_CODE (vdef) == SSA_NAME)
589     {
590       unlink_stmt_vdef (stmt);
591       release_ssa_name (vdef);
592     }
593   gsi_replace (gsi, repl, false);
594 }
595
596 /* Replace the call at *GSI with the new call REPL and fold that
597    again.  */
598
599 static void
600 replace_call_with_call_and_fold (gimple_stmt_iterator *gsi, gimple *repl)
601 {
602   gimple *stmt = gsi_stmt (*gsi);
603   gimple_call_set_lhs (repl, gimple_call_lhs (stmt));
604   gimple_set_location (repl, gimple_location (stmt));
605   if (gimple_vdef (stmt)
606       && TREE_CODE (gimple_vdef (stmt)) == SSA_NAME)
607     {
608       gimple_set_vdef (repl, gimple_vdef (stmt));
609       gimple_set_vuse (repl, gimple_vuse (stmt));
610       SSA_NAME_DEF_STMT (gimple_vdef (repl)) = repl;
611     }
612   gsi_replace (gsi, repl, false);
613   fold_stmt (gsi);
614 }
615
616 /* Return true if VAR is a VAR_DECL or a component thereof.  */
617
618 static bool
619 var_decl_component_p (tree var)
620 {
621   tree inner = var;
622   while (handled_component_p (inner))
623     inner = TREE_OPERAND (inner, 0);
624   return SSA_VAR_P (inner);
625 }
626
627 /* Fold function call to builtin mem{{,p}cpy,move}.  Return
628    false if no simplification can be made.
629    If ENDP is 0, return DEST (like memcpy).
630    If ENDP is 1, return DEST+LEN (like mempcpy).
631    If ENDP is 2, return DEST+LEN-1 (like stpcpy).
632    If ENDP is 3, return DEST, additionally *SRC and *DEST may overlap
633    (memmove).   */
634
635 static bool
636 gimple_fold_builtin_memory_op (gimple_stmt_iterator *gsi,
637                                tree dest, tree src, int endp)
638 {
639   gimple *stmt = gsi_stmt (*gsi);
640   tree lhs = gimple_call_lhs (stmt);
641   tree len = gimple_call_arg (stmt, 2);
642   tree destvar, srcvar;
643   location_t loc = gimple_location (stmt);
644
645   /* If the LEN parameter is zero, return DEST.  */
646   if (integer_zerop (len))
647     {
648       gimple *repl;
649       if (gimple_call_lhs (stmt))
650         repl = gimple_build_assign (gimple_call_lhs (stmt), dest);
651       else
652         repl = gimple_build_nop ();
653       tree vdef = gimple_vdef (stmt);
654       if (vdef && TREE_CODE (vdef) == SSA_NAME)
655         {
656           unlink_stmt_vdef (stmt);
657           release_ssa_name (vdef);
658         }
659       gsi_replace (gsi, repl, false);
660       return true;
661     }
662
663   /* If SRC and DEST are the same (and not volatile), return
664      DEST{,+LEN,+LEN-1}.  */
665   if (operand_equal_p (src, dest, 0))
666     {
667       unlink_stmt_vdef (stmt);
668       if (gimple_vdef (stmt) && TREE_CODE (gimple_vdef (stmt)) == SSA_NAME)
669         release_ssa_name (gimple_vdef (stmt));
670       if (!lhs)
671         {
672           gsi_replace (gsi, gimple_build_nop (), false);
673           return true;
674         }
675       goto done;
676     }
677   else
678     {
679       tree srctype, desttype;
680       unsigned int src_align, dest_align;
681       tree off0;
682
683       /* Inlining of memcpy/memmove may cause bounds lost (if we copy
684          pointers as wide integer) and also may result in huge function
685          size because of inlined bounds copy.  Thus don't inline for
686          functions we want to instrument.  */
687       if (flag_check_pointer_bounds
688           && chkp_instrumentable_p (cfun->decl)
689           /* Even if data may contain pointers we can inline if copy
690              less than a pointer size.  */
691           && (!tree_fits_uhwi_p (len)
692               || compare_tree_int (len, POINTER_SIZE_UNITS) >= 0))
693         return false;
694
695       /* Build accesses at offset zero with a ref-all character type.  */
696       off0 = build_int_cst (build_pointer_type_for_mode (char_type_node,
697                                                          ptr_mode, true), 0);
698
699       /* If we can perform the copy efficiently with first doing all loads
700          and then all stores inline it that way.  Currently efficiently
701          means that we can load all the memory into a single integer
702          register which is what MOVE_MAX gives us.  */
703       src_align = get_pointer_alignment (src);
704       dest_align = get_pointer_alignment (dest);
705       if (tree_fits_uhwi_p (len)
706           && compare_tree_int (len, MOVE_MAX) <= 0
707           /* ???  Don't transform copies from strings with known length this
708              confuses the tree-ssa-strlen.c.  This doesn't handle
709              the case in gcc.dg/strlenopt-8.c which is XFAILed for that
710              reason.  */
711           && !c_strlen (src, 2))
712         {
713           unsigned ilen = tree_to_uhwi (len);
714           if (pow2p_hwi (ilen))
715             {
716               tree type = lang_hooks.types.type_for_size (ilen * 8, 1);
717               if (type
718                   && TYPE_MODE (type) != BLKmode
719                   && (GET_MODE_SIZE (TYPE_MODE (type)) * BITS_PER_UNIT
720                       == ilen * 8)
721                   /* If the destination pointer is not aligned we must be able
722                      to emit an unaligned store.  */
723                   && (dest_align >= GET_MODE_ALIGNMENT (TYPE_MODE (type))
724                       || !SLOW_UNALIGNED_ACCESS (TYPE_MODE (type), dest_align)
725                       || (optab_handler (movmisalign_optab, TYPE_MODE (type))
726                           != CODE_FOR_nothing)))
727                 {
728                   tree srctype = type;
729                   tree desttype = type;
730                   if (src_align < GET_MODE_ALIGNMENT (TYPE_MODE (type)))
731                     srctype = build_aligned_type (type, src_align);
732                   tree srcmem = fold_build2 (MEM_REF, srctype, src, off0);
733                   tree tem = fold_const_aggregate_ref (srcmem);
734                   if (tem)
735                     srcmem = tem;
736                   else if (src_align < GET_MODE_ALIGNMENT (TYPE_MODE (type))
737                            && SLOW_UNALIGNED_ACCESS (TYPE_MODE (type),
738                                                      src_align)
739                            && (optab_handler (movmisalign_optab,
740                                               TYPE_MODE (type))
741                                == CODE_FOR_nothing))
742                     srcmem = NULL_TREE;
743                   if (srcmem)
744                     {
745                       gimple *new_stmt;
746                       if (is_gimple_reg_type (TREE_TYPE (srcmem)))
747                         {
748                           new_stmt = gimple_build_assign (NULL_TREE, srcmem);
749                           srcmem
750                             = create_tmp_reg_or_ssa_name (TREE_TYPE (srcmem),
751                                                           new_stmt);
752                           gimple_assign_set_lhs (new_stmt, srcmem);
753                           gimple_set_vuse (new_stmt, gimple_vuse (stmt));
754                           gsi_insert_before (gsi, new_stmt, GSI_SAME_STMT);
755                         }
756                       if (dest_align < GET_MODE_ALIGNMENT (TYPE_MODE (type)))
757                         desttype = build_aligned_type (type, dest_align);
758                       new_stmt
759                         = gimple_build_assign (fold_build2 (MEM_REF, desttype,
760                                                             dest, off0),
761                                                srcmem);
762                       gimple_set_vuse (new_stmt, gimple_vuse (stmt));
763                       gimple_set_vdef (new_stmt, gimple_vdef (stmt));
764                       if (gimple_vdef (new_stmt)
765                           && TREE_CODE (gimple_vdef (new_stmt)) == SSA_NAME)
766                         SSA_NAME_DEF_STMT (gimple_vdef (new_stmt)) = new_stmt;
767                       if (!lhs)
768                         {
769                           gsi_replace (gsi, new_stmt, false);
770                           return true;
771                         }
772                       gsi_insert_before (gsi, new_stmt, GSI_SAME_STMT);
773                       goto done;
774                     }
775                 }
776             }
777         }
778
779       if (endp == 3)
780         {
781           /* Both DEST and SRC must be pointer types.
782              ??? This is what old code did.  Is the testing for pointer types
783              really mandatory?
784
785              If either SRC is readonly or length is 1, we can use memcpy.  */
786           if (!dest_align || !src_align)
787             return false;
788           if (readonly_data_expr (src)
789               || (tree_fits_uhwi_p (len)
790                   && (MIN (src_align, dest_align) / BITS_PER_UNIT
791                       >= tree_to_uhwi (len))))
792             {
793               tree fn = builtin_decl_implicit (BUILT_IN_MEMCPY);
794               if (!fn)
795                 return false;
796               gimple_call_set_fndecl (stmt, fn);
797               gimple_call_set_arg (stmt, 0, dest);
798               gimple_call_set_arg (stmt, 1, src);
799               fold_stmt (gsi);
800               return true;
801             }
802
803           /* If *src and *dest can't overlap, optimize into memcpy as well.  */
804           if (TREE_CODE (src) == ADDR_EXPR
805               && TREE_CODE (dest) == ADDR_EXPR)
806             {
807               tree src_base, dest_base, fn;
808               HOST_WIDE_INT src_offset = 0, dest_offset = 0;
809               HOST_WIDE_INT maxsize;
810
811               srcvar = TREE_OPERAND (src, 0);
812               src_base = get_addr_base_and_unit_offset (srcvar, &src_offset);
813               if (src_base == NULL)
814                 src_base = srcvar;
815               destvar = TREE_OPERAND (dest, 0);
816               dest_base = get_addr_base_and_unit_offset (destvar,
817                                                          &dest_offset);
818               if (dest_base == NULL)
819                 dest_base = destvar;
820               if (tree_fits_uhwi_p (len))
821                 maxsize = tree_to_uhwi (len);
822               else
823                 maxsize = -1;
824               if (SSA_VAR_P (src_base)
825                   && SSA_VAR_P (dest_base))
826                 {
827                   if (operand_equal_p (src_base, dest_base, 0)
828                       && ranges_overlap_p (src_offset, maxsize,
829                                            dest_offset, maxsize))
830                     return false;
831                 }
832               else if (TREE_CODE (src_base) == MEM_REF
833                        && TREE_CODE (dest_base) == MEM_REF)
834                 {
835                   if (! operand_equal_p (TREE_OPERAND (src_base, 0),
836                                          TREE_OPERAND (dest_base, 0), 0))
837                     return false;
838                   offset_int off = mem_ref_offset (src_base) + src_offset;
839                   if (!wi::fits_shwi_p (off))
840                     return false;
841                   src_offset = off.to_shwi ();
842
843                   off = mem_ref_offset (dest_base) + dest_offset;
844                   if (!wi::fits_shwi_p (off))
845                     return false;
846                   dest_offset = off.to_shwi ();
847                   if (ranges_overlap_p (src_offset, maxsize,
848                                         dest_offset, maxsize))
849                     return false;
850                 }
851               else
852                 return false;
853
854               fn = builtin_decl_implicit (BUILT_IN_MEMCPY);
855               if (!fn)
856                 return false;
857               gimple_call_set_fndecl (stmt, fn);
858               gimple_call_set_arg (stmt, 0, dest);
859               gimple_call_set_arg (stmt, 1, src);
860               fold_stmt (gsi);
861               return true;
862             }
863
864           /* If the destination and source do not alias optimize into
865              memcpy as well.  */
866           if ((is_gimple_min_invariant (dest)
867                || TREE_CODE (dest) == SSA_NAME)
868               && (is_gimple_min_invariant (src)
869                   || TREE_CODE (src) == SSA_NAME))
870             {
871               ao_ref destr, srcr;
872               ao_ref_init_from_ptr_and_size (&destr, dest, len);
873               ao_ref_init_from_ptr_and_size (&srcr, src, len);
874               if (!refs_may_alias_p_1 (&destr, &srcr, false))
875                 {
876                   tree fn;
877                   fn = builtin_decl_implicit (BUILT_IN_MEMCPY);
878                   if (!fn)
879                     return false;
880                   gimple_call_set_fndecl (stmt, fn);
881                   gimple_call_set_arg (stmt, 0, dest);
882                   gimple_call_set_arg (stmt, 1, src);
883                   fold_stmt (gsi);
884                   return true;
885                 }
886             }
887
888           return false;
889         }
890
891       if (!tree_fits_shwi_p (len))
892         return false;
893       /* FIXME:
894          This logic lose for arguments like (type *)malloc (sizeof (type)),
895          since we strip the casts of up to VOID return value from malloc.
896          Perhaps we ought to inherit type from non-VOID argument here?  */
897       STRIP_NOPS (src);
898       STRIP_NOPS (dest);
899       if (!POINTER_TYPE_P (TREE_TYPE (src))
900           || !POINTER_TYPE_P (TREE_TYPE (dest)))
901         return false;
902       /* In the following try to find a type that is most natural to be
903          used for the memcpy source and destination and that allows
904          the most optimization when memcpy is turned into a plain assignment
905          using that type.  In theory we could always use a char[len] type
906          but that only gains us that the destination and source possibly
907          no longer will have their address taken.  */
908       /* As we fold (void *)(p + CST) to (void *)p + CST undo this here.  */
909       if (TREE_CODE (src) == POINTER_PLUS_EXPR)
910         {
911           tree tem = TREE_OPERAND (src, 0);
912           STRIP_NOPS (tem);
913           if (tem != TREE_OPERAND (src, 0))
914             src = build1 (NOP_EXPR, TREE_TYPE (tem), src);
915         }
916       if (TREE_CODE (dest) == POINTER_PLUS_EXPR)
917         {
918           tree tem = TREE_OPERAND (dest, 0);
919           STRIP_NOPS (tem);
920           if (tem != TREE_OPERAND (dest, 0))
921             dest = build1 (NOP_EXPR, TREE_TYPE (tem), dest);
922         }
923       srctype = TREE_TYPE (TREE_TYPE (src));
924       if (TREE_CODE (srctype) == ARRAY_TYPE
925           && !tree_int_cst_equal (TYPE_SIZE_UNIT (srctype), len))
926         {
927           srctype = TREE_TYPE (srctype);
928           STRIP_NOPS (src);
929           src = build1 (NOP_EXPR, build_pointer_type (srctype), src);
930         }
931       desttype = TREE_TYPE (TREE_TYPE (dest));
932       if (TREE_CODE (desttype) == ARRAY_TYPE
933           && !tree_int_cst_equal (TYPE_SIZE_UNIT (desttype), len))
934         {
935           desttype = TREE_TYPE (desttype);
936           STRIP_NOPS (dest);
937           dest = build1 (NOP_EXPR, build_pointer_type (desttype), dest);
938         }
939       if (TREE_ADDRESSABLE (srctype)
940           || TREE_ADDRESSABLE (desttype))
941         return false;
942
943       /* Make sure we are not copying using a floating-point mode or
944          a type whose size possibly does not match its precision.  */
945       if (FLOAT_MODE_P (TYPE_MODE (desttype))
946           || TREE_CODE (desttype) == BOOLEAN_TYPE
947           || TREE_CODE (desttype) == ENUMERAL_TYPE)
948         desttype = bitwise_type_for_mode (TYPE_MODE (desttype));
949       if (FLOAT_MODE_P (TYPE_MODE (srctype))
950           || TREE_CODE (srctype) == BOOLEAN_TYPE
951           || TREE_CODE (srctype) == ENUMERAL_TYPE)
952         srctype = bitwise_type_for_mode (TYPE_MODE (srctype));
953       if (!srctype)
954         srctype = desttype;
955       if (!desttype)
956         desttype = srctype;
957       if (!srctype)
958         return false;
959
960       src_align = get_pointer_alignment (src);
961       dest_align = get_pointer_alignment (dest);
962       if (dest_align < TYPE_ALIGN (desttype)
963           || src_align < TYPE_ALIGN (srctype))
964         return false;
965
966       destvar = dest;
967       STRIP_NOPS (destvar);
968       if (TREE_CODE (destvar) == ADDR_EXPR
969           && var_decl_component_p (TREE_OPERAND (destvar, 0))
970           && tree_int_cst_equal (TYPE_SIZE_UNIT (desttype), len))
971         destvar = fold_build2 (MEM_REF, desttype, destvar, off0);
972       else
973         destvar = NULL_TREE;
974
975       srcvar = src;
976       STRIP_NOPS (srcvar);
977       if (TREE_CODE (srcvar) == ADDR_EXPR
978           && var_decl_component_p (TREE_OPERAND (srcvar, 0))
979           && tree_int_cst_equal (TYPE_SIZE_UNIT (srctype), len))
980         {
981           if (!destvar
982               || src_align >= TYPE_ALIGN (desttype))
983             srcvar = fold_build2 (MEM_REF, destvar ? desttype : srctype,
984                                   srcvar, off0);
985           else if (!STRICT_ALIGNMENT)
986             {
987               srctype = build_aligned_type (TYPE_MAIN_VARIANT (desttype),
988                                             src_align);
989               srcvar = fold_build2 (MEM_REF, srctype, srcvar, off0);
990             }
991           else
992             srcvar = NULL_TREE;
993         }
994       else
995         srcvar = NULL_TREE;
996
997       if (srcvar == NULL_TREE && destvar == NULL_TREE)
998         return false;
999
1000       if (srcvar == NULL_TREE)
1001         {
1002           STRIP_NOPS (src);
1003           if (src_align >= TYPE_ALIGN (desttype))
1004             srcvar = fold_build2 (MEM_REF, desttype, src, off0);
1005           else
1006             {
1007               if (STRICT_ALIGNMENT)
1008                 return false;
1009               srctype = build_aligned_type (TYPE_MAIN_VARIANT (desttype),
1010                                             src_align);
1011               srcvar = fold_build2 (MEM_REF, srctype, src, off0);
1012             }
1013         }
1014       else if (destvar == NULL_TREE)
1015         {
1016           STRIP_NOPS (dest);
1017           if (dest_align >= TYPE_ALIGN (srctype))
1018             destvar = fold_build2 (MEM_REF, srctype, dest, off0);
1019           else
1020             {
1021               if (STRICT_ALIGNMENT)
1022                 return false;
1023               desttype = build_aligned_type (TYPE_MAIN_VARIANT (srctype),
1024                                              dest_align);
1025               destvar = fold_build2 (MEM_REF, desttype, dest, off0);
1026             }
1027         }
1028
1029       gimple *new_stmt;
1030       if (is_gimple_reg_type (TREE_TYPE (srcvar)))
1031         {
1032           tree tem = fold_const_aggregate_ref (srcvar);
1033           if (tem)
1034             srcvar = tem;
1035           if (! is_gimple_min_invariant (srcvar))
1036             {
1037               new_stmt = gimple_build_assign (NULL_TREE, srcvar);
1038               srcvar = create_tmp_reg_or_ssa_name (TREE_TYPE (srcvar),
1039                                                    new_stmt);
1040               gimple_assign_set_lhs (new_stmt, srcvar);
1041               gimple_set_vuse (new_stmt, gimple_vuse (stmt));
1042               gsi_insert_before (gsi, new_stmt, GSI_SAME_STMT);
1043             }
1044         }
1045       new_stmt = gimple_build_assign (destvar, srcvar);
1046       gimple_set_vuse (new_stmt, gimple_vuse (stmt));
1047       gimple_set_vdef (new_stmt, gimple_vdef (stmt));
1048       if (gimple_vdef (new_stmt)
1049           && TREE_CODE (gimple_vdef (new_stmt)) == SSA_NAME)
1050         SSA_NAME_DEF_STMT (gimple_vdef (new_stmt)) = new_stmt;
1051       if (!lhs)
1052         {
1053           gsi_replace (gsi, new_stmt, false);
1054           return true;
1055         }
1056       gsi_insert_before (gsi, new_stmt, GSI_SAME_STMT);
1057     }
1058
1059 done:
1060   gimple_seq stmts = NULL;
1061   if (endp == 0 || endp == 3)
1062     len = NULL_TREE;
1063   else if (endp == 2)
1064     len = gimple_build (&stmts, loc, MINUS_EXPR, TREE_TYPE (len), len,
1065                         ssize_int (1));
1066   if (endp == 2 || endp == 1)
1067     {
1068       len = gimple_convert_to_ptrofftype (&stmts, loc, len);
1069       dest = gimple_build (&stmts, loc, POINTER_PLUS_EXPR,
1070                            TREE_TYPE (dest), dest, len);
1071     }
1072
1073   gsi_insert_seq_before (gsi, stmts, GSI_SAME_STMT);
1074   gimple *repl = gimple_build_assign (lhs, dest);
1075   gsi_replace (gsi, repl, false);
1076   return true;
1077 }
1078
1079 /* Fold function call to builtin memset or bzero at *GSI setting the
1080    memory of size LEN to VAL.  Return whether a simplification was made.  */
1081
1082 static bool
1083 gimple_fold_builtin_memset (gimple_stmt_iterator *gsi, tree c, tree len)
1084 {
1085   gimple *stmt = gsi_stmt (*gsi);
1086   tree etype;
1087   unsigned HOST_WIDE_INT length, cval;
1088
1089   /* If the LEN parameter is zero, return DEST.  */
1090   if (integer_zerop (len))
1091     {
1092       replace_call_with_value (gsi, gimple_call_arg (stmt, 0));
1093       return true;
1094     }
1095
1096   if (! tree_fits_uhwi_p (len))
1097     return false;
1098
1099   if (TREE_CODE (c) != INTEGER_CST)
1100     return false;
1101
1102   tree dest = gimple_call_arg (stmt, 0);
1103   tree var = dest;
1104   if (TREE_CODE (var) != ADDR_EXPR)
1105     return false;
1106
1107   var = TREE_OPERAND (var, 0);
1108   if (TREE_THIS_VOLATILE (var))
1109     return false;
1110
1111   etype = TREE_TYPE (var);
1112   if (TREE_CODE (etype) == ARRAY_TYPE)
1113     etype = TREE_TYPE (etype);
1114
1115   if (!INTEGRAL_TYPE_P (etype)
1116       && !POINTER_TYPE_P (etype))
1117     return NULL_TREE;
1118
1119   if (! var_decl_component_p (var))
1120     return NULL_TREE;
1121
1122   length = tree_to_uhwi (len);
1123   if (GET_MODE_SIZE (TYPE_MODE (etype)) != length
1124       || get_pointer_alignment (dest) / BITS_PER_UNIT < length)
1125     return NULL_TREE;
1126
1127   if (length > HOST_BITS_PER_WIDE_INT / BITS_PER_UNIT)
1128     return NULL_TREE;
1129
1130   if (integer_zerop (c))
1131     cval = 0;
1132   else
1133     {
1134       if (CHAR_BIT != 8 || BITS_PER_UNIT != 8 || HOST_BITS_PER_WIDE_INT > 64)
1135         return NULL_TREE;
1136
1137       cval = TREE_INT_CST_LOW (c);
1138       cval &= 0xff;
1139       cval |= cval << 8;
1140       cval |= cval << 16;
1141       cval |= (cval << 31) << 1;
1142     }
1143
1144   var = fold_build2 (MEM_REF, etype, dest, build_int_cst (ptr_type_node, 0));
1145   gimple *store = gimple_build_assign (var, build_int_cst_type (etype, cval));
1146   gimple_set_vuse (store, gimple_vuse (stmt));
1147   tree vdef = gimple_vdef (stmt);
1148   if (vdef && TREE_CODE (vdef) == SSA_NAME)
1149     {
1150       gimple_set_vdef (store, gimple_vdef (stmt));
1151       SSA_NAME_DEF_STMT (gimple_vdef (stmt)) = store;
1152     }
1153   gsi_insert_before (gsi, store, GSI_SAME_STMT);
1154   if (gimple_call_lhs (stmt))
1155     {
1156       gimple *asgn = gimple_build_assign (gimple_call_lhs (stmt), dest);
1157       gsi_replace (gsi, asgn, false);
1158     }
1159   else
1160     {
1161       gimple_stmt_iterator gsi2 = *gsi;
1162       gsi_prev (gsi);
1163       gsi_remove (&gsi2, true);
1164     }
1165
1166   return true;
1167 }
1168
1169
1170 /* Obtain the minimum and maximum string length or minimum and maximum
1171    value of ARG in LENGTH[0] and LENGTH[1], respectively.
1172    If ARG is an SSA name variable, follow its use-def chains.  When
1173    TYPE == 0, if LENGTH[1] is not equal to the length we determine or
1174    if we are unable to determine the length or value, return False.
1175    VISITED is a bitmap of visited variables.
1176    TYPE is 0 if string length should be obtained, 1 for maximum string
1177    length and 2 for maximum value ARG can have.
1178    When FUZZY is set and the length of a string cannot be determined,
1179    the function instead considers as the maximum possible length the
1180    size of a character array it may refer to.  */
1181
1182 static bool
1183 get_range_strlen (tree arg, tree length[2], bitmap *visited, int type,
1184                   bool fuzzy)
1185 {
1186   tree var, val;
1187   gimple *def_stmt;
1188
1189   /* The minimum and maximum length.  The MAXLEN pointer stays unchanged
1190      but MINLEN may be cleared during the execution of the function.  */
1191   tree *minlen = length;
1192   tree *const maxlen = length + 1;
1193
1194   if (TREE_CODE (arg) != SSA_NAME)
1195     {
1196       /* We can end up with &(*iftmp_1)[0] here as well, so handle it.  */
1197       if (TREE_CODE (arg) == ADDR_EXPR
1198           && TREE_CODE (TREE_OPERAND (arg, 0)) == ARRAY_REF
1199           && integer_zerop (TREE_OPERAND (TREE_OPERAND (arg, 0), 1)))
1200         {
1201           tree aop0 = TREE_OPERAND (TREE_OPERAND (arg, 0), 0);
1202           if (TREE_CODE (aop0) == INDIRECT_REF
1203               && TREE_CODE (TREE_OPERAND (aop0, 0)) == SSA_NAME)
1204             return get_range_strlen (TREE_OPERAND (aop0, 0),
1205                                      length, visited, type, fuzzy);
1206         }
1207
1208       if (type == 2)
1209         {
1210           val = arg;
1211           if (TREE_CODE (val) != INTEGER_CST
1212               || tree_int_cst_sgn (val) < 0)
1213             return false;
1214         }
1215       else
1216         val = c_strlen (arg, 1);
1217
1218       if (!val && fuzzy)
1219         {
1220           if (TREE_CODE (arg) == ADDR_EXPR)
1221             return get_range_strlen (TREE_OPERAND (arg, 0), length,
1222                                      visited, type, fuzzy);
1223
1224           if (TREE_CODE (arg) == COMPONENT_REF
1225               && TREE_CODE (TREE_TYPE (TREE_OPERAND (arg, 1))) == ARRAY_TYPE)
1226             {
1227               /* Use the type of the member array to determine the upper
1228                  bound on the length of the array.  This may be overly
1229                  optimistic if the array itself isn't NUL-terminated and
1230                  the caller relies on the subsequent member to contain
1231                  the NUL.  */
1232               arg = TREE_OPERAND (arg, 1);
1233               val = TYPE_SIZE_UNIT (TREE_TYPE (arg));
1234               if (!val || integer_zerop (val))
1235                 return false;
1236               val = fold_build2 (MINUS_EXPR, TREE_TYPE (val), val,
1237                                  integer_one_node);
1238               /* Avoid using the array size as the minimum.  */
1239               minlen = NULL;
1240             }
1241         }
1242
1243       if (!val)
1244         return false;
1245
1246       if (minlen
1247           && (!*minlen
1248               || (type > 0
1249                   && TREE_CODE (*minlen) == INTEGER_CST
1250                   && TREE_CODE (val) == INTEGER_CST
1251                   && tree_int_cst_lt (val, *minlen))))
1252         *minlen = val;
1253
1254       if (*maxlen)
1255         {
1256           if (type > 0)
1257             {
1258               if (TREE_CODE (*maxlen) != INTEGER_CST
1259                   || TREE_CODE (val) != INTEGER_CST)
1260                 return false;
1261
1262               if (tree_int_cst_lt (*maxlen, val))
1263                 *maxlen = val;
1264               return true;
1265             }
1266           else if (simple_cst_equal (val, *maxlen) != 1)
1267             return false;
1268         }
1269
1270       *maxlen = val;
1271       return true;
1272     }
1273
1274   /* If ARG is registered for SSA update we cannot look at its defining
1275      statement.  */
1276   if (name_registered_for_update_p (arg))
1277     return false;
1278
1279   /* If we were already here, break the infinite cycle.  */
1280   if (!*visited)
1281     *visited = BITMAP_ALLOC (NULL);
1282   if (!bitmap_set_bit (*visited, SSA_NAME_VERSION (arg)))
1283     return true;
1284
1285   var = arg;
1286   def_stmt = SSA_NAME_DEF_STMT (var);
1287
1288   switch (gimple_code (def_stmt))
1289     {
1290       case GIMPLE_ASSIGN:
1291         /* The RHS of the statement defining VAR must either have a
1292            constant length or come from another SSA_NAME with a constant
1293            length.  */
1294         if (gimple_assign_single_p (def_stmt)
1295             || gimple_assign_unary_nop_p (def_stmt))
1296           {
1297             tree rhs = gimple_assign_rhs1 (def_stmt);
1298             return get_range_strlen (rhs, length, visited, type, fuzzy);
1299           }
1300         else if (gimple_assign_rhs_code (def_stmt) == COND_EXPR)
1301           {
1302             tree op2 = gimple_assign_rhs2 (def_stmt);
1303             tree op3 = gimple_assign_rhs3 (def_stmt);
1304             return get_range_strlen (op2, length, visited, type, fuzzy)
1305               && get_range_strlen (op3, length, visited, type, fuzzy);
1306           }
1307         return false;
1308
1309       case GIMPLE_PHI:
1310         {
1311           /* All the arguments of the PHI node must have the same constant
1312              length.  */
1313           unsigned i;
1314
1315           for (i = 0; i < gimple_phi_num_args (def_stmt); i++)
1316           {
1317             tree arg = gimple_phi_arg (def_stmt, i)->def;
1318
1319             /* If this PHI has itself as an argument, we cannot
1320                determine the string length of this argument.  However,
1321                if we can find a constant string length for the other
1322                PHI args then we can still be sure that this is a
1323                constant string length.  So be optimistic and just
1324                continue with the next argument.  */
1325             if (arg == gimple_phi_result (def_stmt))
1326               continue;
1327
1328             if (!get_range_strlen (arg, length, visited, type, fuzzy))
1329               {
1330                 if (fuzzy)
1331                   *maxlen = build_all_ones_cst (size_type_node);
1332                 else
1333                   return false;
1334               }
1335           }
1336         }
1337         return true;
1338
1339       default:
1340         return false;
1341     }
1342 }
1343
1344 /* Determine the minimum and maximum value or string length that ARG
1345    refers to and store each in the first two elements of MINMAXLEN.
1346    For expressions that point to strings of unknown lengths that are
1347    character arrays, use the upper bound of the array as the maximum
1348    length.  For example, given an expression like 'x ? array : "xyz"'
1349    and array declared as 'char array[8]', MINMAXLEN[0] will be set
1350    to 3 and MINMAXLEN[1] to 7, the longest string that could be
1351    stored in array.
1352 */
1353
1354 void get_range_strlen (tree arg, tree minmaxlen[2])
1355 {
1356   bitmap visited = NULL;
1357
1358   minmaxlen[0] = NULL_TREE;
1359   minmaxlen[1] = NULL_TREE;
1360
1361   get_range_strlen (arg, minmaxlen, &visited, 1, true);
1362
1363   if (visited)
1364     BITMAP_FREE (visited);
1365 }
1366
1367 tree
1368 get_maxval_strlen (tree arg, int type)
1369 {
1370   bitmap visited = NULL;
1371   tree len[2] = { NULL_TREE, NULL_TREE };
1372   if (!get_range_strlen (arg, len, &visited, type, false))
1373     len[1] = NULL_TREE;
1374   if (visited)
1375     BITMAP_FREE (visited);
1376
1377   return len[1];
1378 }
1379
1380
1381 /* Fold function call to builtin strcpy with arguments DEST and SRC.
1382    If LEN is not NULL, it represents the length of the string to be
1383    copied.  Return NULL_TREE if no simplification can be made.  */
1384
1385 static bool
1386 gimple_fold_builtin_strcpy (gimple_stmt_iterator *gsi,
1387                             tree dest, tree src)
1388 {
1389   location_t loc = gimple_location (gsi_stmt (*gsi));
1390   tree fn;
1391
1392   /* If SRC and DEST are the same (and not volatile), return DEST.  */
1393   if (operand_equal_p (src, dest, 0))
1394     {
1395       replace_call_with_value (gsi, dest);
1396       return true;
1397     }
1398
1399   if (optimize_function_for_size_p (cfun))
1400     return false;
1401
1402   fn = builtin_decl_implicit (BUILT_IN_MEMCPY);
1403   if (!fn)
1404     return false;
1405
1406   tree len = get_maxval_strlen (src, 0);
1407   if (!len)
1408     return false;
1409
1410   len = fold_convert_loc (loc, size_type_node, len);
1411   len = size_binop_loc (loc, PLUS_EXPR, len, build_int_cst (size_type_node, 1));
1412   len = force_gimple_operand_gsi (gsi, len, true,
1413                                   NULL_TREE, true, GSI_SAME_STMT);
1414   gimple *repl = gimple_build_call (fn, 3, dest, src, len);
1415   replace_call_with_call_and_fold (gsi, repl);
1416   return true;
1417 }
1418
1419 /* Fold function call to builtin strncpy with arguments DEST, SRC, and LEN.
1420    If SLEN is not NULL, it represents the length of the source string.
1421    Return NULL_TREE if no simplification can be made.  */
1422
1423 static bool
1424 gimple_fold_builtin_strncpy (gimple_stmt_iterator *gsi,
1425                              tree dest, tree src, tree len)
1426 {
1427   location_t loc = gimple_location (gsi_stmt (*gsi));
1428   tree fn;
1429
1430   /* If the LEN parameter is zero, return DEST.  */
1431   if (integer_zerop (len))
1432     {
1433       replace_call_with_value (gsi, dest);
1434       return true;
1435     }
1436
1437   /* We can't compare slen with len as constants below if len is not a
1438      constant.  */
1439   if (TREE_CODE (len) != INTEGER_CST)
1440     return false;
1441
1442   /* Now, we must be passed a constant src ptr parameter.  */
1443   tree slen = get_maxval_strlen (src, 0);
1444   if (!slen || TREE_CODE (slen) != INTEGER_CST)
1445     return false;
1446
1447   slen = size_binop_loc (loc, PLUS_EXPR, slen, ssize_int (1));
1448
1449   /* We do not support simplification of this case, though we do
1450      support it when expanding trees into RTL.  */
1451   /* FIXME: generate a call to __builtin_memset.  */
1452   if (tree_int_cst_lt (slen, len))
1453     return false;
1454
1455   /* OK transform into builtin memcpy.  */
1456   fn = builtin_decl_implicit (BUILT_IN_MEMCPY);
1457   if (!fn)
1458     return false;
1459
1460   len = fold_convert_loc (loc, size_type_node, len);
1461   len = force_gimple_operand_gsi (gsi, len, true,
1462                                   NULL_TREE, true, GSI_SAME_STMT);
1463   gimple *repl = gimple_build_call (fn, 3, dest, src, len);
1464   replace_call_with_call_and_fold (gsi, repl);
1465   return true;
1466 }
1467
1468 /* Fold function call to builtin strchr or strrchr.
1469    If both arguments are constant, evaluate and fold the result,
1470    otherwise simplify str(r)chr (str, 0) into str + strlen (str).
1471    In general strlen is significantly faster than strchr
1472    due to being a simpler operation.  */
1473 static bool
1474 gimple_fold_builtin_strchr (gimple_stmt_iterator *gsi, bool is_strrchr)
1475 {
1476   gimple *stmt = gsi_stmt (*gsi);
1477   tree str = gimple_call_arg (stmt, 0);
1478   tree c = gimple_call_arg (stmt, 1);
1479   location_t loc = gimple_location (stmt);
1480   const char *p;
1481   char ch;
1482
1483   if (!gimple_call_lhs (stmt))
1484     return false;
1485
1486   if ((p = c_getstr (str)) && target_char_cst_p (c, &ch))
1487     {
1488       const char *p1 = is_strrchr ? strrchr (p, ch) : strchr (p, ch);
1489
1490       if (p1 == NULL)
1491         {
1492           replace_call_with_value (gsi, integer_zero_node);
1493           return true;
1494         }
1495
1496       tree len = build_int_cst (size_type_node, p1 - p);
1497       gimple_seq stmts = NULL;
1498       gimple *new_stmt = gimple_build_assign (gimple_call_lhs (stmt),
1499                                               POINTER_PLUS_EXPR, str, len);
1500       gimple_seq_add_stmt_without_update (&stmts, new_stmt);
1501       gsi_replace_with_seq_vops (gsi, stmts);
1502       return true;
1503     }
1504
1505   if (!integer_zerop (c))
1506     return false;
1507
1508   /* Transform strrchr (s, 0) to strchr (s, 0) when optimizing for size.  */
1509   if (optimize_function_for_size_p (cfun))
1510     {
1511       tree strchr_fn = builtin_decl_implicit (BUILT_IN_STRCHR);
1512
1513       if (is_strrchr && strchr_fn)
1514         {
1515           gimple *repl = gimple_build_call (strchr_fn, 2, str, c);
1516           replace_call_with_call_and_fold (gsi, repl);
1517           return true;
1518         }
1519
1520       return false;
1521     }
1522
1523   tree len;
1524   tree strlen_fn = builtin_decl_implicit (BUILT_IN_STRLEN);
1525
1526   if (!strlen_fn)
1527     return false;
1528
1529   /* Create newstr = strlen (str).  */
1530   gimple_seq stmts = NULL;
1531   gimple *new_stmt = gimple_build_call (strlen_fn, 1, str);
1532   gimple_set_location (new_stmt, loc);
1533   len = create_tmp_reg_or_ssa_name (size_type_node);
1534   gimple_call_set_lhs (new_stmt, len);
1535   gimple_seq_add_stmt_without_update (&stmts, new_stmt);
1536
1537   /* Create (str p+ strlen (str)).  */
1538   new_stmt = gimple_build_assign (gimple_call_lhs (stmt),
1539                                   POINTER_PLUS_EXPR, str, len);
1540   gimple_seq_add_stmt_without_update (&stmts, new_stmt);
1541   gsi_replace_with_seq_vops (gsi, stmts);
1542   /* gsi now points at the assignment to the lhs, get a
1543      stmt iterator to the strlen.
1544      ???  We can't use gsi_for_stmt as that doesn't work when the
1545      CFG isn't built yet.  */
1546   gimple_stmt_iterator gsi2 = *gsi;
1547   gsi_prev (&gsi2);
1548   fold_stmt (&gsi2);
1549   return true;
1550 }
1551
1552 /* Simplify a call to the strcat builtin.  DST and SRC are the arguments
1553    to the call.
1554
1555    Return NULL_TREE if no simplification was possible, otherwise return the
1556    simplified form of the call as a tree.
1557
1558    The simplified form may be a constant or other expression which
1559    computes the same value, but in a more efficient manner (including
1560    calls to other builtin functions).
1561
1562    The call may contain arguments which need to be evaluated, but
1563    which are not useful to determine the result of the call.  In
1564    this case we return a chain of COMPOUND_EXPRs.  The LHS of each
1565    COMPOUND_EXPR will be an argument which must be evaluated.
1566    COMPOUND_EXPRs are chained through their RHS.  The RHS of the last
1567    COMPOUND_EXPR in the chain will contain the tree for the simplified
1568    form of the builtin function call.  */
1569
1570 static bool
1571 gimple_fold_builtin_strcat (gimple_stmt_iterator *gsi, tree dst, tree src)
1572 {
1573   gimple *stmt = gsi_stmt (*gsi);
1574   location_t loc = gimple_location (stmt);
1575
1576   const char *p = c_getstr (src);
1577
1578   /* If the string length is zero, return the dst parameter.  */
1579   if (p && *p == '\0')
1580     {
1581       replace_call_with_value (gsi, dst);
1582       return true;
1583     }
1584
1585   if (!optimize_bb_for_speed_p (gimple_bb (stmt)))
1586     return false;
1587
1588   /* See if we can store by pieces into (dst + strlen(dst)).  */
1589   tree newdst;
1590   tree strlen_fn = builtin_decl_implicit (BUILT_IN_STRLEN);
1591   tree memcpy_fn = builtin_decl_implicit (BUILT_IN_MEMCPY);
1592
1593   if (!strlen_fn || !memcpy_fn)
1594     return false;
1595
1596   /* If the length of the source string isn't computable don't
1597      split strcat into strlen and memcpy.  */
1598   tree len = get_maxval_strlen (src, 0);
1599   if (! len)
1600     return false;
1601
1602   /* Create strlen (dst).  */
1603   gimple_seq stmts = NULL, stmts2;
1604   gimple *repl = gimple_build_call (strlen_fn, 1, dst);
1605   gimple_set_location (repl, loc);
1606   newdst = create_tmp_reg_or_ssa_name (size_type_node);
1607   gimple_call_set_lhs (repl, newdst);
1608   gimple_seq_add_stmt_without_update (&stmts, repl);
1609
1610   /* Create (dst p+ strlen (dst)).  */
1611   newdst = fold_build_pointer_plus_loc (loc, dst, newdst);
1612   newdst = force_gimple_operand (newdst, &stmts2, true, NULL_TREE);
1613   gimple_seq_add_seq_without_update (&stmts, stmts2);
1614
1615   len = fold_convert_loc (loc, size_type_node, len);
1616   len = size_binop_loc (loc, PLUS_EXPR, len,
1617                         build_int_cst (size_type_node, 1));
1618   len = force_gimple_operand (len, &stmts2, true, NULL_TREE);
1619   gimple_seq_add_seq_without_update (&stmts, stmts2);
1620
1621   repl = gimple_build_call (memcpy_fn, 3, newdst, src, len);
1622   gimple_seq_add_stmt_without_update (&stmts, repl);
1623   if (gimple_call_lhs (stmt))
1624     {
1625       repl = gimple_build_assign (gimple_call_lhs (stmt), dst);
1626       gimple_seq_add_stmt_without_update (&stmts, repl);
1627       gsi_replace_with_seq_vops (gsi, stmts);
1628       /* gsi now points at the assignment to the lhs, get a
1629          stmt iterator to the memcpy call.
1630          ???  We can't use gsi_for_stmt as that doesn't work when the
1631          CFG isn't built yet.  */
1632       gimple_stmt_iterator gsi2 = *gsi;
1633       gsi_prev (&gsi2);
1634       fold_stmt (&gsi2);
1635     }
1636   else
1637     {
1638       gsi_replace_with_seq_vops (gsi, stmts);
1639       fold_stmt (gsi);
1640     }
1641   return true;
1642 }
1643
1644 /* Fold a call to the __strcat_chk builtin FNDECL.  DEST, SRC, and SIZE
1645    are the arguments to the call.  */
1646
1647 static bool
1648 gimple_fold_builtin_strcat_chk (gimple_stmt_iterator *gsi)
1649 {
1650   gimple *stmt = gsi_stmt (*gsi);
1651   tree dest = gimple_call_arg (stmt, 0);
1652   tree src = gimple_call_arg (stmt, 1);
1653   tree size = gimple_call_arg (stmt, 2);
1654   tree fn;
1655   const char *p;
1656
1657
1658   p = c_getstr (src);
1659   /* If the SRC parameter is "", return DEST.  */
1660   if (p && *p == '\0')
1661     {
1662       replace_call_with_value (gsi, dest);
1663       return true;
1664     }
1665
1666   if (! tree_fits_uhwi_p (size) || ! integer_all_onesp (size))
1667     return false;
1668
1669   /* If __builtin_strcat_chk is used, assume strcat is available.  */
1670   fn = builtin_decl_explicit (BUILT_IN_STRCAT);
1671   if (!fn)
1672     return false;
1673
1674   gimple *repl = gimple_build_call (fn, 2, dest, src);
1675   replace_call_with_call_and_fold (gsi, repl);
1676   return true;
1677 }
1678
1679 /* Simplify a call to the strncat builtin.  */
1680
1681 static bool
1682 gimple_fold_builtin_strncat (gimple_stmt_iterator *gsi)
1683 {
1684   gcall *stmt = as_a <gcall *> (gsi_stmt (*gsi));
1685   tree dst = gimple_call_arg (stmt, 0);
1686   tree src = gimple_call_arg (stmt, 1);
1687   tree len = gimple_call_arg (stmt, 2);
1688
1689   const char *p = c_getstr (src);
1690
1691   /* If the requested length is zero, or the src parameter string
1692      length is zero, return the dst parameter.  */
1693   if (integer_zerop (len) || (p && *p == '\0'))
1694     {
1695       replace_call_with_value (gsi, dst);
1696       return true;
1697     }
1698
1699   /* If the requested len is greater than or equal to the string
1700      length, call strcat.  */
1701   if (TREE_CODE (len) == INTEGER_CST && p
1702       && compare_tree_int (len, strlen (p)) >= 0)
1703     {
1704       tree fn = builtin_decl_implicit (BUILT_IN_STRCAT);
1705
1706       /* If the replacement _DECL isn't initialized, don't do the
1707          transformation.  */
1708       if (!fn)
1709         return false;
1710
1711       gcall *repl = gimple_build_call (fn, 2, dst, src);
1712       replace_call_with_call_and_fold (gsi, repl);
1713       return true;
1714     }
1715
1716   return false;
1717 }
1718
1719 /* Fold a call to the __strncat_chk builtin with arguments DEST, SRC,
1720    LEN, and SIZE.  */
1721
1722 static bool 
1723 gimple_fold_builtin_strncat_chk (gimple_stmt_iterator *gsi)
1724 {
1725   gimple *stmt = gsi_stmt (*gsi);
1726   tree dest = gimple_call_arg (stmt, 0);
1727   tree src = gimple_call_arg (stmt, 1);
1728   tree len = gimple_call_arg (stmt, 2);
1729   tree size = gimple_call_arg (stmt, 3);
1730   tree fn;
1731   const char *p;
1732
1733   p = c_getstr (src);
1734   /* If the SRC parameter is "" or if LEN is 0, return DEST.  */
1735   if ((p && *p == '\0')
1736       || integer_zerop (len))
1737     {
1738       replace_call_with_value (gsi, dest);
1739       return true;
1740     }
1741
1742   if (! tree_fits_uhwi_p (size))
1743     return false;
1744
1745   if (! integer_all_onesp (size))
1746     {
1747       tree src_len = c_strlen (src, 1);
1748       if (src_len
1749           && tree_fits_uhwi_p (src_len)
1750           && tree_fits_uhwi_p (len)
1751           && ! tree_int_cst_lt (len, src_len))
1752         {
1753           /* If LEN >= strlen (SRC), optimize into __strcat_chk.  */
1754           fn = builtin_decl_explicit (BUILT_IN_STRCAT_CHK);
1755           if (!fn)
1756             return false;
1757
1758           gimple *repl = gimple_build_call (fn, 3, dest, src, size);
1759           replace_call_with_call_and_fold (gsi, repl);
1760           return true;
1761         }
1762       return false;
1763     }
1764
1765   /* If __builtin_strncat_chk is used, assume strncat is available.  */
1766   fn = builtin_decl_explicit (BUILT_IN_STRNCAT);
1767   if (!fn)
1768     return false;
1769
1770   gimple *repl = gimple_build_call (fn, 3, dest, src, len);
1771   replace_call_with_call_and_fold (gsi, repl);
1772   return true;
1773 }
1774
1775 /* Build and append gimple statements to STMTS that would load a first
1776    character of a memory location identified by STR.  LOC is location
1777    of the statement.  */
1778
1779 static tree
1780 gimple_load_first_char (location_t loc, tree str, gimple_seq *stmts)
1781 {
1782   tree var;
1783
1784   tree cst_uchar_node = build_type_variant (unsigned_char_type_node, 1, 0);
1785   tree cst_uchar_ptr_node
1786     = build_pointer_type_for_mode (cst_uchar_node, ptr_mode, true);
1787   tree off0 = build_int_cst (cst_uchar_ptr_node, 0);
1788
1789   tree temp = fold_build2_loc (loc, MEM_REF, cst_uchar_node, str, off0);
1790   gassign *stmt = gimple_build_assign (NULL_TREE, temp);
1791   var = create_tmp_reg_or_ssa_name (cst_uchar_node, stmt);
1792
1793   gimple_assign_set_lhs (stmt, var);
1794   gimple_seq_add_stmt_without_update (stmts, stmt);
1795
1796   return var;
1797 }
1798
1799 /* Fold a call to the str{n}{case}cmp builtin pointed by GSI iterator.
1800    FCODE is the name of the builtin.  */
1801
1802 static bool
1803 gimple_fold_builtin_string_compare (gimple_stmt_iterator *gsi)
1804 {
1805   gimple *stmt = gsi_stmt (*gsi);
1806   tree callee = gimple_call_fndecl (stmt);
1807   enum built_in_function fcode = DECL_FUNCTION_CODE (callee);
1808
1809   tree type = integer_type_node;
1810   tree str1 = gimple_call_arg (stmt, 0);
1811   tree str2 = gimple_call_arg (stmt, 1);
1812   tree lhs = gimple_call_lhs (stmt);
1813   HOST_WIDE_INT length = -1;
1814
1815   /* Handle strncmp and strncasecmp functions.  */
1816   if (gimple_call_num_args (stmt) == 3)
1817     {
1818       tree len = gimple_call_arg (stmt, 2);
1819       if (tree_fits_uhwi_p (len))
1820         length = tree_to_uhwi (len);
1821     }
1822
1823   /* If the LEN parameter is zero, return zero.  */
1824   if (length == 0)
1825     {
1826       replace_call_with_value (gsi, integer_zero_node);
1827       return true;
1828     }
1829
1830   /* If ARG1 and ARG2 are the same (and not volatile), return zero.  */
1831   if (operand_equal_p (str1, str2, 0))
1832     {
1833       replace_call_with_value (gsi, integer_zero_node);
1834       return true;
1835     }
1836
1837   const char *p1 = c_getstr (str1);
1838   const char *p2 = c_getstr (str2);
1839
1840   /* For known strings, return an immediate value.  */
1841   if (p1 && p2)
1842     {
1843       int r = 0;
1844       bool known_result = false;
1845
1846       switch (fcode)
1847         {
1848         case BUILT_IN_STRCMP:
1849           {
1850             r = strcmp (p1, p2);
1851             known_result = true;
1852             break;
1853           }
1854         case BUILT_IN_STRNCMP:
1855           {
1856             if (length == -1)
1857               break;
1858             r = strncmp (p1, p2, length);
1859             known_result = true;
1860             break;
1861           }
1862         /* Only handleable situation is where the string are equal (result 0),
1863            which is already handled by operand_equal_p case.  */
1864         case BUILT_IN_STRCASECMP:
1865           break;
1866         case BUILT_IN_STRNCASECMP:
1867           {
1868             if (length == -1)
1869               break;
1870             r = strncmp (p1, p2, length);
1871             if (r == 0)
1872               known_result = true;
1873             break;;
1874           }
1875         default:
1876           gcc_unreachable ();
1877         }
1878
1879       if (known_result)
1880         {
1881           replace_call_with_value (gsi, build_cmp_result (type, r));
1882           return true;
1883         }
1884     }
1885
1886   bool nonzero_length = length >= 1
1887     || fcode == BUILT_IN_STRCMP
1888     || fcode == BUILT_IN_STRCASECMP;
1889
1890   location_t loc = gimple_location (stmt);
1891
1892   /* If the second arg is "", return *(const unsigned char*)arg1.  */
1893   if (p2 && *p2 == '\0' && nonzero_length)
1894     {
1895       gimple_seq stmts = NULL;
1896       tree var = gimple_load_first_char (loc, str1, &stmts);
1897       if (lhs)
1898         {
1899           stmt = gimple_build_assign (lhs, NOP_EXPR, var);
1900           gimple_seq_add_stmt_without_update (&stmts, stmt);
1901         }
1902
1903       gsi_replace_with_seq_vops (gsi, stmts);
1904       return true;
1905     }
1906
1907   /* If the first arg is "", return -*(const unsigned char*)arg2.  */
1908   if (p1 && *p1 == '\0' && nonzero_length)
1909     {
1910       gimple_seq stmts = NULL;
1911       tree var = gimple_load_first_char (loc, str2, &stmts);
1912
1913       if (lhs)
1914         {
1915           tree c = create_tmp_reg_or_ssa_name (integer_type_node);
1916           stmt = gimple_build_assign (c, NOP_EXPR, var);
1917           gimple_seq_add_stmt_without_update (&stmts, stmt);
1918
1919           stmt = gimple_build_assign (lhs, NEGATE_EXPR, c);
1920           gimple_seq_add_stmt_without_update (&stmts, stmt);
1921         }
1922
1923       gsi_replace_with_seq_vops (gsi, stmts);
1924       return true;
1925     }
1926
1927   /* If len parameter is one, return an expression corresponding to
1928      (*(const unsigned char*)arg2 - *(const unsigned char*)arg1).  */
1929   if (fcode == BUILT_IN_STRNCMP && length == 1)
1930     {
1931       gimple_seq stmts = NULL;
1932       tree temp1 = gimple_load_first_char (loc, str1, &stmts);
1933       tree temp2 = gimple_load_first_char (loc, str2, &stmts);
1934
1935       if (lhs)
1936         {
1937           tree c1 = create_tmp_reg_or_ssa_name (integer_type_node);
1938           gassign *convert1 = gimple_build_assign (c1, NOP_EXPR, temp1);
1939           gimple_seq_add_stmt_without_update (&stmts, convert1);
1940
1941           tree c2 = create_tmp_reg_or_ssa_name (integer_type_node);
1942           gassign *convert2 = gimple_build_assign (c2, NOP_EXPR, temp2);
1943           gimple_seq_add_stmt_without_update (&stmts, convert2);
1944
1945           stmt = gimple_build_assign (lhs, MINUS_EXPR, c1, c2);
1946           gimple_seq_add_stmt_without_update (&stmts, stmt);
1947         }
1948
1949       gsi_replace_with_seq_vops (gsi, stmts);
1950       return true;
1951     }
1952
1953   return false;
1954 }
1955
1956 /* Fold a call to the memchr pointed by GSI iterator.  */
1957
1958 static bool
1959 gimple_fold_builtin_memchr (gimple_stmt_iterator *gsi)
1960 {
1961   gimple *stmt = gsi_stmt (*gsi);
1962   tree lhs = gimple_call_lhs (stmt);
1963   tree arg1 = gimple_call_arg (stmt, 0);
1964   tree arg2 = gimple_call_arg (stmt, 1);
1965   tree len = gimple_call_arg (stmt, 2);
1966
1967   /* If the LEN parameter is zero, return zero.  */
1968   if (integer_zerop (len))
1969     {
1970       replace_call_with_value (gsi, build_int_cst (ptr_type_node, 0));
1971       return true;
1972     }
1973
1974   char c;
1975   if (TREE_CODE (arg2) != INTEGER_CST
1976       || !tree_fits_uhwi_p (len)
1977       || !target_char_cst_p (arg2, &c))
1978     return false;
1979
1980   unsigned HOST_WIDE_INT length = tree_to_uhwi (len);
1981   unsigned HOST_WIDE_INT string_length;
1982   const char *p1 = c_getstr (arg1, &string_length);
1983
1984   if (p1)
1985     {
1986       const char *r = (const char *)memchr (p1, c, MIN (length, string_length));
1987       if (r == NULL)
1988         {
1989           if (length <= string_length)
1990             {
1991               replace_call_with_value (gsi, build_int_cst (ptr_type_node, 0));
1992               return true;
1993             }
1994         }
1995       else
1996         {
1997           unsigned HOST_WIDE_INT offset = r - p1;
1998           gimple_seq stmts = NULL;
1999           if (lhs != NULL_TREE)
2000             {
2001               tree offset_cst = build_int_cst (TREE_TYPE (len), offset);
2002               gassign *stmt = gimple_build_assign (lhs, POINTER_PLUS_EXPR,
2003                                                    arg1, offset_cst);
2004               gimple_seq_add_stmt_without_update (&stmts, stmt);
2005             }
2006           else
2007             gimple_seq_add_stmt_without_update (&stmts,
2008                                                 gimple_build_nop ());
2009
2010           gsi_replace_with_seq_vops (gsi, stmts);
2011           return true;
2012         }
2013     }
2014
2015   return false;
2016 }
2017
2018 /* Fold a call to the fputs builtin.  ARG0 and ARG1 are the arguments
2019    to the call.  IGNORE is true if the value returned
2020    by the builtin will be ignored.  UNLOCKED is true is true if this
2021    actually a call to fputs_unlocked.  If LEN in non-NULL, it represents
2022    the known length of the string.  Return NULL_TREE if no simplification
2023    was possible.  */
2024
2025 static bool
2026 gimple_fold_builtin_fputs (gimple_stmt_iterator *gsi,
2027                            tree arg0, tree arg1,
2028                            bool unlocked)
2029 {
2030   gimple *stmt = gsi_stmt (*gsi);
2031
2032   /* If we're using an unlocked function, assume the other unlocked
2033      functions exist explicitly.  */
2034   tree const fn_fputc = (unlocked
2035                          ? builtin_decl_explicit (BUILT_IN_FPUTC_UNLOCKED)
2036                          : builtin_decl_implicit (BUILT_IN_FPUTC));
2037   tree const fn_fwrite = (unlocked
2038                           ? builtin_decl_explicit (BUILT_IN_FWRITE_UNLOCKED)
2039                           : builtin_decl_implicit (BUILT_IN_FWRITE));
2040
2041   /* If the return value is used, don't do the transformation.  */
2042   if (gimple_call_lhs (stmt))
2043     return false;
2044
2045   /* Get the length of the string passed to fputs.  If the length
2046      can't be determined, punt.  */
2047   tree len = get_maxval_strlen (arg0, 0);
2048   if (!len
2049       || TREE_CODE (len) != INTEGER_CST)
2050     return false;
2051
2052   switch (compare_tree_int (len, 1))
2053     {
2054     case -1: /* length is 0, delete the call entirely .  */
2055       replace_call_with_value (gsi, integer_zero_node);
2056       return true;
2057
2058     case 0: /* length is 1, call fputc.  */
2059       {
2060         const char *p = c_getstr (arg0);
2061         if (p != NULL)
2062           {
2063             if (!fn_fputc)
2064               return false;
2065
2066             gimple *repl = gimple_build_call (fn_fputc, 2,
2067                                              build_int_cst
2068                                              (integer_type_node, p[0]), arg1);
2069             replace_call_with_call_and_fold (gsi, repl);
2070             return true;
2071           }
2072       }
2073       /* FALLTHROUGH */
2074     case 1: /* length is greater than 1, call fwrite.  */
2075       {
2076         /* If optimizing for size keep fputs.  */
2077         if (optimize_function_for_size_p (cfun))
2078           return false;
2079         /* New argument list transforming fputs(string, stream) to
2080            fwrite(string, 1, len, stream).  */
2081         if (!fn_fwrite)
2082           return false;
2083
2084         gimple *repl = gimple_build_call (fn_fwrite, 4, arg0,
2085                                          size_one_node, len, arg1);
2086         replace_call_with_call_and_fold (gsi, repl);
2087         return true;
2088       }
2089     default:
2090       gcc_unreachable ();
2091     }
2092   return false;
2093 }
2094
2095 /* Fold a call to the __mem{cpy,pcpy,move,set}_chk builtin.
2096    DEST, SRC, LEN, and SIZE are the arguments to the call.
2097    IGNORE is true, if return value can be ignored.  FCODE is the BUILT_IN_*
2098    code of the builtin.  If MAXLEN is not NULL, it is maximum length
2099    passed as third argument.  */
2100
2101 static bool
2102 gimple_fold_builtin_memory_chk (gimple_stmt_iterator *gsi,
2103                                 tree dest, tree src, tree len, tree size,
2104                                 enum built_in_function fcode)
2105 {
2106   gimple *stmt = gsi_stmt (*gsi);
2107   location_t loc = gimple_location (stmt);
2108   bool ignore = gimple_call_lhs (stmt) == NULL_TREE;
2109   tree fn;
2110
2111   /* If SRC and DEST are the same (and not volatile), return DEST
2112      (resp. DEST+LEN for __mempcpy_chk).  */
2113   if (fcode != BUILT_IN_MEMSET_CHK && operand_equal_p (src, dest, 0))
2114     {
2115       if (fcode != BUILT_IN_MEMPCPY_CHK)
2116         {
2117           replace_call_with_value (gsi, dest);
2118           return true;
2119         }
2120       else
2121         {
2122           gimple_seq stmts = NULL;
2123           len = gimple_convert_to_ptrofftype (&stmts, loc, len);
2124           tree temp = gimple_build (&stmts, loc, POINTER_PLUS_EXPR,
2125                                     TREE_TYPE (dest), dest, len);
2126           gsi_insert_seq_before (gsi, stmts, GSI_SAME_STMT);
2127           replace_call_with_value (gsi, temp);
2128           return true;
2129         }
2130     }
2131
2132   if (! tree_fits_uhwi_p (size))
2133     return false;
2134
2135   tree maxlen = get_maxval_strlen (len, 2);
2136   if (! integer_all_onesp (size))
2137     {
2138       if (! tree_fits_uhwi_p (len))
2139         {
2140           /* If LEN is not constant, try MAXLEN too.
2141              For MAXLEN only allow optimizing into non-_ocs function
2142              if SIZE is >= MAXLEN, never convert to __ocs_fail ().  */
2143           if (maxlen == NULL_TREE || ! tree_fits_uhwi_p (maxlen))
2144             {
2145               if (fcode == BUILT_IN_MEMPCPY_CHK && ignore)
2146                 {
2147                   /* (void) __mempcpy_chk () can be optimized into
2148                      (void) __memcpy_chk ().  */
2149                   fn = builtin_decl_explicit (BUILT_IN_MEMCPY_CHK);
2150                   if (!fn)
2151                     return false;
2152
2153                   gimple *repl = gimple_build_call (fn, 4, dest, src, len, size);
2154                   replace_call_with_call_and_fold (gsi, repl);
2155                   return true;
2156                 }
2157               return false;
2158             }
2159         }
2160       else
2161         maxlen = len;
2162
2163       if (tree_int_cst_lt (size, maxlen))
2164         return false;
2165     }
2166
2167   fn = NULL_TREE;
2168   /* If __builtin_mem{cpy,pcpy,move,set}_chk is used, assume
2169      mem{cpy,pcpy,move,set} is available.  */
2170   switch (fcode)
2171     {
2172     case BUILT_IN_MEMCPY_CHK:
2173       fn = builtin_decl_explicit (BUILT_IN_MEMCPY);
2174       break;
2175     case BUILT_IN_MEMPCPY_CHK:
2176       fn = builtin_decl_explicit (BUILT_IN_MEMPCPY);
2177       break;
2178     case BUILT_IN_MEMMOVE_CHK:
2179       fn = builtin_decl_explicit (BUILT_IN_MEMMOVE);
2180       break;
2181     case BUILT_IN_MEMSET_CHK:
2182       fn = builtin_decl_explicit (BUILT_IN_MEMSET);
2183       break;
2184     default:
2185       break;
2186     }
2187
2188   if (!fn)
2189     return false;
2190
2191   gimple *repl = gimple_build_call (fn, 3, dest, src, len);
2192   replace_call_with_call_and_fold (gsi, repl);
2193   return true;
2194 }
2195
2196 /* Fold a call to the __st[rp]cpy_chk builtin.
2197    DEST, SRC, and SIZE are the arguments to the call.
2198    IGNORE is true if return value can be ignored.  FCODE is the BUILT_IN_*
2199    code of the builtin.  If MAXLEN is not NULL, it is maximum length of
2200    strings passed as second argument.  */
2201
2202 static bool
2203 gimple_fold_builtin_stxcpy_chk (gimple_stmt_iterator *gsi,
2204                                 tree dest,
2205                                 tree src, tree size,
2206                                 enum built_in_function fcode)
2207 {
2208   gimple *stmt = gsi_stmt (*gsi);
2209   location_t loc = gimple_location (stmt);
2210   bool ignore = gimple_call_lhs (stmt) == NULL_TREE;
2211   tree len, fn;
2212
2213   /* If SRC and DEST are the same (and not volatile), return DEST.  */
2214   if (fcode == BUILT_IN_STRCPY_CHK && operand_equal_p (src, dest, 0))
2215     {
2216       replace_call_with_value (gsi, dest);
2217       return true;
2218     }
2219
2220   if (! tree_fits_uhwi_p (size))
2221     return false;
2222
2223   tree maxlen = get_maxval_strlen (src, 1);
2224   if (! integer_all_onesp (size))
2225     {
2226       len = c_strlen (src, 1);
2227       if (! len || ! tree_fits_uhwi_p (len))
2228         {
2229           /* If LEN is not constant, try MAXLEN too.
2230              For MAXLEN only allow optimizing into non-_ocs function
2231              if SIZE is >= MAXLEN, never convert to __ocs_fail ().  */
2232           if (maxlen == NULL_TREE || ! tree_fits_uhwi_p (maxlen))
2233             {
2234               if (fcode == BUILT_IN_STPCPY_CHK)
2235                 {
2236                   if (! ignore)
2237                     return false;
2238
2239                   /* If return value of __stpcpy_chk is ignored,
2240                      optimize into __strcpy_chk.  */
2241                   fn = builtin_decl_explicit (BUILT_IN_STRCPY_CHK);
2242                   if (!fn)
2243                     return false;
2244
2245                   gimple *repl = gimple_build_call (fn, 3, dest, src, size);
2246                   replace_call_with_call_and_fold (gsi, repl);
2247                   return true;
2248                 }
2249
2250               if (! len || TREE_SIDE_EFFECTS (len))
2251                 return false;
2252
2253               /* If c_strlen returned something, but not a constant,
2254                  transform __strcpy_chk into __memcpy_chk.  */
2255               fn = builtin_decl_explicit (BUILT_IN_MEMCPY_CHK);
2256               if (!fn)
2257                 return false;
2258
2259               gimple_seq stmts = NULL;
2260               len = gimple_convert (&stmts, loc, size_type_node, len);
2261               len = gimple_build (&stmts, loc, PLUS_EXPR, size_type_node, len,
2262                                   build_int_cst (size_type_node, 1));
2263               gsi_insert_seq_before (gsi, stmts, GSI_SAME_STMT);
2264               gimple *repl = gimple_build_call (fn, 4, dest, src, len, size);
2265               replace_call_with_call_and_fold (gsi, repl);
2266               return true;
2267             }
2268         }
2269       else
2270         maxlen = len;
2271
2272       if (! tree_int_cst_lt (maxlen, size))
2273         return false;
2274     }
2275
2276   /* If __builtin_st{r,p}cpy_chk is used, assume st{r,p}cpy is available.  */
2277   fn = builtin_decl_explicit (fcode == BUILT_IN_STPCPY_CHK
2278                               ? BUILT_IN_STPCPY : BUILT_IN_STRCPY);
2279   if (!fn)
2280     return false;
2281
2282   gimple *repl = gimple_build_call (fn, 2, dest, src);
2283   replace_call_with_call_and_fold (gsi, repl);
2284   return true;
2285 }
2286
2287 /* Fold a call to the __st{r,p}ncpy_chk builtin.  DEST, SRC, LEN, and SIZE
2288    are the arguments to the call.  If MAXLEN is not NULL, it is maximum
2289    length passed as third argument. IGNORE is true if return value can be
2290    ignored. FCODE is the BUILT_IN_* code of the builtin. */
2291
2292 static bool
2293 gimple_fold_builtin_stxncpy_chk (gimple_stmt_iterator *gsi,
2294                                  tree dest, tree src,
2295                                  tree len, tree size,
2296                                  enum built_in_function fcode)
2297 {
2298   gimple *stmt = gsi_stmt (*gsi);
2299   bool ignore = gimple_call_lhs (stmt) == NULL_TREE;
2300   tree fn;
2301
2302   if (fcode == BUILT_IN_STPNCPY_CHK && ignore)
2303     {
2304        /* If return value of __stpncpy_chk is ignored,
2305           optimize into __strncpy_chk.  */
2306        fn = builtin_decl_explicit (BUILT_IN_STRNCPY_CHK);
2307        if (fn)
2308          {
2309            gimple *repl = gimple_build_call (fn, 4, dest, src, len, size);
2310            replace_call_with_call_and_fold (gsi, repl);
2311            return true;
2312          }
2313     }
2314
2315   if (! tree_fits_uhwi_p (size))
2316     return false;
2317
2318   tree maxlen = get_maxval_strlen (len, 2);
2319   if (! integer_all_onesp (size))
2320     {
2321       if (! tree_fits_uhwi_p (len))
2322         {
2323           /* If LEN is not constant, try MAXLEN too.
2324              For MAXLEN only allow optimizing into non-_ocs function
2325              if SIZE is >= MAXLEN, never convert to __ocs_fail ().  */
2326           if (maxlen == NULL_TREE || ! tree_fits_uhwi_p (maxlen))
2327             return false;
2328         }
2329       else
2330         maxlen = len;
2331
2332       if (tree_int_cst_lt (size, maxlen))
2333         return false;
2334     }
2335
2336   /* If __builtin_st{r,p}ncpy_chk is used, assume st{r,p}ncpy is available.  */
2337   fn = builtin_decl_explicit (fcode == BUILT_IN_STPNCPY_CHK
2338                               ? BUILT_IN_STPNCPY : BUILT_IN_STRNCPY);
2339   if (!fn)
2340     return false;
2341
2342   gimple *repl = gimple_build_call (fn, 3, dest, src, len);
2343   replace_call_with_call_and_fold (gsi, repl);
2344   return true;
2345 }
2346
2347 /* Fold function call to builtin stpcpy with arguments DEST and SRC.
2348    Return NULL_TREE if no simplification can be made.  */
2349
2350 static bool
2351 gimple_fold_builtin_stpcpy (gimple_stmt_iterator *gsi)
2352 {
2353   gcall *stmt = as_a <gcall *> (gsi_stmt (*gsi));
2354   location_t loc = gimple_location (stmt);
2355   tree dest = gimple_call_arg (stmt, 0);
2356   tree src = gimple_call_arg (stmt, 1);
2357   tree fn, len, lenp1;
2358
2359   /* If the result is unused, replace stpcpy with strcpy.  */
2360   if (gimple_call_lhs (stmt) == NULL_TREE)
2361     {
2362       tree fn = builtin_decl_implicit (BUILT_IN_STRCPY);
2363       if (!fn)
2364         return false;
2365       gimple_call_set_fndecl (stmt, fn);
2366       fold_stmt (gsi);
2367       return true;
2368     }
2369
2370   len = c_strlen (src, 1);
2371   if (!len
2372       || TREE_CODE (len) != INTEGER_CST)
2373     return false;
2374
2375   if (optimize_function_for_size_p (cfun)
2376       /* If length is zero it's small enough.  */
2377       && !integer_zerop (len))
2378     return false;
2379
2380   /* If the source has a known length replace stpcpy with memcpy.  */
2381   fn = builtin_decl_implicit (BUILT_IN_MEMCPY);
2382   if (!fn)
2383     return false;
2384
2385   gimple_seq stmts = NULL;
2386   tree tem = gimple_convert (&stmts, loc, size_type_node, len);
2387   lenp1 = gimple_build (&stmts, loc, PLUS_EXPR, size_type_node,
2388                         tem, build_int_cst (size_type_node, 1));
2389   gsi_insert_seq_before (gsi, stmts, GSI_SAME_STMT);
2390   gcall *repl = gimple_build_call (fn, 3, dest, src, lenp1);
2391   gimple_set_vuse (repl, gimple_vuse (stmt));
2392   gimple_set_vdef (repl, gimple_vdef (stmt));
2393   if (gimple_vdef (repl)
2394       && TREE_CODE (gimple_vdef (repl)) == SSA_NAME)
2395     SSA_NAME_DEF_STMT (gimple_vdef (repl)) = repl;
2396   gsi_insert_before (gsi, repl, GSI_SAME_STMT);
2397   /* Replace the result with dest + len.  */
2398   stmts = NULL;
2399   tem = gimple_convert (&stmts, loc, sizetype, len);
2400   gsi_insert_seq_before (gsi, stmts, GSI_SAME_STMT);
2401   gassign *ret = gimple_build_assign (gimple_call_lhs (stmt),
2402                                       POINTER_PLUS_EXPR, dest, tem);
2403   gsi_replace (gsi, ret, false);
2404   /* Finally fold the memcpy call.  */
2405   gimple_stmt_iterator gsi2 = *gsi;
2406   gsi_prev (&gsi2);
2407   fold_stmt (&gsi2);
2408   return true;
2409 }
2410
2411 /* Fold a call EXP to {,v}snprintf having NARGS passed as ARGS.  Return
2412    NULL_TREE if a normal call should be emitted rather than expanding
2413    the function inline.  FCODE is either BUILT_IN_SNPRINTF_CHK or
2414    BUILT_IN_VSNPRINTF_CHK.  If MAXLEN is not NULL, it is maximum length
2415    passed as second argument.  */
2416
2417 static bool
2418 gimple_fold_builtin_snprintf_chk (gimple_stmt_iterator *gsi,
2419                                   enum built_in_function fcode)
2420 {
2421   gcall *stmt = as_a <gcall *> (gsi_stmt (*gsi));
2422   tree dest, size, len, fn, fmt, flag;
2423   const char *fmt_str;
2424
2425   /* Verify the required arguments in the original call.  */
2426   if (gimple_call_num_args (stmt) < 5)
2427     return false;
2428
2429   dest = gimple_call_arg (stmt, 0);
2430   len = gimple_call_arg (stmt, 1);
2431   flag = gimple_call_arg (stmt, 2);
2432   size = gimple_call_arg (stmt, 3);
2433   fmt = gimple_call_arg (stmt, 4);
2434
2435   if (! tree_fits_uhwi_p (size))
2436     return false;
2437
2438   if (! integer_all_onesp (size))
2439     {
2440       tree maxlen = get_maxval_strlen (len, 2);
2441       if (! tree_fits_uhwi_p (len))
2442         {
2443           /* If LEN is not constant, try MAXLEN too.
2444              For MAXLEN only allow optimizing into non-_ocs function
2445              if SIZE is >= MAXLEN, never convert to __ocs_fail ().  */
2446           if (maxlen == NULL_TREE || ! tree_fits_uhwi_p (maxlen))
2447             return false;
2448         }
2449       else
2450         maxlen = len;
2451
2452       if (tree_int_cst_lt (size, maxlen))
2453         return false;
2454     }
2455
2456   if (!init_target_chars ())
2457     return false;
2458
2459   /* Only convert __{,v}snprintf_chk to {,v}snprintf if flag is 0
2460      or if format doesn't contain % chars or is "%s".  */
2461   if (! integer_zerop (flag))
2462     {
2463       fmt_str = c_getstr (fmt);
2464       if (fmt_str == NULL)
2465         return false;
2466       if (strchr (fmt_str, target_percent) != NULL
2467           && strcmp (fmt_str, target_percent_s))
2468         return false;
2469     }
2470
2471   /* If __builtin_{,v}snprintf_chk is used, assume {,v}snprintf is
2472      available.  */
2473   fn = builtin_decl_explicit (fcode == BUILT_IN_VSNPRINTF_CHK
2474                               ? BUILT_IN_VSNPRINTF : BUILT_IN_SNPRINTF);
2475   if (!fn)
2476     return false;
2477
2478   /* Replace the called function and the first 5 argument by 3 retaining
2479      trailing varargs.  */
2480   gimple_call_set_fndecl (stmt, fn);
2481   gimple_call_set_fntype (stmt, TREE_TYPE (fn));
2482   gimple_call_set_arg (stmt, 0, dest);
2483   gimple_call_set_arg (stmt, 1, len);
2484   gimple_call_set_arg (stmt, 2, fmt);
2485   for (unsigned i = 3; i < gimple_call_num_args (stmt) - 2; ++i)
2486     gimple_call_set_arg (stmt, i, gimple_call_arg (stmt, i + 2));
2487   gimple_set_num_ops (stmt, gimple_num_ops (stmt) - 2);
2488   fold_stmt (gsi);
2489   return true;
2490 }
2491
2492 /* Fold a call EXP to __{,v}sprintf_chk having NARGS passed as ARGS.
2493    Return NULL_TREE if a normal call should be emitted rather than
2494    expanding the function inline.  FCODE is either BUILT_IN_SPRINTF_CHK
2495    or BUILT_IN_VSPRINTF_CHK.  */
2496
2497 static bool
2498 gimple_fold_builtin_sprintf_chk (gimple_stmt_iterator *gsi,
2499                                  enum built_in_function fcode)
2500 {
2501   gcall *stmt = as_a <gcall *> (gsi_stmt (*gsi));
2502   tree dest, size, len, fn, fmt, flag;
2503   const char *fmt_str;
2504   unsigned nargs = gimple_call_num_args (stmt);
2505
2506   /* Verify the required arguments in the original call.  */
2507   if (nargs < 4)
2508     return false;
2509   dest = gimple_call_arg (stmt, 0);
2510   flag = gimple_call_arg (stmt, 1);
2511   size = gimple_call_arg (stmt, 2);
2512   fmt = gimple_call_arg (stmt, 3);
2513
2514   if (! tree_fits_uhwi_p (size))
2515     return false;
2516
2517   len = NULL_TREE;
2518
2519   if (!init_target_chars ())
2520     return false;
2521
2522   /* Check whether the format is a literal string constant.  */
2523   fmt_str = c_getstr (fmt);
2524   if (fmt_str != NULL)
2525     {
2526       /* If the format doesn't contain % args or %%, we know the size.  */
2527       if (strchr (fmt_str, target_percent) == 0)
2528         {
2529           if (fcode != BUILT_IN_SPRINTF_CHK || nargs == 4)
2530             len = build_int_cstu (size_type_node, strlen (fmt_str));
2531         }
2532       /* If the format is "%s" and first ... argument is a string literal,
2533          we know the size too.  */
2534       else if (fcode == BUILT_IN_SPRINTF_CHK
2535                && strcmp (fmt_str, target_percent_s) == 0)
2536         {
2537           tree arg;
2538
2539           if (nargs == 5)
2540             {
2541               arg = gimple_call_arg (stmt, 4);
2542               if (POINTER_TYPE_P (TREE_TYPE (arg)))
2543                 {
2544                   len = c_strlen (arg, 1);
2545                   if (! len || ! tree_fits_uhwi_p (len))
2546                     len = NULL_TREE;
2547                 }
2548             }
2549         }
2550     }
2551
2552   if (! integer_all_onesp (size))
2553     {
2554       if (! len || ! tree_int_cst_lt (len, size))
2555         return false;
2556     }
2557
2558   /* Only convert __{,v}sprintf_chk to {,v}sprintf if flag is 0
2559      or if format doesn't contain % chars or is "%s".  */
2560   if (! integer_zerop (flag))
2561     {
2562       if (fmt_str == NULL)
2563         return false;
2564       if (strchr (fmt_str, target_percent) != NULL
2565           && strcmp (fmt_str, target_percent_s))
2566         return false;
2567     }
2568
2569   /* If __builtin_{,v}sprintf_chk is used, assume {,v}sprintf is available.  */
2570   fn = builtin_decl_explicit (fcode == BUILT_IN_VSPRINTF_CHK
2571                               ? BUILT_IN_VSPRINTF : BUILT_IN_SPRINTF);
2572   if (!fn)
2573     return false;
2574
2575   /* Replace the called function and the first 4 argument by 2 retaining
2576      trailing varargs.  */
2577   gimple_call_set_fndecl (stmt, fn);
2578   gimple_call_set_fntype (stmt, TREE_TYPE (fn));
2579   gimple_call_set_arg (stmt, 0, dest);
2580   gimple_call_set_arg (stmt, 1, fmt);
2581   for (unsigned i = 2; i < gimple_call_num_args (stmt) - 2; ++i)
2582     gimple_call_set_arg (stmt, i, gimple_call_arg (stmt, i + 2));
2583   gimple_set_num_ops (stmt, gimple_num_ops (stmt) - 2);
2584   fold_stmt (gsi);
2585   return true;
2586 }
2587
2588 /* Simplify a call to the sprintf builtin with arguments DEST, FMT, and ORIG.
2589    ORIG may be null if this is a 2-argument call.  We don't attempt to
2590    simplify calls with more than 3 arguments.
2591
2592    Return NULL_TREE if no simplification was possible, otherwise return the
2593    simplified form of the call as a tree.  If IGNORED is true, it means that
2594    the caller does not use the returned value of the function.  */
2595
2596 static bool
2597 gimple_fold_builtin_sprintf (gimple_stmt_iterator *gsi)
2598 {
2599   gimple *stmt = gsi_stmt (*gsi);
2600   tree dest = gimple_call_arg (stmt, 0);
2601   tree fmt = gimple_call_arg (stmt, 1);
2602   tree orig = NULL_TREE;
2603   const char *fmt_str = NULL;
2604
2605   /* Verify the required arguments in the original call.  We deal with two
2606      types of sprintf() calls: 'sprintf (str, fmt)' and
2607      'sprintf (dest, "%s", orig)'.  */
2608   if (gimple_call_num_args (stmt) > 3)
2609     return false;
2610
2611   if (gimple_call_num_args (stmt) == 3)
2612     orig = gimple_call_arg (stmt, 2);
2613
2614   /* Check whether the format is a literal string constant.  */
2615   fmt_str = c_getstr (fmt);
2616   if (fmt_str == NULL)
2617     return false;
2618
2619   if (!init_target_chars ())
2620     return false;
2621
2622   /* If the format doesn't contain % args or %%, use strcpy.  */
2623   if (strchr (fmt_str, target_percent) == NULL)
2624     {
2625       tree fn = builtin_decl_implicit (BUILT_IN_STRCPY);
2626
2627       if (!fn)
2628         return false;
2629
2630       /* Don't optimize sprintf (buf, "abc", ptr++).  */
2631       if (orig)
2632         return false;
2633
2634       /* Convert sprintf (str, fmt) into strcpy (str, fmt) when
2635          'format' is known to contain no % formats.  */
2636       gimple_seq stmts = NULL;
2637       gimple *repl = gimple_build_call (fn, 2, dest, fmt);
2638       gimple_seq_add_stmt_without_update (&stmts, repl);
2639       if (gimple_call_lhs (stmt))
2640         {
2641           repl = gimple_build_assign (gimple_call_lhs (stmt),
2642                                       build_int_cst (integer_type_node,
2643                                                      strlen (fmt_str)));
2644           gimple_seq_add_stmt_without_update (&stmts, repl);
2645           gsi_replace_with_seq_vops (gsi, stmts);
2646           /* gsi now points at the assignment to the lhs, get a
2647              stmt iterator to the memcpy call.
2648              ???  We can't use gsi_for_stmt as that doesn't work when the
2649              CFG isn't built yet.  */
2650           gimple_stmt_iterator gsi2 = *gsi;
2651           gsi_prev (&gsi2);
2652           fold_stmt (&gsi2);
2653         }
2654       else
2655         {
2656           gsi_replace_with_seq_vops (gsi, stmts);
2657           fold_stmt (gsi);
2658         }
2659       return true;
2660     }
2661
2662   /* If the format is "%s", use strcpy if the result isn't used.  */
2663   else if (fmt_str && strcmp (fmt_str, target_percent_s) == 0)
2664     {
2665       tree fn;
2666       fn = builtin_decl_implicit (BUILT_IN_STRCPY);
2667
2668       if (!fn)
2669         return false;
2670
2671       /* Don't crash on sprintf (str1, "%s").  */
2672       if (!orig)
2673         return false;
2674
2675       tree orig_len = NULL_TREE;
2676       if (gimple_call_lhs (stmt))
2677         {
2678           orig_len = get_maxval_strlen (orig, 0);
2679           if (!orig_len)
2680             return false;
2681         }
2682
2683       /* Convert sprintf (str1, "%s", str2) into strcpy (str1, str2).  */
2684       gimple_seq stmts = NULL;
2685       gimple *repl = gimple_build_call (fn, 2, dest, orig);
2686       gimple_seq_add_stmt_without_update (&stmts, repl);
2687       if (gimple_call_lhs (stmt))
2688         {
2689           if (!useless_type_conversion_p (integer_type_node,
2690                                           TREE_TYPE (orig_len)))
2691             orig_len = fold_convert (integer_type_node, orig_len);
2692           repl = gimple_build_assign (gimple_call_lhs (stmt), orig_len);
2693           gimple_seq_add_stmt_without_update (&stmts, repl);
2694           gsi_replace_with_seq_vops (gsi, stmts);
2695           /* gsi now points at the assignment to the lhs, get a
2696              stmt iterator to the memcpy call.
2697              ???  We can't use gsi_for_stmt as that doesn't work when the
2698              CFG isn't built yet.  */
2699           gimple_stmt_iterator gsi2 = *gsi;
2700           gsi_prev (&gsi2);
2701           fold_stmt (&gsi2);
2702         }
2703       else
2704         {
2705           gsi_replace_with_seq_vops (gsi, stmts);
2706           fold_stmt (gsi);
2707         }
2708       return true;
2709     }
2710   return false;
2711 }
2712
2713 /* Simplify a call to the snprintf builtin with arguments DEST, DESTSIZE,
2714    FMT, and ORIG.  ORIG may be null if this is a 3-argument call.  We don't
2715    attempt to simplify calls with more than 4 arguments.
2716
2717    Return NULL_TREE if no simplification was possible, otherwise return the
2718    simplified form of the call as a tree.  If IGNORED is true, it means that
2719    the caller does not use the returned value of the function.  */
2720
2721 static bool
2722 gimple_fold_builtin_snprintf (gimple_stmt_iterator *gsi)
2723 {
2724   gcall *stmt = as_a <gcall *> (gsi_stmt (*gsi));
2725   tree dest = gimple_call_arg (stmt, 0);
2726   tree destsize = gimple_call_arg (stmt, 1);
2727   tree fmt = gimple_call_arg (stmt, 2);
2728   tree orig = NULL_TREE;
2729   const char *fmt_str = NULL;
2730
2731   if (gimple_call_num_args (stmt) > 4)
2732     return false;
2733
2734   if (gimple_call_num_args (stmt) == 4)
2735     orig = gimple_call_arg (stmt, 3);
2736
2737   if (!tree_fits_uhwi_p (destsize))
2738     return false;
2739   unsigned HOST_WIDE_INT destlen = tree_to_uhwi (destsize);
2740
2741   /* Check whether the format is a literal string constant.  */
2742   fmt_str = c_getstr (fmt);
2743   if (fmt_str == NULL)
2744     return false;
2745
2746   if (!init_target_chars ())
2747     return false;
2748
2749   /* If the format doesn't contain % args or %%, use strcpy.  */
2750   if (strchr (fmt_str, target_percent) == NULL)
2751     {
2752       tree fn = builtin_decl_implicit (BUILT_IN_STRCPY);
2753       if (!fn)
2754         return false;
2755
2756       /* Don't optimize snprintf (buf, 4, "abc", ptr++).  */
2757       if (orig)
2758         return false;
2759
2760       /* We could expand this as
2761          memcpy (str, fmt, cst - 1); str[cst - 1] = '\0';
2762          or to
2763          memcpy (str, fmt_with_nul_at_cstm1, cst);
2764          but in the former case that might increase code size
2765          and in the latter case grow .rodata section too much.
2766          So punt for now.  */
2767       size_t len = strlen (fmt_str);
2768       if (len >= destlen)
2769         return false;
2770
2771       gimple_seq stmts = NULL;
2772       gimple *repl = gimple_build_call (fn, 2, dest, fmt);
2773       gimple_seq_add_stmt_without_update (&stmts, repl);
2774       if (gimple_call_lhs (stmt))
2775         {
2776           repl = gimple_build_assign (gimple_call_lhs (stmt),
2777                                       build_int_cst (integer_type_node, len));
2778           gimple_seq_add_stmt_without_update (&stmts, repl);
2779           gsi_replace_with_seq_vops (gsi, stmts);
2780           /* gsi now points at the assignment to the lhs, get a
2781              stmt iterator to the memcpy call.
2782              ???  We can't use gsi_for_stmt as that doesn't work when the
2783              CFG isn't built yet.  */
2784           gimple_stmt_iterator gsi2 = *gsi;
2785           gsi_prev (&gsi2);
2786           fold_stmt (&gsi2);
2787         }
2788       else
2789         {
2790           gsi_replace_with_seq_vops (gsi, stmts);
2791           fold_stmt (gsi);
2792         }
2793       return true;
2794     }
2795
2796   /* If the format is "%s", use strcpy if the result isn't used.  */
2797   else if (fmt_str && strcmp (fmt_str, target_percent_s) == 0)
2798     {
2799       tree fn = builtin_decl_implicit (BUILT_IN_STRCPY);
2800       if (!fn)
2801         return false;
2802
2803       /* Don't crash on snprintf (str1, cst, "%s").  */
2804       if (!orig)
2805         return false;
2806
2807       tree orig_len = get_maxval_strlen (orig, 0);
2808       if (!orig_len || TREE_CODE (orig_len) != INTEGER_CST)
2809         return false;
2810
2811       /* We could expand this as
2812          memcpy (str1, str2, cst - 1); str1[cst - 1] = '\0';
2813          or to
2814          memcpy (str1, str2_with_nul_at_cstm1, cst);
2815          but in the former case that might increase code size
2816          and in the latter case grow .rodata section too much.
2817          So punt for now.  */
2818       if (compare_tree_int (orig_len, destlen) >= 0)
2819         return false;
2820
2821       /* Convert snprintf (str1, cst, "%s", str2) into
2822          strcpy (str1, str2) if strlen (str2) < cst.  */
2823       gimple_seq stmts = NULL;
2824       gimple *repl = gimple_build_call (fn, 2, dest, orig);
2825       gimple_seq_add_stmt_without_update (&stmts, repl);
2826       if (gimple_call_lhs (stmt))
2827         {
2828           if (!useless_type_conversion_p (integer_type_node,
2829                                           TREE_TYPE (orig_len)))
2830             orig_len = fold_convert (integer_type_node, orig_len);
2831           repl = gimple_build_assign (gimple_call_lhs (stmt), orig_len);
2832           gimple_seq_add_stmt_without_update (&stmts, repl);
2833           gsi_replace_with_seq_vops (gsi, stmts);
2834           /* gsi now points at the assignment to the lhs, get a
2835              stmt iterator to the memcpy call.
2836              ???  We can't use gsi_for_stmt as that doesn't work when the
2837              CFG isn't built yet.  */
2838           gimple_stmt_iterator gsi2 = *gsi;
2839           gsi_prev (&gsi2);
2840           fold_stmt (&gsi2);
2841         }
2842       else
2843         {
2844           gsi_replace_with_seq_vops (gsi, stmts);
2845           fold_stmt (gsi);
2846         }
2847       return true;
2848     }
2849   return false;
2850 }
2851
2852 /* Fold a call to the {,v}fprintf{,_unlocked} and __{,v}printf_chk builtins.
2853    FP, FMT, and ARG are the arguments to the call.  We don't fold calls with
2854    more than 3 arguments, and ARG may be null in the 2-argument case.
2855
2856    Return NULL_TREE if no simplification was possible, otherwise return the
2857    simplified form of the call as a tree.  FCODE is the BUILT_IN_*
2858    code of the function to be simplified.  */
2859
2860 static bool 
2861 gimple_fold_builtin_fprintf (gimple_stmt_iterator *gsi,
2862                              tree fp, tree fmt, tree arg,
2863                              enum built_in_function fcode)
2864 {
2865   gcall *stmt = as_a <gcall *> (gsi_stmt (*gsi));
2866   tree fn_fputc, fn_fputs;
2867   const char *fmt_str = NULL;
2868
2869   /* If the return value is used, don't do the transformation.  */
2870   if (gimple_call_lhs (stmt) != NULL_TREE)
2871     return false;
2872
2873   /* Check whether the format is a literal string constant.  */
2874   fmt_str = c_getstr (fmt);
2875   if (fmt_str == NULL)
2876     return false;
2877
2878   if (fcode == BUILT_IN_FPRINTF_UNLOCKED)
2879     {
2880       /* If we're using an unlocked function, assume the other
2881          unlocked functions exist explicitly.  */
2882       fn_fputc = builtin_decl_explicit (BUILT_IN_FPUTC_UNLOCKED);
2883       fn_fputs = builtin_decl_explicit (BUILT_IN_FPUTS_UNLOCKED);
2884     }
2885   else
2886     {
2887       fn_fputc = builtin_decl_implicit (BUILT_IN_FPUTC);
2888       fn_fputs = builtin_decl_implicit (BUILT_IN_FPUTS);
2889     }
2890
2891   if (!init_target_chars ())
2892     return false;
2893
2894   /* If the format doesn't contain % args or %%, use strcpy.  */
2895   if (strchr (fmt_str, target_percent) == NULL)
2896     {
2897       if (fcode != BUILT_IN_VFPRINTF && fcode != BUILT_IN_VFPRINTF_CHK
2898           && arg)
2899         return false;
2900
2901       /* If the format specifier was "", fprintf does nothing.  */
2902       if (fmt_str[0] == '\0')
2903         {
2904           replace_call_with_value (gsi, NULL_TREE);
2905           return true;
2906         }
2907
2908       /* When "string" doesn't contain %, replace all cases of
2909          fprintf (fp, string) with fputs (string, fp).  The fputs
2910          builtin will take care of special cases like length == 1.  */
2911       if (fn_fputs)
2912         {
2913           gcall *repl = gimple_build_call (fn_fputs, 2, fmt, fp);
2914           replace_call_with_call_and_fold (gsi, repl);
2915           return true;
2916         }
2917     }
2918
2919   /* The other optimizations can be done only on the non-va_list variants.  */
2920   else if (fcode == BUILT_IN_VFPRINTF || fcode == BUILT_IN_VFPRINTF_CHK)
2921     return false;
2922
2923   /* If the format specifier was "%s", call __builtin_fputs (arg, fp).  */
2924   else if (strcmp (fmt_str, target_percent_s) == 0)
2925     {
2926       if (!arg || ! POINTER_TYPE_P (TREE_TYPE (arg)))
2927         return false;
2928       if (fn_fputs)
2929         {
2930           gcall *repl = gimple_build_call (fn_fputs, 2, arg, fp);
2931           replace_call_with_call_and_fold (gsi, repl);
2932           return true;
2933         }
2934     }
2935
2936   /* If the format specifier was "%c", call __builtin_fputc (arg, fp).  */
2937   else if (strcmp (fmt_str, target_percent_c) == 0)
2938     {
2939       if (!arg
2940           || ! useless_type_conversion_p (integer_type_node, TREE_TYPE (arg)))
2941         return false;
2942       if (fn_fputc)
2943         {
2944           gcall *repl = gimple_build_call (fn_fputc, 2, arg, fp);
2945           replace_call_with_call_and_fold (gsi, repl);
2946           return true;
2947         }
2948     }
2949
2950   return false;
2951 }
2952
2953 /* Fold a call to the {,v}printf{,_unlocked} and __{,v}printf_chk builtins.
2954    FMT and ARG are the arguments to the call; we don't fold cases with
2955    more than 2 arguments, and ARG may be null if this is a 1-argument case.
2956
2957    Return NULL_TREE if no simplification was possible, otherwise return the
2958    simplified form of the call as a tree.  FCODE is the BUILT_IN_*
2959    code of the function to be simplified.  */
2960
2961 static bool
2962 gimple_fold_builtin_printf (gimple_stmt_iterator *gsi, tree fmt,
2963                             tree arg, enum built_in_function fcode)
2964 {
2965   gcall *stmt = as_a <gcall *> (gsi_stmt (*gsi));
2966   tree fn_putchar, fn_puts, newarg;
2967   const char *fmt_str = NULL;
2968
2969   /* If the return value is used, don't do the transformation.  */
2970   if (gimple_call_lhs (stmt) != NULL_TREE)
2971     return false;
2972
2973   /* Check whether the format is a literal string constant.  */
2974   fmt_str = c_getstr (fmt);
2975   if (fmt_str == NULL)
2976     return false;
2977
2978   if (fcode == BUILT_IN_PRINTF_UNLOCKED)
2979     {
2980       /* If we're using an unlocked function, assume the other
2981          unlocked functions exist explicitly.  */
2982       fn_putchar = builtin_decl_explicit (BUILT_IN_PUTCHAR_UNLOCKED);
2983       fn_puts = builtin_decl_explicit (BUILT_IN_PUTS_UNLOCKED);
2984     }
2985   else
2986     {
2987       fn_putchar = builtin_decl_implicit (BUILT_IN_PUTCHAR);
2988       fn_puts = builtin_decl_implicit (BUILT_IN_PUTS);
2989     }
2990
2991   if (!init_target_chars ())
2992     return false;
2993
2994   if (strcmp (fmt_str, target_percent_s) == 0
2995       || strchr (fmt_str, target_percent) == NULL)
2996     {
2997       const char *str;
2998
2999       if (strcmp (fmt_str, target_percent_s) == 0)
3000         {
3001           if (fcode == BUILT_IN_VPRINTF || fcode == BUILT_IN_VPRINTF_CHK)
3002             return false;
3003
3004           if (!arg || ! POINTER_TYPE_P (TREE_TYPE (arg)))
3005             return false;
3006
3007           str = c_getstr (arg);
3008           if (str == NULL)
3009             return false;
3010         }
3011       else
3012         {
3013           /* The format specifier doesn't contain any '%' characters.  */
3014           if (fcode != BUILT_IN_VPRINTF && fcode != BUILT_IN_VPRINTF_CHK
3015               && arg)
3016             return false;
3017           str = fmt_str;
3018         }
3019
3020       /* If the string was "", printf does nothing.  */
3021       if (str[0] == '\0')
3022         {
3023           replace_call_with_value (gsi, NULL_TREE);
3024           return true;
3025         }
3026
3027       /* If the string has length of 1, call putchar.  */
3028       if (str[1] == '\0')
3029         {
3030           /* Given printf("c"), (where c is any one character,)
3031              convert "c"[0] to an int and pass that to the replacement
3032              function.  */
3033           newarg = build_int_cst (integer_type_node, str[0]);
3034           if (fn_putchar)
3035             {
3036               gcall *repl = gimple_build_call (fn_putchar, 1, newarg);
3037               replace_call_with_call_and_fold (gsi, repl);
3038               return true;
3039             }
3040         }
3041       else
3042         {
3043           /* If the string was "string\n", call puts("string").  */
3044           size_t len = strlen (str);
3045           if ((unsigned char)str[len - 1] == target_newline
3046               && (size_t) (int) len == len
3047               && (int) len > 0)
3048             {
3049               char *newstr;
3050               tree offset_node, string_cst;
3051
3052               /* Create a NUL-terminated string that's one char shorter
3053                  than the original, stripping off the trailing '\n'.  */
3054               newarg = build_string_literal (len, str);
3055               string_cst = string_constant (newarg, &offset_node);
3056               gcc_checking_assert (string_cst
3057                                    && (TREE_STRING_LENGTH (string_cst)
3058                                        == (int) len)
3059                                    && integer_zerop (offset_node)
3060                                    && (unsigned char)
3061                                       TREE_STRING_POINTER (string_cst)[len - 1]
3062                                       == target_newline);
3063               /* build_string_literal creates a new STRING_CST,
3064                  modify it in place to avoid double copying.  */
3065               newstr = CONST_CAST (char *, TREE_STRING_POINTER (string_cst));
3066               newstr[len - 1] = '\0';
3067               if (fn_puts)
3068                 {
3069                   gcall *repl = gimple_build_call (fn_puts, 1, newarg);
3070                   replace_call_with_call_and_fold (gsi, repl);
3071                   return true;
3072                 }
3073             }
3074           else
3075             /* We'd like to arrange to call fputs(string,stdout) here,
3076                but we need stdout and don't have a way to get it yet.  */
3077             return false;
3078         }
3079     }
3080
3081   /* The other optimizations can be done only on the non-va_list variants.  */
3082   else if (fcode == BUILT_IN_VPRINTF || fcode == BUILT_IN_VPRINTF_CHK)
3083     return false;
3084
3085   /* If the format specifier was "%s\n", call __builtin_puts(arg).  */
3086   else if (strcmp (fmt_str, target_percent_s_newline) == 0)
3087     {
3088       if (!arg || ! POINTER_TYPE_P (TREE_TYPE (arg)))
3089         return false;
3090       if (fn_puts)
3091         {
3092           gcall *repl = gimple_build_call (fn_puts, 1, arg);
3093           replace_call_with_call_and_fold (gsi, repl);
3094           return true;
3095         }
3096     }
3097
3098   /* If the format specifier was "%c", call __builtin_putchar(arg).  */
3099   else if (strcmp (fmt_str, target_percent_c) == 0)
3100     {
3101       if (!arg || ! useless_type_conversion_p (integer_type_node,
3102                                                TREE_TYPE (arg)))
3103         return false;
3104       if (fn_putchar)
3105         {
3106           gcall *repl = gimple_build_call (fn_putchar, 1, arg);
3107           replace_call_with_call_and_fold (gsi, repl);
3108           return true;
3109         }
3110     }
3111
3112   return false;
3113 }
3114
3115
3116
3117 /* Fold a call to __builtin_strlen with known length LEN.  */
3118
3119 static bool
3120 gimple_fold_builtin_strlen (gimple_stmt_iterator *gsi)
3121 {
3122   gimple *stmt = gsi_stmt (*gsi);
3123   tree len = get_maxval_strlen (gimple_call_arg (stmt, 0), 0);
3124   if (!len)
3125     return false;
3126   len = force_gimple_operand_gsi (gsi, len, true, NULL, true, GSI_SAME_STMT);
3127   replace_call_with_value (gsi, len);
3128   return true;
3129 }
3130
3131 /* Fold a call to __builtin_acc_on_device.  */
3132
3133 static bool
3134 gimple_fold_builtin_acc_on_device (gimple_stmt_iterator *gsi, tree arg0)
3135 {
3136   /* Defer folding until we know which compiler we're in.  */
3137   if (symtab->state != EXPANSION)
3138     return false;
3139
3140   unsigned val_host = GOMP_DEVICE_HOST;
3141   unsigned val_dev = GOMP_DEVICE_NONE;
3142
3143 #ifdef ACCEL_COMPILER
3144   val_host = GOMP_DEVICE_NOT_HOST;
3145   val_dev = ACCEL_COMPILER_acc_device;
3146 #endif
3147
3148   location_t loc = gimple_location (gsi_stmt (*gsi));
3149   
3150   tree host_eq = make_ssa_name (boolean_type_node);
3151   gimple *host_ass = gimple_build_assign
3152     (host_eq, EQ_EXPR, arg0, build_int_cst (TREE_TYPE (arg0), val_host));
3153   gimple_set_location (host_ass, loc);
3154   gsi_insert_before (gsi, host_ass, GSI_SAME_STMT);
3155
3156   tree dev_eq = make_ssa_name (boolean_type_node);
3157   gimple *dev_ass = gimple_build_assign
3158     (dev_eq, EQ_EXPR, arg0, build_int_cst (TREE_TYPE (arg0), val_dev));
3159   gimple_set_location (dev_ass, loc);
3160   gsi_insert_before (gsi, dev_ass, GSI_SAME_STMT);
3161
3162   tree result = make_ssa_name (boolean_type_node);
3163   gimple *result_ass = gimple_build_assign
3164     (result, BIT_IOR_EXPR, host_eq, dev_eq);
3165   gimple_set_location (result_ass, loc);
3166   gsi_insert_before (gsi, result_ass, GSI_SAME_STMT);
3167
3168   replace_call_with_value (gsi, result);
3169
3170   return true;
3171 }
3172
3173 /* Fold the non-target builtin at *GSI and return whether any simplification
3174    was made.  */
3175
3176 static bool
3177 gimple_fold_builtin (gimple_stmt_iterator *gsi)
3178 {
3179   gcall *stmt = as_a <gcall *>(gsi_stmt (*gsi));
3180   tree callee = gimple_call_fndecl (stmt);
3181
3182   /* Give up for always_inline inline builtins until they are
3183      inlined.  */
3184   if (avoid_folding_inline_builtin (callee))
3185     return false;
3186
3187   unsigned n = gimple_call_num_args (stmt);
3188   enum built_in_function fcode = DECL_FUNCTION_CODE (callee);
3189   switch (fcode)
3190     {
3191     case BUILT_IN_BZERO:
3192       return gimple_fold_builtin_memset (gsi, integer_zero_node,
3193                                          gimple_call_arg (stmt, 1));
3194     case BUILT_IN_MEMSET:
3195       return gimple_fold_builtin_memset (gsi,
3196                                          gimple_call_arg (stmt, 1),
3197                                          gimple_call_arg (stmt, 2));
3198     case BUILT_IN_BCOPY:
3199       return gimple_fold_builtin_memory_op (gsi, gimple_call_arg (stmt, 1),
3200                                             gimple_call_arg (stmt, 0), 3);
3201     case BUILT_IN_MEMCPY:
3202       return gimple_fold_builtin_memory_op (gsi, gimple_call_arg (stmt, 0),
3203                                             gimple_call_arg (stmt, 1), 0);
3204     case BUILT_IN_MEMPCPY:
3205       return gimple_fold_builtin_memory_op (gsi, gimple_call_arg (stmt, 0),
3206                                             gimple_call_arg (stmt, 1), 1);
3207     case BUILT_IN_MEMMOVE:
3208       return gimple_fold_builtin_memory_op (gsi, gimple_call_arg (stmt, 0),
3209                                             gimple_call_arg (stmt, 1), 3);
3210     case BUILT_IN_SPRINTF_CHK:
3211     case BUILT_IN_VSPRINTF_CHK:
3212       return gimple_fold_builtin_sprintf_chk (gsi, fcode);
3213     case BUILT_IN_STRCAT_CHK:
3214       return gimple_fold_builtin_strcat_chk (gsi);
3215     case BUILT_IN_STRNCAT_CHK:
3216       return gimple_fold_builtin_strncat_chk (gsi);
3217     case BUILT_IN_STRLEN:
3218       return gimple_fold_builtin_strlen (gsi);
3219     case BUILT_IN_STRCPY:
3220       return gimple_fold_builtin_strcpy (gsi,
3221                                          gimple_call_arg (stmt, 0),
3222                                          gimple_call_arg (stmt, 1));
3223     case BUILT_IN_STRNCPY:
3224       return gimple_fold_builtin_strncpy (gsi,
3225                                           gimple_call_arg (stmt, 0),
3226                                           gimple_call_arg (stmt, 1),
3227                                           gimple_call_arg (stmt, 2));
3228     case BUILT_IN_STRCAT:
3229       return gimple_fold_builtin_strcat (gsi, gimple_call_arg (stmt, 0),
3230                                          gimple_call_arg (stmt, 1));
3231     case BUILT_IN_STRNCAT:
3232       return gimple_fold_builtin_strncat (gsi);
3233     case BUILT_IN_INDEX:
3234     case BUILT_IN_STRCHR:
3235       return gimple_fold_builtin_strchr (gsi, false);
3236     case BUILT_IN_RINDEX:
3237     case BUILT_IN_STRRCHR:
3238       return gimple_fold_builtin_strchr (gsi, true);
3239     case BUILT_IN_STRCMP:
3240     case BUILT_IN_STRCASECMP:
3241     case BUILT_IN_STRNCMP:
3242     case BUILT_IN_STRNCASECMP:
3243       return gimple_fold_builtin_string_compare (gsi);
3244     case BUILT_IN_MEMCHR:
3245       return gimple_fold_builtin_memchr (gsi);
3246     case BUILT_IN_FPUTS:
3247       return gimple_fold_builtin_fputs (gsi, gimple_call_arg (stmt, 0),
3248                                         gimple_call_arg (stmt, 1), false);
3249     case BUILT_IN_FPUTS_UNLOCKED:
3250       return gimple_fold_builtin_fputs (gsi, gimple_call_arg (stmt, 0),
3251                                         gimple_call_arg (stmt, 1), true);
3252     case BUILT_IN_MEMCPY_CHK:
3253     case BUILT_IN_MEMPCPY_CHK:
3254     case BUILT_IN_MEMMOVE_CHK:
3255     case BUILT_IN_MEMSET_CHK:
3256       return gimple_fold_builtin_memory_chk (gsi,
3257                                              gimple_call_arg (stmt, 0),
3258                                              gimple_call_arg (stmt, 1),
3259                                              gimple_call_arg (stmt, 2),
3260                                              gimple_call_arg (stmt, 3),
3261                                              fcode);
3262     case BUILT_IN_STPCPY:
3263       return gimple_fold_builtin_stpcpy (gsi);
3264     case BUILT_IN_STRCPY_CHK:
3265     case BUILT_IN_STPCPY_CHK:
3266       return gimple_fold_builtin_stxcpy_chk (gsi,
3267                                              gimple_call_arg (stmt, 0),
3268                                              gimple_call_arg (stmt, 1),
3269                                              gimple_call_arg (stmt, 2),
3270                                              fcode);
3271     case BUILT_IN_STRNCPY_CHK:
3272     case BUILT_IN_STPNCPY_CHK:
3273       return gimple_fold_builtin_stxncpy_chk (gsi,
3274                                               gimple_call_arg (stmt, 0),
3275                                               gimple_call_arg (stmt, 1),
3276                                               gimple_call_arg (stmt, 2),
3277                                               gimple_call_arg (stmt, 3),
3278                                               fcode);
3279     case BUILT_IN_SNPRINTF_CHK:
3280     case BUILT_IN_VSNPRINTF_CHK:
3281       return gimple_fold_builtin_snprintf_chk (gsi, fcode);
3282     case BUILT_IN_SNPRINTF:
3283       return gimple_fold_builtin_snprintf (gsi);
3284     case BUILT_IN_SPRINTF:
3285       return gimple_fold_builtin_sprintf (gsi);
3286     case BUILT_IN_FPRINTF:
3287     case BUILT_IN_FPRINTF_UNLOCKED:
3288     case BUILT_IN_VFPRINTF:
3289       if (n == 2 || n == 3)
3290         return gimple_fold_builtin_fprintf (gsi,
3291                                             gimple_call_arg (stmt, 0),
3292                                             gimple_call_arg (stmt, 1),
3293                                             n == 3
3294                                             ? gimple_call_arg (stmt, 2)
3295                                             : NULL_TREE,
3296                                             fcode);
3297       break;
3298     case BUILT_IN_FPRINTF_CHK:
3299     case BUILT_IN_VFPRINTF_CHK:
3300       if (n == 3 || n == 4)
3301         return gimple_fold_builtin_fprintf (gsi,
3302                                             gimple_call_arg (stmt, 0),
3303                                             gimple_call_arg (stmt, 2),
3304                                             n == 4
3305                                             ? gimple_call_arg (stmt, 3)
3306                                             : NULL_TREE,
3307                                             fcode);
3308       break;
3309     case BUILT_IN_PRINTF:
3310     case BUILT_IN_PRINTF_UNLOCKED:
3311     case BUILT_IN_VPRINTF:
3312       if (n == 1 || n == 2)
3313         return gimple_fold_builtin_printf (gsi, gimple_call_arg (stmt, 0),
3314                                            n == 2
3315                                            ? gimple_call_arg (stmt, 1)
3316                                            : NULL_TREE, fcode);
3317       break;
3318     case BUILT_IN_PRINTF_CHK:
3319     case BUILT_IN_VPRINTF_CHK:
3320       if (n == 2 || n == 3)
3321         return gimple_fold_builtin_printf (gsi, gimple_call_arg (stmt, 1),
3322                                            n == 3
3323                                            ? gimple_call_arg (stmt, 2)
3324                                            : NULL_TREE, fcode);
3325       break;
3326     case BUILT_IN_ACC_ON_DEVICE:
3327       return gimple_fold_builtin_acc_on_device (gsi,
3328                                                 gimple_call_arg (stmt, 0));
3329     default:;
3330     }
3331
3332   /* Try the generic builtin folder.  */
3333   bool ignore = (gimple_call_lhs (stmt) == NULL);
3334   tree result = fold_call_stmt (stmt, ignore);
3335   if (result)
3336     {
3337       if (ignore)
3338         STRIP_NOPS (result);
3339       else
3340         result = fold_convert (gimple_call_return_type (stmt), result);
3341       if (!update_call_from_tree (gsi, result))
3342         gimplify_and_update_call_from_tree (gsi, result);
3343       return true;
3344     }
3345
3346   return false;
3347 }
3348
3349 /* Transform IFN_GOACC_DIM_SIZE and IFN_GOACC_DIM_POS internal
3350    function calls to constants, where possible.  */
3351
3352 static tree
3353 fold_internal_goacc_dim (const gimple *call)
3354 {
3355   int axis = get_oacc_ifn_dim_arg (call);
3356   int size = get_oacc_fn_dim_size (current_function_decl, axis);
3357   bool is_pos = gimple_call_internal_fn (call) == IFN_GOACC_DIM_POS;
3358   tree result = NULL_TREE;
3359
3360   /* If the size is 1, or we only want the size and it is not dynamic,
3361      we know the answer.  */
3362   if (size == 1 || (!is_pos && size))
3363     {
3364       tree type = TREE_TYPE (gimple_call_lhs (call));
3365       result = build_int_cst (type, size - is_pos);
3366     }
3367
3368   return result;
3369 }
3370
3371 /* Return true if stmt is __atomic_compare_exchange_N call which is suitable
3372    for conversion into ATOMIC_COMPARE_EXCHANGE if the second argument is
3373    &var where var is only addressable because of such calls.  */
3374
3375 bool
3376 optimize_atomic_compare_exchange_p (gimple *stmt)
3377 {
3378   if (gimple_call_num_args (stmt) != 6
3379       || !flag_inline_atomics
3380       || !optimize
3381       || (flag_sanitize & (SANITIZE_THREAD | SANITIZE_ADDRESS)) != 0
3382       || !gimple_call_builtin_p (stmt, BUILT_IN_NORMAL)
3383       || !gimple_vdef (stmt)
3384       || !gimple_vuse (stmt))
3385     return false;
3386
3387   tree fndecl = gimple_call_fndecl (stmt);
3388   switch (DECL_FUNCTION_CODE (fndecl))
3389     {
3390     case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_1:
3391     case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_2:
3392     case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_4:
3393     case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_8:
3394     case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_16:
3395       break;
3396     default:
3397       return false;
3398     }
3399
3400   tree expected = gimple_call_arg (stmt, 1);
3401   if (TREE_CODE (expected) != ADDR_EXPR
3402       || !SSA_VAR_P (TREE_OPERAND (expected, 0)))
3403     return false;
3404
3405   tree etype = TREE_TYPE (TREE_OPERAND (expected, 0));
3406   if (!is_gimple_reg_type (etype)
3407       || !auto_var_in_fn_p (TREE_OPERAND (expected, 0), current_function_decl)
3408       || TREE_THIS_VOLATILE (etype)
3409       || VECTOR_TYPE_P (etype)
3410       || TREE_CODE (etype) == COMPLEX_TYPE
3411       /* Don't optimize floating point expected vars, VIEW_CONVERT_EXPRs
3412          might not preserve all the bits.  See PR71716.  */
3413       || SCALAR_FLOAT_TYPE_P (etype)
3414       || TYPE_PRECISION (etype) != GET_MODE_BITSIZE (TYPE_MODE (etype)))
3415     return false;
3416
3417   tree weak = gimple_call_arg (stmt, 3);
3418   if (!integer_zerop (weak) && !integer_onep (weak))
3419     return false;
3420
3421   tree parmt = TYPE_ARG_TYPES (TREE_TYPE (fndecl));
3422   tree itype = TREE_VALUE (TREE_CHAIN (TREE_CHAIN (parmt)));
3423   machine_mode mode = TYPE_MODE (itype);
3424
3425   if (direct_optab_handler (atomic_compare_and_swap_optab, mode)
3426       == CODE_FOR_nothing
3427       && optab_handler (sync_compare_and_swap_optab, mode) == CODE_FOR_nothing)
3428     return false;
3429
3430   if (int_size_in_bytes (etype) != GET_MODE_SIZE (mode))
3431     return false;
3432
3433   return true;
3434 }
3435
3436 /* Fold
3437      r = __atomic_compare_exchange_N (p, &e, d, w, s, f);
3438    into
3439      _Complex uintN_t t = ATOMIC_COMPARE_EXCHANGE (p, e, d, w * 256 + N, s, f);
3440      i = IMAGPART_EXPR <t>;
3441      r = (_Bool) i;
3442      e = REALPART_EXPR <t>;  */
3443
3444 void
3445 fold_builtin_atomic_compare_exchange (gimple_stmt_iterator *gsi)
3446 {
3447   gimple *stmt = gsi_stmt (*gsi);
3448   tree fndecl = gimple_call_fndecl (stmt);
3449   tree parmt = TYPE_ARG_TYPES (TREE_TYPE (fndecl));
3450   tree itype = TREE_VALUE (TREE_CHAIN (TREE_CHAIN (parmt)));
3451   tree ctype = build_complex_type (itype);
3452   tree expected = TREE_OPERAND (gimple_call_arg (stmt, 1), 0);
3453   gimple *g = gimple_build_assign (make_ssa_name (TREE_TYPE (expected)),
3454                                    expected);
3455   gsi_insert_before (gsi, g, GSI_SAME_STMT);
3456   gimple_stmt_iterator gsiret = gsi_for_stmt (g);
3457   if (!useless_type_conversion_p (itype, TREE_TYPE (expected)))
3458     {
3459       g = gimple_build_assign (make_ssa_name (itype), VIEW_CONVERT_EXPR,
3460                                build1 (VIEW_CONVERT_EXPR, itype,
3461                                        gimple_assign_lhs (g)));
3462       gsi_insert_before (gsi, g, GSI_SAME_STMT);
3463     }
3464   int flag = (integer_onep (gimple_call_arg (stmt, 3)) ? 256 : 0)
3465              + int_size_in_bytes (itype);
3466   g = gimple_build_call_internal (IFN_ATOMIC_COMPARE_EXCHANGE, 6,
3467                                   gimple_call_arg (stmt, 0),
3468                                   gimple_assign_lhs (g),
3469                                   gimple_call_arg (stmt, 2),
3470                                   build_int_cst (integer_type_node, flag),
3471                                   gimple_call_arg (stmt, 4),
3472                                   gimple_call_arg (stmt, 5));
3473   tree lhs = make_ssa_name (ctype);
3474   gimple_call_set_lhs (g, lhs);
3475   gimple_set_vdef (g, gimple_vdef (stmt));
3476   gimple_set_vuse (g, gimple_vuse (stmt));
3477   SSA_NAME_DEF_STMT (gimple_vdef (g)) = g;
3478   if (gimple_call_lhs (stmt))
3479     {
3480       gsi_insert_before (gsi, g, GSI_SAME_STMT);
3481       g = gimple_build_assign (make_ssa_name (itype), IMAGPART_EXPR,
3482                                build1 (IMAGPART_EXPR, itype, lhs));
3483       gsi_insert_before (gsi, g, GSI_SAME_STMT);
3484       g = gimple_build_assign (gimple_call_lhs (stmt), NOP_EXPR,
3485                                gimple_assign_lhs (g));
3486     }
3487   gsi_replace (gsi, g, true);
3488   g = gimple_build_assign (make_ssa_name (itype), REALPART_EXPR,
3489                            build1 (REALPART_EXPR, itype, lhs));
3490   gsi_insert_after (gsi, g, GSI_NEW_STMT);
3491   if (!useless_type_conversion_p (TREE_TYPE (expected), itype))
3492     {
3493       g = gimple_build_assign (make_ssa_name (TREE_TYPE (expected)),
3494                                VIEW_CONVERT_EXPR,
3495                                build1 (VIEW_CONVERT_EXPR, TREE_TYPE (expected),
3496                                        gimple_assign_lhs (g)));
3497       gsi_insert_after (gsi, g, GSI_NEW_STMT);
3498     }
3499   g = gimple_build_assign (expected, SSA_NAME, gimple_assign_lhs (g));
3500   gsi_insert_after (gsi, g, GSI_NEW_STMT);
3501   *gsi = gsiret;
3502 }
3503
3504 /* Return true if ARG0 CODE ARG1 in infinite signed precision operation
3505    doesn't fit into TYPE.  The test for overflow should be regardless of
3506    -fwrapv, and even for unsigned types.  */
3507
3508 bool
3509 arith_overflowed_p (enum tree_code code, const_tree type,
3510                     const_tree arg0, const_tree arg1)
3511 {
3512   typedef FIXED_WIDE_INT (WIDE_INT_MAX_PRECISION * 2) widest2_int;
3513   typedef generic_wide_int <wi::extended_tree <WIDE_INT_MAX_PRECISION * 2> >
3514     widest2_int_cst;
3515   widest2_int warg0 = widest2_int_cst (arg0);
3516   widest2_int warg1 = widest2_int_cst (arg1);
3517   widest2_int wres;
3518   switch (code)
3519     {
3520     case PLUS_EXPR: wres = wi::add (warg0, warg1); break;
3521     case MINUS_EXPR: wres = wi::sub (warg0, warg1); break;
3522     case MULT_EXPR: wres = wi::mul (warg0, warg1); break;
3523     default: gcc_unreachable ();
3524     }
3525   signop sign = TYPE_SIGN (type);
3526   if (sign == UNSIGNED && wi::neg_p (wres))
3527     return true;
3528   return wi::min_precision (wres, sign) > TYPE_PRECISION (type);
3529 }
3530
3531 /* Attempt to fold a call statement referenced by the statement iterator GSI.
3532    The statement may be replaced by another statement, e.g., if the call
3533    simplifies to a constant value. Return true if any changes were made.
3534    It is assumed that the operands have been previously folded.  */
3535
3536 static bool
3537 gimple_fold_call (gimple_stmt_iterator *gsi, bool inplace)
3538 {
3539   gcall *stmt = as_a <gcall *> (gsi_stmt (*gsi));
3540   tree callee;
3541   bool changed = false;
3542   unsigned i;
3543
3544   /* Fold *& in call arguments.  */
3545   for (i = 0; i < gimple_call_num_args (stmt); ++i)
3546     if (REFERENCE_CLASS_P (gimple_call_arg (stmt, i)))
3547       {
3548         tree tmp = maybe_fold_reference (gimple_call_arg (stmt, i), false);
3549         if (tmp)
3550           {
3551             gimple_call_set_arg (stmt, i, tmp);
3552             changed = true;
3553           }
3554       }
3555
3556   /* Check for virtual calls that became direct calls.  */
3557   callee = gimple_call_fn (stmt);
3558   if (callee && TREE_CODE (callee) == OBJ_TYPE_REF)
3559     {
3560       if (gimple_call_addr_fndecl (OBJ_TYPE_REF_EXPR (callee)) != NULL_TREE)
3561         {
3562           if (dump_file && virtual_method_call_p (callee)
3563               && !possible_polymorphic_call_target_p
3564                     (callee, stmt, cgraph_node::get (gimple_call_addr_fndecl
3565                                                      (OBJ_TYPE_REF_EXPR (callee)))))
3566             {
3567               fprintf (dump_file,
3568                        "Type inheritance inconsistent devirtualization of ");
3569               print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
3570               fprintf (dump_file, " to ");
3571               print_generic_expr (dump_file, callee, TDF_SLIM);
3572               fprintf (dump_file, "\n");
3573             }
3574
3575           gimple_call_set_fn (stmt, OBJ_TYPE_REF_EXPR (callee));
3576           changed = true;
3577         }
3578       else if (flag_devirtualize && !inplace && virtual_method_call_p (callee))
3579         {
3580           bool final;
3581           vec <cgraph_node *>targets
3582             = possible_polymorphic_call_targets (callee, stmt, &final);
3583           if (final && targets.length () <= 1 && dbg_cnt (devirt))
3584             {
3585               tree lhs = gimple_call_lhs (stmt);
3586               if (dump_enabled_p ())
3587                 {
3588                   location_t loc = gimple_location_safe (stmt);
3589                   dump_printf_loc (MSG_OPTIMIZED_LOCATIONS, loc,
3590                                    "folding virtual function call to %s\n",
3591                                    targets.length () == 1
3592                                    ? targets[0]->name ()
3593                                    : "__builtin_unreachable");
3594                 }
3595               if (targets.length () == 1)
3596                 {
3597                   tree fndecl = targets[0]->decl;
3598                   gimple_call_set_fndecl (stmt, fndecl);
3599                   changed = true;
3600                   /* If changing the call to __cxa_pure_virtual
3601                      or similar noreturn function, adjust gimple_call_fntype
3602                      too.  */
3603                   if (gimple_call_noreturn_p (stmt)
3604                       && VOID_TYPE_P (TREE_TYPE (TREE_TYPE (fndecl)))
3605                       && TYPE_ARG_TYPES (TREE_TYPE (fndecl))
3606                       && (TREE_VALUE (TYPE_ARG_TYPES (TREE_TYPE (fndecl)))
3607                           == void_type_node))
3608                     gimple_call_set_fntype (stmt, TREE_TYPE (fndecl));
3609                   /* If the call becomes noreturn, remove the lhs.  */
3610                   if (lhs
3611                       && gimple_call_noreturn_p (stmt)
3612                       && (VOID_TYPE_P (TREE_TYPE (gimple_call_fntype (stmt)))
3613                           || should_remove_lhs_p (lhs)))
3614                     {
3615                       if (TREE_CODE (lhs) == SSA_NAME)
3616                         {
3617                           tree var = create_tmp_var (TREE_TYPE (lhs));
3618                           tree def = get_or_create_ssa_default_def (cfun, var);
3619                           gimple *new_stmt = gimple_build_assign (lhs, def);
3620                           gsi_insert_before (gsi, new_stmt, GSI_SAME_STMT);
3621                         }
3622                       gimple_call_set_lhs (stmt, NULL_TREE);
3623                     }
3624                   maybe_remove_unused_call_args (cfun, stmt);
3625                 }
3626               else
3627                 {
3628                   tree fndecl = builtin_decl_implicit (BUILT_IN_UNREACHABLE);
3629                   gimple *new_stmt = gimple_build_call (fndecl, 0);
3630                   gimple_set_location (new_stmt, gimple_location (stmt));
3631                   if (lhs && TREE_CODE (lhs) == SSA_NAME)
3632                     {
3633                       tree var = create_tmp_var (TREE_TYPE (lhs));
3634                       tree def = get_or_create_ssa_default_def (cfun, var);
3635
3636                       /* To satisfy condition for
3637                          cgraph_update_edges_for_call_stmt_node,
3638                          we need to preserve GIMPLE_CALL statement
3639                          at position of GSI iterator.  */
3640                       update_call_from_tree (gsi, def);
3641                       gsi_insert_before (gsi, new_stmt, GSI_NEW_STMT);
3642                     }
3643                   else
3644                     {
3645                       gimple_set_vuse (new_stmt, gimple_vuse (stmt));
3646                       gimple_set_vdef (new_stmt, gimple_vdef (stmt));
3647                       gsi_replace (gsi, new_stmt, false);
3648                     }
3649                   return true;
3650                 }
3651             }
3652         }
3653     }
3654
3655   /* Check for indirect calls that became direct calls, and then
3656      no longer require a static chain.  */
3657   if (gimple_call_chain (stmt))
3658     {
3659       tree fn = gimple_call_fndecl (stmt);
3660       if (fn && !DECL_STATIC_CHAIN (fn))
3661         {
3662           gimple_call_set_chain (stmt, NULL);
3663           changed = true;
3664         }
3665       else
3666         {
3667           tree tmp = maybe_fold_reference (gimple_call_chain (stmt), false);
3668           if (tmp)
3669             {
3670               gimple_call_set_chain (stmt, tmp);
3671               changed = true;
3672             }
3673         }
3674     }
3675
3676   if (inplace)
3677     return changed;
3678
3679   /* Check for builtins that CCP can handle using information not
3680      available in the generic fold routines.  */
3681   if (gimple_call_builtin_p (stmt, BUILT_IN_NORMAL))
3682     {
3683       if (gimple_fold_builtin (gsi))
3684         changed = true;
3685     }
3686   else if (gimple_call_builtin_p (stmt, BUILT_IN_MD))
3687     {
3688         changed |= targetm.gimple_fold_builtin (gsi);
3689     }
3690   else if (gimple_call_internal_p (stmt))
3691     {
3692       enum tree_code subcode = ERROR_MARK;
3693       tree result = NULL_TREE;
3694       bool cplx_result = false;
3695       tree overflow = NULL_TREE;
3696       switch (gimple_call_internal_fn (stmt))
3697         {
3698         case IFN_BUILTIN_EXPECT:
3699           result = fold_builtin_expect (gimple_location (stmt),
3700                                         gimple_call_arg (stmt, 0),
3701                                         gimple_call_arg (stmt, 1),
3702                                         gimple_call_arg (stmt, 2));
3703           break;
3704         case IFN_UBSAN_OBJECT_SIZE:
3705           if (integer_all_onesp (gimple_call_arg (stmt, 2))
3706               || (TREE_CODE (gimple_call_arg (stmt, 1)) == INTEGER_CST
3707                   && TREE_CODE (gimple_call_arg (stmt, 2)) == INTEGER_CST
3708                   && tree_int_cst_le (gimple_call_arg (stmt, 1),
3709                                       gimple_call_arg (stmt, 2))))
3710             {
3711               gsi_replace (gsi, gimple_build_nop (), false);
3712               unlink_stmt_vdef (stmt);
3713               release_defs (stmt);
3714               return true;
3715             }
3716           break;
3717         case IFN_GOACC_DIM_SIZE:
3718         case IFN_GOACC_DIM_POS:
3719           result = fold_internal_goacc_dim (stmt);
3720           break;
3721         case IFN_UBSAN_CHECK_ADD:
3722           subcode = PLUS_EXPR;
3723           break;
3724         case IFN_UBSAN_CHECK_SUB:
3725           subcode = MINUS_EXPR;
3726           break;
3727         case IFN_UBSAN_CHECK_MUL:
3728           subcode = MULT_EXPR;
3729           break;
3730         case IFN_ADD_OVERFLOW:
3731           subcode = PLUS_EXPR;
3732           cplx_result = true;
3733           break;
3734         case IFN_SUB_OVERFLOW:
3735           subcode = MINUS_EXPR;
3736           cplx_result = true;
3737           break;
3738         case IFN_MUL_OVERFLOW:
3739           subcode = MULT_EXPR;
3740           cplx_result = true;
3741           break;
3742         default:
3743           break;
3744         }
3745       if (subcode != ERROR_MARK)
3746         {
3747           tree arg0 = gimple_call_arg (stmt, 0);
3748           tree arg1 = gimple_call_arg (stmt, 1);
3749           tree type = TREE_TYPE (arg0);
3750           if (cplx_result)
3751             {
3752               tree lhs = gimple_call_lhs (stmt);
3753               if (lhs == NULL_TREE)
3754                 type = NULL_TREE;
3755               else
3756                 type = TREE_TYPE (TREE_TYPE (lhs));
3757             }
3758           if (type == NULL_TREE)
3759             ;
3760           /* x = y + 0; x = y - 0; x = y * 0; */
3761           else if (integer_zerop (arg1))
3762             result = subcode == MULT_EXPR ? integer_zero_node : arg0;
3763           /* x = 0 + y; x = 0 * y; */
3764           else if (subcode != MINUS_EXPR && integer_zerop (arg0))
3765             result = subcode == MULT_EXPR ? integer_zero_node : arg1;
3766           /* x = y - y; */
3767           else if (subcode == MINUS_EXPR && operand_equal_p (arg0, arg1, 0))
3768             result = integer_zero_node;
3769           /* x = y * 1; x = 1 * y; */
3770           else if (subcode == MULT_EXPR && integer_onep (arg1))
3771             result = arg0;
3772           else if (subcode == MULT_EXPR && integer_onep (arg0))
3773             result = arg1;
3774           else if (TREE_CODE (arg0) == INTEGER_CST
3775                    && TREE_CODE (arg1) == INTEGER_CST)
3776             {
3777               if (cplx_result)
3778                 result = int_const_binop (subcode, fold_convert (type, arg0),
3779                                           fold_convert (type, arg1));
3780               else
3781                 result = int_const_binop (subcode, arg0, arg1);
3782               if (result && arith_overflowed_p (subcode, type, arg0, arg1))
3783                 {
3784                   if (cplx_result)
3785                     overflow = build_one_cst (type);
3786                   else
3787                     result = NULL_TREE;
3788                 }
3789             }
3790           if (result)
3791             {
3792               if (result == integer_zero_node)
3793                 result = build_zero_cst (type);
3794               else if (cplx_result && TREE_TYPE (result) != type)
3795                 {
3796                   if (TREE_CODE (result) == INTEGER_CST)
3797                     {
3798                       if (arith_overflowed_p (PLUS_EXPR, type, result,
3799                                               integer_zero_node))
3800                         overflow = build_one_cst (type);
3801                     }
3802                   else if ((!TYPE_UNSIGNED (TREE_TYPE (result))
3803                             && TYPE_UNSIGNED (type))
3804                            || (TYPE_PRECISION (type)
3805                                < (TYPE_PRECISION (TREE_TYPE (result))
3806                                   + (TYPE_UNSIGNED (TREE_TYPE (result))
3807                                      && !TYPE_UNSIGNED (type)))))
3808                     result = NULL_TREE;
3809                   if (result)
3810                     result = fold_convert (type, result);
3811                 }
3812             }
3813         }
3814
3815       if (result)
3816         {
3817           if (TREE_CODE (result) == INTEGER_CST && TREE_OVERFLOW (result))
3818             result = drop_tree_overflow (result);
3819           if (cplx_result)
3820             {
3821               if (overflow == NULL_TREE)
3822                 overflow = build_zero_cst (TREE_TYPE (result));
3823               tree ctype = build_complex_type (TREE_TYPE (result));
3824               if (TREE_CODE (result) == INTEGER_CST
3825                   && TREE_CODE (overflow) == INTEGER_CST)
3826                 result = build_complex (ctype, result, overflow);
3827               else
3828                 result = build2_loc (gimple_location (stmt), COMPLEX_EXPR,
3829                                      ctype, result, overflow);
3830             }
3831           if (!update_call_from_tree (gsi, result))
3832             gimplify_and_update_call_from_tree (gsi, result);
3833           changed = true;
3834         }
3835     }
3836
3837   return changed;
3838 }
3839
3840
3841 /* Return true whether NAME has a use on STMT.  */
3842
3843 static bool
3844 has_use_on_stmt (tree name, gimple *stmt)
3845 {
3846   imm_use_iterator iter;
3847   use_operand_p use_p;
3848   FOR_EACH_IMM_USE_FAST (use_p, iter, name)
3849     if (USE_STMT (use_p) == stmt)
3850       return true;
3851   return false;
3852 }
3853
3854 /* Worker for fold_stmt_1 dispatch to pattern based folding with
3855    gimple_simplify.
3856
3857    Replaces *GSI with the simplification result in RCODE and OPS
3858    and the associated statements in *SEQ.  Does the replacement
3859    according to INPLACE and returns true if the operation succeeded.  */
3860
3861 static bool
3862 replace_stmt_with_simplification (gimple_stmt_iterator *gsi,
3863                                   code_helper rcode, tree *ops,
3864                                   gimple_seq *seq, bool inplace)
3865 {
3866   gimple *stmt = gsi_stmt (*gsi);
3867
3868   /* Play safe and do not allow abnormals to be mentioned in
3869      newly created statements.  See also maybe_push_res_to_seq.
3870      As an exception allow such uses if there was a use of the
3871      same SSA name on the old stmt.  */
3872   if ((TREE_CODE (ops[0]) == SSA_NAME
3873        && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (ops[0])
3874        && !has_use_on_stmt (ops[0], stmt))
3875       || (ops[1]
3876           && TREE_CODE (ops[1]) == SSA_NAME
3877           && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (ops[1])
3878           && !has_use_on_stmt (ops[1], stmt))
3879       || (ops[2]
3880           && TREE_CODE (ops[2]) == SSA_NAME
3881           && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (ops[2])
3882           && !has_use_on_stmt (ops[2], stmt))
3883       || (COMPARISON_CLASS_P (ops[0])
3884           && ((TREE_CODE (TREE_OPERAND (ops[0], 0)) == SSA_NAME
3885                && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (TREE_OPERAND (ops[0], 0))
3886                && !has_use_on_stmt (TREE_OPERAND (ops[0], 0), stmt))
3887               || (TREE_CODE (TREE_OPERAND (ops[0], 1)) == SSA_NAME
3888                   && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (TREE_OPERAND (ops[0], 1))
3889                   && !has_use_on_stmt (TREE_OPERAND (ops[0], 1), stmt)))))
3890     return false;
3891
3892   /* Don't insert new statements when INPLACE is true, even if we could
3893      reuse STMT for the final statement.  */
3894   if (inplace && !gimple_seq_empty_p (*seq))
3895     return false;
3896
3897   if (gcond *cond_stmt = dyn_cast <gcond *> (stmt))
3898     {
3899       gcc_assert (rcode.is_tree_code ());
3900       if (TREE_CODE_CLASS ((enum tree_code)rcode) == tcc_comparison
3901           /* GIMPLE_CONDs condition may not throw.  */
3902           && (!flag_exceptions
3903               || !cfun->can_throw_non_call_exceptions
3904               || !operation_could_trap_p (rcode,
3905                                           FLOAT_TYPE_P (TREE_TYPE (ops[0])),
3906                                           false, NULL_TREE)))
3907         gimple_cond_set_condition (cond_stmt, rcode, ops[0], ops[1]);
3908       else if (rcode == SSA_NAME)
3909         gimple_cond_set_condition (cond_stmt, NE_EXPR, ops[0],
3910                                    build_zero_cst (TREE_TYPE (ops[0])));
3911       else if (rcode == INTEGER_CST)
3912         {
3913           if (integer_zerop (ops[0]))
3914             gimple_cond_make_false (cond_stmt);
3915           else
3916             gimple_cond_make_true (cond_stmt);
3917         }
3918       else if (!inplace)
3919         {
3920           tree res = maybe_push_res_to_seq (rcode, boolean_type_node,
3921                                             ops, seq);
3922           if (!res)
3923             return false;
3924           gimple_cond_set_condition (cond_stmt, NE_EXPR, res,
3925                                      build_zero_cst (TREE_TYPE (res)));
3926         }
3927       else
3928         return false;
3929       if (dump_file && (dump_flags & TDF_DETAILS))
3930         {
3931           fprintf (dump_file, "gimple_simplified to ");
3932           if (!gimple_seq_empty_p (*seq))
3933             print_gimple_seq (dump_file, *seq, 0, TDF_SLIM);
3934           print_gimple_stmt (dump_file, gsi_stmt (*gsi),
3935                              0, TDF_SLIM);
3936         }
3937       gsi_insert_seq_before (gsi, *seq, GSI_SAME_STMT);
3938       return true;
3939     }
3940   else if (is_gimple_assign (stmt)
3941            && rcode.is_tree_code ())
3942     {
3943       if (!inplace
3944           || gimple_num_ops (stmt) > get_gimple_rhs_num_ops (rcode))
3945         {
3946           maybe_build_generic_op (rcode,
3947                                   TREE_TYPE (gimple_assign_lhs (stmt)), ops);
3948           gimple_assign_set_rhs_with_ops (gsi, rcode, ops[0], ops[1], ops[2]);
3949           if (dump_file && (dump_flags & TDF_DETAILS))
3950             {
3951               fprintf (dump_file, "gimple_simplified to ");
3952               if (!gimple_seq_empty_p (*seq))
3953                 print_gimple_seq (dump_file, *seq, 0, TDF_SLIM);
3954               print_gimple_stmt (dump_file, gsi_stmt (*gsi),
3955                                  0, TDF_SLIM);
3956             }
3957           gsi_insert_seq_before (gsi, *seq, GSI_SAME_STMT);
3958           return true;
3959         }
3960     }
3961   else if (rcode.is_fn_code ()
3962            && gimple_call_combined_fn (stmt) == rcode)
3963     {
3964       unsigned i;
3965       for (i = 0; i < gimple_call_num_args (stmt); ++i)
3966         {
3967           gcc_assert (ops[i] != NULL_TREE);
3968           gimple_call_set_arg (stmt, i, ops[i]);
3969         }
3970       if (i < 3)
3971         gcc_assert (ops[i] == NULL_TREE);
3972       if (dump_file && (dump_flags & TDF_DETAILS))
3973         {
3974           fprintf (dump_file, "gimple_simplified to ");
3975           if (!gimple_seq_empty_p (*seq))
3976             print_gimple_seq (dump_file, *seq, 0, TDF_SLIM);
3977           print_gimple_stmt (dump_file, gsi_stmt (*gsi), 0, TDF_SLIM);
3978         }
3979       gsi_insert_seq_before (gsi, *seq, GSI_SAME_STMT);
3980       return true;
3981     }
3982   else if (!inplace)
3983     {
3984       if (gimple_has_lhs (stmt))
3985         {
3986           tree lhs = gimple_get_lhs (stmt);
3987           if (!maybe_push_res_to_seq (rcode, TREE_TYPE (lhs),
3988                                       ops, seq, lhs))
3989             return false;
3990           if (dump_file && (dump_flags & TDF_DETAILS))
3991             {
3992               fprintf (dump_file, "gimple_simplified to ");
3993               print_gimple_seq (dump_file, *seq, 0, TDF_SLIM);
3994             }
3995           gsi_replace_with_seq_vops (gsi, *seq);
3996           return true;
3997         }
3998       else
3999         gcc_unreachable ();
4000     }
4001
4002   return false;
4003 }
4004
4005 /* Canonicalize MEM_REFs invariant address operand after propagation.  */
4006
4007 static bool
4008 maybe_canonicalize_mem_ref_addr (tree *t)
4009 {
4010   bool res = false;
4011
4012   if (TREE_CODE (*t) == ADDR_EXPR)
4013     t = &TREE_OPERAND (*t, 0);
4014
4015   /* The C and C++ frontends use an ARRAY_REF for indexing with their
4016      generic vector extension.  The actual vector referenced is
4017      view-converted to an array type for this purpose.  If the index
4018      is constant the canonical representation in the middle-end is a
4019      BIT_FIELD_REF so re-write the former to the latter here.  */
4020   if (TREE_CODE (*t) == ARRAY_REF
4021       && TREE_CODE (TREE_OPERAND (*t, 0)) == VIEW_CONVERT_EXPR
4022       && TREE_CODE (TREE_OPERAND (*t, 1)) == INTEGER_CST
4023       && VECTOR_TYPE_P (TREE_TYPE (TREE_OPERAND (TREE_OPERAND (*t, 0), 0))))
4024     {
4025       tree vtype = TREE_TYPE (TREE_OPERAND (TREE_OPERAND (*t, 0), 0));
4026       if (VECTOR_TYPE_P (vtype))
4027         {
4028           tree low = array_ref_low_bound (*t);
4029           if (TREE_CODE (low) == INTEGER_CST)
4030             {
4031               if (tree_int_cst_le (low, TREE_OPERAND (*t, 1)))
4032                 {
4033                   widest_int idx = wi::sub (wi::to_widest (TREE_OPERAND (*t, 1)),
4034                                             wi::to_widest (low));
4035                   idx = wi::mul (idx, wi::to_widest
4036                                          (TYPE_SIZE (TREE_TYPE (*t))));
4037                   widest_int ext
4038                     = wi::add (idx, wi::to_widest (TYPE_SIZE (TREE_TYPE (*t))));
4039                   if (wi::les_p (ext, wi::to_widest (TYPE_SIZE (vtype))))
4040                     {
4041                       *t = build3_loc (EXPR_LOCATION (*t), BIT_FIELD_REF,
4042                                        TREE_TYPE (*t),
4043                                        TREE_OPERAND (TREE_OPERAND (*t, 0), 0),
4044                                        TYPE_SIZE (TREE_TYPE (*t)),
4045                                        wide_int_to_tree (sizetype, idx));
4046                       res = true;
4047                     }
4048                 }
4049             }
4050         }
4051     }
4052
4053   while (handled_component_p (*t))
4054     t = &TREE_OPERAND (*t, 0);
4055
4056   /* Canonicalize MEM [&foo.bar, 0] which appears after propagating
4057      of invariant addresses into a SSA name MEM_REF address.  */
4058   if (TREE_CODE (*t) == MEM_REF
4059       || TREE_CODE (*t) == TARGET_MEM_REF)
4060     {
4061       tree addr = TREE_OPERAND (*t, 0);
4062       if (TREE_CODE (addr) == ADDR_EXPR
4063           && (TREE_CODE (TREE_OPERAND (addr, 0)) == MEM_REF
4064               || handled_component_p (TREE_OPERAND (addr, 0))))
4065         {
4066           tree base;
4067           HOST_WIDE_INT coffset;
4068           base = get_addr_base_and_unit_offset (TREE_OPERAND (addr, 0),
4069                                                 &coffset);
4070           if (!base)
4071             gcc_unreachable ();
4072
4073           TREE_OPERAND (*t, 0) = build_fold_addr_expr (base);
4074           TREE_OPERAND (*t, 1) = int_const_binop (PLUS_EXPR,
4075                                                   TREE_OPERAND (*t, 1),
4076                                                   size_int (coffset));
4077           res = true;
4078         }
4079       gcc_checking_assert (TREE_CODE (TREE_OPERAND (*t, 0)) == DEBUG_EXPR_DECL
4080                            || is_gimple_mem_ref_addr (TREE_OPERAND (*t, 0)));
4081     }
4082
4083   /* Canonicalize back MEM_REFs to plain reference trees if the object
4084      accessed is a decl that has the same access semantics as the MEM_REF.  */
4085   if (TREE_CODE (*t) == MEM_REF
4086       && TREE_CODE (TREE_OPERAND (*t, 0)) == ADDR_EXPR
4087       && integer_zerop (TREE_OPERAND (*t, 1))
4088       && MR_DEPENDENCE_CLIQUE (*t) == 0)
4089     {
4090       tree decl = TREE_OPERAND (TREE_OPERAND (*t, 0), 0);
4091       tree alias_type = TREE_TYPE (TREE_OPERAND (*t, 1));
4092       if (/* Same volatile qualification.  */
4093           TREE_THIS_VOLATILE (*t) == TREE_THIS_VOLATILE (decl)
4094           /* Same TBAA behavior with -fstrict-aliasing.  */
4095           && !TYPE_REF_CAN_ALIAS_ALL (alias_type)
4096           && (TYPE_MAIN_VARIANT (TREE_TYPE (decl))
4097               == TYPE_MAIN_VARIANT (TREE_TYPE (alias_type)))
4098           /* Same alignment.  */
4099           && TYPE_ALIGN (TREE_TYPE (decl)) == TYPE_ALIGN (TREE_TYPE (*t))
4100           /* We have to look out here to not drop a required conversion
4101              from the rhs to the lhs if *t appears on the lhs or vice-versa
4102              if it appears on the rhs.  Thus require strict type
4103              compatibility.  */
4104           && types_compatible_p (TREE_TYPE (*t), TREE_TYPE (decl)))
4105         {
4106           *t = TREE_OPERAND (TREE_OPERAND (*t, 0), 0);
4107           res = true;
4108         }
4109     }
4110
4111   /* Canonicalize TARGET_MEM_REF in particular with respect to
4112      the indexes becoming constant.  */
4113   else if (TREE_CODE (*t) == TARGET_MEM_REF)
4114     {
4115       tree tem = maybe_fold_tmr (*t);
4116       if (tem)
4117         {
4118           *t = tem;
4119           res = true;
4120         }
4121     }
4122
4123   return res;
4124 }
4125
4126 /* Worker for both fold_stmt and fold_stmt_inplace.  The INPLACE argument
4127    distinguishes both cases.  */
4128
4129 static bool
4130 fold_stmt_1 (gimple_stmt_iterator *gsi, bool inplace, tree (*valueize) (tree))
4131 {
4132   bool changed = false;
4133   gimple *stmt = gsi_stmt (*gsi);
4134   bool nowarning = gimple_no_warning_p (stmt);
4135   unsigned i;
4136   fold_defer_overflow_warnings ();
4137
4138   /* First do required canonicalization of [TARGET_]MEM_REF addresses
4139      after propagation.
4140      ???  This shouldn't be done in generic folding but in the
4141      propagation helpers which also know whether an address was
4142      propagated.
4143      Also canonicalize operand order.  */
4144   switch (gimple_code (stmt))
4145     {
4146     case GIMPLE_ASSIGN:
4147       if (gimple_assign_rhs_class (stmt) == GIMPLE_SINGLE_RHS)
4148         {
4149           tree *rhs = gimple_assign_rhs1_ptr (stmt);
4150           if ((REFERENCE_CLASS_P (*rhs)
4151                || TREE_CODE (*rhs) == ADDR_EXPR)
4152               && maybe_canonicalize_mem_ref_addr (rhs))
4153             changed = true;
4154           tree *lhs = gimple_assign_lhs_ptr (stmt);
4155           if (REFERENCE_CLASS_P (*lhs)
4156               && maybe_canonicalize_mem_ref_addr (lhs))
4157             changed = true;
4158         }
4159       else
4160         {
4161           /* Canonicalize operand order.  */
4162           enum tree_code code = gimple_assign_rhs_code (stmt);
4163           if (TREE_CODE_CLASS (code) == tcc_comparison
4164               || commutative_tree_code (code)
4165               || commutative_ternary_tree_code (code))
4166             {
4167               tree rhs1 = gimple_assign_rhs1 (stmt);
4168               tree rhs2 = gimple_assign_rhs2 (stmt);
4169               if (tree_swap_operands_p (rhs1, rhs2))
4170                 {
4171                   gimple_assign_set_rhs1 (stmt, rhs2);
4172                   gimple_assign_set_rhs2 (stmt, rhs1);
4173                   if (TREE_CODE_CLASS (code) == tcc_comparison)
4174                     gimple_assign_set_rhs_code (stmt,
4175                                                 swap_tree_comparison (code));
4176                   changed = true;
4177                 }
4178             }
4179         }
4180       break;
4181     case GIMPLE_CALL:
4182       {
4183         for (i = 0; i < gimple_call_num_args (stmt); ++i)
4184           {
4185             tree *arg = gimple_call_arg_ptr (stmt, i);
4186             if (REFERENCE_CLASS_P (*arg)
4187                 && maybe_canonicalize_mem_ref_addr (arg))
4188               changed = true;
4189           }
4190         tree *lhs = gimple_call_lhs_ptr (stmt);
4191         if (*lhs
4192             && REFERENCE_CLASS_P (*lhs)
4193             && maybe_canonicalize_mem_ref_addr (lhs))
4194           changed = true;
4195         break;
4196       }
4197     case GIMPLE_ASM:
4198       {
4199         gasm *asm_stmt = as_a <gasm *> (stmt);
4200         for (i = 0; i < gimple_asm_noutputs (asm_stmt); ++i)
4201           {
4202             tree link = gimple_asm_output_op (asm_stmt, i);
4203             tree op = TREE_VALUE (link);
4204             if (REFERENCE_CLASS_P (op)
4205                 && maybe_canonicalize_mem_ref_addr (&TREE_VALUE (link)))
4206               changed = true;
4207           }
4208         for (i = 0; i < gimple_asm_ninputs (asm_stmt); ++i)
4209           {
4210             tree link = gimple_asm_input_op (asm_stmt, i);
4211             tree op = TREE_VALUE (link);
4212             if ((REFERENCE_CLASS_P (op)
4213                  || TREE_CODE (op) == ADDR_EXPR)
4214                 && maybe_canonicalize_mem_ref_addr (&TREE_VALUE (link)))
4215               changed = true;
4216           }
4217       }
4218       break;
4219     case GIMPLE_DEBUG:
4220       if (gimple_debug_bind_p (stmt))
4221         {
4222           tree *val = gimple_debug_bind_get_value_ptr (stmt);
4223           if (*val
4224               && (REFERENCE_CLASS_P (*val)
4225                   || TREE_CODE (*val) == ADDR_EXPR)
4226               && maybe_canonicalize_mem_ref_addr (val))
4227             changed = true;
4228         }
4229       break;
4230     case GIMPLE_COND:
4231       {
4232         /* Canonicalize operand order.  */
4233         tree lhs = gimple_cond_lhs (stmt);
4234         tree rhs = gimple_cond_rhs (stmt);
4235         if (tree_swap_operands_p (lhs, rhs))
4236           {
4237             gcond *gc = as_a <gcond *> (stmt);
4238             gimple_cond_set_lhs (gc, rhs);
4239             gimple_cond_set_rhs (gc, lhs);
4240             gimple_cond_set_code (gc,
4241                                   swap_tree_comparison (gimple_cond_code (gc)));
4242             changed = true;
4243           }
4244       }
4245     default:;
4246     }
4247
4248   /* Dispatch to pattern-based folding.  */
4249   if (!inplace
4250       || is_gimple_assign (stmt)
4251       || gimple_code (stmt) == GIMPLE_COND)
4252     {
4253       gimple_seq seq = NULL;
4254       code_helper rcode;
4255       tree ops[3] = {};
4256       if (gimple_simplify (stmt, &rcode, ops, inplace ? NULL : &seq,
4257                            valueize, valueize))
4258         {
4259           if (replace_stmt_with_simplification (gsi, rcode, ops, &seq, inplace))
4260             changed = true;
4261           else
4262             gimple_seq_discard (seq);
4263         }
4264     }
4265
4266   stmt = gsi_stmt (*gsi);
4267
4268   /* Fold the main computation performed by the statement.  */
4269   switch (gimple_code (stmt))
4270     {
4271     case GIMPLE_ASSIGN:
4272       {
4273         /* Try to canonicalize for boolean-typed X the comparisons
4274            X == 0, X == 1, X != 0, and X != 1.  */
4275         if (gimple_assign_rhs_code (stmt) == EQ_EXPR
4276             || gimple_assign_rhs_code (stmt) == NE_EXPR)
4277           {
4278             tree lhs = gimple_assign_lhs (stmt);
4279             tree op1 = gimple_assign_rhs1 (stmt);
4280             tree op2 = gimple_assign_rhs2 (stmt);
4281             tree type = TREE_TYPE (op1);
4282
4283             /* Check whether the comparison operands are of the same boolean
4284                type as the result type is.
4285                Check that second operand is an integer-constant with value
4286                one or zero.  */
4287             if (TREE_CODE (op2) == INTEGER_CST
4288                 && (integer_zerop (op2) || integer_onep (op2))
4289                 && useless_type_conversion_p (TREE_TYPE (lhs), type))
4290               {
4291                 enum tree_code cmp_code = gimple_assign_rhs_code (stmt);
4292                 bool is_logical_not = false;
4293
4294                 /* X == 0 and X != 1 is a logical-not.of X
4295                    X == 1 and X != 0 is X  */
4296                 if ((cmp_code == EQ_EXPR && integer_zerop (op2))
4297                     || (cmp_code == NE_EXPR && integer_onep (op2)))
4298                   is_logical_not = true;
4299
4300                 if (is_logical_not == false)
4301                   gimple_assign_set_rhs_with_ops (gsi, TREE_CODE (op1), op1);
4302                 /* Only for one-bit precision typed X the transformation
4303                    !X -> ~X is valied.  */
4304                 else if (TYPE_PRECISION (type) == 1)
4305                   gimple_assign_set_rhs_with_ops (gsi, BIT_NOT_EXPR, op1);
4306                 /* Otherwise we use !X -> X ^ 1.  */
4307                 else
4308                   gimple_assign_set_rhs_with_ops (gsi, BIT_XOR_EXPR, op1,
4309                                                   build_int_cst (type, 1));
4310                 changed = true;
4311                 break;
4312               }
4313           }
4314
4315         unsigned old_num_ops = gimple_num_ops (stmt);
4316         tree lhs = gimple_assign_lhs (stmt);
4317         tree new_rhs = fold_gimple_assign (gsi);
4318         if (new_rhs
4319             && !useless_type_conversion_p (TREE_TYPE (lhs),
4320                                            TREE_TYPE (new_rhs)))
4321           new_rhs = fold_convert (TREE_TYPE (lhs), new_rhs);
4322         if (new_rhs
4323             && (!inplace
4324                 || get_gimple_rhs_num_ops (TREE_CODE (new_rhs)) < old_num_ops))
4325           {
4326             gimple_assign_set_rhs_from_tree (gsi, new_rhs);
4327             changed = true;
4328           }
4329         break;
4330       }
4331
4332     case GIMPLE_CALL:
4333       changed |= gimple_fold_call (gsi, inplace);
4334       break;
4335
4336     case GIMPLE_ASM:
4337       /* Fold *& in asm operands.  */
4338       {
4339         gasm *asm_stmt = as_a <gasm *> (stmt);
4340         size_t noutputs;
4341         const char **oconstraints;
4342         const char *constraint;
4343         bool allows_mem, allows_reg;
4344
4345         noutputs = gimple_asm_noutputs (asm_stmt);
4346         oconstraints = XALLOCAVEC (const char *, noutputs);
4347
4348         for (i = 0; i < gimple_asm_noutputs (asm_stmt); ++i)
4349           {
4350             tree link = gimple_asm_output_op (asm_stmt, i);
4351             tree op = TREE_VALUE (link);
4352             oconstraints[i]
4353               = TREE_STRING_POINTER (TREE_VALUE (TREE_PURPOSE (link)));
4354             if (REFERENCE_CLASS_P (op)
4355                 && (op = maybe_fold_reference (op, true)) != NULL_TREE)
4356               {
4357                 TREE_VALUE (link) = op;
4358                 changed = true;
4359               }
4360           }
4361         for (i = 0; i < gimple_asm_ninputs (asm_stmt); ++i)
4362           {
4363             tree link = gimple_asm_input_op (asm_stmt, i);
4364             tree op = TREE_VALUE (link);
4365             constraint
4366               = TREE_STRING_POINTER (TREE_VALUE (TREE_PURPOSE (link)));
4367             parse_input_constraint (&constraint, 0, 0, noutputs, 0,
4368                                     oconstraints, &allows_mem, &allows_reg);
4369             if (REFERENCE_CLASS_P (op)
4370                 && (op = maybe_fold_reference (op, !allows_reg && allows_mem))
4371                    != NULL_TREE)
4372               {
4373                 TREE_VALUE (link) = op;
4374                 changed = true;
4375               }
4376           }
4377       }
4378       break;
4379
4380     case GIMPLE_DEBUG:
4381       if (gimple_debug_bind_p (stmt))
4382         {
4383           tree val = gimple_debug_bind_get_value (stmt);
4384           if (val
4385               && REFERENCE_CLASS_P (val))
4386             {
4387               tree tem = maybe_fold_reference (val, false);
4388               if (tem)
4389                 {
4390                   gimple_debug_bind_set_value (stmt, tem);
4391                   changed = true;
4392                 }
4393             }
4394           else if (val
4395                    && TREE_CODE (val) == ADDR_EXPR)
4396             {
4397               tree ref = TREE_OPERAND (val, 0);
4398               tree tem = maybe_fold_reference (ref, false);
4399               if (tem)
4400                 {
4401                   tem = build_fold_addr_expr_with_type (tem, TREE_TYPE (val));
4402                   gimple_debug_bind_set_value (stmt, tem);
4403                   changed = true;
4404                 }
4405             }
4406         }
4407       break;
4408
4409     default:;
4410     }
4411
4412   stmt = gsi_stmt (*gsi);
4413
4414   /* Fold *& on the lhs.  */
4415   if (gimple_has_lhs (stmt))
4416     {
4417       tree lhs = gimple_get_lhs (stmt);
4418       if (lhs && REFERENCE_CLASS_P (lhs))
4419         {
4420           tree new_lhs = maybe_fold_reference (lhs, true);
4421           if (new_lhs)
4422             {
4423               gimple_set_lhs (stmt, new_lhs);
4424               changed = true;
4425             }
4426         }
4427     }
4428
4429   fold_undefer_overflow_warnings (changed && !nowarning, stmt, 0);
4430   return changed;
4431 }
4432
4433 /* Valueziation callback that ends up not following SSA edges.  */
4434
4435 tree
4436 no_follow_ssa_edges (tree)
4437 {
4438   return NULL_TREE;
4439 }
4440
4441 /* Valueization callback that ends up following single-use SSA edges only.  */
4442
4443 tree
4444 follow_single_use_edges (tree val)
4445 {
4446   if (TREE_CODE (val) == SSA_NAME
4447       && !has_single_use (val))
4448     return NULL_TREE;
4449   return val;
4450 }
4451
4452 /* Fold the statement pointed to by GSI.  In some cases, this function may
4453    replace the whole statement with a new one.  Returns true iff folding
4454    makes any changes.
4455    The statement pointed to by GSI should be in valid gimple form but may
4456    be in unfolded state as resulting from for example constant propagation
4457    which can produce *&x = 0.  */
4458
4459 bool
4460 fold_stmt (gimple_stmt_iterator *gsi)
4461 {
4462   return fold_stmt_1 (gsi, false, no_follow_ssa_edges);
4463 }
4464
4465 bool
4466 fold_stmt (gimple_stmt_iterator *gsi, tree (*valueize) (tree))
4467 {
4468   return fold_stmt_1 (gsi, false, valueize);
4469 }
4470
4471 /* Perform the minimal folding on statement *GSI.  Only operations like
4472    *&x created by constant propagation are handled.  The statement cannot
4473    be replaced with a new one.  Return true if the statement was
4474    changed, false otherwise.
4475    The statement *GSI should be in valid gimple form but may
4476    be in unfolded state as resulting from for example constant propagation
4477    which can produce *&x = 0.  */
4478
4479 bool
4480 fold_stmt_inplace (gimple_stmt_iterator *gsi)
4481 {
4482   gimple *stmt = gsi_stmt (*gsi);
4483   bool changed = fold_stmt_1 (gsi, true, no_follow_ssa_edges);
4484   gcc_assert (gsi_stmt (*gsi) == stmt);
4485   return changed;
4486 }
4487
4488 /* Canonicalize and possibly invert the boolean EXPR; return NULL_TREE 
4489    if EXPR is null or we don't know how.
4490    If non-null, the result always has boolean type.  */
4491
4492 static tree
4493 canonicalize_bool (tree expr, bool invert)
4494 {
4495   if (!expr)
4496     return NULL_TREE;
4497   else if (invert)
4498     {
4499       if (integer_nonzerop (expr))
4500         return boolean_false_node;
4501       else if (integer_zerop (expr))
4502         return boolean_true_node;
4503       else if (TREE_CODE (expr) == SSA_NAME)
4504         return fold_build2 (EQ_EXPR, boolean_type_node, expr,
4505                             build_int_cst (TREE_TYPE (expr), 0));
4506       else if (COMPARISON_CLASS_P (expr))
4507         return fold_build2 (invert_tree_comparison (TREE_CODE (expr), false),
4508                             boolean_type_node,
4509                             TREE_OPERAND (expr, 0),
4510                             TREE_OPERAND (expr, 1));
4511       else
4512         return NULL_TREE;
4513     }
4514   else
4515     {
4516       if (TREE_CODE (TREE_TYPE (expr)) == BOOLEAN_TYPE)
4517         return expr;
4518       if (integer_nonzerop (expr))
4519         return boolean_true_node;
4520       else if (integer_zerop (expr))
4521         return boolean_false_node;
4522       else if (TREE_CODE (expr) == SSA_NAME)
4523         return fold_build2 (NE_EXPR, boolean_type_node, expr,
4524                             build_int_cst (TREE_TYPE (expr), 0));
4525       else if (COMPARISON_CLASS_P (expr))
4526         return fold_build2 (TREE_CODE (expr),
4527                             boolean_type_node,
4528                             TREE_OPERAND (expr, 0),
4529                             TREE_OPERAND (expr, 1));
4530       else
4531         return NULL_TREE;
4532     }
4533 }
4534
4535 /* Check to see if a boolean expression EXPR is logically equivalent to the
4536    comparison (OP1 CODE OP2).  Check for various identities involving
4537    SSA_NAMEs.  */
4538
4539 static bool
4540 same_bool_comparison_p (const_tree expr, enum tree_code code,
4541                         const_tree op1, const_tree op2)
4542 {
4543   gimple *s;
4544
4545   /* The obvious case.  */
4546   if (TREE_CODE (expr) == code
4547       && operand_equal_p (TREE_OPERAND (expr, 0), op1, 0)
4548       && operand_equal_p (TREE_OPERAND (expr, 1), op2, 0))
4549     return true;
4550
4551   /* Check for comparing (name, name != 0) and the case where expr
4552      is an SSA_NAME with a definition matching the comparison.  */
4553   if (TREE_CODE (expr) == SSA_NAME
4554       && TREE_CODE (TREE_TYPE (expr)) == BOOLEAN_TYPE)
4555     {
4556       if (operand_equal_p (expr, op1, 0))
4557         return ((code == NE_EXPR && integer_zerop (op2))
4558                 || (code == EQ_EXPR && integer_nonzerop (op2)));
4559       s = SSA_NAME_DEF_STMT (expr);
4560       if (is_gimple_assign (s)
4561           && gimple_assign_rhs_code (s) == code
4562           && operand_equal_p (gimple_assign_rhs1 (s), op1, 0)
4563           && operand_equal_p (gimple_assign_rhs2 (s), op2, 0))
4564         return true;
4565     }
4566
4567   /* If op1 is of the form (name != 0) or (name == 0), and the definition
4568      of name is a comparison, recurse.  */
4569   if (TREE_CODE (op1) == SSA_NAME
4570       && TREE_CODE (TREE_TYPE (op1)) == BOOLEAN_TYPE)
4571     {
4572       s = SSA_NAME_DEF_STMT (op1);
4573       if (is_gimple_assign (s)
4574           && TREE_CODE_CLASS (gimple_assign_rhs_code (s)) == tcc_comparison)
4575         {
4576           enum tree_code c = gimple_assign_rhs_code (s);
4577           if ((c == NE_EXPR && integer_zerop (op2))
4578               || (c == EQ_EXPR && integer_nonzerop (op2)))
4579             return same_bool_comparison_p (expr, c,
4580                                            gimple_assign_rhs1 (s),
4581                                            gimple_assign_rhs2 (s));
4582           if ((c == EQ_EXPR && integer_zerop (op2))
4583               || (c == NE_EXPR && integer_nonzerop (op2)))
4584             return same_bool_comparison_p (expr,
4585                                            invert_tree_comparison (c, false),
4586                                            gimple_assign_rhs1 (s),
4587                                            gimple_assign_rhs2 (s));
4588         }
4589     }
4590   return false;
4591 }
4592
4593 /* Check to see if two boolean expressions OP1 and OP2 are logically
4594    equivalent.  */
4595
4596 static bool
4597 same_bool_result_p (const_tree op1, const_tree op2)
4598 {
4599   /* Simple cases first.  */
4600   if (operand_equal_p (op1, op2, 0))
4601     return true;
4602
4603   /* Check the cases where at least one of the operands is a comparison.
4604      These are a bit smarter than operand_equal_p in that they apply some
4605      identifies on SSA_NAMEs.  */
4606   if (COMPARISON_CLASS_P (op2)
4607       && same_bool_comparison_p (op1, TREE_CODE (op2),
4608                                  TREE_OPERAND (op2, 0),
4609                                  TREE_OPERAND (op2, 1)))
4610     return true;
4611   if (COMPARISON_CLASS_P (op1)
4612       && same_bool_comparison_p (op2, TREE_CODE (op1),
4613                                  TREE_OPERAND (op1, 0),
4614                                  TREE_OPERAND (op1, 1)))
4615     return true;
4616
4617   /* Default case.  */
4618   return false;
4619 }
4620
4621 /* Forward declarations for some mutually recursive functions.  */
4622
4623 static tree
4624 and_comparisons_1 (enum tree_code code1, tree op1a, tree op1b,
4625                    enum tree_code code2, tree op2a, tree op2b);
4626 static tree
4627 and_var_with_comparison (tree var, bool invert,
4628                          enum tree_code code2, tree op2a, tree op2b);
4629 static tree
4630 and_var_with_comparison_1 (gimple *stmt,
4631                            enum tree_code code2, tree op2a, tree op2b);
4632 static tree
4633 or_comparisons_1 (enum tree_code code1, tree op1a, tree op1b,
4634                   enum tree_code code2, tree op2a, tree op2b);
4635 static tree
4636 or_var_with_comparison (tree var, bool invert,
4637                         enum tree_code code2, tree op2a, tree op2b);
4638 static tree
4639 or_var_with_comparison_1 (gimple *stmt,
4640                           enum tree_code code2, tree op2a, tree op2b);
4641
4642 /* Helper function for and_comparisons_1:  try to simplify the AND of the
4643    ssa variable VAR with the comparison specified by (OP2A CODE2 OP2B).
4644    If INVERT is true, invert the value of the VAR before doing the AND.
4645    Return NULL_EXPR if we can't simplify this to a single expression.  */
4646
4647 static tree
4648 and_var_with_comparison (tree var, bool invert,
4649                          enum tree_code code2, tree op2a, tree op2b)
4650 {
4651   tree t;
4652   gimple *stmt = SSA_NAME_DEF_STMT (var);
4653
4654   /* We can only deal with variables whose definitions are assignments.  */
4655   if (!is_gimple_assign (stmt))
4656     return NULL_TREE;
4657   
4658   /* If we have an inverted comparison, apply DeMorgan's law and rewrite
4659      !var AND (op2a code2 op2b) => !(var OR !(op2a code2 op2b))
4660      Then we only have to consider the simpler non-inverted cases.  */
4661   if (invert)
4662     t = or_var_with_comparison_1 (stmt, 
4663                                   invert_tree_comparison (code2, false),
4664                                   op2a, op2b);
4665   else
4666     t = and_var_with_comparison_1 (stmt, code2, op2a, op2b);
4667   return canonicalize_bool (t, invert);
4668 }
4669
4670 /* Try to simplify the AND of the ssa variable defined by the assignment
4671    STMT with the comparison specified by (OP2A CODE2 OP2B).
4672    Return NULL_EXPR if we can't simplify this to a single expression.  */
4673
4674 static tree
4675 and_var_with_comparison_1 (gimple *stmt,
4676                            enum tree_code code2, tree op2a, tree op2b)
4677 {
4678   tree var = gimple_assign_lhs (stmt);
4679   tree true_test_var = NULL_TREE;
4680   tree false_test_var = NULL_TREE;
4681   enum tree_code innercode = gimple_assign_rhs_code (stmt);
4682
4683   /* Check for identities like (var AND (var == 0)) => false.  */
4684   if (TREE_CODE (op2a) == SSA_NAME
4685       && TREE_CODE (TREE_TYPE (var)) == BOOLEAN_TYPE)
4686     {
4687       if ((code2 == NE_EXPR && integer_zerop (op2b))
4688           || (code2 == EQ_EXPR && integer_nonzerop (op2b)))
4689         {
4690           true_test_var = op2a;
4691           if (var == true_test_var)
4692             return var;
4693         }
4694       else if ((code2 == EQ_EXPR && integer_zerop (op2b))
4695                || (code2 == NE_EXPR && integer_nonzerop (op2b)))
4696         {
4697           false_test_var = op2a;
4698           if (var == false_test_var)
4699             return boolean_false_node;
4700         }
4701     }
4702
4703   /* If the definition is a comparison, recurse on it.  */
4704   if (TREE_CODE_CLASS (innercode) == tcc_comparison)
4705     {
4706       tree t = and_comparisons_1 (innercode,
4707                                   gimple_assign_rhs1 (stmt),
4708                                   gimple_assign_rhs2 (stmt),
4709                                   code2,
4710                                   op2a,
4711                                   op2b);
4712       if (t)
4713         return t;
4714     }
4715
4716   /* If the definition is an AND or OR expression, we may be able to
4717      simplify by reassociating.  */
4718   if (TREE_CODE (TREE_TYPE (var)) == BOOLEAN_TYPE
4719       && (innercode == BIT_AND_EXPR || innercode == BIT_IOR_EXPR))
4720     {
4721       tree inner1 = gimple_assign_rhs1 (stmt);
4722       tree inner2 = gimple_assign_rhs2 (stmt);
4723       gimple *s;
4724       tree t;
4725       tree partial = NULL_TREE;
4726       bool is_and = (innercode == BIT_AND_EXPR);
4727       
4728       /* Check for boolean identities that don't require recursive examination
4729          of inner1/inner2:
4730          inner1 AND (inner1 AND inner2) => inner1 AND inner2 => var
4731          inner1 AND (inner1 OR inner2) => inner1
4732          !inner1 AND (inner1 AND inner2) => false
4733          !inner1 AND (inner1 OR inner2) => !inner1 AND inner2
4734          Likewise for similar cases involving inner2.  */
4735       if (inner1 == true_test_var)
4736         return (is_and ? var : inner1);
4737       else if (inner2 == true_test_var)
4738         return (is_and ? var : inner2);
4739       else if (inner1 == false_test_var)
4740         return (is_and
4741                 ? boolean_false_node
4742                 : and_var_with_comparison (inner2, false, code2, op2a, op2b));
4743       else if (inner2 == false_test_var)
4744         return (is_and
4745                 ? boolean_false_node
4746                 : and_var_with_comparison (inner1, false, code2, op2a, op2b));
4747
4748       /* Next, redistribute/reassociate the AND across the inner tests.
4749          Compute the first partial result, (inner1 AND (op2a code op2b))  */
4750       if (TREE_CODE (inner1) == SSA_NAME
4751           && is_gimple_assign (s = SSA_NAME_DEF_STMT (inner1))
4752           && TREE_CODE_CLASS (gimple_assign_rhs_code (s)) == tcc_comparison
4753           && (t = maybe_fold_and_comparisons (gimple_assign_rhs_code (s),
4754                                               gimple_assign_rhs1 (s),
4755                                               gimple_assign_rhs2 (s),
4756                                               code2, op2a, op2b)))
4757         {
4758           /* Handle the AND case, where we are reassociating:
4759              (inner1 AND inner2) AND (op2a code2 op2b)
4760              => (t AND inner2)
4761              If the partial result t is a constant, we win.  Otherwise
4762              continue on to try reassociating with the other inner test.  */
4763           if (is_and)
4764             {
4765               if (integer_onep (t))
4766                 return inner2;
4767               else if (integer_zerop (t))
4768                 return boolean_false_node;
4769             }
4770
4771           /* Handle the OR case, where we are redistributing:
4772              (inner1 OR inner2) AND (op2a code2 op2b)
4773              => (t OR (inner2 AND (op2a code2 op2b)))  */
4774           else if (integer_onep (t))
4775             return boolean_true_node;
4776
4777           /* Save partial result for later.  */
4778           partial = t;
4779         }
4780       
4781       /* Compute the second partial result, (inner2 AND (op2a code op2b)) */
4782       if (TREE_CODE (inner2) == SSA_NAME
4783           && is_gimple_assign (s = SSA_NAME_DEF_STMT (inner2))
4784           && TREE_CODE_CLASS (gimple_assign_rhs_code (s)) == tcc_comparison
4785           && (t = maybe_fold_and_comparisons (gimple_assign_rhs_code (s),
4786                                               gimple_assign_rhs1 (s),
4787                                               gimple_assign_rhs2 (s),
4788                                               code2, op2a, op2b)))
4789         {
4790           /* Handle the AND case, where we are reassociating:
4791              (inner1 AND inner2) AND (op2a code2 op2b)
4792              => (inner1 AND t)  */
4793           if (is_and)
4794             {
4795               if (integer_onep (t))
4796                 return inner1;
4797               else if (integer_zerop (t))
4798                 return boolean_false_node;
4799               /* If both are the same, we can apply the identity
4800                  (x AND x) == x.  */
4801               else if (partial && same_bool_result_p (t, partial))
4802                 return t;
4803             }
4804
4805           /* Handle the OR case. where we are redistributing:
4806              (inner1 OR inner2) AND (op2a code2 op2b)
4807              => (t OR (inner1 AND (op2a code2 op2b)))
4808              => (t OR partial)  */
4809           else
4810             {
4811               if (integer_onep (t))
4812                 return boolean_true_node;
4813               else if (partial)
4814                 {
4815                   /* We already got a simplification for the other
4816                      operand to the redistributed OR expression.  The
4817                      interesting case is when at least one is false.
4818                      Or, if both are the same, we can apply the identity
4819                      (x OR x) == x.  */
4820                   if (integer_zerop (partial))
4821                     return t;
4822                   else if (integer_zerop (t))
4823                     return partial;
4824                   else if (same_bool_result_p (t, partial))
4825                     return t;
4826                 }
4827             }
4828         }
4829     }
4830   return NULL_TREE;
4831 }
4832
4833 /* Try to simplify the AND of two comparisons defined by
4834    (OP1A CODE1 OP1B) and (OP2A CODE2 OP2B), respectively.
4835    If this can be done without constructing an intermediate value,
4836    return the resulting tree; otherwise NULL_TREE is returned.
4837    This function is deliberately asymmetric as it recurses on SSA_DEFs
4838    in the first comparison but not the second.  */
4839
4840 static tree
4841 and_comparisons_1 (enum tree_code code1, tree op1a, tree op1b,
4842                    enum tree_code code2, tree op2a, tree op2b)
4843 {
4844   tree truth_type = truth_type_for (TREE_TYPE (op1a));
4845
4846   /* First check for ((x CODE1 y) AND (x CODE2 y)).  */
4847   if (operand_equal_p (op1a, op2a, 0)
4848       && operand_equal_p (op1b, op2b, 0))
4849     {
4850       /* Result will be either NULL_TREE, or a combined comparison.  */
4851       tree t = combine_comparisons (UNKNOWN_LOCATION,
4852                                     TRUTH_ANDIF_EXPR, code1, code2,
4853                                     truth_type, op1a, op1b);
4854       if (t)
4855         return t;
4856     }
4857
4858   /* Likewise the swapped case of the above.  */
4859   if (operand_equal_p (op1a, op2b, 0)
4860       && operand_equal_p (op1b, op2a, 0))
4861     {
4862       /* Result will be either NULL_TREE, or a combined comparison.  */
4863       tree t = combine_comparisons (UNKNOWN_LOCATION,
4864                                     TRUTH_ANDIF_EXPR, code1,
4865                                     swap_tree_comparison (code2),
4866                                     truth_type, op1a, op1b);
4867       if (t)
4868         return t;
4869     }
4870
4871   /* If both comparisons are of the same value against constants, we might
4872      be able to merge them.  */
4873   if (operand_equal_p (op1a, op2a, 0)
4874       && TREE_CODE (op1b) == INTEGER_CST
4875       && TREE_CODE (op2b) == INTEGER_CST)
4876     {
4877       int cmp = tree_int_cst_compare (op1b, op2b);
4878
4879       /* If we have (op1a == op1b), we should either be able to
4880          return that or FALSE, depending on whether the constant op1b
4881          also satisfies the other comparison against op2b.  */
4882       if (code1 == EQ_EXPR)
4883         {
4884           bool done = true;
4885           bool val;
4886           switch (code2)
4887             {
4888             case EQ_EXPR: val = (cmp == 0); break;
4889             case NE_EXPR: val = (cmp != 0); break;
4890             case LT_EXPR: val = (cmp < 0); break;
4891             case GT_EXPR: val = (cmp > 0); break;
4892             case LE_EXPR: val = (cmp <= 0); break;
4893             case GE_EXPR: val = (cmp >= 0); break;
4894             default: done = false;
4895             }
4896           if (done)
4897             {
4898               if (val)
4899                 return fold_build2 (code1, boolean_type_node, op1a, op1b);
4900               else
4901                 return boolean_false_node;
4902             }
4903         }
4904       /* Likewise if the second comparison is an == comparison.  */
4905       else if (code2 == EQ_EXPR)
4906         {
4907           bool done = true;
4908           bool val;
4909           switch (code1)
4910             {
4911             case EQ_EXPR: val = (cmp == 0); break;
4912             case NE_EXPR: val = (cmp != 0); break;
4913             case LT_EXPR: val = (cmp > 0); break;
4914             case GT_EXPR: val = (cmp < 0); break;
4915             case LE_EXPR: val = (cmp >= 0); break;
4916             case GE_EXPR: val = (cmp <= 0); break;
4917             default: done = false;
4918             }
4919           if (done)
4920             {
4921               if (val)
4922                 return fold_build2 (code2, boolean_type_node, op2a, op2b);
4923               else
4924                 return boolean_false_node;
4925             }
4926         }
4927
4928       /* Same business with inequality tests.  */
4929       else if (code1 == NE_EXPR)
4930         {
4931           bool val;
4932           switch (code2)
4933             {
4934             case EQ_EXPR: val = (cmp != 0); break;
4935             case NE_EXPR: val = (cmp == 0); break;
4936             case LT_EXPR: val = (cmp >= 0); break;
4937             case GT_EXPR: val = (cmp <= 0); break;
4938             case LE_EXPR: val = (cmp > 0); break;
4939             case GE_EXPR: val = (cmp < 0); break;
4940             default:
4941               val = false;
4942             }
4943           if (val)
4944             return fold_build2 (code2, boolean_type_node, op2a, op2b);
4945         }
4946       else if (code2 == NE_EXPR)
4947         {
4948           bool val;
4949           switch (code1)
4950             {
4951             case EQ_EXPR: val = (cmp == 0); break;
4952             case NE_EXPR: val = (cmp != 0); break;
4953             case LT_EXPR: val = (cmp <= 0); break;
4954             case GT_EXPR: val = (cmp >= 0); break;
4955             case LE_EXPR: val = (cmp < 0); break;
4956             case GE_EXPR: val = (cmp > 0); break;
4957             default:
4958               val = false;
4959             }
4960           if (val)
4961             return fold_build2 (code1, boolean_type_node, op1a, op1b);
4962         }
4963
4964       /* Chose the more restrictive of two < or <= comparisons.  */
4965       else if ((code1 == LT_EXPR || code1 == LE_EXPR)
4966                && (code2 == LT_EXPR || code2 == LE_EXPR))
4967         {
4968           if ((cmp < 0) || (cmp == 0 && code1 == LT_EXPR))
4969             return fold_build2 (code1, boolean_type_node, op1a, op1b);
4970           else
4971             return fold_build2 (code2, boolean_type_node, op2a, op2b);
4972         }
4973
4974       /* Likewise chose the more restrictive of two > or >= comparisons.  */
4975       else if ((code1 == GT_EXPR || code1 == GE_EXPR)
4976                && (code2 == GT_EXPR || code2 == GE_EXPR))
4977         {
4978           if ((cmp > 0) || (cmp == 0 && code1 == GT_EXPR))
4979             return fold_build2 (code1, boolean_type_node, op1a, op1b);
4980           else
4981             return fold_build2 (code2, boolean_type_node, op2a, op2b);
4982         }
4983
4984       /* Check for singleton ranges.  */
4985       else if (cmp == 0
4986                && ((code1 == LE_EXPR && code2 == GE_EXPR)
4987                    || (code1 == GE_EXPR && code2 == LE_EXPR)))
4988         return fold_build2 (EQ_EXPR, boolean_type_node, op1a, op2b);
4989
4990       /* Check for disjoint ranges. */
4991       else if (cmp <= 0
4992                && (code1 == LT_EXPR || code1 == LE_EXPR)
4993                && (code2 == GT_EXPR || code2 == GE_EXPR))
4994         return boolean_false_node;
4995       else if (cmp >= 0
4996                && (code1 == GT_EXPR || code1 == GE_EXPR)
4997                && (code2 == LT_EXPR || code2 == LE_EXPR))
4998         return boolean_false_node;
4999     }
5000
5001   /* Perhaps the first comparison is (NAME != 0) or (NAME == 1) where
5002      NAME's definition is a truth value.  See if there are any simplifications
5003      that can be done against the NAME's definition.  */
5004   if (TREE_CODE (op1a) == SSA_NAME
5005       && (code1 == NE_EXPR || code1 == EQ_EXPR)
5006       && (integer_zerop (op1b) || integer_onep (op1b)))
5007     {
5008       bool invert = ((code1 == EQ_EXPR && integer_zerop (op1b))
5009                      || (code1 == NE_EXPR && integer_onep (op1b)));
5010       gimple *stmt = SSA_NAME_DEF_STMT (op1a);
5011       switch (gimple_code (stmt))
5012         {
5013         case GIMPLE_ASSIGN:
5014           /* Try to simplify by copy-propagating the definition.  */
5015           return and_var_with_comparison (op1a, invert, code2, op2a, op2b);
5016
5017         case GIMPLE_PHI:
5018           /* If every argument to the PHI produces the same result when
5019              ANDed with the second comparison, we win.
5020              Do not do this unless the type is bool since we need a bool
5021              result here anyway.  */
5022           if (TREE_CODE (TREE_TYPE (op1a)) == BOOLEAN_TYPE)
5023             {
5024               tree result = NULL_TREE;
5025               unsigned i;
5026               for (i = 0; i < gimple_phi_num_args (stmt); i++)
5027                 {
5028                   tree arg = gimple_phi_arg_def (stmt, i);
5029                   
5030                   /* If this PHI has itself as an argument, ignore it.
5031                      If all the other args produce the same result,
5032                      we're still OK.  */
5033                   if (arg == gimple_phi_result (stmt))
5034                     continue;
5035                   else if (TREE_CODE (arg) == INTEGER_CST)
5036                     {
5037                       if (invert ? integer_nonzerop (arg) : integer_zerop (arg))
5038                         {
5039                           if (!result)
5040                             result = boolean_false_node;
5041                           else if (!integer_zerop (result))
5042                             return NULL_TREE;
5043                         }
5044                       else if (!result)
5045                         result = fold_build2 (code2, boolean_type_node,
5046                                               op2a, op2b);
5047                       else if (!same_bool_comparison_p (result,
5048                                                         code2, op2a, op2b))
5049                         return NULL_TREE;
5050                     }
5051                   else if (TREE_CODE (arg) == SSA_NAME
5052                            && !SSA_NAME_IS_DEFAULT_DEF (arg))
5053                     {
5054                       tree temp;
5055                       gimple *def_stmt = SSA_NAME_DEF_STMT (arg);
5056                       /* In simple cases we can look through PHI nodes,
5057                          but we have to be careful with loops.
5058                          See PR49073.  */
5059                       if (! dom_info_available_p (CDI_DOMINATORS)
5060                           || gimple_bb (def_stmt) == gimple_bb (stmt)
5061                           || dominated_by_p (CDI_DOMINATORS,
5062                                              gimple_bb (def_stmt),
5063                                              gimple_bb (stmt)))
5064                         return NULL_TREE;
5065                       temp = and_var_with_comparison (arg, invert, code2,
5066                                                       op2a, op2b);
5067                       if (!temp)
5068                         return NULL_TREE;
5069                       else if (!result)
5070                         result = temp;
5071                       else if (!same_bool_result_p (result, temp))
5072                         return NULL_TREE;
5073                     }
5074                   else
5075                     return NULL_TREE;
5076                 }
5077               return result;
5078             }
5079
5080         default:
5081           break;
5082         }
5083     }
5084   return NULL_TREE;
5085 }
5086
5087 /* Try to simplify the AND of two comparisons, specified by
5088    (OP1A CODE1 OP1B) and (OP2B CODE2 OP2B), respectively.
5089    If this can be simplified to a single expression (without requiring
5090    introducing more SSA variables to hold intermediate values),
5091    return the resulting tree.  Otherwise return NULL_TREE.
5092    If the result expression is non-null, it has boolean type.  */
5093
5094 tree
5095 maybe_fold_and_comparisons (enum tree_code code1, tree op1a, tree op1b,
5096                             enum tree_code code2, tree op2a, tree op2b)
5097 {
5098   tree t = and_comparisons_1 (code1, op1a, op1b, code2, op2a, op2b);
5099   if (t)
5100     return t;
5101   else
5102     return and_comparisons_1 (code2, op2a, op2b, code1, op1a, op1b);
5103 }
5104
5105 /* Helper function for or_comparisons_1:  try to simplify the OR of the
5106    ssa variable VAR with the comparison specified by (OP2A CODE2 OP2B).
5107    If INVERT is true, invert the value of VAR before doing the OR.
5108    Return NULL_EXPR if we can't simplify this to a single expression.  */
5109
5110 static tree
5111 or_var_with_comparison (tree var, bool invert,
5112                         enum tree_code code2, tree op2a, tree op2b)
5113 {
5114   tree t;
5115   gimple *stmt = SSA_NAME_DEF_STMT (var);
5116
5117   /* We can only deal with variables whose definitions are assignments.  */
5118   if (!is_gimple_assign (stmt))
5119     return NULL_TREE;
5120   
5121   /* If we have an inverted comparison, apply DeMorgan's law and rewrite
5122      !var OR (op2a code2 op2b) => !(var AND !(op2a code2 op2b))
5123      Then we only have to consider the simpler non-inverted cases.  */
5124   if (invert)
5125     t = and_var_with_comparison_1 (stmt, 
5126                                    invert_tree_comparison (code2, false),
5127                                    op2a, op2b);
5128   else
5129     t = or_var_with_comparison_1 (stmt, code2, op2a, op2b);
5130   return canonicalize_bool (t, invert);
5131 }
5132
5133 /* Try to simplify the OR of the ssa variable defined by the assignment
5134    STMT with the comparison specified by (OP2A CODE2 OP2B).
5135    Return NULL_EXPR if we can't simplify this to a single expression.  */
5136
5137 static tree
5138 or_var_with_comparison_1 (gimple *stmt,
5139                           enum tree_code code2, tree op2a, tree op2b)
5140 {
5141   tree var = gimple_assign_lhs (stmt);
5142   tree true_test_var = NULL_TREE;
5143   tree false_test_var = NULL_TREE;
5144   enum tree_code innercode = gimple_assign_rhs_code (stmt);
5145
5146   /* Check for identities like (var OR (var != 0)) => true .  */
5147   if (TREE_CODE (op2a) == SSA_NAME
5148       && TREE_CODE (TREE_TYPE (var)) == BOOLEAN_TYPE)
5149     {
5150       if ((code2 == NE_EXPR && integer_zerop (op2b))
5151           || (code2 == EQ_EXPR && integer_nonzerop (op2b)))
5152         {
5153           true_test_var = op2a;
5154           if (var == true_test_var)
5155             return var;
5156         }
5157       else if ((code2 == EQ_EXPR && integer_zerop (op2b))
5158                || (code2 == NE_EXPR && integer_nonzerop (op2b)))
5159         {
5160           false_test_var = op2a;
5161           if (var == false_test_var)
5162             return boolean_true_node;
5163         }
5164     }
5165
5166   /* If the definition is a comparison, recurse on it.  */
5167   if (TREE_CODE_CLASS (innercode) == tcc_comparison)
5168     {
5169       tree t = or_comparisons_1 (innercode,
5170                                  gimple_assign_rhs1 (stmt),
5171                                  gimple_assign_rhs2 (stmt),
5172                                  code2,
5173                                  op2a,
5174                                  op2b);
5175       if (t)
5176         return t;
5177     }
5178   
5179   /* If the definition is an AND or OR expression, we may be able to
5180      simplify by reassociating.  */
5181   if (TREE_CODE (TREE_TYPE (var)) == BOOLEAN_TYPE
5182       && (innercode == BIT_AND_EXPR || innercode == BIT_IOR_EXPR))
5183     {
5184       tree inner1 = gimple_assign_rhs1 (stmt);
5185       tree inner2 = gimple_assign_rhs2 (stmt);
5186       gimple *s;
5187       tree t;
5188       tree partial = NULL_TREE;
5189       bool is_or = (innercode == BIT_IOR_EXPR);
5190       
5191       /* Check for boolean identities that don't require recursive examination
5192          of inner1/inner2:
5193          inner1 OR (inner1 OR inner2) => inner1 OR inner2 => var
5194          inner1 OR (inner1 AND inner2) => inner1
5195          !inner1 OR (inner1 OR inner2) => true
5196          !inner1 OR (inner1 AND inner2) => !inner1 OR inner2
5197       */
5198       if (inner1 == true_test_var)
5199         return (is_or ? var : inner1);
5200       else if (inner2 == true_test_var)
5201         return (is_or ? var : inner2);
5202       else if (inner1 == false_test_var)
5203         return (is_or
5204                 ? boolean_true_node
5205                 : or_var_with_comparison (inner2, false, code2, op2a, op2b));
5206       else if (inner2 == false_test_var)
5207         return (is_or
5208                 ? boolean_true_node
5209                 : or_var_with_comparison (inner1, false, code2, op2a, op2b));
5210       
5211       /* Next, redistribute/reassociate the OR across the inner tests.
5212          Compute the first partial result, (inner1 OR (op2a code op2b))  */
5213       if (TREE_CODE (inner1) == SSA_NAME
5214           && is_gimple_assign (s = SSA_NAME_DEF_STMT (inner1))
5215           && TREE_CODE_CLASS (gimple_assign_rhs_code (s)) == tcc_comparison
5216           && (t = maybe_fold_or_comparisons (gimple_assign_rhs_code (s),
5217                                              gimple_assign_rhs1 (s),
5218                                              gimple_assign_rhs2 (s),
5219                                              code2, op2a, op2b)))
5220         {
5221           /* Handle the OR case, where we are reassociating:
5222              (inner1 OR inner2) OR (op2a code2 op2b)
5223              => (t OR inner2)
5224              If the partial result t is a constant, we win.  Otherwise
5225              continue on to try reassociating with the other inner test.  */
5226           if (is_or)
5227             {
5228               if (integer_onep (t))
5229                 return boolean_true_node;
5230               else if (integer_zerop (t))
5231                 return inner2;
5232             }
5233           
5234           /* Handle the AND case, where we are redistributing:
5235              (inner1 AND inner2) OR (op2a code2 op2b)
5236              => (t AND (inner2 OR (op2a code op2b)))  */
5237           else if (integer_zerop (t))
5238             return boolean_false_node;
5239
5240           /* Save partial result for later.  */
5241           partial = t;
5242         }
5243       
5244       /* Compute the second partial result, (inner2 OR (op2a code op2b)) */
5245       if (TREE_CODE (inner2) == SSA_NAME
5246           && is_gimple_assign (s = SSA_NAME_DEF_STMT (inner2))
5247           && TREE_CODE_CLASS (gimple_assign_rhs_code (s)) == tcc_comparison
5248           && (t = maybe_fold_or_comparisons (gimple_assign_rhs_code (s),
5249                                              gimple_assign_rhs1 (s),
5250                                              gimple_assign_rhs2 (s),
5251                                              code2, op2a, op2b)))
5252         {
5253           /* Handle the OR case, where we are reassociating:
5254              (inner1 OR inner2) OR (op2a code2 op2b)
5255              => (inner1 OR t)
5256              => (t OR partial)  */
5257           if (is_or)
5258             {
5259               if (integer_zerop (t))
5260                 return inner1;
5261               else if (integer_onep (t))
5262                 return boolean_true_node;
5263               /* If both are the same, we can apply the identity
5264                  (x OR x) == x.  */
5265               else if (partial && same_bool_result_p (t, partial))
5266                 return t;
5267             }
5268           
5269           /* Handle the AND case, where we are redistributing:
5270              (inner1 AND inner2) OR (op2a code2 op2b)
5271              => (t AND (inner1 OR (op2a code2 op2b)))
5272              => (t AND partial)  */
5273           else 
5274             {
5275               if (integer_zerop (t))
5276                 return boolean_false_node;
5277               else if (partial)
5278                 {
5279                   /* We already got a simplification for the other
5280                      operand to the redistributed AND expression.  The
5281                      interesting case is when at least one is true.
5282                      Or, if both are the same, we can apply the identity
5283                      (x AND x) == x.  */
5284                   if (integer_onep (partial))
5285                     return t;
5286                   else if (integer_onep (t))
5287                     return partial;
5288                   else if (same_bool_result_p (t, partial))
5289                     return t;
5290                 }
5291             }
5292         }
5293     }
5294   return NULL_TREE;
5295 }
5296
5297 /* Try to simplify the OR of two comparisons defined by
5298    (OP1A CODE1 OP1B) and (OP2A CODE2 OP2B), respectively.
5299    If this can be done without constructing an intermediate value,
5300    return the resulting tree; otherwise NULL_TREE is returned.
5301    This function is deliberately asymmetric as it recurses on SSA_DEFs
5302    in the first comparison but not the second.  */
5303
5304 static tree
5305 or_comparisons_1 (enum tree_code code1, tree op1a, tree op1b,
5306                   enum tree_code code2, tree op2a, tree op2b)
5307 {
5308   tree truth_type = truth_type_for (TREE_TYPE (op1a));
5309
5310   /* First check for ((x CODE1 y) OR (x CODE2 y)).  */
5311   if (operand_equal_p (op1a, op2a, 0)
5312       && operand_equal_p (op1b, op2b, 0))
5313     {
5314       /* Result will be either NULL_TREE, or a combined comparison.  */
5315       tree t = combine_comparisons (UNKNOWN_LOCATION,
5316                                     TRUTH_ORIF_EXPR, code1, code2,
5317                                     truth_type, op1a, op1b);
5318       if (t)
5319         return t;
5320     }
5321
5322   /* Likewise the swapped case of the above.  */
5323   if (operand_equal_p (op1a, op2b, 0)
5324       && operand_equal_p (op1b, op2a, 0))
5325     {
5326       /* Result will be either NULL_TREE, or a combined comparison.  */
5327       tree t = combine_comparisons (UNKNOWN_LOCATION,
5328                                     TRUTH_ORIF_EXPR, code1,
5329                                     swap_tree_comparison (code2),
5330                                     truth_type, op1a, op1b);
5331       if (t)
5332         return t;
5333     }
5334
5335   /* If both comparisons are of the same value against constants, we might
5336      be able to merge them.  */
5337   if (operand_equal_p (op1a, op2a, 0)
5338       && TREE_CODE (op1b) == INTEGER_CST
5339       && TREE_CODE (op2b) == INTEGER_CST)
5340     {
5341       int cmp = tree_int_cst_compare (op1b, op2b);
5342
5343       /* If we have (op1a != op1b), we should either be able to
5344          return that or TRUE, depending on whether the constant op1b
5345          also satisfies the other comparison against op2b.  */
5346       if (code1 == NE_EXPR)
5347         {
5348           bool done = true;
5349           bool val;
5350           switch (code2)
5351             {
5352             case EQ_EXPR: val = (cmp == 0); break;
5353             case NE_EXPR: val = (cmp != 0); break;
5354             case LT_EXPR: val = (cmp < 0); break;
5355             case GT_EXPR: val = (cmp > 0); break;
5356             case LE_EXPR: val = (cmp <= 0); break;
5357             case GE_EXPR: val = (cmp >= 0); break;
5358             default: done = false;
5359             }
5360           if (done)
5361             {
5362               if (val)
5363                 return boolean_true_node;
5364               else
5365                 return fold_build2 (code1, boolean_type_node, op1a, op1b);
5366             }
5367         }
5368       /* Likewise if the second comparison is a != comparison.  */
5369       else if (code2 == NE_EXPR)
5370         {
5371           bool done = true;
5372           bool val;
5373           switch (code1)
5374             {
5375             case EQ_EXPR: val = (cmp == 0); break;
5376             case NE_EXPR: val = (cmp != 0); break;
5377             case LT_EXPR: val = (cmp > 0); break;
5378             case GT_EXPR: val = (cmp < 0); break;
5379             case LE_EXPR: val = (cmp >= 0); break;
5380             case GE_EXPR: val = (cmp <= 0); break;
5381             default: done = false;
5382             }
5383           if (done)
5384             {
5385               if (val)
5386                 return boolean_true_node;
5387               else
5388                 return fold_build2 (code2, boolean_type_node, op2a, op2b);
5389             }
5390         }
5391
5392       /* See if an equality test is redundant with the other comparison.  */
5393       else if (code1 == EQ_EXPR)
5394         {
5395           bool val;
5396           switch (code2)
5397             {
5398             case EQ_EXPR: val = (cmp == 0); break;
5399             case NE_EXPR: val = (cmp != 0); break;
5400             case LT_EXPR: val = (cmp < 0); break;
5401             case GT_EXPR: val = (cmp > 0); break;
5402             case LE_EXPR: val = (cmp <= 0); break;
5403             case GE_EXPR: val = (cmp >= 0); break;
5404             default:
5405               val = false;
5406             }
5407           if (val)
5408             return fold_build2 (code2, boolean_type_node, op2a, op2b);
5409         }
5410       else if (code2 == EQ_EXPR)
5411         {
5412           bool val;
5413           switch (code1)
5414             {
5415             case EQ_EXPR: val = (cmp == 0); break;
5416             case NE_EXPR: val = (cmp != 0); break;
5417             case LT_EXPR: val = (cmp > 0); break;
5418             case GT_EXPR: val = (cmp < 0); break;
5419             case LE_EXPR: val = (cmp >= 0); break;
5420             case GE_EXPR: val = (cmp <= 0); break;
5421             default:
5422               val = false;
5423             }
5424           if (val)
5425             return fold_build2 (code1, boolean_type_node, op1a, op1b);
5426         }
5427
5428       /* Chose the less restrictive of two < or <= comparisons.  */
5429       else if ((code1 == LT_EXPR || code1 == LE_EXPR)
5430                && (code2 == LT_EXPR || code2 == LE_EXPR))
5431         {
5432           if ((cmp < 0) || (cmp == 0 && code1 == LT_EXPR))
5433             return fold_build2 (code2, boolean_type_node, op2a, op2b);
5434           else
5435             return fold_build2 (code1, boolean_type_node, op1a, op1b);
5436         }
5437
5438       /* Likewise chose the less restrictive of two > or >= comparisons.  */
5439       else if ((code1 == GT_EXPR || code1 == GE_EXPR)
5440                && (code2 == GT_EXPR || code2 == GE_EXPR))
5441         {
5442           if ((cmp > 0) || (cmp == 0 && code1 == GT_EXPR))
5443             return fold_build2 (code2, boolean_type_node, op2a, op2b);
5444           else
5445             return fold_build2 (code1, boolean_type_node, op1a, op1b);
5446         }
5447
5448       /* Check for singleton ranges.  */
5449       else if (cmp == 0
5450                && ((code1 == LT_EXPR && code2 == GT_EXPR)
5451                    || (code1 == GT_EXPR && code2 == LT_EXPR)))
5452         return fold_build2 (NE_EXPR, boolean_type_node, op1a, op2b);
5453
5454       /* Check for less/greater pairs that don't restrict the range at all.  */
5455       else if (cmp >= 0
5456                && (code1 == LT_EXPR || code1 == LE_EXPR)
5457                && (code2 == GT_EXPR || code2 == GE_EXPR))
5458         return boolean_true_node;
5459       else if (cmp <= 0
5460                && (code1 == GT_EXPR || code1 == GE_EXPR)
5461                && (code2 == LT_EXPR || code2 == LE_EXPR))
5462         return boolean_true_node;
5463     }
5464
5465   /* Perhaps the first comparison is (NAME != 0) or (NAME == 1) where
5466      NAME's definition is a truth value.  See if there are any simplifications
5467      that can be done against the NAME's definition.  */
5468   if (TREE_CODE (op1a) == SSA_NAME
5469       && (code1 == NE_EXPR || code1 == EQ_EXPR)
5470       && (integer_zerop (op1b) || integer_onep (op1b)))
5471     {
5472       bool invert = ((code1 == EQ_EXPR && integer_zerop (op1b))
5473                      || (code1 == NE_EXPR && integer_onep (op1b)));
5474       gimple *stmt = SSA_NAME_DEF_STMT (op1a);
5475       switch (gimple_code (stmt))
5476         {
5477         case GIMPLE_ASSIGN:
5478           /* Try to simplify by copy-propagating the definition.  */
5479           return or_var_with_comparison (op1a, invert, code2, op2a, op2b);
5480
5481         case GIMPLE_PHI:
5482           /* If every argument to the PHI produces the same result when
5483              ORed with the second comparison, we win.
5484              Do not do this unless the type is bool since we need a bool
5485              result here anyway.  */
5486           if (TREE_CODE (TREE_TYPE (op1a)) == BOOLEAN_TYPE)
5487             {
5488               tree result = NULL_TREE;
5489               unsigned i;
5490               for (i = 0; i < gimple_phi_num_args (stmt); i++)
5491                 {
5492                   tree arg = gimple_phi_arg_def (stmt, i);
5493                   
5494                   /* If this PHI has itself as an argument, ignore it.
5495                      If all the other args produce the same result,
5496                      we're still OK.  */
5497                   if (arg == gimple_phi_result (stmt))
5498                     continue;
5499                   else if (TREE_CODE (arg) == INTEGER_CST)
5500                     {
5501                       if (invert ? integer_zerop (arg) : integer_nonzerop (arg))
5502                         {
5503                           if (!result)
5504                             result = boolean_true_node;
5505                           else if (!integer_onep (result))
5506                             return NULL_TREE;
5507                         }
5508                       else if (!result)
5509                         result = fold_build2 (code2, boolean_type_node,
5510                                               op2a, op2b);
5511                       else if (!same_bool_comparison_p (result,
5512                                                         code2, op2a, op2b))
5513                         return NULL_TREE;
5514                     }
5515                   else if (TREE_CODE (arg) == SSA_NAME
5516                            && !SSA_NAME_IS_DEFAULT_DEF (arg))
5517                     {
5518                       tree temp;
5519                       gimple *def_stmt = SSA_NAME_DEF_STMT (arg);
5520                       /* In simple cases we can look through PHI nodes,
5521                          but we have to be careful with loops.
5522                          See PR49073.  */
5523                       if (! dom_info_available_p (CDI_DOMINATORS)
5524                           || gimple_bb (def_stmt) == gimple_bb (stmt)
5525                           || dominated_by_p (CDI_DOMINATORS,
5526                                              gimple_bb (def_stmt),
5527                                              gimple_bb (stmt)))
5528                         return NULL_TREE;
5529                       temp = or_var_with_comparison (arg, invert, code2,
5530                                                      op2a, op2b);
5531                       if (!temp)
5532                         return NULL_TREE;
5533                       else if (!result)
5534                         result = temp;
5535                       else if (!same_bool_result_p (result, temp))
5536                         return NULL_TREE;
5537                     }
5538                   else
5539                     return NULL_TREE;
5540                 }
5541               return result;
5542             }
5543
5544         default:
5545           break;
5546         }
5547     }
5548   return NULL_TREE;
5549 }
5550
5551 /* Try to simplify the OR of two comparisons, specified by
5552    (OP1A CODE1 OP1B) and (OP2B CODE2 OP2B), respectively.
5553    If this can be simplified to a single expression (without requiring
5554    introducing more SSA variables to hold intermediate values),
5555    return the resulting tree.  Otherwise return NULL_TREE.
5556    If the result expression is non-null, it has boolean type.  */
5557
5558 tree
5559 maybe_fold_or_comparisons (enum tree_code code1, tree op1a, tree op1b,
5560                            enum tree_code code2, tree op2a, tree op2b)
5561 {
5562   tree t = or_comparisons_1 (code1, op1a, op1b, code2, op2a, op2b);
5563   if (t)
5564     return t;
5565   else
5566     return or_comparisons_1 (code2, op2a, op2b, code1, op1a, op1b);
5567 }
5568
5569
5570 /* Fold STMT to a constant using VALUEIZE to valueize SSA names.
5571
5572    Either NULL_TREE, a simplified but non-constant or a constant
5573    is returned.
5574
5575    ???  This should go into a gimple-fold-inline.h file to be eventually
5576    privatized with the single valueize function used in the various TUs
5577    to avoid the indirect function call overhead.  */
5578
5579 tree
5580 gimple_fold_stmt_to_constant_1 (gimple *stmt, tree (*valueize) (tree),
5581                                 tree (*gvalueize) (tree))
5582 {
5583   code_helper rcode;
5584   tree ops[3] = {};
5585   /* ???  The SSA propagators do not correctly deal with following SSA use-def
5586      edges if there are intermediate VARYING defs.  For this reason
5587      do not follow SSA edges here even though SCCVN can technically
5588      just deal fine with that.  */
5589   if (gimple_simplify (stmt, &rcode, ops, NULL, gvalueize, valueize))
5590     {
5591       tree res = NULL_TREE;
5592       if (gimple_simplified_result_is_gimple_val (rcode, ops))
5593         res = ops[0];
5594       else if (mprts_hook)
5595         res = mprts_hook (rcode, gimple_expr_type (stmt), ops);
5596       if (res)
5597         {
5598           if (dump_file && dump_flags & TDF_DETAILS)
5599             {
5600               fprintf (dump_file, "Match-and-simplified ");
5601               print_gimple_expr (dump_file, stmt, 0, TDF_SLIM);
5602               fprintf (dump_file, " to ");
5603               print_generic_expr (dump_file, res, 0);
5604               fprintf (dump_file, "\n");
5605             }
5606           return res;
5607         }
5608     }
5609
5610   location_t loc = gimple_location (stmt);
5611   switch (gimple_code (stmt))
5612     {
5613     case GIMPLE_ASSIGN:
5614       {
5615         enum tree_code subcode = gimple_assign_rhs_code (stmt);
5616
5617         switch (get_gimple_rhs_class (subcode))
5618           {
5619           case GIMPLE_SINGLE_RHS:
5620             {
5621               tree rhs = gimple_assign_rhs1 (stmt);
5622               enum tree_code_class kind = TREE_CODE_CLASS (subcode);
5623
5624               if (TREE_CODE (rhs) == SSA_NAME)
5625                 {
5626                   /* If the RHS is an SSA_NAME, return its known constant value,
5627                      if any.  */
5628                   return (*valueize) (rhs);
5629                 }
5630               /* Handle propagating invariant addresses into address
5631                  operations.  */
5632               else if (TREE_CODE (rhs) == ADDR_EXPR
5633                        && !is_gimple_min_invariant (rhs))
5634                 {
5635                   HOST_WIDE_INT offset = 0;
5636                   tree base;
5637                   base = get_addr_base_and_unit_offset_1 (TREE_OPERAND (rhs, 0),
5638                                                           &offset,
5639                                                           valueize);
5640                   if (base
5641                       && (CONSTANT_CLASS_P (base)
5642                           || decl_address_invariant_p (base)))
5643                     return build_invariant_address (TREE_TYPE (rhs),
5644                                                     base, offset);
5645                 }
5646               else if (TREE_CODE (rhs) == CONSTRUCTOR
5647                        && TREE_CODE (TREE_TYPE (rhs)) == VECTOR_TYPE
5648                        && (CONSTRUCTOR_NELTS (rhs)
5649                            == TYPE_VECTOR_SUBPARTS (TREE_TYPE (rhs))))
5650                 {
5651                   unsigned i;
5652                   tree val, *vec;
5653
5654                   vec = XALLOCAVEC (tree,
5655                                     TYPE_VECTOR_SUBPARTS (TREE_TYPE (rhs)));
5656                   FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (rhs), i, val)
5657                     {
5658                       val = (*valueize) (val);
5659                       if (TREE_CODE (val) == INTEGER_CST
5660                           || TREE_CODE (val) == REAL_CST
5661                           || TREE_CODE (val) == FIXED_CST)
5662                         vec[i] = val;
5663                       else
5664                         return NULL_TREE;
5665                     }
5666
5667                   return build_vector (TREE_TYPE (rhs), vec);
5668                 }
5669               if (subcode == OBJ_TYPE_REF)
5670                 {
5671                   tree val = (*valueize) (OBJ_TYPE_REF_EXPR (rhs));
5672                   /* If callee is constant, we can fold away the wrapper.  */
5673                   if (is_gimple_min_invariant (val))
5674                     return val;
5675                 }
5676
5677               if (kind == tcc_reference)
5678                 {
5679                   if ((TREE_CODE (rhs) == VIEW_CONVERT_EXPR
5680                        || TREE_CODE (rhs) == REALPART_EXPR
5681                        || TREE_CODE (rhs) == IMAGPART_EXPR)
5682                       && TREE_CODE (TREE_OPERAND (rhs, 0)) == SSA_NAME)
5683                     {
5684                       tree val = (*valueize) (TREE_OPERAND (rhs, 0));
5685                       return fold_unary_loc (EXPR_LOCATION (rhs),
5686                                              TREE_CODE (rhs),
5687                                              TREE_TYPE (rhs), val);
5688                     }
5689                   else if (TREE_CODE (rhs) == BIT_FIELD_REF
5690                            && TREE_CODE (TREE_OPERAND (rhs, 0)) == SSA_NAME)
5691                     {
5692                       tree val = (*valueize) (TREE_OPERAND (rhs, 0));
5693                       return fold_ternary_loc (EXPR_LOCATION (rhs),
5694                                                TREE_CODE (rhs),
5695                                                TREE_TYPE (rhs), val,
5696                                                TREE_OPERAND (rhs, 1),
5697                                                TREE_OPERAND (rhs, 2));
5698                     }
5699                   else if (TREE_CODE (rhs) == MEM_REF
5700                            && TREE_CODE (TREE_OPERAND (rhs, 0)) == SSA_NAME)
5701                     {
5702                       tree val = (*valueize) (TREE_OPERAND (rhs, 0));
5703                       if (TREE_CODE (val) == ADDR_EXPR
5704                           && is_gimple_min_invariant (val))
5705                         {
5706                           tree tem = fold_build2 (MEM_REF, TREE_TYPE (rhs),
5707                                                   unshare_expr (val),
5708                                                   TREE_OPERAND (rhs, 1));
5709                           if (tem)
5710                             rhs = tem;
5711                         }
5712                     }
5713                   return fold_const_aggregate_ref_1 (rhs, valueize);
5714                 }
5715               else if (kind == tcc_declaration)
5716                 return get_symbol_constant_value (rhs);
5717               return rhs;
5718             }
5719
5720           case GIMPLE_UNARY_RHS:
5721             return NULL_TREE;
5722
5723           case GIMPLE_BINARY_RHS:
5724             /* Translate &x + CST into an invariant form suitable for
5725                further propagation.  */
5726             if (subcode == POINTER_PLUS_EXPR)
5727               {
5728                 tree op0 = (*valueize) (gimple_assign_rhs1 (stmt));
5729                 tree op1 = (*valueize) (gimple_assign_rhs2 (stmt));
5730                 if (TREE_CODE (op0) == ADDR_EXPR
5731                     && TREE_CODE (op1) == INTEGER_CST)
5732                   {
5733                     tree off = fold_convert (ptr_type_node, op1);
5734                     return build_fold_addr_expr_loc
5735                         (loc,
5736                          fold_build2 (MEM_REF,
5737                                       TREE_TYPE (TREE_TYPE (op0)),
5738                                       unshare_expr (op0), off));
5739                   }
5740               }
5741             /* Canonicalize bool != 0 and bool == 0 appearing after
5742                valueization.  While gimple_simplify handles this
5743                it can get confused by the ~X == 1 -> X == 0 transform
5744                which we cant reduce to a SSA name or a constant
5745                (and we have no way to tell gimple_simplify to not
5746                consider those transforms in the first place).  */
5747             else if (subcode == EQ_EXPR
5748                      || subcode == NE_EXPR)
5749               {
5750                 tree lhs = gimple_assign_lhs (stmt);
5751                 tree op0 = gimple_assign_rhs1 (stmt);
5752                 if (useless_type_conversion_p (TREE_TYPE (lhs),
5753                                                TREE_TYPE (op0)))
5754                   {
5755                     tree op1 = (*valueize) (gimple_assign_rhs2 (stmt));
5756                     op0 = (*valueize) (op0);
5757                     if (TREE_CODE (op0) == INTEGER_CST)
5758                       std::swap (op0, op1);
5759                     if (TREE_CODE (op1) == INTEGER_CST
5760                         && ((subcode == NE_EXPR && integer_zerop (op1))
5761                             || (subcode == EQ_EXPR && integer_onep (op1))))
5762                       return op0;
5763                   }
5764               }
5765             return NULL_TREE;
5766
5767           case GIMPLE_TERNARY_RHS:
5768             {
5769               /* Handle ternary operators that can appear in GIMPLE form.  */
5770               tree op0 = (*valueize) (gimple_assign_rhs1 (stmt));
5771               tree op1 = (*valueize) (gimple_assign_rhs2 (stmt));
5772               tree op2 = (*valueize) (gimple_assign_rhs3 (stmt));
5773               return fold_ternary_loc (loc, subcode,
5774                                        gimple_expr_type (stmt), op0, op1, op2);
5775             }
5776
5777           default:
5778             gcc_unreachable ();
5779           }
5780       }
5781
5782     case GIMPLE_CALL:
5783       {
5784         tree fn;
5785         gcall *call_stmt = as_a <gcall *> (stmt);
5786
5787         if (gimple_call_internal_p (stmt))
5788           {
5789             enum tree_code subcode = ERROR_MARK;
5790             switch (gimple_call_internal_fn (stmt))
5791               {
5792               case IFN_UBSAN_CHECK_ADD:
5793                 subcode = PLUS_EXPR;
5794                 break;
5795               case IFN_UBSAN_CHECK_SUB:
5796                 subcode = MINUS_EXPR;
5797                 break;
5798               case IFN_UBSAN_CHECK_MUL:
5799                 subcode = MULT_EXPR;
5800                 break;
5801               case IFN_BUILTIN_EXPECT:
5802                   {
5803                     tree arg0 = gimple_call_arg (stmt, 0);
5804                     tree op0 = (*valueize) (arg0);
5805                     if (TREE_CODE (op0) == INTEGER_CST)
5806                       return op0;
5807                     return NULL_TREE;
5808                   }
5809               default:
5810                 return NULL_TREE;
5811               }
5812             tree arg0 = gimple_call_arg (stmt, 0);
5813             tree arg1 = gimple_call_arg (stmt, 1);
5814             tree op0 = (*valueize) (arg0);
5815             tree op1 = (*valueize) (arg1);
5816
5817             if (TREE_CODE (op0) != INTEGER_CST
5818                 || TREE_CODE (op1) != INTEGER_CST)
5819               {
5820                 switch (subcode)
5821                   {
5822                   case MULT_EXPR:
5823                     /* x * 0 = 0 * x = 0 without overflow.  */
5824                     if (integer_zerop (op0) || integer_zerop (op1))
5825                       return build_zero_cst (TREE_TYPE (arg0));
5826                     break;
5827                   case MINUS_EXPR:
5828                     /* y - y = 0 without overflow.  */
5829                     if (operand_equal_p (op0, op1, 0))
5830                       return build_zero_cst (TREE_TYPE (arg0));
5831                     break;
5832                   default:
5833                     break;
5834                   }
5835               }
5836             tree res
5837               = fold_binary_loc (loc, subcode, TREE_TYPE (arg0), op0, op1);
5838             if (res
5839                 && TREE_CODE (res) == INTEGER_CST
5840                 && !TREE_OVERFLOW (res))
5841               return res;
5842             return NULL_TREE;
5843           }
5844
5845         fn = (*valueize) (gimple_call_fn (stmt));
5846         if (TREE_CODE (fn) == ADDR_EXPR
5847             && TREE_CODE (TREE_OPERAND (fn, 0)) == FUNCTION_DECL
5848             && DECL_BUILT_IN (TREE_OPERAND (fn, 0))
5849             && gimple_builtin_call_types_compatible_p (stmt,
5850                                                        TREE_OPERAND (fn, 0)))
5851           {
5852             tree *args = XALLOCAVEC (tree, gimple_call_num_args (stmt));
5853             tree retval;
5854             unsigned i;
5855             for (i = 0; i < gimple_call_num_args (stmt); ++i)
5856               args[i] = (*valueize) (gimple_call_arg (stmt, i));
5857             retval = fold_builtin_call_array (loc,
5858                                          gimple_call_return_type (call_stmt),
5859                                          fn, gimple_call_num_args (stmt), args);
5860             if (retval)
5861               {
5862                 /* fold_call_expr wraps the result inside a NOP_EXPR.  */
5863                 STRIP_NOPS (retval);
5864                 retval = fold_convert (gimple_call_return_type (call_stmt),
5865                                        retval);
5866               }
5867             return retval;
5868           }
5869         return NULL_TREE;
5870       }
5871
5872     default:
5873       return NULL_TREE;
5874     }
5875 }
5876
5877 /* Fold STMT to a constant using VALUEIZE to valueize SSA names.
5878    Returns NULL_TREE if folding to a constant is not possible, otherwise
5879    returns a constant according to is_gimple_min_invariant.  */
5880
5881 tree
5882 gimple_fold_stmt_to_constant (gimple *stmt, tree (*valueize) (tree))
5883 {
5884   tree res = gimple_fold_stmt_to_constant_1 (stmt, valueize);
5885   if (res && is_gimple_min_invariant (res))
5886     return res;
5887   return NULL_TREE;
5888 }
5889
5890
5891 /* The following set of functions are supposed to fold references using
5892    their constant initializers.  */
5893
5894 /* See if we can find constructor defining value of BASE.
5895    When we know the consructor with constant offset (such as
5896    base is array[40] and we do know constructor of array), then
5897    BIT_OFFSET is adjusted accordingly.
5898
5899    As a special case, return error_mark_node when constructor
5900    is not explicitly available, but it is known to be zero
5901    such as 'static const int a;'.  */
5902 static tree
5903 get_base_constructor (tree base, HOST_WIDE_INT *bit_offset,
5904                       tree (*valueize)(tree))
5905 {
5906   HOST_WIDE_INT bit_offset2, size, max_size;
5907   bool reverse;
5908
5909   if (TREE_CODE (base) == MEM_REF)
5910     {
5911       if (!integer_zerop (TREE_OPERAND (base, 1)))
5912         {
5913           if (!tree_fits_shwi_p (TREE_OPERAND (base, 1)))
5914             return NULL_TREE;
5915           *bit_offset += (mem_ref_offset (base).to_short_addr ()
5916                           * BITS_PER_UNIT);
5917         }
5918
5919       if (valueize
5920           && TREE_CODE (TREE_OPERAND (base, 0)) == SSA_NAME)
5921         base = valueize (TREE_OPERAND (base, 0));
5922       if (!base || TREE_CODE (base) != ADDR_EXPR)
5923         return NULL_TREE;
5924       base = TREE_OPERAND (base, 0);
5925     }
5926   else if (valueize
5927            && TREE_CODE (base) == SSA_NAME)
5928     base = valueize (base);
5929
5930   /* Get a CONSTRUCTOR.  If BASE is a VAR_DECL, get its
5931      DECL_INITIAL.  If BASE is a nested reference into another
5932      ARRAY_REF or COMPONENT_REF, make a recursive call to resolve
5933      the inner reference.  */
5934   switch (TREE_CODE (base))
5935     {
5936     case VAR_DECL:
5937     case CONST_DECL:
5938       {
5939         tree init = ctor_for_folding (base);
5940
5941         /* Our semantic is exact opposite of ctor_for_folding;
5942            NULL means unknown, while error_mark_node is 0.  */
5943         if (init == error_mark_node)
5944           return NULL_TREE;
5945         if (!init)
5946           return error_mark_node;
5947         return init;
5948       }
5949
5950     case VIEW_CONVERT_EXPR:
5951       return get_base_constructor (TREE_OPERAND (base, 0),
5952                                    bit_offset, valueize);
5953
5954     case ARRAY_REF:
5955     case COMPONENT_REF:
5956       base = get_ref_base_and_extent (base, &bit_offset2, &size, &max_size,
5957                                       &reverse);
5958       if (max_size == -1 || size != max_size)
5959         return NULL_TREE;
5960       *bit_offset +=  bit_offset2;
5961       return get_base_constructor (base, bit_offset, valueize);
5962
5963     case CONSTRUCTOR:
5964       return base;
5965
5966     default:
5967       if (CONSTANT_CLASS_P (base))
5968         return base;
5969
5970       return NULL_TREE;
5971     }
5972 }
5973
5974 /* CTOR is CONSTRUCTOR of an array type.  Fold reference of type TYPE and size
5975    SIZE to the memory at bit OFFSET.  */
5976
5977 static tree
5978 fold_array_ctor_reference (tree type, tree ctor,
5979                            unsigned HOST_WIDE_INT offset,
5980                            unsigned HOST_WIDE_INT size,
5981                            tree from_decl)
5982 {
5983   offset_int low_bound;
5984   offset_int elt_size;
5985   offset_int access_index;
5986   tree domain_type = NULL_TREE;
5987   HOST_WIDE_INT inner_offset;
5988
5989   /* Compute low bound and elt size.  */
5990   if (TREE_CODE (TREE_TYPE (ctor)) == ARRAY_TYPE)
5991     domain_type = TYPE_DOMAIN (TREE_TYPE (ctor));
5992   if (domain_type && TYPE_MIN_VALUE (domain_type))
5993     {
5994       /* Static constructors for variably sized objects makes no sense.  */
5995       if (TREE_CODE (TYPE_MIN_VALUE (domain_type)) != INTEGER_CST)
5996         return NULL_TREE;
5997       low_bound = wi::to_offset (TYPE_MIN_VALUE (domain_type));
5998     }
5999   else
6000     low_bound = 0;
6001   /* Static constructors for variably sized objects makes no sense.  */
6002   if (TREE_CODE (TYPE_SIZE_UNIT (TREE_TYPE (TREE_TYPE (ctor)))) != INTEGER_CST)
6003     return NULL_TREE;
6004   elt_size = wi::to_offset (TYPE_SIZE_UNIT (TREE_TYPE (TREE_TYPE (ctor))));
6005
6006   /* We can handle only constantly sized accesses that are known to not
6007      be larger than size of array element.  */
6008   if (!TYPE_SIZE_UNIT (type)
6009       || TREE_CODE (TYPE_SIZE_UNIT (type)) != INTEGER_CST
6010       || elt_size < wi::to_offset (TYPE_SIZE_UNIT (type))
6011       || elt_size == 0)
6012     return NULL_TREE;
6013
6014   /* Compute the array index we look for.  */
6015   access_index = wi::udiv_trunc (offset_int (offset / BITS_PER_UNIT),
6016                                  elt_size);
6017   access_index += low_bound;
6018
6019   /* And offset within the access.  */
6020   inner_offset = offset % (elt_size.to_uhwi () * BITS_PER_UNIT);
6021
6022   /* See if the array field is large enough to span whole access.  We do not
6023      care to fold accesses spanning multiple array indexes.  */
6024   if (inner_offset + size > elt_size.to_uhwi () * BITS_PER_UNIT)
6025     return NULL_TREE;
6026   if (tree val = get_array_ctor_element_at_index (ctor, access_index))
6027     return fold_ctor_reference (type, val, inner_offset, size, from_decl);
6028
6029   /* When memory is not explicitely mentioned in constructor,
6030      it is 0 (or out of range).  */
6031   return build_zero_cst (type);
6032 }
6033
6034 /* CTOR is CONSTRUCTOR of an aggregate or vector.
6035    Fold reference of type TYPE and size SIZE to the memory at bit OFFSET.  */
6036
6037 static tree
6038 fold_nonarray_ctor_reference (tree type, tree ctor,
6039                               unsigned HOST_WIDE_INT offset,
6040                               unsigned HOST_WIDE_INT size,
6041                               tree from_decl)
6042 {
6043   unsigned HOST_WIDE_INT cnt;
6044   tree cfield, cval;
6045
6046   FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (ctor), cnt, cfield,
6047                             cval)
6048     {
6049       tree byte_offset = DECL_FIELD_OFFSET (cfield);
6050       tree field_offset = DECL_FIELD_BIT_OFFSET (cfield);
6051       tree field_size = DECL_SIZE (cfield);
6052       offset_int bitoffset;
6053       offset_int bitoffset_end, access_end;
6054
6055       /* Variable sized objects in static constructors makes no sense,
6056          but field_size can be NULL for flexible array members.  */
6057       gcc_assert (TREE_CODE (field_offset) == INTEGER_CST
6058                   && TREE_CODE (byte_offset) == INTEGER_CST
6059                   && (field_size != NULL_TREE
6060                       ? TREE_CODE (field_size) == INTEGER_CST
6061                       : TREE_CODE (TREE_TYPE (cfield)) == ARRAY_TYPE));
6062
6063       /* Compute bit offset of the field.  */
6064       bitoffset = (wi::to_offset (field_offset)
6065                    + (wi::to_offset (byte_offset) << LOG2_BITS_PER_UNIT));
6066       /* Compute bit offset where the field ends.  */
6067       if (field_size != NULL_TREE)
6068         bitoffset_end = bitoffset + wi::to_offset (field_size);
6069       else
6070         bitoffset_end = 0;
6071
6072       access_end = offset_int (offset) + size;
6073
6074       /* Is there any overlap between [OFFSET, OFFSET+SIZE) and
6075          [BITOFFSET, BITOFFSET_END)?  */
6076       if (wi::cmps (access_end, bitoffset) > 0
6077           && (field_size == NULL_TREE
6078               || wi::lts_p (offset, bitoffset_end)))
6079         {
6080           offset_int inner_offset = offset_int (offset) - bitoffset;
6081           /* We do have overlap.  Now see if field is large enough to
6082              cover the access.  Give up for accesses spanning multiple
6083              fields.  */
6084           if (wi::cmps (access_end, bitoffset_end) > 0)
6085             return NULL_TREE;
6086           if (offset < bitoffset)
6087             return NULL_TREE;
6088           return fold_ctor_reference (type, cval,
6089                                       inner_offset.to_uhwi (), size,
6090                                       from_decl);
6091         }
6092     }
6093   /* When memory is not explicitely mentioned in constructor, it is 0.  */
6094   return build_zero_cst (type);
6095 }
6096
6097 /* CTOR is value initializing memory, fold reference of type TYPE and size SIZE
6098    to the memory at bit OFFSET.  */
6099
6100 tree
6101 fold_ctor_reference (tree type, tree ctor, unsigned HOST_WIDE_INT offset,
6102                      unsigned HOST_WIDE_INT size, tree from_decl)
6103 {
6104   tree ret;
6105
6106   /* We found the field with exact match.  */
6107   if (useless_type_conversion_p (type, TREE_TYPE (ctor))
6108       && !offset)
6109     return canonicalize_constructor_val (unshare_expr (ctor), from_decl);
6110
6111   /* We are at the end of walk, see if we can view convert the
6112      result.  */
6113   if (!AGGREGATE_TYPE_P (TREE_TYPE (ctor)) && !offset
6114       /* VIEW_CONVERT_EXPR is defined only for matching sizes.  */
6115       && !compare_tree_int (TYPE_SIZE (type), size)
6116       && !compare_tree_int (TYPE_SIZE (TREE_TYPE (ctor)), size))
6117     {
6118       ret = canonicalize_constructor_val (unshare_expr (ctor), from_decl);
6119       ret = fold_unary (VIEW_CONVERT_EXPR, type, ret);
6120       if (ret)
6121         STRIP_USELESS_TYPE_CONVERSION (ret);
6122       return ret;
6123     }
6124   /* For constants and byte-aligned/sized reads try to go through
6125      native_encode/interpret.  */
6126   if (CONSTANT_CLASS_P (ctor)
6127       && BITS_PER_UNIT == 8
6128       && offset % BITS_PER_UNIT == 0
6129       && size % BITS_PER_UNIT == 0
6130       && size <= MAX_BITSIZE_MODE_ANY_MODE)
6131     {
6132       unsigned char buf[MAX_BITSIZE_MODE_ANY_MODE / BITS_PER_UNIT];
6133       int len = native_encode_expr (ctor, buf, size / BITS_PER_UNIT,
6134                                     offset / BITS_PER_UNIT);
6135       if (len > 0)
6136         return native_interpret_expr (type, buf, len);
6137     }
6138   if (TREE_CODE (ctor) == CONSTRUCTOR)
6139     {
6140
6141       if (TREE_CODE (TREE_TYPE (ctor)) == ARRAY_TYPE
6142           || TREE_CODE (TREE_TYPE (ctor)) == VECTOR_TYPE)
6143         return fold_array_ctor_reference (type, ctor, offset, size,
6144                                           from_decl);
6145       else
6146         return fold_nonarray_ctor_reference (type, ctor, offset, size,
6147                                              from_decl);
6148     }
6149
6150   return NULL_TREE;
6151 }
6152
6153 /* Return the tree representing the element referenced by T if T is an
6154    ARRAY_REF or COMPONENT_REF into constant aggregates valuezing SSA
6155    names using VALUEIZE.  Return NULL_TREE otherwise.  */
6156
6157 tree
6158 fold_const_aggregate_ref_1 (tree t, tree (*valueize) (tree))
6159 {
6160   tree ctor, idx, base;
6161   HOST_WIDE_INT offset, size, max_size;
6162   tree tem;
6163   bool reverse;
6164
6165   if (TREE_THIS_VOLATILE (t))
6166     return NULL_TREE;
6167
6168   if (DECL_P (t))
6169     return get_symbol_constant_value (t);
6170
6171   tem = fold_read_from_constant_string (t);
6172   if (tem)
6173     return tem;
6174
6175   switch (TREE_CODE (t))
6176     {
6177     case ARRAY_REF:
6178     case ARRAY_RANGE_REF:
6179       /* Constant indexes are handled well by get_base_constructor.
6180          Only special case variable offsets.
6181          FIXME: This code can't handle nested references with variable indexes
6182          (they will be handled only by iteration of ccp).  Perhaps we can bring
6183          get_ref_base_and_extent here and make it use a valueize callback.  */
6184       if (TREE_CODE (TREE_OPERAND (t, 1)) == SSA_NAME
6185           && valueize
6186           && (idx = (*valueize) (TREE_OPERAND (t, 1)))
6187           && TREE_CODE (idx) == INTEGER_CST)
6188         {
6189           tree low_bound, unit_size;
6190
6191           /* If the resulting bit-offset is constant, track it.  */
6192           if ((low_bound = array_ref_low_bound (t),
6193                TREE_CODE (low_bound) == INTEGER_CST)
6194               && (unit_size = array_ref_element_size (t),
6195                   tree_fits_uhwi_p (unit_size)))
6196             {
6197               offset_int woffset
6198                 = wi::sext (wi::to_offset (idx) - wi::to_offset (low_bound),
6199                             TYPE_PRECISION (TREE_TYPE (idx)));
6200
6201               if (wi::fits_shwi_p (woffset))
6202                 {
6203                   offset = woffset.to_shwi ();
6204                   /* TODO: This code seems wrong, multiply then check
6205                      to see if it fits.  */
6206                   offset *= tree_to_uhwi (unit_size);
6207                   offset *= BITS_PER_UNIT;
6208
6209                   base = TREE_OPERAND (t, 0);
6210                   ctor = get_base_constructor (base, &offset, valueize);
6211                   /* Empty constructor.  Always fold to 0.  */
6212                   if (ctor == error_mark_node)
6213                     return build_zero_cst (TREE_TYPE (t));
6214                   /* Out of bound array access.  Value is undefined,
6215                      but don't fold.  */
6216                   if (offset < 0)
6217                     return NULL_TREE;
6218                   /* We can not determine ctor.  */
6219                   if (!ctor)
6220                     return NULL_TREE;
6221                   return fold_ctor_reference (TREE_TYPE (t), ctor, offset,
6222                                               tree_to_uhwi (unit_size)
6223                                               * BITS_PER_UNIT,
6224                                               base);
6225                 }
6226             }
6227         }
6228       /* Fallthru.  */
6229
6230     case COMPONENT_REF:
6231     case BIT_FIELD_REF:
6232     case TARGET_MEM_REF:
6233     case MEM_REF:
6234       base = get_ref_base_and_extent (t, &offset, &size, &max_size, &reverse);
6235       ctor = get_base_constructor (base, &offset, valueize);
6236
6237       /* Empty constructor.  Always fold to 0.  */
6238       if (ctor == error_mark_node)
6239         return build_zero_cst (TREE_TYPE (t));
6240       /* We do not know precise address.  */
6241       if (max_size == -1 || max_size != size)
6242         return NULL_TREE;
6243       /* We can not determine ctor.  */
6244       if (!ctor)
6245         return NULL_TREE;
6246
6247       /* Out of bound array access.  Value is undefined, but don't fold.  */
6248       if (offset < 0)
6249         return NULL_TREE;
6250
6251       return fold_ctor_reference (TREE_TYPE (t), ctor, offset, size,
6252                                   base);
6253
6254     case REALPART_EXPR:
6255     case IMAGPART_EXPR:
6256       {
6257         tree c = fold_const_aggregate_ref_1 (TREE_OPERAND (t, 0), valueize);
6258         if (c && TREE_CODE (c) == COMPLEX_CST)
6259           return fold_build1_loc (EXPR_LOCATION (t),
6260                               TREE_CODE (t), TREE_TYPE (t), c);
6261         break;
6262       }
6263
6264     default:
6265       break;
6266     }
6267
6268   return NULL_TREE;
6269 }
6270
6271 tree
6272 fold_const_aggregate_ref (tree t)
6273 {
6274   return fold_const_aggregate_ref_1 (t, NULL);
6275 }
6276
6277 /* Lookup virtual method with index TOKEN in a virtual table V
6278    at OFFSET.  
6279    Set CAN_REFER if non-NULL to false if method
6280    is not referable or if the virtual table is ill-formed (such as rewriten
6281    by non-C++ produced symbol). Otherwise just return NULL in that calse.  */
6282
6283 tree
6284 gimple_get_virt_method_for_vtable (HOST_WIDE_INT token,
6285                                    tree v,
6286                                    unsigned HOST_WIDE_INT offset,
6287                                    bool *can_refer)
6288 {
6289   tree vtable = v, init, fn;
6290   unsigned HOST_WIDE_INT size;
6291   unsigned HOST_WIDE_INT elt_size, access_index;
6292   tree domain_type;
6293
6294   if (can_refer)
6295     *can_refer = true;
6296
6297   /* First of all double check we have virtual table.  */
6298   if (!VAR_P (v) || !DECL_VIRTUAL_P (v))
6299     {
6300       /* Pass down that we lost track of the target.  */
6301       if (can_refer)
6302         *can_refer = false;
6303       return NULL_TREE;
6304     }
6305
6306   init = ctor_for_folding (v);
6307
6308   /* The virtual tables should always be born with constructors
6309      and we always should assume that they are avaialble for
6310      folding.  At the moment we do not stream them in all cases,
6311      but it should never happen that ctor seem unreachable.  */
6312   gcc_assert (init);
6313   if (init == error_mark_node)
6314     {
6315       gcc_assert (in_lto_p);
6316       /* Pass down that we lost track of the target.  */
6317       if (can_refer)
6318         *can_refer = false;
6319       return NULL_TREE;
6320     }
6321   gcc_checking_assert (TREE_CODE (TREE_TYPE (v)) == ARRAY_TYPE);
6322   size = tree_to_uhwi (TYPE_SIZE (TREE_TYPE (TREE_TYPE (v))));
6323   offset *= BITS_PER_UNIT;
6324   offset += token * size;
6325
6326   /* Lookup the value in the constructor that is assumed to be array.
6327      This is equivalent to
6328      fn = fold_ctor_reference (TREE_TYPE (TREE_TYPE (v)), init,
6329                                offset, size, NULL);
6330      but in a constant time.  We expect that frontend produced a simple
6331      array without indexed initializers.  */
6332
6333   gcc_checking_assert (TREE_CODE (TREE_TYPE (init)) == ARRAY_TYPE);
6334   domain_type = TYPE_DOMAIN (TREE_TYPE (init));
6335   gcc_checking_assert (integer_zerop (TYPE_MIN_VALUE (domain_type)));
6336   elt_size = tree_to_uhwi (TYPE_SIZE_UNIT (TREE_TYPE (TREE_TYPE (init))));
6337
6338   access_index = offset / BITS_PER_UNIT / elt_size;
6339   gcc_checking_assert (offset % (elt_size * BITS_PER_UNIT) == 0);
6340
6341   /* This code makes an assumption that there are no 
6342      indexed fileds produced by C++ FE, so we can directly index the array. */
6343   if (access_index < CONSTRUCTOR_NELTS (init))
6344     {
6345       fn = CONSTRUCTOR_ELT (init, access_index)->value;
6346       gcc_checking_assert (!CONSTRUCTOR_ELT (init, access_index)->index);
6347       STRIP_NOPS (fn);
6348     }
6349   else
6350     fn = NULL;
6351
6352   /* For type inconsistent program we may end up looking up virtual method
6353      in virtual table that does not contain TOKEN entries.  We may overrun
6354      the virtual table and pick up a constant or RTTI info pointer.
6355      In any case the call is undefined.  */
6356   if (!fn
6357       || (TREE_CODE (fn) != ADDR_EXPR && TREE_CODE (fn) != FDESC_EXPR)
6358       || TREE_CODE (TREE_OPERAND (fn, 0)) != FUNCTION_DECL)
6359     fn = builtin_decl_implicit (BUILT_IN_UNREACHABLE);
6360   else
6361     {
6362       fn = TREE_OPERAND (fn, 0);
6363
6364       /* When cgraph node is missing and function is not public, we cannot
6365          devirtualize.  This can happen in WHOPR when the actual method
6366          ends up in other partition, because we found devirtualization
6367          possibility too late.  */
6368       if (!can_refer_decl_in_current_unit_p (fn, vtable))
6369         {
6370           if (can_refer)
6371             {
6372               *can_refer = false;
6373               return fn;
6374             }
6375           return NULL_TREE;
6376         }
6377     }
6378
6379   /* Make sure we create a cgraph node for functions we'll reference.
6380      They can be non-existent if the reference comes from an entry
6381      of an external vtable for example.  */
6382   cgraph_node::get_create (fn);
6383
6384   return fn;
6385 }
6386
6387 /* Return a declaration of a function which an OBJ_TYPE_REF references. TOKEN
6388    is integer form of OBJ_TYPE_REF_TOKEN of the reference expression.
6389    KNOWN_BINFO carries the binfo describing the true type of
6390    OBJ_TYPE_REF_OBJECT(REF).
6391    Set CAN_REFER if non-NULL to false if method
6392    is not referable or if the virtual table is ill-formed (such as rewriten
6393    by non-C++ produced symbol). Otherwise just return NULL in that calse.  */
6394
6395 tree
6396 gimple_get_virt_method_for_binfo (HOST_WIDE_INT token, tree known_binfo,
6397                                   bool *can_refer)
6398 {
6399   unsigned HOST_WIDE_INT offset;
6400   tree v;
6401
6402   v = BINFO_VTABLE (known_binfo);
6403   /* If there is no virtual methods table, leave the OBJ_TYPE_REF alone.  */
6404   if (!v)
6405     return NULL_TREE;
6406
6407   if (!vtable_pointer_value_to_vtable (v, &v, &offset))
6408     {
6409       if (can_refer)
6410         *can_refer = false;
6411       return NULL_TREE;
6412     }
6413   return gimple_get_virt_method_for_vtable (token, v, offset, can_refer);
6414 }
6415
6416 /* Given a pointer value OP0, return a simplified version of an
6417    indirection through OP0, or NULL_TREE if no simplification is
6418    possible.  Note that the resulting type may be different from
6419    the type pointed to in the sense that it is still compatible
6420    from the langhooks point of view. */
6421
6422 tree
6423 gimple_fold_indirect_ref (tree t)
6424 {
6425   tree ptype = TREE_TYPE (t), type = TREE_TYPE (ptype);
6426   tree sub = t;
6427   tree subtype;
6428
6429   STRIP_NOPS (sub);
6430   subtype = TREE_TYPE (sub);
6431   if (!POINTER_TYPE_P (subtype))
6432     return NULL_TREE;
6433
6434   if (TREE_CODE (sub) == ADDR_EXPR)
6435     {
6436       tree op = TREE_OPERAND (sub, 0);
6437       tree optype = TREE_TYPE (op);
6438       /* *&p => p */
6439       if (useless_type_conversion_p (type, optype))
6440         return op;
6441
6442       /* *(foo *)&fooarray => fooarray[0] */
6443       if (TREE_CODE (optype) == ARRAY_TYPE
6444           && TREE_CODE (TYPE_SIZE (TREE_TYPE (optype))) == INTEGER_CST
6445           && useless_type_conversion_p (type, TREE_TYPE (optype)))
6446        {
6447          tree type_domain = TYPE_DOMAIN (optype);
6448          tree min_val = size_zero_node;
6449          if (type_domain && TYPE_MIN_VALUE (type_domain))
6450            min_val = TYPE_MIN_VALUE (type_domain);
6451          if (TREE_CODE (min_val) == INTEGER_CST)
6452            return build4 (ARRAY_REF, type, op, min_val, NULL_TREE, NULL_TREE);
6453        }
6454       /* *(foo *)&complexfoo => __real__ complexfoo */
6455       else if (TREE_CODE (optype) == COMPLEX_TYPE
6456                && useless_type_conversion_p (type, TREE_TYPE (optype)))
6457         return fold_build1 (REALPART_EXPR, type, op);
6458       /* *(foo *)&vectorfoo => BIT_FIELD_REF<vectorfoo,...> */
6459       else if (TREE_CODE (optype) == VECTOR_TYPE
6460                && useless_type_conversion_p (type, TREE_TYPE (optype)))
6461         {
6462           tree part_width = TYPE_SIZE (type);
6463           tree index = bitsize_int (0);
6464           return fold_build3 (BIT_FIELD_REF, type, op, part_width, index);
6465         }
6466     }
6467
6468   /* *(p + CST) -> ...  */
6469   if (TREE_CODE (sub) == POINTER_PLUS_EXPR
6470       && TREE_CODE (TREE_OPERAND (sub, 1)) == INTEGER_CST)
6471     {
6472       tree addr = TREE_OPERAND (sub, 0);
6473       tree off = TREE_OPERAND (sub, 1);
6474       tree addrtype;
6475
6476       STRIP_NOPS (addr);
6477       addrtype = TREE_TYPE (addr);
6478
6479       /* ((foo*)&vectorfoo)[1] -> BIT_FIELD_REF<vectorfoo,...> */
6480       if (TREE_CODE (addr) == ADDR_EXPR
6481           && TREE_CODE (TREE_TYPE (addrtype)) == VECTOR_TYPE
6482           && useless_type_conversion_p (type, TREE_TYPE (TREE_TYPE (addrtype)))
6483           && tree_fits_uhwi_p (off))
6484         {
6485           unsigned HOST_WIDE_INT offset = tree_to_uhwi (off);
6486           tree part_width = TYPE_SIZE (type);
6487           unsigned HOST_WIDE_INT part_widthi
6488             = tree_to_shwi (part_width) / BITS_PER_UNIT;
6489           unsigned HOST_WIDE_INT indexi = offset * BITS_PER_UNIT;
6490           tree index = bitsize_int (indexi);
6491           if (offset / part_widthi
6492               < TYPE_VECTOR_SUBPARTS (TREE_TYPE (addrtype)))
6493             return fold_build3 (BIT_FIELD_REF, type, TREE_OPERAND (addr, 0),
6494                                 part_width, index);
6495         }
6496
6497       /* ((foo*)&complexfoo)[1] -> __imag__ complexfoo */
6498       if (TREE_CODE (addr) == ADDR_EXPR
6499           && TREE_CODE (TREE_TYPE (addrtype)) == COMPLEX_TYPE
6500           && useless_type_conversion_p (type, TREE_TYPE (TREE_TYPE (addrtype))))
6501         {
6502           tree size = TYPE_SIZE_UNIT (type);
6503           if (tree_int_cst_equal (size, off))
6504             return fold_build1 (IMAGPART_EXPR, type, TREE_OPERAND (addr, 0));
6505         }
6506
6507       /* *(p + CST) -> MEM_REF <p, CST>.  */
6508       if (TREE_CODE (addr) != ADDR_EXPR
6509           || DECL_P (TREE_OPERAND (addr, 0)))
6510         return fold_build2 (MEM_REF, type,
6511                             addr,
6512                             wide_int_to_tree (ptype, off));
6513     }
6514
6515   /* *(foo *)fooarrptr => (*fooarrptr)[0] */
6516   if (TREE_CODE (TREE_TYPE (subtype)) == ARRAY_TYPE
6517       && TREE_CODE (TYPE_SIZE (TREE_TYPE (TREE_TYPE (subtype)))) == INTEGER_CST
6518       && useless_type_conversion_p (type, TREE_TYPE (TREE_TYPE (subtype))))
6519     {
6520       tree type_domain;
6521       tree min_val = size_zero_node;
6522       tree osub = sub;
6523       sub = gimple_fold_indirect_ref (sub);
6524       if (! sub)
6525         sub = build1 (INDIRECT_REF, TREE_TYPE (subtype), osub);
6526       type_domain = TYPE_DOMAIN (TREE_TYPE (sub));
6527       if (type_domain && TYPE_MIN_VALUE (type_domain))
6528         min_val = TYPE_MIN_VALUE (type_domain);
6529       if (TREE_CODE (min_val) == INTEGER_CST)
6530         return build4 (ARRAY_REF, type, sub, min_val, NULL_TREE, NULL_TREE);
6531     }
6532
6533   return NULL_TREE;
6534 }
6535
6536 /* Return true if CODE is an operation that when operating on signed
6537    integer types involves undefined behavior on overflow and the
6538    operation can be expressed with unsigned arithmetic.  */
6539
6540 bool
6541 arith_code_with_undefined_signed_overflow (tree_code code)
6542 {
6543   switch (code)
6544     {
6545     case PLUS_EXPR:
6546     case MINUS_EXPR:
6547     case MULT_EXPR:
6548     case NEGATE_EXPR:
6549     case POINTER_PLUS_EXPR:
6550       return true;
6551     default:
6552       return false;
6553     }
6554 }
6555
6556 /* Rewrite STMT, an assignment with a signed integer or pointer arithmetic
6557    operation that can be transformed to unsigned arithmetic by converting
6558    its operand, carrying out the operation in the corresponding unsigned
6559    type and converting the result back to the original type.
6560
6561    Returns a sequence of statements that replace STMT and also contain
6562    a modified form of STMT itself.  */
6563
6564 gimple_seq
6565 rewrite_to_defined_overflow (gimple *stmt)
6566 {
6567   if (dump_file && (dump_flags & TDF_DETAILS))
6568     {
6569       fprintf (dump_file, "rewriting stmt with undefined signed "
6570                "overflow ");
6571       print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
6572     }
6573
6574   tree lhs = gimple_assign_lhs (stmt);
6575   tree type = unsigned_type_for (TREE_TYPE (lhs));
6576   gimple_seq stmts = NULL;
6577   for (unsigned i = 1; i < gimple_num_ops (stmt); ++i)
6578     {
6579       tree op = gimple_op (stmt, i);
6580       op = gimple_convert (&stmts, type, op);
6581       gimple_set_op (stmt, i, op);
6582     }
6583   gimple_assign_set_lhs (stmt, make_ssa_name (type, stmt));
6584   if (gimple_assign_rhs_code (stmt) == POINTER_PLUS_EXPR)
6585     gimple_assign_set_rhs_code (stmt, PLUS_EXPR);
6586   gimple_seq_add_stmt (&stmts, stmt);
6587   gimple *cvt = gimple_build_assign (lhs, NOP_EXPR, gimple_assign_lhs (stmt));
6588   gimple_seq_add_stmt (&stmts, cvt);
6589
6590   return stmts;
6591 }
6592
6593
6594 /* The valueization hook we use for the gimple_build API simplification.
6595    This makes us match fold_buildN behavior by only combining with
6596    statements in the sequence(s) we are currently building.  */
6597
6598 static tree
6599 gimple_build_valueize (tree op)
6600 {
6601   if (gimple_bb (SSA_NAME_DEF_STMT (op)) == NULL)
6602     return op;
6603   return NULL_TREE;
6604 }
6605
6606 /* Build the expression CODE OP0 of type TYPE with location LOC,
6607    simplifying it first if possible.  Returns the built
6608    expression value and appends statements possibly defining it
6609    to SEQ.  */
6610
6611 tree
6612 gimple_build (gimple_seq *seq, location_t loc,
6613               enum tree_code code, tree type, tree op0)
6614 {
6615   tree res = gimple_simplify (code, type, op0, seq, gimple_build_valueize);
6616   if (!res)
6617     {
6618       res = create_tmp_reg_or_ssa_name (type);
6619       gimple *stmt;
6620       if (code == REALPART_EXPR
6621           || code == IMAGPART_EXPR
6622           || code == VIEW_CONVERT_EXPR)
6623         stmt = gimple_build_assign (res, code, build1 (code, type, op0));
6624       else
6625         stmt = gimple_build_assign (res, code, op0);
6626       gimple_set_location (stmt, loc);
6627       gimple_seq_add_stmt_without_update (seq, stmt);
6628     }
6629   return res;
6630 }
6631
6632 /* Build the expression OP0 CODE OP1 of type TYPE with location LOC,
6633    simplifying it first if possible.  Returns the built
6634    expression value and appends statements possibly defining it
6635    to SEQ.  */
6636
6637 tree
6638 gimple_build (gimple_seq *seq, location_t loc,
6639               enum tree_code code, tree type, tree op0, tree op1)
6640 {
6641   tree res = gimple_simplify (code, type, op0, op1, seq, gimple_build_valueize);
6642   if (!res)
6643     {
6644       res = create_tmp_reg_or_ssa_name (type);
6645       gimple *stmt = gimple_build_assign (res, code, op0, op1);
6646       gimple_set_location (stmt, loc);
6647       gimple_seq_add_stmt_without_update (seq, stmt);
6648     }
6649   return res;
6650 }
6651
6652 /* Build the expression (CODE OP0 OP1 OP2) of type TYPE with location LOC,
6653    simplifying it first if possible.  Returns the built
6654    expression value and appends statements possibly defining it
6655    to SEQ.  */
6656
6657 tree
6658 gimple_build (gimple_seq *seq, location_t loc,
6659               enum tree_code code, tree type, tree op0, tree op1, tree op2)
6660 {
6661   tree res = gimple_simplify (code, type, op0, op1, op2,
6662                               seq, gimple_build_valueize);
6663   if (!res)
6664     {
6665       res = create_tmp_reg_or_ssa_name (type);
6666       gimple *stmt;
6667       if (code == BIT_FIELD_REF)
6668         stmt = gimple_build_assign (res, code,
6669                                     build3 (code, type, op0, op1, op2));
6670       else
6671         stmt = gimple_build_assign (res, code, op0, op1, op2);
6672       gimple_set_location (stmt, loc);
6673       gimple_seq_add_stmt_without_update (seq, stmt);
6674     }
6675   return res;
6676 }
6677
6678 /* Build the call FN (ARG0) with a result of type TYPE
6679    (or no result if TYPE is void) with location LOC,
6680    simplifying it first if possible.  Returns the built
6681    expression value (or NULL_TREE if TYPE is void) and appends
6682    statements possibly defining it to SEQ.  */
6683
6684 tree
6685 gimple_build (gimple_seq *seq, location_t loc,
6686               enum built_in_function fn, tree type, tree arg0)
6687 {
6688   tree res = gimple_simplify (fn, type, arg0, seq, gimple_build_valueize);
6689   if (!res)
6690     {
6691       tree decl = builtin_decl_implicit (fn);
6692       gimple *stmt = gimple_build_call (decl, 1, arg0);
6693       if (!VOID_TYPE_P (type))
6694         {
6695           res = create_tmp_reg_or_ssa_name (type);
6696           gimple_call_set_lhs (stmt, res);
6697         }
6698       gimple_set_location (stmt, loc);
6699       gimple_seq_add_stmt_without_update (seq, stmt);
6700     }
6701   return res;
6702 }
6703
6704 /* Build the call FN (ARG0, ARG1) with a result of type TYPE
6705    (or no result if TYPE is void) with location LOC,
6706    simplifying it first if possible.  Returns the built
6707    expression value (or NULL_TREE if TYPE is void) and appends
6708    statements possibly defining it to SEQ.  */
6709
6710 tree
6711 gimple_build (gimple_seq *seq, location_t loc,
6712               enum built_in_function fn, tree type, tree arg0, tree arg1)
6713 {
6714   tree res = gimple_simplify (fn, type, arg0, arg1, seq, gimple_build_valueize);
6715   if (!res)
6716     {
6717       tree decl = builtin_decl_implicit (fn);
6718       gimple *stmt = gimple_build_call (decl, 2, arg0, arg1);
6719       if (!VOID_TYPE_P (type))
6720         {
6721           res = create_tmp_reg_or_ssa_name (type);
6722           gimple_call_set_lhs (stmt, res);
6723         }
6724       gimple_set_location (stmt, loc);
6725       gimple_seq_add_stmt_without_update (seq, stmt);
6726     }
6727   return res;
6728 }
6729
6730 /* Build the call FN (ARG0, ARG1, ARG2) with a result of type TYPE
6731    (or no result if TYPE is void) with location LOC,
6732    simplifying it first if possible.  Returns the built
6733    expression value (or NULL_TREE if TYPE is void) and appends
6734    statements possibly defining it to SEQ.  */
6735
6736 tree
6737 gimple_build (gimple_seq *seq, location_t loc,
6738               enum built_in_function fn, tree type,
6739               tree arg0, tree arg1, tree arg2)
6740 {
6741   tree res = gimple_simplify (fn, type, arg0, arg1, arg2,
6742                               seq, gimple_build_valueize);
6743   if (!res)
6744     {
6745       tree decl = builtin_decl_implicit (fn);
6746       gimple *stmt = gimple_build_call (decl, 3, arg0, arg1, arg2);
6747       if (!VOID_TYPE_P (type))
6748         {
6749           res = create_tmp_reg_or_ssa_name (type);
6750           gimple_call_set_lhs (stmt, res);
6751         }
6752       gimple_set_location (stmt, loc);
6753       gimple_seq_add_stmt_without_update (seq, stmt);
6754     }
6755   return res;
6756 }
6757
6758 /* Build the conversion (TYPE) OP with a result of type TYPE
6759    with location LOC if such conversion is neccesary in GIMPLE,
6760    simplifying it first.
6761    Returns the built expression value and appends
6762    statements possibly defining it to SEQ.  */
6763
6764 tree
6765 gimple_convert (gimple_seq *seq, location_t loc, tree type, tree op)
6766 {
6767   if (useless_type_conversion_p (type, TREE_TYPE (op)))
6768     return op;
6769   return gimple_build (seq, loc, NOP_EXPR, type, op);
6770 }
6771
6772 /* Build the conversion (ptrofftype) OP with a result of a type
6773    compatible with ptrofftype with location LOC if such conversion
6774    is neccesary in GIMPLE, simplifying it first.
6775    Returns the built expression value and appends
6776    statements possibly defining it to SEQ.  */
6777
6778 tree
6779 gimple_convert_to_ptrofftype (gimple_seq *seq, location_t loc, tree op)
6780 {
6781   if (ptrofftype_p (TREE_TYPE (op)))
6782     return op;
6783   return gimple_convert (seq, loc, sizetype, op);
6784 }
6785
6786 /* Return true if the result of assignment STMT is known to be non-negative.
6787    If the return value is based on the assumption that signed overflow is
6788    undefined, set *STRICT_OVERFLOW_P to true; otherwise, don't change
6789    *STRICT_OVERFLOW_P.  DEPTH is the current nesting depth of the query.  */
6790
6791 static bool
6792 gimple_assign_nonnegative_warnv_p (gimple *stmt, bool *strict_overflow_p,
6793                                    int depth)
6794 {
6795   enum tree_code code = gimple_assign_rhs_code (stmt);
6796   switch (get_gimple_rhs_class (code))
6797     {
6798     case GIMPLE_UNARY_RHS:
6799       return tree_unary_nonnegative_warnv_p (gimple_assign_rhs_code (stmt),
6800                                              gimple_expr_type (stmt),
6801                                              gimple_assign_rhs1 (stmt),
6802                                              strict_overflow_p, depth);
6803     case GIMPLE_BINARY_RHS:
6804       return tree_binary_nonnegative_warnv_p (gimple_assign_rhs_code (stmt),
6805                                               gimple_expr_type (stmt),
6806                                               gimple_assign_rhs1 (stmt),
6807                                               gimple_assign_rhs2 (stmt),
6808                                               strict_overflow_p, depth);
6809     case GIMPLE_TERNARY_RHS:
6810       return false;
6811     case GIMPLE_SINGLE_RHS:
6812       return tree_single_nonnegative_warnv_p (gimple_assign_rhs1 (stmt),
6813                                               strict_overflow_p, depth);
6814     case GIMPLE_INVALID_RHS:
6815       break;
6816     }
6817   gcc_unreachable ();
6818 }
6819
6820 /* Return true if return value of call STMT is known to be non-negative.
6821    If the return value is based on the assumption that signed overflow is
6822    undefined, set *STRICT_OVERFLOW_P to true; otherwise, don't change
6823    *STRICT_OVERFLOW_P.  DEPTH is the current nesting depth of the query.  */
6824
6825 static bool
6826 gimple_call_nonnegative_warnv_p (gimple *stmt, bool *strict_overflow_p,
6827                                  int depth)
6828 {
6829   tree arg0 = gimple_call_num_args (stmt) > 0 ?
6830     gimple_call_arg (stmt, 0) : NULL_TREE;
6831   tree arg1 = gimple_call_num_args (stmt) > 1 ?
6832     gimple_call_arg (stmt, 1) : NULL_TREE;
6833
6834   return tree_call_nonnegative_warnv_p (gimple_expr_type (stmt),
6835                                         gimple_call_combined_fn (stmt),
6836                                         arg0,
6837                                         arg1,
6838                                         strict_overflow_p, depth);
6839 }
6840
6841 /* Return true if return value of call STMT is known to be non-negative.
6842    If the return value is based on the assumption that signed overflow is
6843    undefined, set *STRICT_OVERFLOW_P to true; otherwise, don't change
6844    *STRICT_OVERFLOW_P.  DEPTH is the current nesting depth of the query.  */
6845
6846 static bool
6847 gimple_phi_nonnegative_warnv_p (gimple *stmt, bool *strict_overflow_p,
6848                                 int depth)
6849 {
6850   for (unsigned i = 0; i < gimple_phi_num_args (stmt); ++i)
6851     {
6852       tree arg = gimple_phi_arg_def (stmt, i);
6853       if (!tree_single_nonnegative_warnv_p (arg, strict_overflow_p, depth + 1))
6854         return false;
6855     }
6856   return true;
6857 }
6858
6859 /* Return true if STMT is known to compute a non-negative value.
6860    If the return value is based on the assumption that signed overflow is
6861    undefined, set *STRICT_OVERFLOW_P to true; otherwise, don't change
6862    *STRICT_OVERFLOW_P.  DEPTH is the current nesting depth of the query.  */
6863
6864 bool
6865 gimple_stmt_nonnegative_warnv_p (gimple *stmt, bool *strict_overflow_p,
6866                                  int depth)
6867 {
6868   switch (gimple_code (stmt))
6869     {
6870     case GIMPLE_ASSIGN:
6871       return gimple_assign_nonnegative_warnv_p (stmt, strict_overflow_p,
6872                                                 depth);
6873     case GIMPLE_CALL:
6874       return gimple_call_nonnegative_warnv_p (stmt, strict_overflow_p,
6875                                               depth);
6876     case GIMPLE_PHI:
6877       return gimple_phi_nonnegative_warnv_p (stmt, strict_overflow_p,
6878                                              depth);
6879     default:
6880       return false;
6881     }
6882 }
6883
6884 /* Return true if the floating-point value computed by assignment STMT
6885    is known to have an integer value.  We also allow +Inf, -Inf and NaN
6886    to be considered integer values. Return false for signaling NaN.
6887
6888    DEPTH is the current nesting depth of the query.  */
6889
6890 static bool
6891 gimple_assign_integer_valued_real_p (gimple *stmt, int depth)
6892 {
6893   enum tree_code code = gimple_assign_rhs_code (stmt);
6894   switch (get_gimple_rhs_class (code))
6895     {
6896     case GIMPLE_UNARY_RHS:
6897       return integer_valued_real_unary_p (gimple_assign_rhs_code (stmt),
6898                                           gimple_assign_rhs1 (stmt), depth);
6899     case GIMPLE_BINARY_RHS:
6900       return integer_valued_real_binary_p (gimple_assign_rhs_code (stmt),
6901                                            gimple_assign_rhs1 (stmt),
6902                                            gimple_assign_rhs2 (stmt), depth);
6903     case GIMPLE_TERNARY_RHS:
6904       return false;
6905     case GIMPLE_SINGLE_RHS:
6906       return integer_valued_real_single_p (gimple_assign_rhs1 (stmt), depth);
6907     case GIMPLE_INVALID_RHS:
6908       break;
6909     }
6910   gcc_unreachable ();
6911 }
6912
6913 /* Return true if the floating-point value computed by call STMT is known
6914    to have an integer value.  We also allow +Inf, -Inf and NaN to be
6915    considered integer values. Return false for signaling NaN.
6916
6917    DEPTH is the current nesting depth of the query.  */
6918
6919 static bool
6920 gimple_call_integer_valued_real_p (gimple *stmt, int depth)
6921 {
6922   tree arg0 = (gimple_call_num_args (stmt) > 0
6923                ? gimple_call_arg (stmt, 0)
6924                : NULL_TREE);
6925   tree arg1 = (gimple_call_num_args (stmt) > 1
6926                ? gimple_call_arg (stmt, 1)
6927                : NULL_TREE);
6928   return integer_valued_real_call_p (gimple_call_combined_fn (stmt),
6929                                      arg0, arg1, depth);
6930 }
6931
6932 /* Return true if the floating-point result of phi STMT is known to have
6933    an integer value.  We also allow +Inf, -Inf and NaN to be considered
6934    integer values. Return false for signaling NaN.
6935
6936    DEPTH is the current nesting depth of the query.  */
6937
6938 static bool
6939 gimple_phi_integer_valued_real_p (gimple *stmt, int depth)
6940 {
6941   for (unsigned i = 0; i < gimple_phi_num_args (stmt); ++i)
6942     {
6943       tree arg = gimple_phi_arg_def (stmt, i);
6944       if (!integer_valued_real_single_p (arg, depth + 1))
6945         return false;
6946     }
6947   return true;
6948 }
6949
6950 /* Return true if the floating-point value computed by STMT is known
6951    to have an integer value.  We also allow +Inf, -Inf and NaN to be
6952    considered integer values. Return false for signaling NaN.
6953
6954    DEPTH is the current nesting depth of the query.  */
6955
6956 bool
6957 gimple_stmt_integer_valued_real_p (gimple *stmt, int depth)
6958 {
6959   switch (gimple_code (stmt))
6960     {
6961     case GIMPLE_ASSIGN:
6962       return gimple_assign_integer_valued_real_p (stmt, depth);
6963     case GIMPLE_CALL:
6964       return gimple_call_integer_valued_real_p (stmt, depth);
6965     case GIMPLE_PHI:
6966       return gimple_phi_integer_valued_real_p (stmt, depth);
6967     default:
6968       return false;
6969     }
6970 }