OSDN Git Service

238361166b9c0bec70815c8437776ff42a4a2432
[pf3gnuchains/gcc-fork.git] / gcc / tree-ssa-ccp.c
1 /* Conditional constant propagation pass for the GNU compiler.
2    Copyright (C) 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009
3    Free Software Foundation, Inc.
4    Adapted from original RTL SSA-CCP by Daniel Berlin <dberlin@dberlin.org>
5    Adapted to GIMPLE trees by Diego Novillo <dnovillo@redhat.com>
6
7 This file is part of GCC.
8
9 GCC is free software; you can redistribute it and/or modify it
10 under the terms of the GNU General Public License as published by the
11 Free Software Foundation; either version 3, or (at your option) any
12 later version.
13
14 GCC is distributed in the hope that it will be useful, but WITHOUT
15 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
16 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
17 for more details.
18
19 You should have received a copy of the GNU General Public License
20 along with GCC; see the file COPYING3.  If not see
21 <http://www.gnu.org/licenses/>.  */
22
23 /* Conditional constant propagation (CCP) is based on the SSA
24    propagation engine (tree-ssa-propagate.c).  Constant assignments of
25    the form VAR = CST are propagated from the assignments into uses of
26    VAR, which in turn may generate new constants.  The simulation uses
27    a four level lattice to keep track of constant values associated
28    with SSA names.  Given an SSA name V_i, it may take one of the
29    following values:
30
31         UNINITIALIZED   ->  the initial state of the value.  This value
32                             is replaced with a correct initial value
33                             the first time the value is used, so the
34                             rest of the pass does not need to care about
35                             it.  Using this value simplifies initialization
36                             of the pass, and prevents us from needlessly
37                             scanning statements that are never reached.
38
39         UNDEFINED       ->  V_i is a local variable whose definition
40                             has not been processed yet.  Therefore we
41                             don't yet know if its value is a constant
42                             or not.
43
44         CONSTANT        ->  V_i has been found to hold a constant
45                             value C.
46
47         VARYING         ->  V_i cannot take a constant value, or if it
48                             does, it is not possible to determine it
49                             at compile time.
50
51    The core of SSA-CCP is in ccp_visit_stmt and ccp_visit_phi_node:
52
53    1- In ccp_visit_stmt, we are interested in assignments whose RHS
54       evaluates into a constant and conditional jumps whose predicate
55       evaluates into a boolean true or false.  When an assignment of
56       the form V_i = CONST is found, V_i's lattice value is set to
57       CONSTANT and CONST is associated with it.  This causes the
58       propagation engine to add all the SSA edges coming out the
59       assignment into the worklists, so that statements that use V_i
60       can be visited.
61
62       If the statement is a conditional with a constant predicate, we
63       mark the outgoing edges as executable or not executable
64       depending on the predicate's value.  This is then used when
65       visiting PHI nodes to know when a PHI argument can be ignored.
66
67
68    2- In ccp_visit_phi_node, if all the PHI arguments evaluate to the
69       same constant C, then the LHS of the PHI is set to C.  This
70       evaluation is known as the "meet operation".  Since one of the
71       goals of this evaluation is to optimistically return constant
72       values as often as possible, it uses two main short cuts:
73
74       - If an argument is flowing in through a non-executable edge, it
75         is ignored.  This is useful in cases like this:
76
77                         if (PRED)
78                           a_9 = 3;
79                         else
80                           a_10 = 100;
81                         a_11 = PHI (a_9, a_10)
82
83         If PRED is known to always evaluate to false, then we can
84         assume that a_11 will always take its value from a_10, meaning
85         that instead of consider it VARYING (a_9 and a_10 have
86         different values), we can consider it CONSTANT 100.
87
88       - If an argument has an UNDEFINED value, then it does not affect
89         the outcome of the meet operation.  If a variable V_i has an
90         UNDEFINED value, it means that either its defining statement
91         hasn't been visited yet or V_i has no defining statement, in
92         which case the original symbol 'V' is being used
93         uninitialized.  Since 'V' is a local variable, the compiler
94         may assume any initial value for it.
95
96
97    After propagation, every variable V_i that ends up with a lattice
98    value of CONSTANT will have the associated constant value in the
99    array CONST_VAL[i].VALUE.  That is fed into substitute_and_fold for
100    final substitution and folding.
101
102
103    Constant propagation in stores and loads (STORE-CCP)
104    ----------------------------------------------------
105
106    While CCP has all the logic to propagate constants in GIMPLE
107    registers, it is missing the ability to associate constants with
108    stores and loads (i.e., pointer dereferences, structures and
109    global/aliased variables).  We don't keep loads and stores in
110    SSA, but we do build a factored use-def web for them (in the
111    virtual operands).
112
113    For instance, consider the following code fragment:
114
115           struct A a;
116           const int B = 42;
117
118           void foo (int i)
119           {
120             if (i > 10)
121               a.a = 42;
122             else
123               {
124                 a.b = 21;
125                 a.a = a.b + 21;
126               }
127
128             if (a.a != B)
129               never_executed ();
130           }
131
132    We should be able to deduce that the predicate 'a.a != B' is always
133    false.  To achieve this, we associate constant values to the SSA
134    names in the VDEF operands for each store.  Additionally,
135    since we also glob partial loads/stores with the base symbol, we
136    also keep track of the memory reference where the constant value
137    was stored (in the MEM_REF field of PROP_VALUE_T).  For instance,
138
139         # a_5 = VDEF <a_4>
140         a.a = 2;
141
142         # VUSE <a_5>
143         x_3 = a.b;
144
145    In the example above, CCP will associate value '2' with 'a_5', but
146    it would be wrong to replace the load from 'a.b' with '2', because
147    '2' had been stored into a.a.
148
149    Note that the initial value of virtual operands is VARYING, not
150    UNDEFINED.  Consider, for instance global variables:
151
152         int A;
153
154         foo (int i)
155         {
156           if (i_3 > 10)
157             A_4 = 3;
158           # A_5 = PHI (A_4, A_2);
159
160           # VUSE <A_5>
161           A.0_6 = A;
162
163           return A.0_6;
164         }
165
166    The value of A_2 cannot be assumed to be UNDEFINED, as it may have
167    been defined outside of foo.  If we were to assume it UNDEFINED, we
168    would erroneously optimize the above into 'return 3;'.
169
170    Though STORE-CCP is not too expensive, it does have to do more work
171    than regular CCP, so it is only enabled at -O2.  Both regular CCP
172    and STORE-CCP use the exact same algorithm.  The only distinction
173    is that when doing STORE-CCP, the boolean variable DO_STORE_CCP is
174    set to true.  This affects the evaluation of statements and PHI
175    nodes.
176
177    References:
178
179      Constant propagation with conditional branches,
180      Wegman and Zadeck, ACM TOPLAS 13(2):181-210.
181
182      Building an Optimizing Compiler,
183      Robert Morgan, Butterworth-Heinemann, 1998, Section 8.9.
184
185      Advanced Compiler Design and Implementation,
186      Steven Muchnick, Morgan Kaufmann, 1997, Section 12.6  */
187
188 #include "config.h"
189 #include "system.h"
190 #include "coretypes.h"
191 #include "tm.h"
192 #include "tree.h"
193 #include "flags.h"
194 #include "rtl.h"
195 #include "tm_p.h"
196 #include "ggc.h"
197 #include "basic-block.h"
198 #include "output.h"
199 #include "expr.h"
200 #include "function.h"
201 #include "diagnostic.h"
202 #include "timevar.h"
203 #include "tree-dump.h"
204 #include "tree-flow.h"
205 #include "tree-pass.h"
206 #include "tree-ssa-propagate.h"
207 #include "value-prof.h"
208 #include "langhooks.h"
209 #include "target.h"
210 #include "toplev.h"
211 #include "dbgcnt.h"
212
213
214 /* Possible lattice values.  */
215 typedef enum
216 {
217   UNINITIALIZED,
218   UNDEFINED,
219   CONSTANT,
220   VARYING
221 } ccp_lattice_t;
222
223 /* Array of propagated constant values.  After propagation,
224    CONST_VAL[I].VALUE holds the constant value for SSA_NAME(I).  If
225    the constant is held in an SSA name representing a memory store
226    (i.e., a VDEF), CONST_VAL[I].MEM_REF will contain the actual
227    memory reference used to store (i.e., the LHS of the assignment
228    doing the store).  */
229 static prop_value_t *const_val;
230
231 static void canonicalize_float_value (prop_value_t *);
232 static bool ccp_fold_stmt (gimple_stmt_iterator *);
233
234 /* Dump constant propagation value VAL to file OUTF prefixed by PREFIX.  */
235
236 static void
237 dump_lattice_value (FILE *outf, const char *prefix, prop_value_t val)
238 {
239   switch (val.lattice_val)
240     {
241     case UNINITIALIZED:
242       fprintf (outf, "%sUNINITIALIZED", prefix);
243       break;
244     case UNDEFINED:
245       fprintf (outf, "%sUNDEFINED", prefix);
246       break;
247     case VARYING:
248       fprintf (outf, "%sVARYING", prefix);
249       break;
250     case CONSTANT:
251       fprintf (outf, "%sCONSTANT ", prefix);
252       print_generic_expr (outf, val.value, dump_flags);
253       break;
254     default:
255       gcc_unreachable ();
256     }
257 }
258
259
260 /* Print lattice value VAL to stderr.  */
261
262 void debug_lattice_value (prop_value_t val);
263
264 void
265 debug_lattice_value (prop_value_t val)
266 {
267   dump_lattice_value (stderr, "", val);
268   fprintf (stderr, "\n");
269 }
270
271
272
273 /* If SYM is a constant variable with known value, return the value.
274    NULL_TREE is returned otherwise.  */
275
276 tree
277 get_symbol_constant_value (tree sym)
278 {
279   if (TREE_STATIC (sym)
280       && (TREE_READONLY (sym)
281           || TREE_CODE (sym) == CONST_DECL))
282     {
283       tree val = DECL_INITIAL (sym);
284       if (val)
285         {
286           STRIP_USELESS_TYPE_CONVERSION (val);
287           if (is_gimple_min_invariant (val))
288             {
289               if (TREE_CODE (val) == ADDR_EXPR)
290                 {
291                   tree base = get_base_address (TREE_OPERAND (val, 0));
292                   if (base && TREE_CODE (base) == VAR_DECL)
293                     {
294                       TREE_ADDRESSABLE (base) = 1;
295                       if (gimple_referenced_vars (cfun))
296                         add_referenced_var (base);
297                     }
298                 }
299               return val;
300             }
301         }
302       /* Variables declared 'const' without an initializer
303          have zero as the initializer if they may not be
304          overridden at link or run time.  */
305       if (!val
306           && !DECL_EXTERNAL (sym)
307           && targetm.binds_local_p (sym)
308           && (INTEGRAL_TYPE_P (TREE_TYPE (sym))
309                || SCALAR_FLOAT_TYPE_P (TREE_TYPE (sym))))
310         return fold_convert (TREE_TYPE (sym), integer_zero_node);
311     }
312
313   return NULL_TREE;
314 }
315
316 /* Compute a default value for variable VAR and store it in the
317    CONST_VAL array.  The following rules are used to get default
318    values:
319
320    1- Global and static variables that are declared constant are
321       considered CONSTANT.
322
323    2- Any other value is considered UNDEFINED.  This is useful when
324       considering PHI nodes.  PHI arguments that are undefined do not
325       change the constant value of the PHI node, which allows for more
326       constants to be propagated.
327
328    3- Variables defined by statements other than assignments and PHI
329       nodes are considered VARYING.
330
331    4- Initial values of variables that are not GIMPLE registers are
332       considered VARYING.  */
333
334 static prop_value_t
335 get_default_value (tree var)
336 {
337   tree sym = SSA_NAME_VAR (var);
338   prop_value_t val = { UNINITIALIZED, NULL_TREE };
339   gimple stmt;
340
341   stmt = SSA_NAME_DEF_STMT (var);
342
343   if (gimple_nop_p (stmt))
344     {
345       /* Variables defined by an empty statement are those used
346          before being initialized.  If VAR is a local variable, we
347          can assume initially that it is UNDEFINED, otherwise we must
348          consider it VARYING.  */
349       if (is_gimple_reg (sym) && TREE_CODE (sym) != PARM_DECL)
350         val.lattice_val = UNDEFINED;
351       else
352         val.lattice_val = VARYING;
353     }
354   else if (is_gimple_assign (stmt)
355            /* Value-returning GIMPLE_CALL statements assign to
356               a variable, and are treated similarly to GIMPLE_ASSIGN.  */
357            || (is_gimple_call (stmt)
358                && gimple_call_lhs (stmt) != NULL_TREE)
359            || gimple_code (stmt) == GIMPLE_PHI)
360     {
361       tree cst;
362       if (gimple_assign_single_p (stmt)
363           && DECL_P (gimple_assign_rhs1 (stmt))
364           && (cst = get_symbol_constant_value (gimple_assign_rhs1 (stmt))))
365         {
366           val.lattice_val = CONSTANT;
367           val.value = cst;
368         }
369       else
370         /* Any other variable defined by an assignment or a PHI node
371            is considered UNDEFINED.  */
372         val.lattice_val = UNDEFINED;
373     }
374   else
375     {
376       /* Otherwise, VAR will never take on a constant value.  */
377       val.lattice_val = VARYING;
378     }
379
380   return val;
381 }
382
383
384 /* Get the constant value associated with variable VAR.  */
385
386 static inline prop_value_t *
387 get_value (tree var)
388 {
389   prop_value_t *val;
390
391   if (const_val == NULL)
392     return NULL;
393
394   val = &const_val[SSA_NAME_VERSION (var)];
395   if (val->lattice_val == UNINITIALIZED)
396     *val = get_default_value (var);
397
398   canonicalize_float_value (val);
399
400   return val;
401 }
402
403 /* Sets the value associated with VAR to VARYING.  */
404
405 static inline void
406 set_value_varying (tree var)
407 {
408   prop_value_t *val = &const_val[SSA_NAME_VERSION (var)];
409
410   val->lattice_val = VARYING;
411   val->value = NULL_TREE;
412 }
413
414 /* For float types, modify the value of VAL to make ccp work correctly
415    for non-standard values (-0, NaN):
416
417    If HONOR_SIGNED_ZEROS is false, and VAL = -0, we canonicalize it to 0.
418    If HONOR_NANS is false, and VAL is NaN, we canonicalize it to UNDEFINED.
419      This is to fix the following problem (see PR 29921): Suppose we have
420
421      x = 0.0 * y
422
423      and we set value of y to NaN.  This causes value of x to be set to NaN.
424      When we later determine that y is in fact VARYING, fold uses the fact
425      that HONOR_NANS is false, and we try to change the value of x to 0,
426      causing an ICE.  With HONOR_NANS being false, the real appearance of
427      NaN would cause undefined behavior, though, so claiming that y (and x)
428      are UNDEFINED initially is correct.  */
429
430 static void
431 canonicalize_float_value (prop_value_t *val)
432 {
433   enum machine_mode mode;
434   tree type;
435   REAL_VALUE_TYPE d;
436
437   if (val->lattice_val != CONSTANT
438       || TREE_CODE (val->value) != REAL_CST)
439     return;
440
441   d = TREE_REAL_CST (val->value);
442   type = TREE_TYPE (val->value);
443   mode = TYPE_MODE (type);
444
445   if (!HONOR_SIGNED_ZEROS (mode)
446       && REAL_VALUE_MINUS_ZERO (d))
447     {
448       val->value = build_real (type, dconst0);
449       return;
450     }
451
452   if (!HONOR_NANS (mode)
453       && REAL_VALUE_ISNAN (d))
454     {
455       val->lattice_val = UNDEFINED;
456       val->value = NULL;
457       return;
458     }
459 }
460
461 /* Set the value for variable VAR to NEW_VAL.  Return true if the new
462    value is different from VAR's previous value.  */
463
464 static bool
465 set_lattice_value (tree var, prop_value_t new_val)
466 {
467   prop_value_t *old_val = get_value (var);
468
469   canonicalize_float_value (&new_val);
470
471   /* Lattice transitions must always be monotonically increasing in
472      value.  If *OLD_VAL and NEW_VAL are the same, return false to
473      inform the caller that this was a non-transition.  */
474
475   gcc_assert (old_val->lattice_val < new_val.lattice_val
476               || (old_val->lattice_val == new_val.lattice_val
477                   && ((!old_val->value && !new_val.value)
478                       || operand_equal_p (old_val->value, new_val.value, 0))));
479
480   if (old_val->lattice_val != new_val.lattice_val)
481     {
482       if (dump_file && (dump_flags & TDF_DETAILS))
483         {
484           dump_lattice_value (dump_file, "Lattice value changed to ", new_val);
485           fprintf (dump_file, ".  Adding SSA edges to worklist.\n");
486         }
487
488       *old_val = new_val;
489
490       gcc_assert (new_val.lattice_val != UNDEFINED);
491       return true;
492     }
493
494   return false;
495 }
496
497
498 /* Return the likely CCP lattice value for STMT.
499
500    If STMT has no operands, then return CONSTANT.
501
502    Else if undefinedness of operands of STMT cause its value to be
503    undefined, then return UNDEFINED.
504
505    Else if any operands of STMT are constants, then return CONSTANT.
506
507    Else return VARYING.  */
508
509 static ccp_lattice_t
510 likely_value (gimple stmt)
511 {
512   bool has_constant_operand, has_undefined_operand, all_undefined_operands;
513   tree use;
514   ssa_op_iter iter;
515   unsigned i;
516
517   enum gimple_code code = gimple_code (stmt);
518
519   /* This function appears to be called only for assignments, calls,
520      conditionals, and switches, due to the logic in visit_stmt.  */
521   gcc_assert (code == GIMPLE_ASSIGN
522               || code == GIMPLE_CALL
523               || code == GIMPLE_COND
524               || code == GIMPLE_SWITCH);
525
526   /* If the statement has volatile operands, it won't fold to a
527      constant value.  */
528   if (gimple_has_volatile_ops (stmt))
529     return VARYING;
530
531   /* Arrive here for more complex cases.  */
532   has_constant_operand = false;
533   has_undefined_operand = false;
534   all_undefined_operands = true;
535   FOR_EACH_SSA_TREE_OPERAND (use, stmt, iter, SSA_OP_USE)
536     {
537       prop_value_t *val = get_value (use);
538
539       if (val->lattice_val == UNDEFINED)
540         has_undefined_operand = true;
541       else
542         all_undefined_operands = false;
543
544       if (val->lattice_val == CONSTANT)
545         has_constant_operand = true;
546     }
547
548   /* There may be constants in regular rhs operands.  For calls we
549      have to ignore lhs, fndecl and static chain, otherwise only
550      the lhs.  */
551   for (i = (is_gimple_call (stmt) ? 2 : 0) + gimple_has_lhs (stmt);
552        i < gimple_num_ops (stmt); ++i)
553     {
554       tree op = gimple_op (stmt, i);
555       if (!op || TREE_CODE (op) == SSA_NAME)
556         continue;
557       if (is_gimple_min_invariant (op))
558         has_constant_operand = true;
559     }
560
561   /* If the operation combines operands like COMPLEX_EXPR make sure to
562      not mark the result UNDEFINED if only one part of the result is
563      undefined.  */
564   if (has_undefined_operand && all_undefined_operands)
565     return UNDEFINED;
566   else if (code == GIMPLE_ASSIGN && has_undefined_operand)
567     {
568       switch (gimple_assign_rhs_code (stmt))
569         {
570         /* Unary operators are handled with all_undefined_operands.  */
571         case PLUS_EXPR:
572         case MINUS_EXPR:
573         case POINTER_PLUS_EXPR:
574           /* Not MIN_EXPR, MAX_EXPR.  One VARYING operand may be selected.
575              Not bitwise operators, one VARYING operand may specify the
576              result completely.  Not logical operators for the same reason.
577              Not COMPLEX_EXPR as one VARYING operand makes the result partly
578              not UNDEFINED.  Not *DIV_EXPR, comparisons and shifts because
579              the undefined operand may be promoted.  */
580           return UNDEFINED;
581
582         default:
583           ;
584         }
585     }
586   /* If there was an UNDEFINED operand but the result may be not UNDEFINED
587      fall back to VARYING even if there were CONSTANT operands.  */
588   if (has_undefined_operand)
589     return VARYING;
590
591   /* We do not consider virtual operands here -- load from read-only
592      memory may have only VARYING virtual operands, but still be
593      constant.  */
594   if (has_constant_operand
595       || gimple_references_memory_p (stmt))
596     return CONSTANT;
597
598   return VARYING;
599 }
600
601 /* Returns true if STMT cannot be constant.  */
602
603 static bool
604 surely_varying_stmt_p (gimple stmt)
605 {
606   /* If the statement has operands that we cannot handle, it cannot be
607      constant.  */
608   if (gimple_has_volatile_ops (stmt))
609     return true;
610
611   /* If it is a call and does not return a value or is not a
612      builtin and not an indirect call, it is varying.  */
613   if (is_gimple_call (stmt))
614     {
615       tree fndecl;
616       if (!gimple_call_lhs (stmt)
617           || ((fndecl = gimple_call_fndecl (stmt)) != NULL_TREE
618               && !DECL_BUILT_IN (fndecl)))
619         return true;
620     }
621
622   /* Any other store operation is not interesting.  */
623   else if (gimple_vdef (stmt))
624     return true;
625
626   /* Anything other than assignments and conditional jumps are not
627      interesting for CCP.  */
628   if (gimple_code (stmt) != GIMPLE_ASSIGN
629       && gimple_code (stmt) != GIMPLE_COND
630       && gimple_code (stmt) != GIMPLE_SWITCH
631       && gimple_code (stmt) != GIMPLE_CALL)
632     return true;
633
634   return false;
635 }
636
637 /* Initialize local data structures for CCP.  */
638
639 static void
640 ccp_initialize (void)
641 {
642   basic_block bb;
643
644   const_val = XCNEWVEC (prop_value_t, num_ssa_names);
645
646   /* Initialize simulation flags for PHI nodes and statements.  */
647   FOR_EACH_BB (bb)
648     {
649       gimple_stmt_iterator i;
650
651       for (i = gsi_start_bb (bb); !gsi_end_p (i); gsi_next (&i))
652         {
653           gimple stmt = gsi_stmt (i);
654           bool is_varying;
655
656           /* If the statement is a control insn, then we do not
657              want to avoid simulating the statement once.  Failure
658              to do so means that those edges will never get added.  */
659           if (stmt_ends_bb_p (stmt))
660             is_varying = false;
661           else
662             is_varying = surely_varying_stmt_p (stmt);
663
664           if (is_varying)
665             {
666               tree def;
667               ssa_op_iter iter;
668
669               /* If the statement will not produce a constant, mark
670                  all its outputs VARYING.  */
671               FOR_EACH_SSA_TREE_OPERAND (def, stmt, iter, SSA_OP_ALL_DEFS)
672                 set_value_varying (def);
673             }
674           prop_set_simulate_again (stmt, !is_varying);
675         }
676     }
677
678   /* Now process PHI nodes.  We never clear the simulate_again flag on
679      phi nodes, since we do not know which edges are executable yet,
680      except for phi nodes for virtual operands when we do not do store ccp.  */
681   FOR_EACH_BB (bb)
682     {
683       gimple_stmt_iterator i;
684
685       for (i = gsi_start_phis (bb); !gsi_end_p (i); gsi_next (&i))
686         {
687           gimple phi = gsi_stmt (i);
688
689           if (!is_gimple_reg (gimple_phi_result (phi)))
690             prop_set_simulate_again (phi, false);
691           else
692             prop_set_simulate_again (phi, true);
693         }
694     }
695 }
696
697 /* Debug count support. Reset the values of ssa names
698    VARYING when the total number ssa names analyzed is
699    beyond the debug count specified.  */
700
701 static void
702 do_dbg_cnt (void)
703 {
704   unsigned i;
705   for (i = 0; i < num_ssa_names; i++)
706     {
707       if (!dbg_cnt (ccp))
708         {
709           const_val[i].lattice_val = VARYING;
710           const_val[i].value = NULL_TREE;
711         }
712     }
713 }
714
715
716 /* Do final substitution of propagated values, cleanup the flowgraph and
717    free allocated storage.
718
719    Return TRUE when something was optimized.  */
720
721 static bool
722 ccp_finalize (void)
723 {
724   bool something_changed;
725
726   do_dbg_cnt ();
727   /* Perform substitutions based on the known constant values.  */
728   something_changed = substitute_and_fold (const_val, ccp_fold_stmt);
729
730   free (const_val);
731   const_val = NULL;
732   return something_changed;;
733 }
734
735
736 /* Compute the meet operator between *VAL1 and *VAL2.  Store the result
737    in VAL1.
738
739                 any  M UNDEFINED   = any
740                 any  M VARYING     = VARYING
741                 Ci   M Cj          = Ci         if (i == j)
742                 Ci   M Cj          = VARYING    if (i != j)
743    */
744
745 static void
746 ccp_lattice_meet (prop_value_t *val1, prop_value_t *val2)
747 {
748   if (val1->lattice_val == UNDEFINED)
749     {
750       /* UNDEFINED M any = any   */
751       *val1 = *val2;
752     }
753   else if (val2->lattice_val == UNDEFINED)
754     {
755       /* any M UNDEFINED = any
756          Nothing to do.  VAL1 already contains the value we want.  */
757       ;
758     }
759   else if (val1->lattice_val == VARYING
760            || val2->lattice_val == VARYING)
761     {
762       /* any M VARYING = VARYING.  */
763       val1->lattice_val = VARYING;
764       val1->value = NULL_TREE;
765     }
766   else if (val1->lattice_val == CONSTANT
767            && val2->lattice_val == CONSTANT
768            && simple_cst_equal (val1->value, val2->value) == 1)
769     {
770       /* Ci M Cj = Ci           if (i == j)
771          Ci M Cj = VARYING      if (i != j)
772
773          If these two values come from memory stores, make sure that
774          they come from the same memory reference.  */
775       val1->lattice_val = CONSTANT;
776       val1->value = val1->value;
777     }
778   else
779     {
780       /* Any other combination is VARYING.  */
781       val1->lattice_val = VARYING;
782       val1->value = NULL_TREE;
783     }
784 }
785
786
787 /* Loop through the PHI_NODE's parameters for BLOCK and compare their
788    lattice values to determine PHI_NODE's lattice value.  The value of a
789    PHI node is determined calling ccp_lattice_meet with all the arguments
790    of the PHI node that are incoming via executable edges.  */
791
792 static enum ssa_prop_result
793 ccp_visit_phi_node (gimple phi)
794 {
795   unsigned i;
796   prop_value_t *old_val, new_val;
797
798   if (dump_file && (dump_flags & TDF_DETAILS))
799     {
800       fprintf (dump_file, "\nVisiting PHI node: ");
801       print_gimple_stmt (dump_file, phi, 0, dump_flags);
802     }
803
804   old_val = get_value (gimple_phi_result (phi));
805   switch (old_val->lattice_val)
806     {
807     case VARYING:
808       return SSA_PROP_VARYING;
809
810     case CONSTANT:
811       new_val = *old_val;
812       break;
813
814     case UNDEFINED:
815       new_val.lattice_val = UNDEFINED;
816       new_val.value = NULL_TREE;
817       break;
818
819     default:
820       gcc_unreachable ();
821     }
822
823   for (i = 0; i < gimple_phi_num_args (phi); i++)
824     {
825       /* Compute the meet operator over all the PHI arguments flowing
826          through executable edges.  */
827       edge e = gimple_phi_arg_edge (phi, i);
828
829       if (dump_file && (dump_flags & TDF_DETAILS))
830         {
831           fprintf (dump_file,
832               "\n    Argument #%d (%d -> %d %sexecutable)\n",
833               i, e->src->index, e->dest->index,
834               (e->flags & EDGE_EXECUTABLE) ? "" : "not ");
835         }
836
837       /* If the incoming edge is executable, Compute the meet operator for
838          the existing value of the PHI node and the current PHI argument.  */
839       if (e->flags & EDGE_EXECUTABLE)
840         {
841           tree arg = gimple_phi_arg (phi, i)->def;
842           prop_value_t arg_val;
843
844           if (is_gimple_min_invariant (arg))
845             {
846               arg_val.lattice_val = CONSTANT;
847               arg_val.value = arg;
848             }
849           else
850             arg_val = *(get_value (arg));
851
852           ccp_lattice_meet (&new_val, &arg_val);
853
854           if (dump_file && (dump_flags & TDF_DETAILS))
855             {
856               fprintf (dump_file, "\t");
857               print_generic_expr (dump_file, arg, dump_flags);
858               dump_lattice_value (dump_file, "\tValue: ", arg_val);
859               fprintf (dump_file, "\n");
860             }
861
862           if (new_val.lattice_val == VARYING)
863             break;
864         }
865     }
866
867   if (dump_file && (dump_flags & TDF_DETAILS))
868     {
869       dump_lattice_value (dump_file, "\n    PHI node value: ", new_val);
870       fprintf (dump_file, "\n\n");
871     }
872
873   /* Make the transition to the new value.  */
874   if (set_lattice_value (gimple_phi_result (phi), new_val))
875     {
876       if (new_val.lattice_val == VARYING)
877         return SSA_PROP_VARYING;
878       else
879         return SSA_PROP_INTERESTING;
880     }
881   else
882     return SSA_PROP_NOT_INTERESTING;
883 }
884
885 /* Return true if we may propagate the address expression ADDR into the
886    dereference DEREF and cancel them.  */
887
888 bool
889 may_propagate_address_into_dereference (tree addr, tree deref)
890 {
891   gcc_assert (INDIRECT_REF_P (deref)
892               && TREE_CODE (addr) == ADDR_EXPR);
893
894   /* Don't propagate if ADDR's operand has incomplete type.  */
895   if (!COMPLETE_TYPE_P (TREE_TYPE (TREE_OPERAND (addr, 0))))
896     return false;
897
898   /* If the address is invariant then we do not need to preserve restrict
899      qualifications.  But we do need to preserve volatile qualifiers until
900      we can annotate the folded dereference itself properly.  */
901   if (is_gimple_min_invariant (addr)
902       && (!TREE_THIS_VOLATILE (deref)
903           || TYPE_VOLATILE (TREE_TYPE (addr))))
904     return useless_type_conversion_p (TREE_TYPE (deref),
905                                       TREE_TYPE (TREE_OPERAND (addr, 0)));
906
907   /* Else both the address substitution and the folding must result in
908      a valid useless type conversion sequence.  */
909   return (useless_type_conversion_p (TREE_TYPE (TREE_OPERAND (deref, 0)),
910                                      TREE_TYPE (addr))
911           && useless_type_conversion_p (TREE_TYPE (deref),
912                                         TREE_TYPE (TREE_OPERAND (addr, 0))));
913 }
914
915 /* CCP specific front-end to the non-destructive constant folding
916    routines.
917
918    Attempt to simplify the RHS of STMT knowing that one or more
919    operands are constants.
920
921    If simplification is possible, return the simplified RHS,
922    otherwise return the original RHS or NULL_TREE.  */
923
924 static tree
925 ccp_fold (gimple stmt)
926 {
927   location_t loc = gimple_location (stmt);
928   switch (gimple_code (stmt))
929     {
930     case GIMPLE_ASSIGN:
931       {
932         enum tree_code subcode = gimple_assign_rhs_code (stmt);
933
934         switch (get_gimple_rhs_class (subcode))
935           {
936           case GIMPLE_SINGLE_RHS:
937             {
938               tree rhs = gimple_assign_rhs1 (stmt);
939               enum tree_code_class kind = TREE_CODE_CLASS (subcode);
940
941               if (TREE_CODE (rhs) == SSA_NAME)
942                 {
943                   /* If the RHS is an SSA_NAME, return its known constant value,
944                      if any.  */
945                   return get_value (rhs)->value;
946                 }
947               /* Handle propagating invariant addresses into address operations.
948                  The folding we do here matches that in tree-ssa-forwprop.c.  */
949               else if (TREE_CODE (rhs) == ADDR_EXPR)
950                 {
951                   tree *base;
952                   base = &TREE_OPERAND (rhs, 0);
953                   while (handled_component_p (*base))
954                     base = &TREE_OPERAND (*base, 0);
955                   if (TREE_CODE (*base) == INDIRECT_REF
956                       && TREE_CODE (TREE_OPERAND (*base, 0)) == SSA_NAME)
957                     {
958                       prop_value_t *val = get_value (TREE_OPERAND (*base, 0));
959                       if (val->lattice_val == CONSTANT
960                           && TREE_CODE (val->value) == ADDR_EXPR
961                           && may_propagate_address_into_dereference
962                                (val->value, *base))
963                         {
964                           /* We need to return a new tree, not modify the IL
965                              or share parts of it.  So play some tricks to
966                              avoid manually building it.  */
967                           tree ret, save = *base;
968                           *base = TREE_OPERAND (val->value, 0);
969                           ret = unshare_expr (rhs);
970                           recompute_tree_invariant_for_addr_expr (ret);
971                           *base = save;
972                           return ret;
973                         }
974                     }
975                 }
976               else if (TREE_CODE (rhs) == CONSTRUCTOR
977                        && TREE_CODE (TREE_TYPE (rhs)) == VECTOR_TYPE
978                        && (CONSTRUCTOR_NELTS (rhs)
979                            == TYPE_VECTOR_SUBPARTS (TREE_TYPE (rhs))))
980                 {
981                   unsigned i;
982                   tree val, list;
983
984                   list = NULL_TREE;
985                   FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (rhs), i, val)
986                     {
987                       if (TREE_CODE (val) == SSA_NAME
988                           && get_value (val)->lattice_val == CONSTANT)
989                         val = get_value (val)->value;
990                       if (TREE_CODE (val) == INTEGER_CST
991                           || TREE_CODE (val) == REAL_CST
992                           || TREE_CODE (val) == FIXED_CST)
993                         list = tree_cons (NULL_TREE, val, list);
994                       else
995                         return NULL_TREE;
996                     }
997
998                   return build_vector (TREE_TYPE (rhs), nreverse (list));
999                 }
1000
1001               if (kind == tcc_reference)
1002                 {
1003                   if ((TREE_CODE (rhs) == VIEW_CONVERT_EXPR
1004                        || TREE_CODE (rhs) == REALPART_EXPR
1005                        || TREE_CODE (rhs) == IMAGPART_EXPR)
1006                       && TREE_CODE (TREE_OPERAND (rhs, 0)) == SSA_NAME)
1007                     {
1008                       prop_value_t *val = get_value (TREE_OPERAND (rhs, 0));
1009                       if (val->lattice_val == CONSTANT)
1010                         return fold_unary_loc (EXPR_LOCATION (rhs),
1011                                            TREE_CODE (rhs),
1012                                            TREE_TYPE (rhs), val->value);
1013                     }
1014                   else if (TREE_CODE (rhs) == INDIRECT_REF
1015                            && TREE_CODE (TREE_OPERAND (rhs, 0)) == SSA_NAME)
1016                     {
1017                       prop_value_t *val = get_value (TREE_OPERAND (rhs, 0));
1018                       if (val->lattice_val == CONSTANT
1019                           && TREE_CODE (val->value) == ADDR_EXPR
1020                           && useless_type_conversion_p (TREE_TYPE (rhs),
1021                                                         TREE_TYPE (TREE_TYPE (val->value))))
1022                         rhs = TREE_OPERAND (val->value, 0);
1023                     }
1024                   return fold_const_aggregate_ref (rhs);
1025                 }
1026               else if (kind == tcc_declaration)
1027                 return get_symbol_constant_value (rhs);
1028               return rhs;
1029             }
1030
1031           case GIMPLE_UNARY_RHS:
1032             {
1033               /* Handle unary operators that can appear in GIMPLE form.
1034                  Note that we know the single operand must be a constant,
1035                  so this should almost always return a simplified RHS.  */
1036               tree lhs = gimple_assign_lhs (stmt);
1037               tree op0 = gimple_assign_rhs1 (stmt);
1038
1039               /* Simplify the operand down to a constant.  */
1040               if (TREE_CODE (op0) == SSA_NAME)
1041                 {
1042                   prop_value_t *val = get_value (op0);
1043                   if (val->lattice_val == CONSTANT)
1044                     op0 = get_value (op0)->value;
1045                 }
1046
1047               /* Conversions are useless for CCP purposes if they are
1048                  value-preserving.  Thus the restrictions that
1049                  useless_type_conversion_p places for pointer type conversions
1050                  do not apply here.  Substitution later will only substitute to
1051                  allowed places.  */
1052               if (CONVERT_EXPR_CODE_P (subcode)
1053                   && POINTER_TYPE_P (TREE_TYPE (lhs))
1054                   && POINTER_TYPE_P (TREE_TYPE (op0))
1055                   /* Do not allow differences in volatile qualification
1056                      as this might get us confused as to whether a
1057                      propagation destination statement is volatile
1058                      or not.  See PR36988.  */
1059                   && (TYPE_VOLATILE (TREE_TYPE (TREE_TYPE (lhs)))
1060                       == TYPE_VOLATILE (TREE_TYPE (TREE_TYPE (op0)))))
1061                 {
1062                   tree tem;
1063                   /* Still try to generate a constant of correct type.  */
1064                   if (!useless_type_conversion_p (TREE_TYPE (lhs),
1065                                                   TREE_TYPE (op0))
1066                       && ((tem = maybe_fold_offset_to_address
1067                            (loc,
1068                             op0, integer_zero_node, TREE_TYPE (lhs)))
1069                           != NULL_TREE))
1070                     return tem;
1071                   return op0;
1072                 }
1073
1074               return
1075                 fold_unary_ignore_overflow_loc (loc, subcode,
1076                                                 gimple_expr_type (stmt), op0);
1077             }
1078
1079           case GIMPLE_BINARY_RHS:
1080             {
1081               /* Handle binary operators that can appear in GIMPLE form.  */
1082               tree op0 = gimple_assign_rhs1 (stmt);
1083               tree op1 = gimple_assign_rhs2 (stmt);
1084
1085               /* Simplify the operands down to constants when appropriate.  */
1086               if (TREE_CODE (op0) == SSA_NAME)
1087                 {
1088                   prop_value_t *val = get_value (op0);
1089                   if (val->lattice_val == CONSTANT)
1090                     op0 = val->value;
1091                 }
1092
1093               if (TREE_CODE (op1) == SSA_NAME)
1094                 {
1095                   prop_value_t *val = get_value (op1);
1096                   if (val->lattice_val == CONSTANT)
1097                     op1 = val->value;
1098                 }
1099
1100               /* Fold &foo + CST into an invariant reference if possible.  */
1101               if (gimple_assign_rhs_code (stmt) == POINTER_PLUS_EXPR
1102                   && TREE_CODE (op0) == ADDR_EXPR
1103                   && TREE_CODE (op1) == INTEGER_CST)
1104                 {
1105                   tree tem = maybe_fold_offset_to_address
1106                     (loc, op0, op1, TREE_TYPE (op0));
1107                   if (tem != NULL_TREE)
1108                     return tem;
1109                 }
1110
1111               return fold_binary_loc (loc, subcode,
1112                                   gimple_expr_type (stmt), op0, op1);
1113             }
1114
1115           default:
1116             gcc_unreachable ();
1117           }
1118       }
1119       break;
1120
1121     case GIMPLE_CALL:
1122       {
1123         tree fn = gimple_call_fn (stmt);
1124         prop_value_t *val;
1125
1126         if (TREE_CODE (fn) == SSA_NAME)
1127           {
1128             val = get_value (fn);
1129             if (val->lattice_val == CONSTANT)
1130               fn = val->value;
1131           }
1132         if (TREE_CODE (fn) == ADDR_EXPR
1133             && TREE_CODE (TREE_OPERAND (fn, 0)) == FUNCTION_DECL
1134             && DECL_BUILT_IN (TREE_OPERAND (fn, 0)))
1135           {
1136             tree *args = XALLOCAVEC (tree, gimple_call_num_args (stmt));
1137             tree call, retval;
1138             unsigned i;
1139             for (i = 0; i < gimple_call_num_args (stmt); ++i)
1140               {
1141                 args[i] = gimple_call_arg (stmt, i);
1142                 if (TREE_CODE (args[i]) == SSA_NAME)
1143                   {
1144                     val = get_value (args[i]);
1145                     if (val->lattice_val == CONSTANT)
1146                       args[i] = val->value;
1147                   }
1148               }
1149             call = build_call_array_loc (loc,
1150                                          gimple_call_return_type (stmt),
1151                                          fn, gimple_call_num_args (stmt), args);
1152             retval = fold_call_expr (EXPR_LOCATION (call), call, false);
1153             if (retval)
1154               /* fold_call_expr wraps the result inside a NOP_EXPR.  */
1155               STRIP_NOPS (retval);
1156             return retval;
1157           }
1158         return NULL_TREE;
1159       }
1160
1161     case GIMPLE_COND:
1162       {
1163         /* Handle comparison operators that can appear in GIMPLE form.  */
1164         tree op0 = gimple_cond_lhs (stmt);
1165         tree op1 = gimple_cond_rhs (stmt);
1166         enum tree_code code = gimple_cond_code (stmt);
1167
1168         /* Simplify the operands down to constants when appropriate.  */
1169         if (TREE_CODE (op0) == SSA_NAME)
1170           {
1171             prop_value_t *val = get_value (op0);
1172             if (val->lattice_val == CONSTANT)
1173               op0 = val->value;
1174           }
1175
1176         if (TREE_CODE (op1) == SSA_NAME)
1177           {
1178             prop_value_t *val = get_value (op1);
1179             if (val->lattice_val == CONSTANT)
1180               op1 = val->value;
1181           }
1182
1183         return fold_binary_loc (loc, code, boolean_type_node, op0, op1);
1184       }
1185
1186     case GIMPLE_SWITCH:
1187       {
1188         tree rhs = gimple_switch_index (stmt);
1189
1190         if (TREE_CODE (rhs) == SSA_NAME)
1191           {
1192             /* If the RHS is an SSA_NAME, return its known constant value,
1193                if any.  */
1194             return get_value (rhs)->value;
1195           }
1196
1197         return rhs;
1198       }
1199
1200     default:
1201       gcc_unreachable ();
1202     }
1203 }
1204
1205
1206 /* Return the tree representing the element referenced by T if T is an
1207    ARRAY_REF or COMPONENT_REF into constant aggregates.  Return
1208    NULL_TREE otherwise.  */
1209
1210 tree
1211 fold_const_aggregate_ref (tree t)
1212 {
1213   prop_value_t *value;
1214   tree base, ctor, idx, field;
1215   unsigned HOST_WIDE_INT cnt;
1216   tree cfield, cval;
1217
1218   if (TREE_CODE_CLASS (TREE_CODE (t)) == tcc_declaration)
1219     return get_symbol_constant_value (t);
1220
1221   switch (TREE_CODE (t))
1222     {
1223     case ARRAY_REF:
1224       /* Get a CONSTRUCTOR.  If BASE is a VAR_DECL, get its
1225          DECL_INITIAL.  If BASE is a nested reference into another
1226          ARRAY_REF or COMPONENT_REF, make a recursive call to resolve
1227          the inner reference.  */
1228       base = TREE_OPERAND (t, 0);
1229       switch (TREE_CODE (base))
1230         {
1231         case VAR_DECL:
1232           if (!TREE_READONLY (base)
1233               || TREE_CODE (TREE_TYPE (base)) != ARRAY_TYPE
1234               || !targetm.binds_local_p (base))
1235             return NULL_TREE;
1236
1237           ctor = DECL_INITIAL (base);
1238           break;
1239
1240         case ARRAY_REF:
1241         case COMPONENT_REF:
1242           ctor = fold_const_aggregate_ref (base);
1243           break;
1244
1245         case STRING_CST:
1246         case CONSTRUCTOR:
1247           ctor = base;
1248           break;
1249
1250         default:
1251           return NULL_TREE;
1252         }
1253
1254       if (ctor == NULL_TREE
1255           || (TREE_CODE (ctor) != CONSTRUCTOR
1256               && TREE_CODE (ctor) != STRING_CST)
1257           || !TREE_STATIC (ctor))
1258         return NULL_TREE;
1259
1260       /* Get the index.  If we have an SSA_NAME, try to resolve it
1261          with the current lattice value for the SSA_NAME.  */
1262       idx = TREE_OPERAND (t, 1);
1263       switch (TREE_CODE (idx))
1264         {
1265         case SSA_NAME:
1266           if ((value = get_value (idx))
1267               && value->lattice_val == CONSTANT
1268               && TREE_CODE (value->value) == INTEGER_CST)
1269             idx = value->value;
1270           else
1271             return NULL_TREE;
1272           break;
1273
1274         case INTEGER_CST:
1275           break;
1276
1277         default:
1278           return NULL_TREE;
1279         }
1280
1281       /* Fold read from constant string.  */
1282       if (TREE_CODE (ctor) == STRING_CST)
1283         {
1284           if ((TYPE_MODE (TREE_TYPE (t))
1285                == TYPE_MODE (TREE_TYPE (TREE_TYPE (ctor))))
1286               && (GET_MODE_CLASS (TYPE_MODE (TREE_TYPE (TREE_TYPE (ctor))))
1287                   == MODE_INT)
1288               && GET_MODE_SIZE (TYPE_MODE (TREE_TYPE (TREE_TYPE (ctor)))) == 1
1289               && compare_tree_int (idx, TREE_STRING_LENGTH (ctor)) < 0)
1290             return build_int_cst_type (TREE_TYPE (t),
1291                                        (TREE_STRING_POINTER (ctor)
1292                                         [TREE_INT_CST_LOW (idx)]));
1293           return NULL_TREE;
1294         }
1295
1296       /* Whoo-hoo!  I'll fold ya baby.  Yeah!  */
1297       FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (ctor), cnt, cfield, cval)
1298         if (tree_int_cst_equal (cfield, idx))
1299           {
1300             STRIP_USELESS_TYPE_CONVERSION (cval);
1301             if (TREE_CODE (cval) == ADDR_EXPR)
1302               {
1303                 tree base = get_base_address (TREE_OPERAND (cval, 0));
1304                 if (base && TREE_CODE (base) == VAR_DECL)
1305                   add_referenced_var (base);
1306               }
1307             return cval;
1308           }
1309       break;
1310
1311     case COMPONENT_REF:
1312       /* Get a CONSTRUCTOR.  If BASE is a VAR_DECL, get its
1313          DECL_INITIAL.  If BASE is a nested reference into another
1314          ARRAY_REF or COMPONENT_REF, make a recursive call to resolve
1315          the inner reference.  */
1316       base = TREE_OPERAND (t, 0);
1317       switch (TREE_CODE (base))
1318         {
1319         case VAR_DECL:
1320           if (!TREE_READONLY (base)
1321               || TREE_CODE (TREE_TYPE (base)) != RECORD_TYPE
1322               || !targetm.binds_local_p (base))
1323             return NULL_TREE;
1324
1325           ctor = DECL_INITIAL (base);
1326           break;
1327
1328         case ARRAY_REF:
1329         case COMPONENT_REF:
1330           ctor = fold_const_aggregate_ref (base);
1331           break;
1332
1333         default:
1334           return NULL_TREE;
1335         }
1336
1337       if (ctor == NULL_TREE
1338           || TREE_CODE (ctor) != CONSTRUCTOR
1339           || !TREE_STATIC (ctor))
1340         return NULL_TREE;
1341
1342       field = TREE_OPERAND (t, 1);
1343
1344       FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (ctor), cnt, cfield, cval)
1345         if (cfield == field
1346             /* FIXME: Handle bit-fields.  */
1347             && ! DECL_BIT_FIELD (cfield))
1348           {
1349             STRIP_USELESS_TYPE_CONVERSION (cval);
1350             if (TREE_CODE (cval) == ADDR_EXPR)
1351               {
1352                 tree base = get_base_address (TREE_OPERAND (cval, 0));
1353                 if (base && TREE_CODE (base) == VAR_DECL)
1354                   add_referenced_var (base);
1355               }
1356             return cval;
1357           }
1358       break;
1359
1360     case REALPART_EXPR:
1361     case IMAGPART_EXPR:
1362       {
1363         tree c = fold_const_aggregate_ref (TREE_OPERAND (t, 0));
1364         if (c && TREE_CODE (c) == COMPLEX_CST)
1365           return fold_build1_loc (EXPR_LOCATION (t),
1366                               TREE_CODE (t), TREE_TYPE (t), c);
1367         break;
1368       }
1369
1370     case INDIRECT_REF:
1371       {
1372         tree base = TREE_OPERAND (t, 0);
1373         if (TREE_CODE (base) == SSA_NAME
1374             && (value = get_value (base))
1375             && value->lattice_val == CONSTANT
1376             && TREE_CODE (value->value) == ADDR_EXPR
1377             && useless_type_conversion_p (TREE_TYPE (t),
1378                                           TREE_TYPE (TREE_TYPE (value->value))))
1379           return fold_const_aggregate_ref (TREE_OPERAND (value->value, 0));
1380         break;
1381       }
1382
1383     default:
1384       break;
1385     }
1386
1387   return NULL_TREE;
1388 }
1389
1390 /* Evaluate statement STMT.
1391    Valid only for assignments, calls, conditionals, and switches. */
1392
1393 static prop_value_t
1394 evaluate_stmt (gimple stmt)
1395 {
1396   prop_value_t val;
1397   tree simplified = NULL_TREE;
1398   ccp_lattice_t likelyvalue = likely_value (stmt);
1399   bool is_constant;
1400
1401   fold_defer_overflow_warnings ();
1402
1403   /* If the statement is likely to have a CONSTANT result, then try
1404      to fold the statement to determine the constant value.  */
1405   /* FIXME.  This is the only place that we call ccp_fold.
1406      Since likely_value never returns CONSTANT for calls, we will
1407      not attempt to fold them, including builtins that may profit.  */
1408   if (likelyvalue == CONSTANT)
1409     simplified = ccp_fold (stmt);
1410   /* If the statement is likely to have a VARYING result, then do not
1411      bother folding the statement.  */
1412   else if (likelyvalue == VARYING)
1413     {
1414       enum gimple_code code = gimple_code (stmt);
1415       if (code == GIMPLE_ASSIGN)
1416         {
1417           enum tree_code subcode = gimple_assign_rhs_code (stmt);
1418
1419           /* Other cases cannot satisfy is_gimple_min_invariant
1420              without folding.  */
1421           if (get_gimple_rhs_class (subcode) == GIMPLE_SINGLE_RHS)
1422             simplified = gimple_assign_rhs1 (stmt);
1423         }
1424       else if (code == GIMPLE_SWITCH)
1425         simplified = gimple_switch_index (stmt);
1426       else
1427         /* These cannot satisfy is_gimple_min_invariant without folding.  */
1428         gcc_assert (code == GIMPLE_CALL || code == GIMPLE_COND);
1429     }
1430
1431   is_constant = simplified && is_gimple_min_invariant (simplified);
1432
1433   fold_undefer_overflow_warnings (is_constant, stmt, 0);
1434
1435   if (dump_file && (dump_flags & TDF_DETAILS))
1436     {
1437       fprintf (dump_file, "which is likely ");
1438       switch (likelyvalue)
1439         {
1440         case CONSTANT:
1441           fprintf (dump_file, "CONSTANT");
1442           break;
1443         case UNDEFINED:
1444           fprintf (dump_file, "UNDEFINED");
1445           break;
1446         case VARYING:
1447           fprintf (dump_file, "VARYING");
1448           break;
1449         default:;
1450         }
1451       fprintf (dump_file, "\n");
1452     }
1453
1454   if (is_constant)
1455     {
1456       /* The statement produced a constant value.  */
1457       val.lattice_val = CONSTANT;
1458       val.value = simplified;
1459     }
1460   else
1461     {
1462       /* The statement produced a nonconstant value.  If the statement
1463          had UNDEFINED operands, then the result of the statement
1464          should be UNDEFINED.  Otherwise, the statement is VARYING.  */
1465       if (likelyvalue == UNDEFINED)
1466         val.lattice_val = likelyvalue;
1467       else
1468         val.lattice_val = VARYING;
1469
1470       val.value = NULL_TREE;
1471     }
1472
1473   return val;
1474 }
1475
1476 /* Fold the stmt at *GSI with CCP specific information that propagating
1477    and regular folding does not catch.  */
1478
1479 static bool
1480 ccp_fold_stmt (gimple_stmt_iterator *gsi)
1481 {
1482   gimple stmt = gsi_stmt (*gsi);
1483
1484   switch (gimple_code (stmt))
1485     {
1486     case GIMPLE_COND:
1487       {
1488         prop_value_t val;
1489         /* Statement evaluation will handle type mismatches in constants
1490            more gracefully than the final propagation.  This allows us to
1491            fold more conditionals here.  */
1492         val = evaluate_stmt (stmt);
1493         if (val.lattice_val != CONSTANT
1494             || TREE_CODE (val.value) != INTEGER_CST)
1495           return false;
1496
1497         if (integer_zerop (val.value))
1498           gimple_cond_make_false (stmt);
1499         else
1500           gimple_cond_make_true (stmt);
1501
1502         return true;
1503       }
1504
1505     case GIMPLE_CALL:
1506       {
1507         tree lhs = gimple_call_lhs (stmt);
1508         prop_value_t *val;
1509         tree argt;
1510         bool changed = false;
1511         unsigned i;
1512
1513         /* If the call was folded into a constant make sure it goes
1514            away even if we cannot propagate into all uses because of
1515            type issues.  */
1516         if (lhs
1517             && TREE_CODE (lhs) == SSA_NAME
1518             && (val = get_value (lhs))
1519             && val->lattice_val == CONSTANT)
1520           {
1521             tree new_rhs = unshare_expr (val->value);
1522             bool res;
1523             if (!useless_type_conversion_p (TREE_TYPE (lhs),
1524                                             TREE_TYPE (new_rhs)))
1525               new_rhs = fold_convert (TREE_TYPE (lhs), new_rhs);
1526             res = update_call_from_tree (gsi, new_rhs);
1527             gcc_assert (res);
1528             return true;
1529           }
1530
1531         /* Propagate into the call arguments.  Compared to replace_uses_in
1532            this can use the argument slot types for type verification
1533            instead of the current argument type.  We also can safely
1534            drop qualifiers here as we are dealing with constants anyway.  */
1535         argt = TYPE_ARG_TYPES (TREE_TYPE (TREE_TYPE (gimple_call_fn (stmt))));
1536         for (i = 0; i < gimple_call_num_args (stmt) && argt;
1537              ++i, argt = TREE_CHAIN (argt))
1538           {
1539             tree arg = gimple_call_arg (stmt, i);
1540             if (TREE_CODE (arg) == SSA_NAME
1541                 && (val = get_value (arg))
1542                 && val->lattice_val == CONSTANT
1543                 && useless_type_conversion_p
1544                      (TYPE_MAIN_VARIANT (TREE_VALUE (argt)),
1545                       TYPE_MAIN_VARIANT (TREE_TYPE (val->value))))
1546               {
1547                 gimple_call_set_arg (stmt, i, unshare_expr (val->value));
1548                 changed = true;
1549               }
1550           }
1551
1552         return changed;
1553       }
1554
1555     default:
1556       return false;
1557     }
1558 }
1559
1560 /* Visit the assignment statement STMT.  Set the value of its LHS to the
1561    value computed by the RHS and store LHS in *OUTPUT_P.  If STMT
1562    creates virtual definitions, set the value of each new name to that
1563    of the RHS (if we can derive a constant out of the RHS).
1564    Value-returning call statements also perform an assignment, and
1565    are handled here.  */
1566
1567 static enum ssa_prop_result
1568 visit_assignment (gimple stmt, tree *output_p)
1569 {
1570   prop_value_t val;
1571   enum ssa_prop_result retval;
1572
1573   tree lhs = gimple_get_lhs (stmt);
1574
1575   gcc_assert (gimple_code (stmt) != GIMPLE_CALL
1576               || gimple_call_lhs (stmt) != NULL_TREE);
1577
1578   if (gimple_assign_copy_p (stmt))
1579     {
1580       tree rhs = gimple_assign_rhs1 (stmt);
1581
1582       if  (TREE_CODE (rhs) == SSA_NAME)
1583         {
1584           /* For a simple copy operation, we copy the lattice values.  */
1585           prop_value_t *nval = get_value (rhs);
1586           val = *nval;
1587         }
1588       else
1589         val = evaluate_stmt (stmt);
1590     }
1591   else
1592     /* Evaluate the statement, which could be
1593        either a GIMPLE_ASSIGN or a GIMPLE_CALL.  */
1594     val = evaluate_stmt (stmt);
1595
1596   retval = SSA_PROP_NOT_INTERESTING;
1597
1598   /* Set the lattice value of the statement's output.  */
1599   if (TREE_CODE (lhs) == SSA_NAME)
1600     {
1601       /* If STMT is an assignment to an SSA_NAME, we only have one
1602          value to set.  */
1603       if (set_lattice_value (lhs, val))
1604         {
1605           *output_p = lhs;
1606           if (val.lattice_val == VARYING)
1607             retval = SSA_PROP_VARYING;
1608           else
1609             retval = SSA_PROP_INTERESTING;
1610         }
1611     }
1612
1613   return retval;
1614 }
1615
1616
1617 /* Visit the conditional statement STMT.  Return SSA_PROP_INTERESTING
1618    if it can determine which edge will be taken.  Otherwise, return
1619    SSA_PROP_VARYING.  */
1620
1621 static enum ssa_prop_result
1622 visit_cond_stmt (gimple stmt, edge *taken_edge_p)
1623 {
1624   prop_value_t val;
1625   basic_block block;
1626
1627   block = gimple_bb (stmt);
1628   val = evaluate_stmt (stmt);
1629
1630   /* Find which edge out of the conditional block will be taken and add it
1631      to the worklist.  If no single edge can be determined statically,
1632      return SSA_PROP_VARYING to feed all the outgoing edges to the
1633      propagation engine.  */
1634   *taken_edge_p = val.value ? find_taken_edge (block, val.value) : 0;
1635   if (*taken_edge_p)
1636     return SSA_PROP_INTERESTING;
1637   else
1638     return SSA_PROP_VARYING;
1639 }
1640
1641
1642 /* Evaluate statement STMT.  If the statement produces an output value and
1643    its evaluation changes the lattice value of its output, return
1644    SSA_PROP_INTERESTING and set *OUTPUT_P to the SSA_NAME holding the
1645    output value.
1646
1647    If STMT is a conditional branch and we can determine its truth
1648    value, set *TAKEN_EDGE_P accordingly.  If STMT produces a varying
1649    value, return SSA_PROP_VARYING.  */
1650
1651 static enum ssa_prop_result
1652 ccp_visit_stmt (gimple stmt, edge *taken_edge_p, tree *output_p)
1653 {
1654   tree def;
1655   ssa_op_iter iter;
1656
1657   if (dump_file && (dump_flags & TDF_DETAILS))
1658     {
1659       fprintf (dump_file, "\nVisiting statement:\n");
1660       print_gimple_stmt (dump_file, stmt, 0, dump_flags);
1661     }
1662
1663   switch (gimple_code (stmt))
1664     {
1665       case GIMPLE_ASSIGN:
1666         /* If the statement is an assignment that produces a single
1667            output value, evaluate its RHS to see if the lattice value of
1668            its output has changed.  */
1669         return visit_assignment (stmt, output_p);
1670
1671       case GIMPLE_CALL:
1672         /* A value-returning call also performs an assignment.  */
1673         if (gimple_call_lhs (stmt) != NULL_TREE)
1674           return visit_assignment (stmt, output_p);
1675         break;
1676
1677       case GIMPLE_COND:
1678       case GIMPLE_SWITCH:
1679         /* If STMT is a conditional branch, see if we can determine
1680            which branch will be taken.   */
1681         /* FIXME.  It appears that we should be able to optimize
1682            computed GOTOs here as well.  */
1683         return visit_cond_stmt (stmt, taken_edge_p);
1684
1685       default:
1686         break;
1687     }
1688
1689   /* Any other kind of statement is not interesting for constant
1690      propagation and, therefore, not worth simulating.  */
1691   if (dump_file && (dump_flags & TDF_DETAILS))
1692     fprintf (dump_file, "No interesting values produced.  Marked VARYING.\n");
1693
1694   /* Definitions made by statements other than assignments to
1695      SSA_NAMEs represent unknown modifications to their outputs.
1696      Mark them VARYING.  */
1697   FOR_EACH_SSA_TREE_OPERAND (def, stmt, iter, SSA_OP_ALL_DEFS)
1698     {
1699       prop_value_t v = { VARYING, NULL_TREE };
1700       set_lattice_value (def, v);
1701     }
1702
1703   return SSA_PROP_VARYING;
1704 }
1705
1706
1707 /* Main entry point for SSA Conditional Constant Propagation.  */
1708
1709 static unsigned int
1710 do_ssa_ccp (void)
1711 {
1712   ccp_initialize ();
1713   ssa_propagate (ccp_visit_stmt, ccp_visit_phi_node);
1714   if (ccp_finalize ())
1715     return (TODO_cleanup_cfg | TODO_update_ssa | TODO_remove_unused_locals);
1716   else
1717     return 0;
1718 }
1719
1720
1721 static bool
1722 gate_ccp (void)
1723 {
1724   return flag_tree_ccp != 0;
1725 }
1726
1727
1728 struct gimple_opt_pass pass_ccp =
1729 {
1730  {
1731   GIMPLE_PASS,
1732   "ccp",                                /* name */
1733   gate_ccp,                             /* gate */
1734   do_ssa_ccp,                           /* execute */
1735   NULL,                                 /* sub */
1736   NULL,                                 /* next */
1737   0,                                    /* static_pass_number */
1738   TV_TREE_CCP,                          /* tv_id */
1739   PROP_cfg | PROP_ssa,                  /* properties_required */
1740   0,                                    /* properties_provided */
1741   0,                                    /* properties_destroyed */
1742   0,                                    /* todo_flags_start */
1743   TODO_dump_func | TODO_verify_ssa
1744   | TODO_verify_stmts | TODO_ggc_collect/* todo_flags_finish */
1745  }
1746 };
1747
1748
1749 /* A subroutine of fold_stmt.  Attempts to fold *(A+O) to A[X].
1750    BASE is an array type.  OFFSET is a byte displacement.  ORIG_TYPE
1751    is the desired result type.
1752
1753    LOC is the location of the original expression.  */
1754
1755 static tree
1756 maybe_fold_offset_to_array_ref (location_t loc, tree base, tree offset,
1757                                 tree orig_type,
1758                                 bool allow_negative_idx)
1759 {
1760   tree min_idx, idx, idx_type, elt_offset = integer_zero_node;
1761   tree array_type, elt_type, elt_size;
1762   tree domain_type;
1763
1764   /* If BASE is an ARRAY_REF, we can pick up another offset (this time
1765      measured in units of the size of elements type) from that ARRAY_REF).
1766      We can't do anything if either is variable.
1767
1768      The case we handle here is *(&A[N]+O).  */
1769   if (TREE_CODE (base) == ARRAY_REF)
1770     {
1771       tree low_bound = array_ref_low_bound (base);
1772
1773       elt_offset = TREE_OPERAND (base, 1);
1774       if (TREE_CODE (low_bound) != INTEGER_CST
1775           || TREE_CODE (elt_offset) != INTEGER_CST)
1776         return NULL_TREE;
1777
1778       elt_offset = int_const_binop (MINUS_EXPR, elt_offset, low_bound, 0);
1779       base = TREE_OPERAND (base, 0);
1780     }
1781
1782   /* Ignore stupid user tricks of indexing non-array variables.  */
1783   array_type = TREE_TYPE (base);
1784   if (TREE_CODE (array_type) != ARRAY_TYPE)
1785     return NULL_TREE;
1786   elt_type = TREE_TYPE (array_type);
1787   if (!useless_type_conversion_p (orig_type, elt_type))
1788     return NULL_TREE;
1789
1790   /* Use signed size type for intermediate computation on the index.  */
1791   idx_type = signed_type_for (size_type_node);
1792
1793   /* If OFFSET and ELT_OFFSET are zero, we don't care about the size of the
1794      element type (so we can use the alignment if it's not constant).
1795      Otherwise, compute the offset as an index by using a division.  If the
1796      division isn't exact, then don't do anything.  */
1797   elt_size = TYPE_SIZE_UNIT (elt_type);
1798   if (!elt_size)
1799     return NULL;
1800   if (integer_zerop (offset))
1801     {
1802       if (TREE_CODE (elt_size) != INTEGER_CST)
1803         elt_size = size_int (TYPE_ALIGN (elt_type));
1804
1805       idx = build_int_cst (idx_type, 0);
1806     }
1807   else
1808     {
1809       unsigned HOST_WIDE_INT lquo, lrem;
1810       HOST_WIDE_INT hquo, hrem;
1811       double_int soffset;
1812
1813       /* The final array offset should be signed, so we need
1814          to sign-extend the (possibly pointer) offset here
1815          and use signed division.  */
1816       soffset = double_int_sext (tree_to_double_int (offset),
1817                                  TYPE_PRECISION (TREE_TYPE (offset)));
1818       if (TREE_CODE (elt_size) != INTEGER_CST
1819           || div_and_round_double (TRUNC_DIV_EXPR, 0,
1820                                    soffset.low, soffset.high,
1821                                    TREE_INT_CST_LOW (elt_size),
1822                                    TREE_INT_CST_HIGH (elt_size),
1823                                    &lquo, &hquo, &lrem, &hrem)
1824           || lrem || hrem)
1825         return NULL_TREE;
1826
1827       idx = build_int_cst_wide (idx_type, lquo, hquo);
1828     }
1829
1830   /* Assume the low bound is zero.  If there is a domain type, get the
1831      low bound, if any, convert the index into that type, and add the
1832      low bound.  */
1833   min_idx = build_int_cst (idx_type, 0);
1834   domain_type = TYPE_DOMAIN (array_type);
1835   if (domain_type)
1836     {
1837       idx_type = domain_type;
1838       if (TYPE_MIN_VALUE (idx_type))
1839         min_idx = TYPE_MIN_VALUE (idx_type);
1840       else
1841         min_idx = fold_convert (idx_type, min_idx);
1842
1843       if (TREE_CODE (min_idx) != INTEGER_CST)
1844         return NULL_TREE;
1845
1846       elt_offset = fold_convert (idx_type, elt_offset);
1847     }
1848
1849   if (!integer_zerop (min_idx))
1850     idx = int_const_binop (PLUS_EXPR, idx, min_idx, 0);
1851   if (!integer_zerop (elt_offset))
1852     idx = int_const_binop (PLUS_EXPR, idx, elt_offset, 0);
1853
1854   /* Make sure to possibly truncate late after offsetting.  */
1855   idx = fold_convert (idx_type, idx);
1856
1857   /* We don't want to construct access past array bounds. For example
1858        char *(c[4]);
1859        c[3][2];
1860      should not be simplified into (*c)[14] or tree-vrp will
1861      give false warnings.  The same is true for
1862        struct A { long x; char d[0]; } *a;
1863        (char *)a - 4;
1864      which should be not folded to &a->d[-8].  */
1865   if (domain_type
1866       && TYPE_MAX_VALUE (domain_type)
1867       && TREE_CODE (TYPE_MAX_VALUE (domain_type)) == INTEGER_CST)
1868     {
1869       tree up_bound = TYPE_MAX_VALUE (domain_type);
1870
1871       if (tree_int_cst_lt (up_bound, idx)
1872           /* Accesses after the end of arrays of size 0 (gcc
1873              extension) and 1 are likely intentional ("struct
1874              hack").  */
1875           && compare_tree_int (up_bound, 1) > 0)
1876         return NULL_TREE;
1877     }
1878   if (domain_type
1879       && TYPE_MIN_VALUE (domain_type))
1880     {
1881       if (!allow_negative_idx
1882           && TREE_CODE (TYPE_MIN_VALUE (domain_type)) == INTEGER_CST
1883           && tree_int_cst_lt (idx, TYPE_MIN_VALUE (domain_type)))
1884         return NULL_TREE;
1885     }
1886   else if (!allow_negative_idx
1887            && compare_tree_int (idx, 0) < 0)
1888     return NULL_TREE;
1889
1890   {
1891     tree t = build4 (ARRAY_REF, elt_type, base, idx, NULL_TREE, NULL_TREE);
1892     SET_EXPR_LOCATION (t, loc);
1893     return t;
1894   }
1895 }
1896
1897
1898 /* Attempt to fold *(S+O) to S.X.
1899    BASE is a record type.  OFFSET is a byte displacement.  ORIG_TYPE
1900    is the desired result type.
1901
1902    LOC is the location of the original expression.  */
1903
1904 static tree
1905 maybe_fold_offset_to_component_ref (location_t loc, tree record_type,
1906                                     tree base, tree offset, tree orig_type)
1907 {
1908   tree f, t, field_type, tail_array_field, field_offset;
1909   tree ret;
1910   tree new_base;
1911
1912   if (TREE_CODE (record_type) != RECORD_TYPE
1913       && TREE_CODE (record_type) != UNION_TYPE
1914       && TREE_CODE (record_type) != QUAL_UNION_TYPE)
1915     return NULL_TREE;
1916
1917   /* Short-circuit silly cases.  */
1918   if (useless_type_conversion_p (record_type, orig_type))
1919     return NULL_TREE;
1920
1921   tail_array_field = NULL_TREE;
1922   for (f = TYPE_FIELDS (record_type); f ; f = TREE_CHAIN (f))
1923     {
1924       int cmp;
1925
1926       if (TREE_CODE (f) != FIELD_DECL)
1927         continue;
1928       if (DECL_BIT_FIELD (f))
1929         continue;
1930
1931       if (!DECL_FIELD_OFFSET (f))
1932         continue;
1933       field_offset = byte_position (f);
1934       if (TREE_CODE (field_offset) != INTEGER_CST)
1935         continue;
1936
1937       /* ??? Java creates "interesting" fields for representing base classes.
1938          They have no name, and have no context.  With no context, we get into
1939          trouble with nonoverlapping_component_refs_p.  Skip them.  */
1940       if (!DECL_FIELD_CONTEXT (f))
1941         continue;
1942
1943       /* The previous array field isn't at the end.  */
1944       tail_array_field = NULL_TREE;
1945
1946       /* Check to see if this offset overlaps with the field.  */
1947       cmp = tree_int_cst_compare (field_offset, offset);
1948       if (cmp > 0)
1949         continue;
1950
1951       field_type = TREE_TYPE (f);
1952
1953       /* Here we exactly match the offset being checked.  If the types match,
1954          then we can return that field.  */
1955       if (cmp == 0
1956           && useless_type_conversion_p (orig_type, field_type))
1957         {
1958           t = build3 (COMPONENT_REF, field_type, base, f, NULL_TREE);
1959           return t;
1960         }
1961
1962       /* Don't care about offsets into the middle of scalars.  */
1963       if (!AGGREGATE_TYPE_P (field_type))
1964         continue;
1965
1966       /* Check for array at the end of the struct.  This is often
1967          used as for flexible array members.  We should be able to
1968          turn this into an array access anyway.  */
1969       if (TREE_CODE (field_type) == ARRAY_TYPE)
1970         tail_array_field = f;
1971
1972       /* Check the end of the field against the offset.  */
1973       if (!DECL_SIZE_UNIT (f)
1974           || TREE_CODE (DECL_SIZE_UNIT (f)) != INTEGER_CST)
1975         continue;
1976       t = int_const_binop (MINUS_EXPR, offset, field_offset, 1);
1977       if (!tree_int_cst_lt (t, DECL_SIZE_UNIT (f)))
1978         continue;
1979
1980       /* If we matched, then set offset to the displacement into
1981          this field.  */
1982       new_base = build3 (COMPONENT_REF, field_type, base, f, NULL_TREE);
1983       SET_EXPR_LOCATION (new_base, loc);
1984
1985       /* Recurse to possibly find the match.  */
1986       ret = maybe_fold_offset_to_array_ref (loc, new_base, t, orig_type,
1987                                             f == TYPE_FIELDS (record_type));
1988       if (ret)
1989         return ret;
1990       ret = maybe_fold_offset_to_component_ref (loc, field_type, new_base, t,
1991                                                 orig_type);
1992       if (ret)
1993         return ret;
1994     }
1995
1996   if (!tail_array_field)
1997     return NULL_TREE;
1998
1999   f = tail_array_field;
2000   field_type = TREE_TYPE (f);
2001   offset = int_const_binop (MINUS_EXPR, offset, byte_position (f), 1);
2002
2003   /* If we get here, we've got an aggregate field, and a possibly
2004      nonzero offset into them.  Recurse and hope for a valid match.  */
2005   base = build3 (COMPONENT_REF, field_type, base, f, NULL_TREE);
2006   SET_EXPR_LOCATION (base, loc);
2007
2008   t = maybe_fold_offset_to_array_ref (loc, base, offset, orig_type,
2009                                       f == TYPE_FIELDS (record_type));
2010   if (t)
2011     return t;
2012   return maybe_fold_offset_to_component_ref (loc, field_type, base, offset,
2013                                              orig_type);
2014 }
2015
2016 /* Attempt to express (ORIG_TYPE)BASE+OFFSET as BASE->field_of_orig_type
2017    or BASE[index] or by combination of those.
2018
2019    LOC is the location of original expression.
2020
2021    Before attempting the conversion strip off existing ADDR_EXPRs and
2022    handled component refs.  */
2023
2024 tree
2025 maybe_fold_offset_to_reference (location_t loc, tree base, tree offset,
2026                                 tree orig_type)
2027 {
2028   tree ret;
2029   tree type;
2030
2031   STRIP_NOPS (base);
2032   if (TREE_CODE (base) != ADDR_EXPR)
2033     return NULL_TREE;
2034
2035   base = TREE_OPERAND (base, 0);
2036
2037   /* Handle case where existing COMPONENT_REF pick e.g. wrong field of union,
2038      so it needs to be removed and new COMPONENT_REF constructed.
2039      The wrong COMPONENT_REF are often constructed by folding the
2040      (type *)&object within the expression (type *)&object+offset  */
2041   if (handled_component_p (base))
2042     {
2043       HOST_WIDE_INT sub_offset, size, maxsize;
2044       tree newbase;
2045       newbase = get_ref_base_and_extent (base, &sub_offset,
2046                                          &size, &maxsize);
2047       gcc_assert (newbase);
2048       if (size == maxsize
2049           && size != -1
2050           && !(sub_offset & (BITS_PER_UNIT - 1)))
2051         {
2052           base = newbase;
2053           if (sub_offset)
2054             offset = int_const_binop (PLUS_EXPR, offset,
2055                                       build_int_cst (TREE_TYPE (offset),
2056                                                      sub_offset / BITS_PER_UNIT), 1);
2057         }
2058     }
2059   if (useless_type_conversion_p (orig_type, TREE_TYPE (base))
2060       && integer_zerop (offset))
2061     return base;
2062   type = TREE_TYPE (base);
2063
2064   ret = maybe_fold_offset_to_component_ref (loc, type, base, offset, orig_type);
2065   if (!ret)
2066     ret = maybe_fold_offset_to_array_ref (loc, base, offset, orig_type, true);
2067
2068   return ret;
2069 }
2070
2071 /* Attempt to express (ORIG_TYPE)&BASE+OFFSET as &BASE->field_of_orig_type
2072    or &BASE[index] or by combination of those.
2073
2074    LOC is the location of the original expression.
2075
2076    Before attempting the conversion strip off existing component refs.  */
2077
2078 tree
2079 maybe_fold_offset_to_address (location_t loc, tree addr, tree offset,
2080                               tree orig_type)
2081 {
2082   tree t;
2083
2084   gcc_assert (POINTER_TYPE_P (TREE_TYPE (addr))
2085               && POINTER_TYPE_P (orig_type));
2086
2087   t = maybe_fold_offset_to_reference (loc, addr, offset,
2088                                       TREE_TYPE (orig_type));
2089   if (t != NULL_TREE)
2090     {
2091       tree orig = addr;
2092       tree ptr_type;
2093
2094       /* For __builtin_object_size to function correctly we need to
2095          make sure not to fold address arithmetic so that we change
2096          reference from one array to another.  This would happen for
2097          example for
2098
2099            struct X { char s1[10]; char s2[10] } s;
2100            char *foo (void) { return &s.s2[-4]; }
2101
2102          where we need to avoid generating &s.s1[6].  As the C and
2103          C++ frontends create different initial trees
2104          (char *) &s.s1 + -4  vs.  &s.s1[-4]  we have to do some
2105          sophisticated comparisons here.  Note that checking for the
2106          condition after the fact is easier than trying to avoid doing
2107          the folding.  */
2108       STRIP_NOPS (orig);
2109       if (TREE_CODE (orig) == ADDR_EXPR)
2110         orig = TREE_OPERAND (orig, 0);
2111       if ((TREE_CODE (orig) == ARRAY_REF
2112            || (TREE_CODE (orig) == COMPONENT_REF
2113                && TREE_CODE (TREE_TYPE (TREE_OPERAND (orig, 1))) == ARRAY_TYPE))
2114           && (TREE_CODE (t) == ARRAY_REF
2115               || TREE_CODE (t) == COMPONENT_REF)
2116           && !operand_equal_p (TREE_CODE (orig) == ARRAY_REF
2117                                ? TREE_OPERAND (orig, 0) : orig,
2118                                TREE_CODE (t) == ARRAY_REF
2119                                ? TREE_OPERAND (t, 0) : t, 0))
2120         return NULL_TREE;
2121
2122       ptr_type = build_pointer_type (TREE_TYPE (t));
2123       if (!useless_type_conversion_p (orig_type, ptr_type))
2124         return NULL_TREE;
2125       return build_fold_addr_expr_with_type_loc (loc, t, ptr_type);
2126     }
2127
2128   return NULL_TREE;
2129 }
2130
2131 /* A subroutine of fold_stmt.  Attempt to simplify *(BASE+OFFSET).
2132    Return the simplified expression, or NULL if nothing could be done.  */
2133
2134 static tree
2135 maybe_fold_stmt_indirect (tree expr, tree base, tree offset)
2136 {
2137   tree t;
2138   bool volatile_p = TREE_THIS_VOLATILE (expr);
2139   location_t loc = EXPR_LOCATION (expr);
2140
2141   /* We may well have constructed a double-nested PLUS_EXPR via multiple
2142      substitutions.  Fold that down to one.  Remove NON_LVALUE_EXPRs that
2143      are sometimes added.  */
2144   base = fold (base);
2145   STRIP_TYPE_NOPS (base);
2146   TREE_OPERAND (expr, 0) = base;
2147
2148   /* One possibility is that the address reduces to a string constant.  */
2149   t = fold_read_from_constant_string (expr);
2150   if (t)
2151     return t;
2152
2153   /* Add in any offset from a POINTER_PLUS_EXPR.  */
2154   if (TREE_CODE (base) == POINTER_PLUS_EXPR)
2155     {
2156       tree offset2;
2157
2158       offset2 = TREE_OPERAND (base, 1);
2159       if (TREE_CODE (offset2) != INTEGER_CST)
2160         return NULL_TREE;
2161       base = TREE_OPERAND (base, 0);
2162
2163       offset = fold_convert (sizetype,
2164                              int_const_binop (PLUS_EXPR, offset, offset2, 1));
2165     }
2166
2167   if (TREE_CODE (base) == ADDR_EXPR)
2168     {
2169       tree base_addr = base;
2170
2171       /* Strip the ADDR_EXPR.  */
2172       base = TREE_OPERAND (base, 0);
2173
2174       /* Fold away CONST_DECL to its value, if the type is scalar.  */
2175       if (TREE_CODE (base) == CONST_DECL
2176           && is_gimple_min_invariant (DECL_INITIAL (base)))
2177         return DECL_INITIAL (base);
2178
2179       /* If there is no offset involved simply return the folded base.  */
2180       if (integer_zerop (offset))
2181         return base;
2182
2183       /* Try folding *(&B+O) to B.X.  */
2184       t = maybe_fold_offset_to_reference (loc, base_addr, offset,
2185                                           TREE_TYPE (expr));
2186       if (t)
2187         {
2188           /* Preserve volatileness of the original expression.
2189              We can end up with a plain decl here which is shared
2190              and we shouldn't mess with its flags.  */
2191           if (!SSA_VAR_P (t))
2192             TREE_THIS_VOLATILE (t) = volatile_p;
2193           return t;
2194         }
2195     }
2196   else
2197     {
2198       /* We can get here for out-of-range string constant accesses,
2199          such as "_"[3].  Bail out of the entire substitution search
2200          and arrange for the entire statement to be replaced by a
2201          call to __builtin_trap.  In all likelihood this will all be
2202          constant-folded away, but in the meantime we can't leave with
2203          something that get_expr_operands can't understand.  */
2204
2205       t = base;
2206       STRIP_NOPS (t);
2207       if (TREE_CODE (t) == ADDR_EXPR
2208           && TREE_CODE (TREE_OPERAND (t, 0)) == STRING_CST)
2209         {
2210           /* FIXME: Except that this causes problems elsewhere with dead
2211              code not being deleted, and we die in the rtl expanders
2212              because we failed to remove some ssa_name.  In the meantime,
2213              just return zero.  */
2214           /* FIXME2: This condition should be signaled by
2215              fold_read_from_constant_string directly, rather than
2216              re-checking for it here.  */
2217           return integer_zero_node;
2218         }
2219
2220       /* Try folding *(B+O) to B->X.  Still an improvement.  */
2221       if (POINTER_TYPE_P (TREE_TYPE (base)))
2222         {
2223           t = maybe_fold_offset_to_reference (loc, base, offset,
2224                                               TREE_TYPE (expr));
2225           if (t)
2226             return t;
2227         }
2228     }
2229
2230   /* Otherwise we had an offset that we could not simplify.  */
2231   return NULL_TREE;
2232 }
2233
2234
2235 /* A quaint feature extant in our address arithmetic is that there
2236    can be hidden type changes here.  The type of the result need
2237    not be the same as the type of the input pointer.
2238
2239    What we're after here is an expression of the form
2240         (T *)(&array + const)
2241    where array is OP0, const is OP1, RES_TYPE is T and
2242    the cast doesn't actually exist, but is implicit in the
2243    type of the POINTER_PLUS_EXPR.  We'd like to turn this into
2244         &array[x]
2245    which may be able to propagate further.  */
2246
2247 tree
2248 maybe_fold_stmt_addition (location_t loc, tree res_type, tree op0, tree op1)
2249 {
2250   tree ptd_type;
2251   tree t;
2252
2253   /* The first operand should be an ADDR_EXPR.  */
2254   if (TREE_CODE (op0) != ADDR_EXPR)
2255     return NULL_TREE;
2256   op0 = TREE_OPERAND (op0, 0);
2257
2258   /* It had better be a constant.  */
2259   if (TREE_CODE (op1) != INTEGER_CST)
2260     {
2261       /* Or op0 should now be A[0] and the non-constant offset defined
2262          via a multiplication by the array element size.  */
2263       if (TREE_CODE (op0) == ARRAY_REF
2264           && integer_zerop (TREE_OPERAND (op0, 1))
2265           && TREE_CODE (op1) == SSA_NAME
2266           && host_integerp (TYPE_SIZE_UNIT (TREE_TYPE (op0)), 1))
2267         {
2268           gimple offset_def = SSA_NAME_DEF_STMT (op1);
2269           if (!is_gimple_assign (offset_def))
2270             return NULL_TREE;
2271
2272           if (gimple_assign_rhs_code (offset_def) == MULT_EXPR
2273               && TREE_CODE (gimple_assign_rhs2 (offset_def)) == INTEGER_CST
2274               && tree_int_cst_equal (gimple_assign_rhs2 (offset_def),
2275                                      TYPE_SIZE_UNIT (TREE_TYPE (op0))))
2276             return build_fold_addr_expr
2277                           (build4 (ARRAY_REF, TREE_TYPE (op0),
2278                                    TREE_OPERAND (op0, 0),
2279                                    gimple_assign_rhs1 (offset_def),
2280                                    TREE_OPERAND (op0, 2),
2281                                    TREE_OPERAND (op0, 3)));
2282           else if (integer_onep (TYPE_SIZE_UNIT (TREE_TYPE (op0)))
2283                    && gimple_assign_rhs_code (offset_def) != MULT_EXPR)
2284             return build_fold_addr_expr
2285                           (build4 (ARRAY_REF, TREE_TYPE (op0),
2286                                    TREE_OPERAND (op0, 0),
2287                                    op1,
2288                                    TREE_OPERAND (op0, 2),
2289                                    TREE_OPERAND (op0, 3)));
2290         }
2291       return NULL_TREE;
2292     }
2293
2294   /* If the first operand is an ARRAY_REF, expand it so that we can fold
2295      the offset into it.  */
2296   while (TREE_CODE (op0) == ARRAY_REF)
2297     {
2298       tree array_obj = TREE_OPERAND (op0, 0);
2299       tree array_idx = TREE_OPERAND (op0, 1);
2300       tree elt_type = TREE_TYPE (op0);
2301       tree elt_size = TYPE_SIZE_UNIT (elt_type);
2302       tree min_idx;
2303
2304       if (TREE_CODE (array_idx) != INTEGER_CST)
2305         break;
2306       if (TREE_CODE (elt_size) != INTEGER_CST)
2307         break;
2308
2309       /* Un-bias the index by the min index of the array type.  */
2310       min_idx = TYPE_DOMAIN (TREE_TYPE (array_obj));
2311       if (min_idx)
2312         {
2313           min_idx = TYPE_MIN_VALUE (min_idx);
2314           if (min_idx)
2315             {
2316               if (TREE_CODE (min_idx) != INTEGER_CST)
2317                 break;
2318
2319               array_idx = fold_convert (TREE_TYPE (min_idx), array_idx);
2320               if (!integer_zerop (min_idx))
2321                 array_idx = int_const_binop (MINUS_EXPR, array_idx,
2322                                              min_idx, 0);
2323             }
2324         }
2325
2326       /* Convert the index to a byte offset.  */
2327       array_idx = fold_convert (sizetype, array_idx);
2328       array_idx = int_const_binop (MULT_EXPR, array_idx, elt_size, 0);
2329
2330       /* Update the operands for the next round, or for folding.  */
2331       op1 = int_const_binop (PLUS_EXPR,
2332                              array_idx, op1, 0);
2333       op0 = array_obj;
2334     }
2335
2336   ptd_type = TREE_TYPE (res_type);
2337   /* If we want a pointer to void, reconstruct the reference from the
2338      array element type.  A pointer to that can be trivially converted
2339      to void *.  This happens as we fold (void *)(ptr p+ off).  */
2340   if (VOID_TYPE_P (ptd_type)
2341       && TREE_CODE (TREE_TYPE (op0)) == ARRAY_TYPE)
2342     ptd_type = TREE_TYPE (TREE_TYPE (op0));
2343
2344   /* At which point we can try some of the same things as for indirects.  */
2345   t = maybe_fold_offset_to_array_ref (loc, op0, op1, ptd_type, true);
2346   if (!t)
2347     t = maybe_fold_offset_to_component_ref (loc, TREE_TYPE (op0), op0, op1,
2348                                             ptd_type);
2349   if (t)
2350     {
2351       t = build1 (ADDR_EXPR, res_type, t);
2352       SET_EXPR_LOCATION (t, loc);
2353     }
2354
2355   return t;
2356 }
2357
2358 /* Subroutine of fold_stmt.  We perform several simplifications of the
2359    memory reference tree EXPR and make sure to re-gimplify them properly
2360    after propagation of constant addresses.  IS_LHS is true if the
2361    reference is supposed to be an lvalue.  */
2362
2363 static tree
2364 maybe_fold_reference (tree expr, bool is_lhs)
2365 {
2366   tree *t = &expr;
2367
2368   if (TREE_CODE (expr) == ARRAY_REF
2369       && !is_lhs)
2370     {
2371       tree tem = fold_read_from_constant_string (expr);
2372       if (tem)
2373         return tem;
2374     }
2375
2376   /* ???  We might want to open-code the relevant remaining cases
2377      to avoid using the generic fold.  */
2378   if (handled_component_p (*t)
2379       && CONSTANT_CLASS_P (TREE_OPERAND (*t, 0)))
2380     {
2381       tree tem = fold (*t);
2382       if (tem != *t)
2383         return tem;
2384     }
2385
2386   while (handled_component_p (*t))
2387     t = &TREE_OPERAND (*t, 0);
2388
2389   if (TREE_CODE (*t) == INDIRECT_REF)
2390     {
2391       tree tem = maybe_fold_stmt_indirect (*t, TREE_OPERAND (*t, 0),
2392                                            integer_zero_node);
2393       /* Avoid folding *"abc" = 5 into 'a' = 5.  */
2394       if (is_lhs && tem && CONSTANT_CLASS_P (tem))
2395         tem = NULL_TREE;
2396       if (!tem
2397           && TREE_CODE (TREE_OPERAND (*t, 0)) == ADDR_EXPR)
2398         /* If we had a good reason for propagating the address here,
2399            make sure we end up with valid gimple.  See PR34989.  */
2400         tem = TREE_OPERAND (TREE_OPERAND (*t, 0), 0);
2401
2402       if (tem)
2403         {
2404           *t = tem;
2405           tem = maybe_fold_reference (expr, is_lhs);
2406           if (tem)
2407             return tem;
2408           return expr;
2409         }
2410     }
2411   else if (!is_lhs
2412            && DECL_P (*t))
2413     {
2414       tree tem = get_symbol_constant_value (*t);
2415       if (tem)
2416         {
2417           *t = tem;
2418           tem = maybe_fold_reference (expr, is_lhs);
2419           if (tem)
2420             return tem;
2421           return expr;
2422         }
2423     }
2424
2425   return NULL_TREE;
2426 }
2427
2428
2429 /* Return the string length, maximum string length or maximum value of
2430    ARG in LENGTH.
2431    If ARG is an SSA name variable, follow its use-def chains.  If LENGTH
2432    is not NULL and, for TYPE == 0, its value is not equal to the length
2433    we determine or if we are unable to determine the length or value,
2434    return false.  VISITED is a bitmap of visited variables.
2435    TYPE is 0 if string length should be returned, 1 for maximum string
2436    length and 2 for maximum value ARG can have.  */
2437
2438 static bool
2439 get_maxval_strlen (tree arg, tree *length, bitmap visited, int type)
2440 {
2441   tree var, val;
2442   gimple def_stmt;
2443
2444   if (TREE_CODE (arg) != SSA_NAME)
2445     {
2446       if (TREE_CODE (arg) == COND_EXPR)
2447         return get_maxval_strlen (COND_EXPR_THEN (arg), length, visited, type)
2448                && get_maxval_strlen (COND_EXPR_ELSE (arg), length, visited, type);
2449       /* We can end up with &(*iftmp_1)[0] here as well, so handle it.  */
2450       else if (TREE_CODE (arg) == ADDR_EXPR
2451                && TREE_CODE (TREE_OPERAND (arg, 0)) == ARRAY_REF
2452                && integer_zerop (TREE_OPERAND (TREE_OPERAND (arg, 0), 1)))
2453         {
2454           tree aop0 = TREE_OPERAND (TREE_OPERAND (arg, 0), 0);
2455           if (TREE_CODE (aop0) == INDIRECT_REF
2456               && TREE_CODE (TREE_OPERAND (aop0, 0)) == SSA_NAME)
2457             return get_maxval_strlen (TREE_OPERAND (aop0, 0),
2458                                       length, visited, type);
2459         }
2460
2461       if (type == 2)
2462         {
2463           val = arg;
2464           if (TREE_CODE (val) != INTEGER_CST
2465               || tree_int_cst_sgn (val) < 0)
2466             return false;
2467         }
2468       else
2469         val = c_strlen (arg, 1);
2470       if (!val)
2471         return false;
2472
2473       if (*length)
2474         {
2475           if (type > 0)
2476             {
2477               if (TREE_CODE (*length) != INTEGER_CST
2478                   || TREE_CODE (val) != INTEGER_CST)
2479                 return false;
2480
2481               if (tree_int_cst_lt (*length, val))
2482                 *length = val;
2483               return true;
2484             }
2485           else if (simple_cst_equal (val, *length) != 1)
2486             return false;
2487         }
2488
2489       *length = val;
2490       return true;
2491     }
2492
2493   /* If we were already here, break the infinite cycle.  */
2494   if (bitmap_bit_p (visited, SSA_NAME_VERSION (arg)))
2495     return true;
2496   bitmap_set_bit (visited, SSA_NAME_VERSION (arg));
2497
2498   var = arg;
2499   def_stmt = SSA_NAME_DEF_STMT (var);
2500
2501   switch (gimple_code (def_stmt))
2502     {
2503       case GIMPLE_ASSIGN:
2504         /* The RHS of the statement defining VAR must either have a
2505            constant length or come from another SSA_NAME with a constant
2506            length.  */
2507         if (gimple_assign_single_p (def_stmt)
2508             || gimple_assign_unary_nop_p (def_stmt))
2509           {
2510             tree rhs = gimple_assign_rhs1 (def_stmt);
2511             return get_maxval_strlen (rhs, length, visited, type);
2512           }
2513         return false;
2514
2515       case GIMPLE_PHI:
2516         {
2517           /* All the arguments of the PHI node must have the same constant
2518              length.  */
2519           unsigned i;
2520
2521           for (i = 0; i < gimple_phi_num_args (def_stmt); i++)
2522           {
2523             tree arg = gimple_phi_arg (def_stmt, i)->def;
2524
2525             /* If this PHI has itself as an argument, we cannot
2526                determine the string length of this argument.  However,
2527                if we can find a constant string length for the other
2528                PHI args then we can still be sure that this is a
2529                constant string length.  So be optimistic and just
2530                continue with the next argument.  */
2531             if (arg == gimple_phi_result (def_stmt))
2532               continue;
2533
2534             if (!get_maxval_strlen (arg, length, visited, type))
2535               return false;
2536           }
2537         }
2538         return true;
2539
2540       default:
2541         return false;
2542     }
2543 }
2544
2545
2546 /* Fold builtin call in statement STMT.  Returns a simplified tree.
2547    We may return a non-constant expression, including another call
2548    to a different function and with different arguments, e.g.,
2549    substituting memcpy for strcpy when the string length is known.
2550    Note that some builtins expand into inline code that may not
2551    be valid in GIMPLE.  Callers must take care.  */
2552
2553 static tree
2554 ccp_fold_builtin (gimple stmt)
2555 {
2556   tree result, val[3];
2557   tree callee, a;
2558   int arg_idx, type;
2559   bitmap visited;
2560   bool ignore;
2561   int nargs;
2562   location_t loc = gimple_location (stmt);
2563
2564   gcc_assert (is_gimple_call (stmt));
2565
2566   ignore = (gimple_call_lhs (stmt) == NULL);
2567
2568   /* First try the generic builtin folder.  If that succeeds, return the
2569      result directly.  */
2570   result = fold_call_stmt (stmt, ignore);
2571   if (result)
2572     {
2573       if (ignore)
2574         STRIP_NOPS (result);
2575       return result;
2576     }
2577
2578   /* Ignore MD builtins.  */
2579   callee = gimple_call_fndecl (stmt);
2580   if (DECL_BUILT_IN_CLASS (callee) == BUILT_IN_MD)
2581     return NULL_TREE;
2582
2583   /* If the builtin could not be folded, and it has no argument list,
2584      we're done.  */
2585   nargs = gimple_call_num_args (stmt);
2586   if (nargs == 0)
2587     return NULL_TREE;
2588
2589   /* Limit the work only for builtins we know how to simplify.  */
2590   switch (DECL_FUNCTION_CODE (callee))
2591     {
2592     case BUILT_IN_STRLEN:
2593     case BUILT_IN_FPUTS:
2594     case BUILT_IN_FPUTS_UNLOCKED:
2595       arg_idx = 0;
2596       type = 0;
2597       break;
2598     case BUILT_IN_STRCPY:
2599     case BUILT_IN_STRNCPY:
2600       arg_idx = 1;
2601       type = 0;
2602       break;
2603     case BUILT_IN_MEMCPY_CHK:
2604     case BUILT_IN_MEMPCPY_CHK:
2605     case BUILT_IN_MEMMOVE_CHK:
2606     case BUILT_IN_MEMSET_CHK:
2607     case BUILT_IN_STRNCPY_CHK:
2608       arg_idx = 2;
2609       type = 2;
2610       break;
2611     case BUILT_IN_STRCPY_CHK:
2612     case BUILT_IN_STPCPY_CHK:
2613       arg_idx = 1;
2614       type = 1;
2615       break;
2616     case BUILT_IN_SNPRINTF_CHK:
2617     case BUILT_IN_VSNPRINTF_CHK:
2618       arg_idx = 1;
2619       type = 2;
2620       break;
2621     default:
2622       return NULL_TREE;
2623     }
2624
2625   if (arg_idx >= nargs)
2626     return NULL_TREE;
2627
2628   /* Try to use the dataflow information gathered by the CCP process.  */
2629   visited = BITMAP_ALLOC (NULL);
2630   bitmap_clear (visited);
2631
2632   memset (val, 0, sizeof (val));
2633   a = gimple_call_arg (stmt, arg_idx);
2634   if (!get_maxval_strlen (a, &val[arg_idx], visited, type))
2635     val[arg_idx] = NULL_TREE;
2636
2637   BITMAP_FREE (visited);
2638
2639   result = NULL_TREE;
2640   switch (DECL_FUNCTION_CODE (callee))
2641     {
2642     case BUILT_IN_STRLEN:
2643       if (val[0] && nargs == 1)
2644         {
2645           tree new_val =
2646               fold_convert (TREE_TYPE (gimple_call_lhs (stmt)), val[0]);
2647
2648           /* If the result is not a valid gimple value, or not a cast
2649              of a valid gimple value, then we can not use the result.  */
2650           if (is_gimple_val (new_val)
2651               || (is_gimple_cast (new_val)
2652                   && is_gimple_val (TREE_OPERAND (new_val, 0))))
2653             return new_val;
2654         }
2655       break;
2656
2657     case BUILT_IN_STRCPY:
2658       if (val[1] && is_gimple_val (val[1]) && nargs == 2)
2659         result = fold_builtin_strcpy (loc, callee,
2660                                       gimple_call_arg (stmt, 0),
2661                                       gimple_call_arg (stmt, 1),
2662                                       val[1]);
2663       break;
2664
2665     case BUILT_IN_STRNCPY:
2666       if (val[1] && is_gimple_val (val[1]) && nargs == 3)
2667         result = fold_builtin_strncpy (loc, callee,
2668                                        gimple_call_arg (stmt, 0),
2669                                        gimple_call_arg (stmt, 1),
2670                                        gimple_call_arg (stmt, 2),
2671                                        val[1]);
2672       break;
2673
2674     case BUILT_IN_FPUTS:
2675       if (nargs == 2)
2676         result = fold_builtin_fputs (loc, gimple_call_arg (stmt, 0),
2677                                      gimple_call_arg (stmt, 1),
2678                                      ignore, false, val[0]);
2679       break;
2680
2681     case BUILT_IN_FPUTS_UNLOCKED:
2682       if (nargs == 2)
2683         result = fold_builtin_fputs (loc, gimple_call_arg (stmt, 0),
2684                                      gimple_call_arg (stmt, 1),
2685                                      ignore, true, val[0]);
2686       break;
2687
2688     case BUILT_IN_MEMCPY_CHK:
2689     case BUILT_IN_MEMPCPY_CHK:
2690     case BUILT_IN_MEMMOVE_CHK:
2691     case BUILT_IN_MEMSET_CHK:
2692       if (val[2] && is_gimple_val (val[2]) && nargs == 4)
2693         result = fold_builtin_memory_chk (loc, callee,
2694                                           gimple_call_arg (stmt, 0),
2695                                           gimple_call_arg (stmt, 1),
2696                                           gimple_call_arg (stmt, 2),
2697                                           gimple_call_arg (stmt, 3),
2698                                           val[2], ignore,
2699                                           DECL_FUNCTION_CODE (callee));
2700       break;
2701
2702     case BUILT_IN_STRCPY_CHK:
2703     case BUILT_IN_STPCPY_CHK:
2704       if (val[1] && is_gimple_val (val[1]) && nargs == 3)
2705         result = fold_builtin_stxcpy_chk (loc, callee,
2706                                           gimple_call_arg (stmt, 0),
2707                                           gimple_call_arg (stmt, 1),
2708                                           gimple_call_arg (stmt, 2),
2709                                           val[1], ignore,
2710                                           DECL_FUNCTION_CODE (callee));
2711       break;
2712
2713     case BUILT_IN_STRNCPY_CHK:
2714       if (val[2] && is_gimple_val (val[2]) && nargs == 4)
2715         result = fold_builtin_strncpy_chk (loc, gimple_call_arg (stmt, 0),
2716                                            gimple_call_arg (stmt, 1),
2717                                            gimple_call_arg (stmt, 2),
2718                                            gimple_call_arg (stmt, 3),
2719                                            val[2]);
2720       break;
2721
2722     case BUILT_IN_SNPRINTF_CHK:
2723     case BUILT_IN_VSNPRINTF_CHK:
2724       if (val[1] && is_gimple_val (val[1]))
2725         result = gimple_fold_builtin_snprintf_chk (stmt, val[1],
2726                                                    DECL_FUNCTION_CODE (callee));
2727       break;
2728
2729     default:
2730       gcc_unreachable ();
2731     }
2732
2733   if (result && ignore)
2734     result = fold_ignored_result (result);
2735   return result;
2736 }
2737
2738 /* Attempt to fold an assignment statement pointed-to by SI.  Returns a
2739    replacement rhs for the statement or NULL_TREE if no simplification
2740    could be made.  It is assumed that the operands have been previously
2741    folded.  */
2742
2743 static tree
2744 fold_gimple_assign (gimple_stmt_iterator *si)
2745 {
2746   gimple stmt = gsi_stmt (*si);
2747   enum tree_code subcode = gimple_assign_rhs_code (stmt);
2748   location_t loc = gimple_location (stmt);
2749
2750   tree result = NULL_TREE;
2751
2752   switch (get_gimple_rhs_class (subcode))
2753     {
2754     case GIMPLE_SINGLE_RHS:
2755       {
2756         tree rhs = gimple_assign_rhs1 (stmt);
2757
2758         /* Try to fold a conditional expression.  */
2759         if (TREE_CODE (rhs) == COND_EXPR)
2760           {
2761             tree op0 = COND_EXPR_COND (rhs);
2762             tree tem;
2763             bool set = false;
2764             location_t cond_loc = EXPR_LOCATION (rhs);
2765
2766             if (COMPARISON_CLASS_P (op0))
2767               {
2768                 fold_defer_overflow_warnings ();
2769                 tem = fold_binary_loc (cond_loc,
2770                                    TREE_CODE (op0), TREE_TYPE (op0),
2771                                    TREE_OPERAND (op0, 0),
2772                                    TREE_OPERAND (op0, 1));
2773                 /* This is actually a conditional expression, not a GIMPLE
2774                    conditional statement, however, the valid_gimple_rhs_p
2775                    test still applies.  */
2776                 set = (tem && is_gimple_condexpr (tem)
2777                        && valid_gimple_rhs_p (tem));
2778                 fold_undefer_overflow_warnings (set, stmt, 0);
2779               }
2780             else if (is_gimple_min_invariant (op0))
2781               {
2782                 tem = op0;
2783                 set = true;
2784               }
2785             else
2786               return NULL_TREE;
2787
2788             if (set)
2789               result = fold_build3_loc (cond_loc, COND_EXPR, TREE_TYPE (rhs), tem,
2790                                     COND_EXPR_THEN (rhs), COND_EXPR_ELSE (rhs));
2791           }
2792
2793         else if (TREE_CODE (rhs) == TARGET_MEM_REF)
2794           return maybe_fold_tmr (rhs);
2795
2796         else if (REFERENCE_CLASS_P (rhs))
2797           return maybe_fold_reference (rhs, false);
2798
2799         else if (TREE_CODE (rhs) == ADDR_EXPR)
2800           {
2801             tree tem = maybe_fold_reference (TREE_OPERAND (rhs, 0), true);
2802             if (tem)
2803               result = fold_convert (TREE_TYPE (rhs),
2804                                      build_fold_addr_expr_loc (loc, tem));
2805           }
2806
2807         else if (TREE_CODE (rhs) == CONSTRUCTOR
2808                  && TREE_CODE (TREE_TYPE (rhs)) == VECTOR_TYPE
2809                  && (CONSTRUCTOR_NELTS (rhs)
2810                      == TYPE_VECTOR_SUBPARTS (TREE_TYPE (rhs))))
2811           {
2812             /* Fold a constant vector CONSTRUCTOR to VECTOR_CST.  */
2813             unsigned i;
2814             tree val;
2815
2816             FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (rhs), i, val)
2817               if (TREE_CODE (val) != INTEGER_CST
2818                   && TREE_CODE (val) != REAL_CST
2819                   && TREE_CODE (val) != FIXED_CST)
2820                 return NULL_TREE;
2821
2822             return build_vector_from_ctor (TREE_TYPE (rhs),
2823                                            CONSTRUCTOR_ELTS (rhs));
2824           }
2825
2826         else if (DECL_P (rhs))
2827           return get_symbol_constant_value (rhs);
2828
2829         /* If we couldn't fold the RHS, hand over to the generic
2830            fold routines.  */
2831         if (result == NULL_TREE)
2832           result = fold (rhs);
2833
2834         /* Strip away useless type conversions.  Both the NON_LVALUE_EXPR
2835            that may have been added by fold, and "useless" type
2836            conversions that might now be apparent due to propagation.  */
2837         STRIP_USELESS_TYPE_CONVERSION (result);
2838
2839         if (result != rhs && valid_gimple_rhs_p (result))
2840           return result;
2841
2842         return NULL_TREE;
2843       }
2844       break;
2845
2846     case GIMPLE_UNARY_RHS:
2847       {
2848         tree rhs = gimple_assign_rhs1 (stmt);
2849
2850         result = fold_unary_loc (loc, subcode, gimple_expr_type (stmt), rhs);
2851         if (result)
2852           {
2853             /* If the operation was a conversion do _not_ mark a
2854                resulting constant with TREE_OVERFLOW if the original
2855                constant was not.  These conversions have implementation
2856                defined behavior and retaining the TREE_OVERFLOW flag
2857                here would confuse later passes such as VRP.  */
2858             if (CONVERT_EXPR_CODE_P (subcode)
2859                 && TREE_CODE (result) == INTEGER_CST
2860                 && TREE_CODE (rhs) == INTEGER_CST)
2861               TREE_OVERFLOW (result) = TREE_OVERFLOW (rhs);
2862
2863             STRIP_USELESS_TYPE_CONVERSION (result);
2864             if (valid_gimple_rhs_p (result))
2865               return result;
2866           }
2867         else if (CONVERT_EXPR_CODE_P (subcode)
2868                  && POINTER_TYPE_P (gimple_expr_type (stmt))
2869                  && POINTER_TYPE_P (TREE_TYPE (gimple_assign_rhs1 (stmt))))
2870           {
2871             tree type = gimple_expr_type (stmt);
2872             tree t = maybe_fold_offset_to_address (loc,
2873                                                    gimple_assign_rhs1 (stmt),
2874                                                    integer_zero_node, type);
2875             if (t)
2876               return t;
2877           }
2878       }
2879       break;
2880
2881     case GIMPLE_BINARY_RHS:
2882       /* Try to fold pointer addition.  */
2883       if (gimple_assign_rhs_code (stmt) == POINTER_PLUS_EXPR)
2884         {
2885           tree type = TREE_TYPE (gimple_assign_rhs1 (stmt));
2886           if (TREE_CODE (TREE_TYPE (type)) == ARRAY_TYPE)
2887             {
2888               type = build_pointer_type (TREE_TYPE (TREE_TYPE (type)));
2889               if (!useless_type_conversion_p
2890                     (TREE_TYPE (gimple_assign_lhs (stmt)), type))
2891                 type = TREE_TYPE (gimple_assign_rhs1 (stmt));
2892             }
2893           result = maybe_fold_stmt_addition (gimple_location (stmt),
2894                                              type,
2895                                              gimple_assign_rhs1 (stmt),
2896                                              gimple_assign_rhs2 (stmt));
2897         }
2898
2899       if (!result)
2900         result = fold_binary_loc (loc, subcode,
2901                               TREE_TYPE (gimple_assign_lhs (stmt)),
2902                               gimple_assign_rhs1 (stmt),
2903                               gimple_assign_rhs2 (stmt));
2904
2905       if (result)
2906         {
2907           STRIP_USELESS_TYPE_CONVERSION (result);
2908           if (valid_gimple_rhs_p (result))
2909             return result;
2910
2911           /* Fold might have produced non-GIMPLE, so if we trust it blindly
2912              we lose canonicalization opportunities.  Do not go again
2913              through fold here though, or the same non-GIMPLE will be
2914              produced.  */
2915           if (commutative_tree_code (subcode)
2916               && tree_swap_operands_p (gimple_assign_rhs1 (stmt),
2917                                        gimple_assign_rhs2 (stmt), false))
2918             return build2 (subcode, TREE_TYPE (gimple_assign_lhs (stmt)),
2919                            gimple_assign_rhs2 (stmt),
2920                            gimple_assign_rhs1 (stmt));
2921         }
2922       break;
2923
2924     case GIMPLE_INVALID_RHS:
2925       gcc_unreachable ();
2926     }
2927
2928   return NULL_TREE;
2929 }
2930
2931 /* Attempt to fold a conditional statement. Return true if any changes were
2932    made. We only attempt to fold the condition expression, and do not perform
2933    any transformation that would require alteration of the cfg.  It is
2934    assumed that the operands have been previously folded.  */
2935
2936 static bool
2937 fold_gimple_cond (gimple stmt)
2938 {
2939   tree result = fold_binary_loc (gimple_location (stmt),
2940                              gimple_cond_code (stmt),
2941                              boolean_type_node,
2942                              gimple_cond_lhs (stmt),
2943                              gimple_cond_rhs (stmt));
2944
2945   if (result)
2946     {
2947       STRIP_USELESS_TYPE_CONVERSION (result);
2948       if (is_gimple_condexpr (result) && valid_gimple_rhs_p (result))
2949         {
2950           gimple_cond_set_condition_from_tree (stmt, result);
2951           return true;
2952         }
2953     }
2954
2955   return false;
2956 }
2957
2958 static void gimplify_and_update_call_from_tree (gimple_stmt_iterator *, tree);
2959
2960 /* Attempt to fold a call statement referenced by the statement iterator GSI.
2961    The statement may be replaced by another statement, e.g., if the call
2962    simplifies to a constant value. Return true if any changes were made.
2963    It is assumed that the operands have been previously folded.  */
2964
2965 static bool
2966 fold_gimple_call (gimple_stmt_iterator *gsi)
2967 {
2968   gimple stmt = gsi_stmt (*gsi);
2969
2970   tree callee = gimple_call_fndecl (stmt);
2971
2972   /* Check for builtins that CCP can handle using information not
2973      available in the generic fold routines.  */
2974   if (callee && DECL_BUILT_IN (callee))
2975     {
2976       tree result = ccp_fold_builtin (stmt);
2977
2978       if (result)
2979         {
2980           if (!update_call_from_tree (gsi, result))
2981             gimplify_and_update_call_from_tree (gsi, result);
2982           return true;
2983         }
2984     }
2985   else
2986     {
2987       /* Check for resolvable OBJ_TYPE_REF.  The only sorts we can resolve
2988          here are when we've propagated the address of a decl into the
2989          object slot.  */
2990       /* ??? Should perhaps do this in fold proper.  However, doing it
2991          there requires that we create a new CALL_EXPR, and that requires
2992          copying EH region info to the new node.  Easier to just do it
2993          here where we can just smash the call operand.  */
2994       /* ??? Is there a good reason not to do this in fold_stmt_inplace?  */
2995       callee = gimple_call_fn (stmt);
2996       if (TREE_CODE (callee) == OBJ_TYPE_REF
2997           && lang_hooks.fold_obj_type_ref
2998           && TREE_CODE (OBJ_TYPE_REF_OBJECT (callee)) == ADDR_EXPR
2999           && DECL_P (TREE_OPERAND
3000                      (OBJ_TYPE_REF_OBJECT (callee), 0)))
3001         {
3002           tree t;
3003
3004           /* ??? Caution: Broken ADDR_EXPR semantics means that
3005              looking at the type of the operand of the addr_expr
3006              can yield an array type.  See silly exception in
3007              check_pointer_types_r.  */
3008           t = TREE_TYPE (TREE_TYPE (OBJ_TYPE_REF_OBJECT (callee)));
3009           t = lang_hooks.fold_obj_type_ref (callee, t);
3010           if (t)
3011             {
3012               gimple_call_set_fn (stmt, t);
3013               return true;
3014             }
3015         }
3016     }
3017
3018   return false;
3019 }
3020
3021 /* Worker for both fold_stmt and fold_stmt_inplace.  The INPLACE argument
3022    distinguishes both cases.  */
3023
3024 static bool
3025 fold_stmt_1 (gimple_stmt_iterator *gsi, bool inplace)
3026 {
3027   bool changed = false;
3028   gimple stmt = gsi_stmt (*gsi);
3029   unsigned i;
3030
3031   /* Fold the main computation performed by the statement.  */
3032   switch (gimple_code (stmt))
3033     {
3034     case GIMPLE_ASSIGN:
3035       {
3036         unsigned old_num_ops = gimple_num_ops (stmt);
3037         tree new_rhs = fold_gimple_assign (gsi);
3038         if (new_rhs != NULL_TREE
3039             && (!inplace
3040                 || get_gimple_rhs_num_ops (TREE_CODE (new_rhs)) < old_num_ops))
3041           {
3042             gimple_assign_set_rhs_from_tree (gsi, new_rhs);
3043             changed = true;
3044           }
3045         break;
3046       }
3047
3048     case GIMPLE_COND:
3049       changed |= fold_gimple_cond (stmt);
3050       break;
3051
3052     case GIMPLE_CALL:
3053       /* Fold *& in call arguments.  */
3054       for (i = 0; i < gimple_call_num_args (stmt); ++i)
3055         if (REFERENCE_CLASS_P (gimple_call_arg (stmt, i)))
3056           {
3057             tree tmp = maybe_fold_reference (gimple_call_arg (stmt, i), false);
3058             if (tmp)
3059               {
3060                 gimple_call_set_arg (stmt, i, tmp);
3061                 changed = true;
3062               }
3063           }
3064       /* The entire statement may be replaced in this case.  */
3065       if (!inplace)
3066         changed |= fold_gimple_call (gsi);
3067       break;
3068
3069     case GIMPLE_ASM:
3070       /* Fold *& in asm operands.  */
3071       for (i = 0; i < gimple_asm_noutputs (stmt); ++i)
3072         {
3073           tree link = gimple_asm_output_op (stmt, i);
3074           tree op = TREE_VALUE (link);
3075           if (REFERENCE_CLASS_P (op)
3076               && (op = maybe_fold_reference (op, true)) != NULL_TREE)
3077             {
3078               TREE_VALUE (link) = op;
3079               changed = true;
3080             }
3081         }
3082       for (i = 0; i < gimple_asm_ninputs (stmt); ++i)
3083         {
3084           tree link = gimple_asm_input_op (stmt, i);
3085           tree op = TREE_VALUE (link);
3086           if (REFERENCE_CLASS_P (op)
3087               && (op = maybe_fold_reference (op, false)) != NULL_TREE)
3088             {
3089               TREE_VALUE (link) = op;
3090               changed = true;
3091             }
3092         }
3093       break;
3094
3095     default:;
3096     }
3097
3098   stmt = gsi_stmt (*gsi);
3099
3100   /* Fold *& on the lhs.  */
3101   if (gimple_has_lhs (stmt))
3102     {
3103       tree lhs = gimple_get_lhs (stmt);
3104       if (lhs && REFERENCE_CLASS_P (lhs))
3105         {
3106           tree new_lhs = maybe_fold_reference (lhs, true);
3107           if (new_lhs)
3108             {
3109               gimple_set_lhs (stmt, new_lhs);
3110               changed = true;
3111             }
3112         }
3113     }
3114
3115   return changed;
3116 }
3117
3118 /* Fold the statement pointed to by GSI.  In some cases, this function may
3119    replace the whole statement with a new one.  Returns true iff folding
3120    makes any changes.
3121    The statement pointed to by GSI should be in valid gimple form but may
3122    be in unfolded state as resulting from for example constant propagation
3123    which can produce *&x = 0.  */
3124
3125 bool
3126 fold_stmt (gimple_stmt_iterator *gsi)
3127 {
3128   return fold_stmt_1 (gsi, false);
3129 }
3130
3131 /* Perform the minimal folding on statement STMT.  Only operations like
3132    *&x created by constant propagation are handled.  The statement cannot
3133    be replaced with a new one.  Return true if the statement was
3134    changed, false otherwise.
3135    The statement STMT should be in valid gimple form but may
3136    be in unfolded state as resulting from for example constant propagation
3137    which can produce *&x = 0.  */
3138
3139 bool
3140 fold_stmt_inplace (gimple stmt)
3141 {
3142   gimple_stmt_iterator gsi = gsi_for_stmt (stmt);
3143   bool changed = fold_stmt_1 (&gsi, true);
3144   gcc_assert (gsi_stmt (gsi) == stmt);
3145   return changed;
3146 }
3147
3148 /* Try to optimize out __builtin_stack_restore.  Optimize it out
3149    if there is another __builtin_stack_restore in the same basic
3150    block and no calls or ASM_EXPRs are in between, or if this block's
3151    only outgoing edge is to EXIT_BLOCK and there are no calls or
3152    ASM_EXPRs after this __builtin_stack_restore.  */
3153
3154 static tree
3155 optimize_stack_restore (gimple_stmt_iterator i)
3156 {
3157   tree callee;
3158   gimple stmt;
3159
3160   basic_block bb = gsi_bb (i);
3161   gimple call = gsi_stmt (i);
3162
3163   if (gimple_code (call) != GIMPLE_CALL
3164       || gimple_call_num_args (call) != 1
3165       || TREE_CODE (gimple_call_arg (call, 0)) != SSA_NAME
3166       || !POINTER_TYPE_P (TREE_TYPE (gimple_call_arg (call, 0))))
3167     return NULL_TREE;
3168
3169   for (gsi_next (&i); !gsi_end_p (i); gsi_next (&i))
3170     {
3171       stmt = gsi_stmt (i);
3172       if (gimple_code (stmt) == GIMPLE_ASM)
3173         return NULL_TREE;
3174       if (gimple_code (stmt) != GIMPLE_CALL)
3175         continue;
3176
3177       callee = gimple_call_fndecl (stmt);
3178       if (!callee || DECL_BUILT_IN_CLASS (callee) != BUILT_IN_NORMAL)
3179         return NULL_TREE;
3180
3181       if (DECL_FUNCTION_CODE (callee) == BUILT_IN_STACK_RESTORE)
3182         goto second_stack_restore;
3183     }
3184
3185   if (!gsi_end_p (i))
3186     return NULL_TREE;
3187
3188   /* Allow one successor of the exit block, or zero successors.  */
3189   switch (EDGE_COUNT (bb->succs))
3190     {
3191     case 0:
3192       break;
3193     case 1:
3194       if (single_succ_edge (bb)->dest != EXIT_BLOCK_PTR)
3195         return NULL_TREE;
3196       break;
3197     default:
3198       return NULL_TREE;
3199     }
3200  second_stack_restore:
3201
3202   /* If there's exactly one use, then zap the call to __builtin_stack_save.
3203      If there are multiple uses, then the last one should remove the call.
3204      In any case, whether the call to __builtin_stack_save can be removed
3205      or not is irrelevant to removing the call to __builtin_stack_restore.  */
3206   if (has_single_use (gimple_call_arg (call, 0)))
3207     {
3208       gimple stack_save = SSA_NAME_DEF_STMT (gimple_call_arg (call, 0));
3209       if (is_gimple_call (stack_save))
3210         {
3211           callee = gimple_call_fndecl (stack_save);
3212           if (callee
3213               && DECL_BUILT_IN_CLASS (callee) == BUILT_IN_NORMAL
3214               && DECL_FUNCTION_CODE (callee) == BUILT_IN_STACK_SAVE)
3215             {
3216               gimple_stmt_iterator stack_save_gsi;
3217               tree rhs;
3218
3219               stack_save_gsi = gsi_for_stmt (stack_save);
3220               rhs = build_int_cst (TREE_TYPE (gimple_call_arg (call, 0)), 0);
3221               update_call_from_tree (&stack_save_gsi, rhs);
3222             }
3223         }
3224     }
3225
3226   /* No effect, so the statement will be deleted.  */
3227   return integer_zero_node;
3228 }
3229
3230 /* If va_list type is a simple pointer and nothing special is needed,
3231    optimize __builtin_va_start (&ap, 0) into ap = __builtin_next_arg (0),
3232    __builtin_va_end (&ap) out as NOP and __builtin_va_copy into a simple
3233    pointer assignment.  */
3234
3235 static tree
3236 optimize_stdarg_builtin (gimple call)
3237 {
3238   tree callee, lhs, rhs, cfun_va_list;
3239   bool va_list_simple_ptr;
3240   location_t loc = gimple_location (call);
3241
3242   if (gimple_code (call) != GIMPLE_CALL)
3243     return NULL_TREE;
3244
3245   callee = gimple_call_fndecl (call);
3246
3247   cfun_va_list = targetm.fn_abi_va_list (callee);
3248   va_list_simple_ptr = POINTER_TYPE_P (cfun_va_list)
3249                        && (TREE_TYPE (cfun_va_list) == void_type_node
3250                            || TREE_TYPE (cfun_va_list) == char_type_node);
3251
3252   switch (DECL_FUNCTION_CODE (callee))
3253     {
3254     case BUILT_IN_VA_START:
3255       if (!va_list_simple_ptr
3256           || targetm.expand_builtin_va_start != NULL
3257           || built_in_decls[BUILT_IN_NEXT_ARG] == NULL)
3258         return NULL_TREE;
3259
3260       if (gimple_call_num_args (call) != 2)
3261         return NULL_TREE;
3262
3263       lhs = gimple_call_arg (call, 0);
3264       if (!POINTER_TYPE_P (TREE_TYPE (lhs))
3265           || TYPE_MAIN_VARIANT (TREE_TYPE (TREE_TYPE (lhs)))
3266              != TYPE_MAIN_VARIANT (cfun_va_list))
3267         return NULL_TREE;
3268
3269       lhs = build_fold_indirect_ref_loc (loc, lhs);
3270       rhs = build_call_expr_loc (loc, built_in_decls[BUILT_IN_NEXT_ARG],
3271                              1, integer_zero_node);
3272       rhs = fold_convert_loc (loc, TREE_TYPE (lhs), rhs);
3273       return build2 (MODIFY_EXPR, TREE_TYPE (lhs), lhs, rhs);
3274
3275     case BUILT_IN_VA_COPY:
3276       if (!va_list_simple_ptr)
3277         return NULL_TREE;
3278
3279       if (gimple_call_num_args (call) != 2)
3280         return NULL_TREE;
3281
3282       lhs = gimple_call_arg (call, 0);
3283       if (!POINTER_TYPE_P (TREE_TYPE (lhs))
3284           || TYPE_MAIN_VARIANT (TREE_TYPE (TREE_TYPE (lhs)))
3285              != TYPE_MAIN_VARIANT (cfun_va_list))
3286         return NULL_TREE;
3287
3288       lhs = build_fold_indirect_ref_loc (loc, lhs);
3289       rhs = gimple_call_arg (call, 1);
3290       if (TYPE_MAIN_VARIANT (TREE_TYPE (rhs))
3291           != TYPE_MAIN_VARIANT (cfun_va_list))
3292         return NULL_TREE;
3293
3294       rhs = fold_convert_loc (loc, TREE_TYPE (lhs), rhs);
3295       return build2 (MODIFY_EXPR, TREE_TYPE (lhs), lhs, rhs);
3296
3297     case BUILT_IN_VA_END:
3298       /* No effect, so the statement will be deleted.  */
3299       return integer_zero_node;
3300
3301     default:
3302       gcc_unreachable ();
3303     }
3304 }
3305
3306 /* Convert EXPR into a GIMPLE value suitable for substitution on the
3307    RHS of an assignment.  Insert the necessary statements before
3308    iterator *SI_P.  The statement at *SI_P, which must be a GIMPLE_CALL
3309    is replaced.  If the call is expected to produces a result, then it
3310    is replaced by an assignment of the new RHS to the result variable.
3311    If the result is to be ignored, then the call is replaced by a
3312    GIMPLE_NOP.  */
3313
3314 static void
3315 gimplify_and_update_call_from_tree (gimple_stmt_iterator *si_p, tree expr)
3316 {
3317   tree lhs;
3318   tree tmp = NULL_TREE;  /* Silence warning.  */
3319   gimple stmt, new_stmt;
3320   gimple_stmt_iterator i;
3321   gimple_seq stmts = gimple_seq_alloc();
3322   struct gimplify_ctx gctx;
3323
3324   stmt = gsi_stmt (*si_p);
3325
3326   gcc_assert (is_gimple_call (stmt));
3327
3328   lhs = gimple_call_lhs (stmt);
3329
3330   push_gimplify_context (&gctx);
3331
3332   if (lhs == NULL_TREE)
3333     gimplify_and_add (expr, &stmts);
3334   else
3335     tmp = get_initialized_tmp_var (expr, &stmts, NULL);
3336
3337   pop_gimplify_context (NULL);
3338
3339   if (gimple_has_location (stmt))
3340     annotate_all_with_location (stmts, gimple_location (stmt));
3341
3342   /* The replacement can expose previously unreferenced variables.  */
3343   for (i = gsi_start (stmts); !gsi_end_p (i); gsi_next (&i))
3344   {
3345     new_stmt = gsi_stmt (i);
3346     find_new_referenced_vars (new_stmt);
3347     gsi_insert_before (si_p, new_stmt, GSI_NEW_STMT);
3348     mark_symbols_for_renaming (new_stmt);
3349     gsi_next (si_p);
3350   }
3351
3352   if (lhs == NULL_TREE)
3353     {
3354       new_stmt = gimple_build_nop ();
3355       unlink_stmt_vdef (stmt);
3356       release_defs (stmt);
3357     }
3358   else
3359     {
3360       new_stmt = gimple_build_assign (lhs, tmp);
3361       gimple_set_vuse (new_stmt, gimple_vuse (stmt));
3362       gimple_set_vdef (new_stmt, gimple_vdef (stmt));
3363       move_ssa_defining_stmt_for_defs (new_stmt, stmt);
3364     }
3365
3366   gimple_set_location (new_stmt, gimple_location (stmt));
3367   gsi_replace (si_p, new_stmt, false);
3368 }
3369
3370 /* A simple pass that attempts to fold all builtin functions.  This pass
3371    is run after we've propagated as many constants as we can.  */
3372
3373 static unsigned int
3374 execute_fold_all_builtins (void)
3375 {
3376   bool cfg_changed = false;
3377   basic_block bb;
3378   unsigned int todoflags = 0;
3379
3380   FOR_EACH_BB (bb)
3381     {
3382       gimple_stmt_iterator i;
3383       for (i = gsi_start_bb (bb); !gsi_end_p (i); )
3384         {
3385           gimple stmt, old_stmt;
3386           tree callee, result;
3387           enum built_in_function fcode;
3388
3389           stmt = gsi_stmt (i);
3390
3391           if (gimple_code (stmt) != GIMPLE_CALL)
3392             {
3393               gsi_next (&i);
3394               continue;
3395             }
3396           callee = gimple_call_fndecl (stmt);
3397           if (!callee || DECL_BUILT_IN_CLASS (callee) != BUILT_IN_NORMAL)
3398             {
3399               gsi_next (&i);
3400               continue;
3401             }
3402           fcode = DECL_FUNCTION_CODE (callee);
3403
3404           result = ccp_fold_builtin (stmt);
3405
3406           if (result)
3407             gimple_remove_stmt_histograms (cfun, stmt);
3408
3409           if (!result)
3410             switch (DECL_FUNCTION_CODE (callee))
3411               {
3412               case BUILT_IN_CONSTANT_P:
3413                 /* Resolve __builtin_constant_p.  If it hasn't been
3414                    folded to integer_one_node by now, it's fairly
3415                    certain that the value simply isn't constant.  */
3416                 result = integer_zero_node;
3417                 break;
3418
3419               case BUILT_IN_STACK_RESTORE:
3420                 result = optimize_stack_restore (i);
3421                 if (result)
3422                   break;
3423                 gsi_next (&i);
3424                 continue;
3425
3426               case BUILT_IN_VA_START:
3427               case BUILT_IN_VA_END:
3428               case BUILT_IN_VA_COPY:
3429                 /* These shouldn't be folded before pass_stdarg.  */
3430                 result = optimize_stdarg_builtin (stmt);
3431                 if (result)
3432                   break;
3433                 /* FALLTHRU */
3434
3435               default:
3436                 gsi_next (&i);
3437                 continue;
3438               }
3439
3440           if (dump_file && (dump_flags & TDF_DETAILS))
3441             {
3442               fprintf (dump_file, "Simplified\n  ");
3443               print_gimple_stmt (dump_file, stmt, 0, dump_flags);
3444             }
3445
3446           old_stmt = stmt;
3447           if (!update_call_from_tree (&i, result))
3448             {
3449               gimplify_and_update_call_from_tree (&i, result);
3450               todoflags |= TODO_update_address_taken;
3451             }
3452
3453           stmt = gsi_stmt (i);
3454           update_stmt (stmt);
3455
3456           if (maybe_clean_or_replace_eh_stmt (old_stmt, stmt)
3457               && gimple_purge_dead_eh_edges (bb))
3458             cfg_changed = true;
3459
3460           if (dump_file && (dump_flags & TDF_DETAILS))
3461             {
3462               fprintf (dump_file, "to\n  ");
3463               print_gimple_stmt (dump_file, stmt, 0, dump_flags);
3464               fprintf (dump_file, "\n");
3465             }
3466
3467           /* Retry the same statement if it changed into another
3468              builtin, there might be new opportunities now.  */
3469           if (gimple_code (stmt) != GIMPLE_CALL)
3470             {
3471               gsi_next (&i);
3472               continue;
3473             }
3474           callee = gimple_call_fndecl (stmt);
3475           if (!callee
3476               || DECL_BUILT_IN_CLASS (callee) != BUILT_IN_NORMAL
3477               || DECL_FUNCTION_CODE (callee) == fcode)
3478             gsi_next (&i);
3479         }
3480     }
3481
3482   /* Delete unreachable blocks.  */
3483   if (cfg_changed)
3484     todoflags |= TODO_cleanup_cfg;
3485
3486   return todoflags;
3487 }
3488
3489
3490 struct gimple_opt_pass pass_fold_builtins =
3491 {
3492  {
3493   GIMPLE_PASS,
3494   "fab",                                /* name */
3495   NULL,                                 /* gate */
3496   execute_fold_all_builtins,            /* execute */
3497   NULL,                                 /* sub */
3498   NULL,                                 /* next */
3499   0,                                    /* static_pass_number */
3500   TV_NONE,                              /* tv_id */
3501   PROP_cfg | PROP_ssa,                  /* properties_required */
3502   0,                                    /* properties_provided */
3503   0,                                    /* properties_destroyed */
3504   0,                                    /* todo_flags_start */
3505   TODO_dump_func
3506     | TODO_verify_ssa
3507     | TODO_update_ssa                   /* todo_flags_finish */
3508  }
3509 };