OSDN Git Service

* tree-ssa-propagate.c (cfg_blocks_add) Assert we're not trying
[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 Free Software Foundation, Inc.
3    Adapted from original RTL SSA-CCP by Daniel Berlin <dberlin@dberlin.org>
4    Adapted to GIMPLE trees by Diego Novillo <dnovillo@redhat.com>
5
6 This file is part of GCC.
7    
8 GCC is free software; you can redistribute it and/or modify it
9 under the terms of the GNU General Public License as published by the
10 Free Software Foundation; either version 2, or (at your option) any
11 later version.
12    
13 GCC is distributed in the hope that it will be useful, but WITHOUT
14 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
15 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
16 for more details.
17    
18 You should have received a copy of the GNU General Public License
19 along with GCC; see the file COPYING.  If not, write to the Free
20 Software Foundation, 59 Temple Place - Suite 330, Boston, MA
21 02111-1307, USA.  */
22
23 /* Conditional constant propagation.
24
25    References:
26
27      Constant propagation with conditional branches,
28      Wegman and Zadeck, ACM TOPLAS 13(2):181-210.
29
30      Building an Optimizing Compiler,
31      Robert Morgan, Butterworth-Heinemann, 1998, Section 8.9.
32
33      Advanced Compiler Design and Implementation,
34      Steven Muchnick, Morgan Kaufmann, 1997, Section 12.6  */
35
36 #include "config.h"
37 #include "system.h"
38 #include "coretypes.h"
39 #include "tm.h"
40 #include "tree.h"
41 #include "flags.h"
42 #include "rtl.h"
43 #include "tm_p.h"
44 #include "ggc.h"
45 #include "basic-block.h"
46 #include "output.h"
47 #include "errors.h"
48 #include "expr.h"
49 #include "function.h"
50 #include "diagnostic.h"
51 #include "timevar.h"
52 #include "tree-dump.h"
53 #include "tree-flow.h"
54 #include "tree-pass.h"
55 #include "tree-ssa-propagate.h"
56 #include "langhooks.h"
57
58
59 /* Possible lattice values.  */
60 typedef enum
61 {
62   UNINITIALIZED = 0,
63   UNDEFINED,
64   UNKNOWN_VAL,
65   CONSTANT,
66   VARYING
67 } latticevalue;
68
69 /* Main structure for CCP.  Contains the lattice value and, if it's a
70     constant, the constant value.  */
71 typedef struct
72 {
73   latticevalue lattice_val;
74   tree const_val;
75 } value;
76
77 /* This is used to track the current value of each variable.  */
78 static value *value_vector;
79
80
81 /* Dump lattice value VAL to file OUTF prefixed by PREFIX.  */
82
83 static void
84 dump_lattice_value (FILE *outf, const char *prefix, value val)
85 {
86   switch (val.lattice_val)
87     {
88     case UNDEFINED:
89       fprintf (outf, "%sUNDEFINED", prefix);
90       break;
91     case VARYING:
92       fprintf (outf, "%sVARYING", prefix);
93       break;
94     case UNKNOWN_VAL:
95       fprintf (outf, "%sUNKNOWN_VAL", prefix);
96       break;
97     case CONSTANT:
98       fprintf (outf, "%sCONSTANT ", prefix);
99       print_generic_expr (outf, val.const_val, dump_flags);
100       break;
101     default:
102       gcc_unreachable ();
103     }
104 }
105
106
107 /* Return a default value for variable VAR using the following rules:
108
109    1- Function arguments are considered VARYING.
110    
111    2- Global and static variables that are declared constant are
112       considered CONSTANT.
113
114    3- Any other virtually defined variable is considered UNKNOWN_VAL.
115
116    4- Any other value is considered UNDEFINED.  This is useful when
117       considering PHI nodes.  PHI arguments that are undefined do not
118       change the constant value of the PHI node, which allows for more
119       constants to be propagated.  */
120
121 static value
122 get_default_value (tree var)
123 {
124   value val;
125   tree sym;
126
127   if (TREE_CODE (var) == SSA_NAME)
128     sym = SSA_NAME_VAR (var);
129   else
130     {
131       gcc_assert (DECL_P (var));
132       sym = var;
133     }
134
135   val.lattice_val = UNDEFINED;
136   val.const_val = NULL_TREE;
137
138   if (TREE_CODE (var) == SSA_NAME
139       && SSA_NAME_VALUE (var)
140       && is_gimple_min_invariant (SSA_NAME_VALUE (var)))
141     {
142       val.lattice_val = CONSTANT;
143       val.const_val = SSA_NAME_VALUE (var);
144     }
145   else if (TREE_CODE (sym) == PARM_DECL || TREE_THIS_VOLATILE (sym))
146     {
147       /* Function arguments and volatile variables are considered VARYING.  */
148       val.lattice_val = VARYING;
149     }
150   else if (TREE_STATIC (sym))
151     {
152       /* Globals and static variables are considered UNKNOWN_VAL,
153          unless they are declared 'const'.  */
154       if (TREE_READONLY (sym)
155           && DECL_INITIAL (sym)
156           && is_gimple_min_invariant (DECL_INITIAL (sym)))
157         {
158           val.lattice_val = CONSTANT;
159           val.const_val = DECL_INITIAL (sym);
160         }
161       else
162         {
163           val.const_val = NULL_TREE;
164           val.lattice_val = UNKNOWN_VAL;
165         }
166     }
167   else if (!is_gimple_reg (sym))
168     {
169       val.const_val = NULL_TREE;
170       val.lattice_val = UNKNOWN_VAL;
171     }
172   else
173     {
174       enum tree_code code;
175       tree stmt = SSA_NAME_DEF_STMT (var);
176
177       if (!IS_EMPTY_STMT (stmt))
178         {
179           code = TREE_CODE (stmt);
180           if (code != MODIFY_EXPR && code != PHI_NODE)
181             val.lattice_val = VARYING;
182         }
183     }
184
185   return val;
186 }
187
188 /* Get the constant value associated with variable VAR.  */
189
190 static value *
191 get_value (tree var)
192 {
193   value *val;
194
195   gcc_assert (TREE_CODE (var) == SSA_NAME);
196
197   val = &value_vector[SSA_NAME_VERSION (var)];
198   if (val->lattice_val == UNINITIALIZED)
199     *val = get_default_value (var);
200
201   return val;
202 }
203
204
205 /* Set the lattice value for variable VAR to VAL.  Return true if VAL
206    is different from VAR's previous value.  */
207
208 static bool
209 set_lattice_value (tree var, value val)
210 {
211   value *old = get_value (var);
212
213   if (val.lattice_val == UNDEFINED)
214     {
215       /* CONSTANT->UNDEFINED is never a valid state transition.  */
216       gcc_assert (old->lattice_val != CONSTANT);
217         
218       /* UNKNOWN_VAL->UNDEFINED is never a valid state transition.  */
219       gcc_assert (old->lattice_val != UNKNOWN_VAL);
220
221       /* VARYING->UNDEFINED is generally not a valid state transition,
222          except for values which are initialized to VARYING.  */
223       gcc_assert (old->lattice_val != VARYING
224                   || get_default_value (var).lattice_val == VARYING);
225     }
226   else if (val.lattice_val == CONSTANT)
227     /* VARYING -> CONSTANT is an invalid state transition, except
228         for objects which start off in a VARYING state.  */
229     gcc_assert (old->lattice_val != VARYING
230                 || get_default_value (var).lattice_val == VARYING);
231
232   /* If the constant for VAR has changed, then this VAR is really varying.  */
233   if (old->lattice_val == CONSTANT
234       && val.lattice_val == CONSTANT
235       && !simple_cst_equal (old->const_val, val.const_val))
236     {
237       val.lattice_val = VARYING;
238       val.const_val = NULL_TREE;
239     }
240
241   if (old->lattice_val != val.lattice_val)
242     {
243       if (dump_file && (dump_flags & TDF_DETAILS))
244         {
245           dump_lattice_value (dump_file, "Lattice value changed to ", val);
246           fprintf (dump_file, ".  Adding definition to SSA edges.\n");
247         }
248
249       *old = val;
250       return true;
251     }
252
253   return false;
254 }
255
256
257 /* Set the lattice value for the variable VAR to VARYING.  */
258
259 static void
260 def_to_varying (tree var)
261 {
262   value val;
263   val.lattice_val = VARYING;
264   val.const_val = NULL_TREE;
265   set_lattice_value (var, val);
266 }
267
268
269 /* Return the likely latticevalue for STMT.
270
271    If STMT has no operands, then return CONSTANT.
272
273    Else if any operands of STMT are undefined, then return UNDEFINED.
274
275    Else if any operands of STMT are constants, then return CONSTANT.
276
277    Else return VARYING.  */
278
279 static latticevalue
280 likely_value (tree stmt)
281 {
282   vuse_optype vuses;
283   int found_constant = 0;
284   stmt_ann_t ann;
285   tree use;
286   ssa_op_iter iter;
287
288   /* If the statement makes aliased loads or has volatile operands, it
289      won't fold to a constant value.  */
290   ann = stmt_ann (stmt);
291   if (ann->makes_aliased_loads || ann->has_volatile_ops)
292     return VARYING;
293
294   /* A CALL_EXPR is assumed to be varying.  This may be overly conservative,
295      in the presence of const and pure calls.  */
296   if (get_call_expr_in (stmt) != NULL_TREE)
297     return VARYING;
298
299   get_stmt_operands (stmt);
300
301   FOR_EACH_SSA_TREE_OPERAND (use, stmt, iter, SSA_OP_USE)
302     {
303       value *val = get_value (use);
304
305       if (val->lattice_val == UNDEFINED)
306         return UNDEFINED;
307
308       if (val->lattice_val == CONSTANT)
309         found_constant = 1;
310     }
311     
312   vuses = VUSE_OPS (ann);
313   
314   if (NUM_VUSES (vuses))
315     {
316       tree vuse = VUSE_OP (vuses, 0);
317       value *val = get_value (vuse);
318       
319       if (val->lattice_val == UNKNOWN_VAL)
320         return UNKNOWN_VAL;
321         
322       /* There should be no VUSE operands that are UNDEFINED.  */
323       gcc_assert (val->lattice_val != UNDEFINED);
324         
325       if (val->lattice_val == CONSTANT)
326         found_constant = 1;
327     }
328
329   return ((found_constant || (!USE_OPS (ann) && !vuses)) ? CONSTANT : VARYING);
330 }
331
332
333 /* Function indicating whether we ought to include information for VAR
334    when calculating immediate uses.  */
335
336 static bool
337 need_imm_uses_for (tree var)
338 {
339   return get_value (var)->lattice_val != VARYING;
340 }
341
342
343 /* Initialize local data structures for CCP.  */
344
345 static void
346 ccp_initialize (void)
347 {
348   basic_block bb;
349   sbitmap is_may_def;
350
351   value_vector = (value *) xmalloc (num_ssa_names * sizeof (value));
352   memset (value_vector, 0, num_ssa_names * sizeof (value));
353
354   /* Set of SSA_NAMEs that are defined by a V_MAY_DEF.  */
355   is_may_def = sbitmap_alloc (num_ssa_names);
356   sbitmap_zero (is_may_def);
357
358   /* Initialize simulation flags for PHI nodes and statements.  */
359   FOR_EACH_BB (bb)
360     {
361       block_stmt_iterator i;
362
363       /* Mark all V_MAY_DEF operands VARYING.  */
364       for (i = bsi_start (bb); !bsi_end_p (i); bsi_next (&i))
365         {
366           bool is_varying = false;
367           tree stmt = bsi_stmt (i);
368           ssa_op_iter iter;
369           tree def;
370
371           get_stmt_operands (stmt);
372
373           /* Get the default value for each DEF and V_MUST_DEF.  */
374           FOR_EACH_SSA_TREE_OPERAND (def, stmt, iter, 
375                                      (SSA_OP_DEF | SSA_OP_VMUSTDEF))
376             {
377               if (get_value (def)->lattice_val == VARYING)
378                 is_varying = true;
379             }
380
381           /* Mark all V_MAY_DEF operands VARYING.  */
382           FOR_EACH_SSA_TREE_OPERAND (def, stmt, iter, SSA_OP_VMAYDEF)
383             {
384               get_value (def)->lattice_val = VARYING;
385               SET_BIT (is_may_def, SSA_NAME_VERSION (def));
386             }
387
388           /* Statements other than MODIFY_EXPR, COND_EXPR and
389              SWITCH_EXPR are not interesting for constant propagation.
390              Mark them VARYING.  */
391           if (TREE_CODE (stmt) != MODIFY_EXPR
392               && TREE_CODE (stmt) != COND_EXPR
393               && TREE_CODE (stmt) != SWITCH_EXPR)
394             is_varying = true;
395
396           DONT_SIMULATE_AGAIN (stmt) = is_varying;
397         }
398     }
399
400   /* Now process PHI nodes.  */
401   FOR_EACH_BB (bb)
402     {
403       tree phi, var;
404       int x;
405
406       for (phi = phi_nodes (bb); phi; phi = PHI_CHAIN (phi))
407         {
408           value *val = get_value (PHI_RESULT (phi));
409
410           for (x = 0; x < PHI_NUM_ARGS (phi); x++)
411             {
412               var = PHI_ARG_DEF (phi, x);
413
414               /* If one argument has a V_MAY_DEF, the result is
415                  VARYING.  */
416               if (TREE_CODE (var) == SSA_NAME)
417                 {
418                   if (TEST_BIT (is_may_def, SSA_NAME_VERSION (var)))
419                     {
420                       val->lattice_val = VARYING;
421                       SET_BIT (is_may_def, SSA_NAME_VERSION (PHI_RESULT (phi)));
422                       break;
423                     }
424                 }
425             }
426
427           DONT_SIMULATE_AGAIN (phi) = (val->lattice_val == VARYING);
428         }
429     }
430
431   sbitmap_free (is_may_def);
432
433   /* Compute immediate uses for variables we care about.  */
434   compute_immediate_uses (TDFA_USE_OPS | TDFA_USE_VOPS, need_imm_uses_for);
435 }
436
437
438 /* Replace USE references in statement STMT with their immediate reaching
439    definition.  Return true if at least one reference was replaced.  If
440    REPLACED_ADDRESSES_P is given, it will be set to true if an address
441    constant was replaced.  */
442
443 static bool
444 replace_uses_in (tree stmt, bool *replaced_addresses_p)
445 {
446   bool replaced = false;
447   use_operand_p use;
448   ssa_op_iter iter;
449
450   if (replaced_addresses_p)
451     *replaced_addresses_p = false;
452
453   get_stmt_operands (stmt);
454
455   FOR_EACH_SSA_USE_OPERAND (use, stmt, iter, SSA_OP_USE)
456     {
457       tree tuse = USE_FROM_PTR (use);
458       value *val = get_value (tuse);
459
460       if (val->lattice_val != CONSTANT)
461         continue;
462
463       if (TREE_CODE (stmt) == ASM_EXPR
464           && !may_propagate_copy_into_asm (tuse))
465         continue;
466
467       SET_USE (use, val->const_val);
468
469       replaced = true;
470       if (POINTER_TYPE_P (TREE_TYPE (tuse)) && replaced_addresses_p)
471         *replaced_addresses_p = true;
472     }
473
474   return replaced;
475 }
476
477
478 /* Replace the VUSE references in statement STMT with its immediate reaching
479    definition.  Return true if the reference was replaced.  If
480    REPLACED_ADDRESSES_P is given, it will be set to true if an address
481    constant was replaced.  */
482
483 static bool
484 replace_vuse_in (tree stmt, bool *replaced_addresses_p)
485 {
486   bool replaced = false;
487   vuse_optype vuses;
488   use_operand_p vuse;
489   value *val;
490
491   if (replaced_addresses_p)
492     *replaced_addresses_p = false;
493
494   get_stmt_operands (stmt);
495
496   vuses = STMT_VUSE_OPS (stmt);
497
498   if (NUM_VUSES (vuses) != 1)
499     return false;
500
501   vuse = VUSE_OP_PTR (vuses, 0);
502   val = get_value (USE_FROM_PTR (vuse));
503
504   if (val->lattice_val == CONSTANT
505       && TREE_CODE (stmt) == MODIFY_EXPR
506       && DECL_P (TREE_OPERAND (stmt, 1))
507       && TREE_OPERAND (stmt, 1) == SSA_NAME_VAR (USE_FROM_PTR (vuse)))
508     {
509       TREE_OPERAND (stmt, 1) = val->const_val;
510       replaced = true;
511       if (POINTER_TYPE_P (TREE_TYPE (USE_FROM_PTR (vuse))) 
512           && replaced_addresses_p)
513         *replaced_addresses_p = true;
514     }
515
516   return replaced;
517 }
518
519
520 /* Perform final substitution and folding.  After this pass the program
521    should still be in SSA form.  */
522
523 static void
524 substitute_and_fold (void)
525 {
526   basic_block bb;
527   unsigned int i;
528
529   if (dump_file && (dump_flags & TDF_DETAILS))
530     fprintf (dump_file,
531              "\nSubstituing constants and folding statements\n\n");
532
533   /* Substitute constants in every statement of every basic block.  */
534   FOR_EACH_BB (bb)
535     {
536       block_stmt_iterator i;
537       tree phi;
538
539       /* Propagate our known constants into PHI nodes.  */
540       for (phi = phi_nodes (bb); phi; phi = PHI_CHAIN (phi))
541         {
542           int i;
543
544           for (i = 0; i < PHI_NUM_ARGS (phi); i++)
545             {
546               value *new_val;
547               use_operand_p orig_p = PHI_ARG_DEF_PTR (phi, i);
548               tree orig = USE_FROM_PTR (orig_p);
549
550               if (! SSA_VAR_P (orig))
551                 break;
552
553               new_val = get_value (orig);
554               if (new_val->lattice_val == CONSTANT
555                   && may_propagate_copy (orig, new_val->const_val))
556                 SET_USE (orig_p, new_val->const_val);
557             }
558         }
559
560       for (i = bsi_start (bb); !bsi_end_p (i); bsi_next (&i))
561         {
562           bool replaced_address;
563           tree stmt = bsi_stmt (i);
564
565           /* Skip statements that have been folded already.  */
566           if (stmt_modified_p (stmt) || !is_exec_stmt (stmt))
567             continue;
568
569           /* Replace the statement with its folded version and mark it
570              folded.  */
571           if (dump_file && (dump_flags & TDF_DETAILS))
572             {
573               fprintf (dump_file, "Line %d: replaced ", get_lineno (stmt));
574               print_generic_stmt (dump_file, stmt, TDF_SLIM);
575             }
576
577           if (replace_uses_in (stmt, &replaced_address)
578               || replace_vuse_in (stmt, &replaced_address))
579             {
580               bool changed = fold_stmt (bsi_stmt_ptr (i));
581               stmt = bsi_stmt(i);
582               /* If we folded a builtin function, we'll likely
583                  need to rename VDEFs.  */
584               if (replaced_address || changed)
585                 {
586                   mark_new_vars_to_rename (stmt, vars_to_rename);
587                   if (maybe_clean_eh_stmt (stmt))
588                     tree_purge_dead_eh_edges (bb);
589                 }
590               else
591                 modify_stmt (stmt);
592             }
593
594           if (dump_file && (dump_flags & TDF_DETAILS))
595             {
596               fprintf (dump_file, " with ");
597               print_generic_stmt (dump_file, stmt, TDF_SLIM);
598               fprintf (dump_file, "\n");
599             }
600         }
601     }
602
603   /* And transfer what we learned from VALUE_VECTOR into the
604      SSA_NAMEs themselves.  This probably isn't terribly important
605      since we probably constant propagated the values to their
606      use sites above.  */
607   for (i = 0; i < num_ssa_names; i++)
608     {
609       tree name = ssa_name (i);
610       value *value;
611
612       if (!name)
613         continue;
614
615       value = get_value (name);
616       if (value->lattice_val == CONSTANT
617           && is_gimple_reg (name)
618           && is_gimple_min_invariant (value->const_val))
619         SSA_NAME_VALUE (name) = value->const_val;
620     }
621 }
622
623
624 /* Free allocated storage.  */
625
626 static void
627 ccp_finalize (void)
628 {
629   /* Perform substitutions based on the known constant values.  */
630   substitute_and_fold ();
631
632   free (value_vector);
633 }
634
635
636
637 /* Compute the meet operator between VAL1 and VAL2:
638
639                 any  M UNDEFINED     = any
640                 any  M VARYING       = VARYING
641                 any  M UNKNOWN_VAL   = UNKNOWN_VAL
642                 Ci   M Cj            = Ci       if (i == j)
643                 Ci   M Cj            = VARYING  if (i != j)  */
644 static value
645 ccp_lattice_meet (value val1, value val2)
646 {
647   value result;
648
649   /* any M UNDEFINED = any.  */
650   if (val1.lattice_val == UNDEFINED)
651     return val2;
652   else if (val2.lattice_val == UNDEFINED)
653     return val1;
654
655   /* any M VARYING = VARYING.  */
656   if (val1.lattice_val == VARYING || val2.lattice_val == VARYING)
657     {
658       result.lattice_val = VARYING;
659       result.const_val = NULL_TREE;
660       return result;
661     }
662
663   /* any M UNKNOWN_VAL = UNKNOWN_VAL.  */
664   if (val1.lattice_val == UNKNOWN_VAL 
665       || val2.lattice_val == UNKNOWN_VAL)
666     {
667       result.lattice_val = UNKNOWN_VAL;
668       result.const_val = NULL_TREE;
669       return result;
670     }
671
672   /* Ci M Cj = Ci       if (i == j)
673      Ci M Cj = VARYING  if (i != j)  */
674   if (simple_cst_equal (val1.const_val, val2.const_val) == 1)
675     {
676       result.lattice_val = CONSTANT;
677       result.const_val = val1.const_val;
678     }
679   else
680     {
681       result.lattice_val = VARYING;
682       result.const_val = NULL_TREE;
683     }
684
685   return result;
686 }
687
688
689 /* Loop through the PHI_NODE's parameters for BLOCK and compare their
690    lattice values to determine PHI_NODE's lattice value.  The value of a
691    PHI node is determined calling ccp_lattice_meet() with all the arguments
692    of the PHI node that are incoming via executable edges.  */
693
694 static enum ssa_prop_result
695 ccp_visit_phi_node (tree phi)
696 {
697   value new_val, *old_val;
698   int i;
699
700   if (dump_file && (dump_flags & TDF_DETAILS))
701     {
702       fprintf (dump_file, "\nVisiting PHI node: ");
703       print_generic_expr (dump_file, phi, dump_flags);
704     }
705
706   old_val = get_value (PHI_RESULT (phi));
707   switch (old_val->lattice_val)
708     {
709     case VARYING:
710       return SSA_PROP_NOT_INTERESTING;
711
712     case CONSTANT:
713       new_val = *old_val;
714       break;
715
716     case UNKNOWN_VAL:
717       /* To avoid the default value of UNKNOWN_VAL overriding
718          that of its possible constant arguments, temporarily
719          set the PHI node's default lattice value to be 
720          UNDEFINED.  If the PHI node's old value was UNKNOWN_VAL and
721          the new value is UNDEFINED, then we prevent the invalid
722          transition by not calling set_lattice_value.  */
723       new_val.lattice_val = UNDEFINED;
724       new_val.const_val = NULL_TREE;
725       break;
726
727     case UNDEFINED:
728     case UNINITIALIZED:
729       new_val.lattice_val = UNDEFINED;
730       new_val.const_val = NULL_TREE;
731       break;
732
733     default:
734       gcc_unreachable ();
735     }
736
737   for (i = 0; i < PHI_NUM_ARGS (phi); i++)
738     {
739       /* Compute the meet operator over all the PHI arguments.  */
740       edge e = PHI_ARG_EDGE (phi, i);
741
742       if (dump_file && (dump_flags & TDF_DETAILS))
743         {
744           fprintf (dump_file,
745               "\n    Argument #%d (%d -> %d %sexecutable)\n",
746               i, e->src->index, e->dest->index,
747               (e->flags & EDGE_EXECUTABLE) ? "" : "not ");
748         }
749
750       /* If the incoming edge is executable, Compute the meet operator for
751          the existing value of the PHI node and the current PHI argument.  */
752       if (e->flags & EDGE_EXECUTABLE)
753         {
754           tree rdef = PHI_ARG_DEF (phi, i);
755           value *rdef_val, val;
756
757           if (is_gimple_min_invariant (rdef))
758             {
759               val.lattice_val = CONSTANT;
760               val.const_val = rdef;
761               rdef_val = &val;
762             }
763           else
764             rdef_val = get_value (rdef);
765
766           new_val = ccp_lattice_meet (new_val, *rdef_val);
767
768           if (dump_file && (dump_flags & TDF_DETAILS))
769             {
770               fprintf (dump_file, "\t");
771               print_generic_expr (dump_file, rdef, dump_flags);
772               dump_lattice_value (dump_file, "\tValue: ", *rdef_val);
773               fprintf (dump_file, "\n");
774             }
775
776           if (new_val.lattice_val == VARYING)
777             break;
778         }
779     }
780
781   if (dump_file && (dump_flags & TDF_DETAILS))
782     {
783       dump_lattice_value (dump_file, "\n    PHI node value: ", new_val);
784       fprintf (dump_file, "\n\n");
785     }
786
787   /* Check for an invalid change from UNKNOWN_VAL to UNDEFINED.  */
788   if (old_val->lattice_val == UNKNOWN_VAL
789       && new_val.lattice_val == UNDEFINED)
790     return SSA_PROP_NOT_INTERESTING;
791
792   /* Otherwise, make the transition to the new value.  */
793   if (set_lattice_value (PHI_RESULT (phi), new_val))
794     {
795       if (new_val.lattice_val == VARYING)
796         return SSA_PROP_VARYING;
797       else
798         return SSA_PROP_INTERESTING;
799     }
800   else
801     return SSA_PROP_NOT_INTERESTING;
802 }
803
804
805 /* CCP specific front-end to the non-destructive constant folding
806    routines.
807
808    Attempt to simplify the RHS of STMT knowing that one or more
809    operands are constants.
810
811    If simplification is possible, return the simplified RHS,
812    otherwise return the original RHS.  */
813
814 static tree
815 ccp_fold (tree stmt)
816 {
817   tree rhs = get_rhs (stmt);
818   enum tree_code code = TREE_CODE (rhs);
819   enum tree_code_class kind = TREE_CODE_CLASS (code);
820   tree retval = NULL_TREE;
821   vuse_optype vuses;
822   
823   vuses = STMT_VUSE_OPS (stmt);
824
825   /* If the RHS is just a variable, then that variable must now have
826      a constant value that we can return directly.  */
827   if (TREE_CODE (rhs) == SSA_NAME)
828     return get_value (rhs)->const_val;
829   else if (DECL_P (rhs) 
830            && NUM_VUSES (vuses) == 1
831            && rhs == SSA_NAME_VAR (VUSE_OP (vuses, 0)))
832     return get_value (VUSE_OP (vuses, 0))->const_val;
833
834   /* Unary operators.  Note that we know the single operand must
835      be a constant.  So this should almost always return a
836      simplified RHS.  */
837   if (kind == tcc_unary)
838     {
839       /* Handle unary operators which can appear in GIMPLE form.  */
840       tree op0 = TREE_OPERAND (rhs, 0);
841
842       /* Simplify the operand down to a constant.  */
843       if (TREE_CODE (op0) == SSA_NAME)
844         {
845           value *val = get_value (op0);
846           if (val->lattice_val == CONSTANT)
847             op0 = get_value (op0)->const_val;
848         }
849
850       retval = nondestructive_fold_unary_to_constant (code,
851                                                       TREE_TYPE (rhs),
852                                                       op0);
853
854       /* If we folded, but did not create an invariant, then we can not
855          use this expression.  */
856       if (retval && ! is_gimple_min_invariant (retval))
857         return NULL;
858
859       /* If we could not fold the expression, but the arguments are all
860          constants and gimple values, then build and return the new
861          expression. 
862
863          In some cases the new expression is still something we can
864          use as a replacement for an argument.  This happens with
865          NOP conversions of types for example.
866
867          In other cases the new expression can not be used as a
868          replacement for an argument (as it would create non-gimple
869          code).  But the new expression can still be used to derive
870          other constants.  */
871       if (! retval && is_gimple_min_invariant (op0))
872         return build1 (code, TREE_TYPE (rhs), op0);
873     }
874
875   /* Binary and comparison operators.  We know one or both of the
876      operands are constants.  */
877   else if (kind == tcc_binary
878            || kind == tcc_comparison
879            || code == TRUTH_AND_EXPR
880            || code == TRUTH_OR_EXPR
881            || code == TRUTH_XOR_EXPR)
882     {
883       /* Handle binary and comparison operators that can appear in
884          GIMPLE form.  */
885       tree op0 = TREE_OPERAND (rhs, 0);
886       tree op1 = TREE_OPERAND (rhs, 1);
887
888       /* Simplify the operands down to constants when appropriate.  */
889       if (TREE_CODE (op0) == SSA_NAME)
890         {
891           value *val = get_value (op0);
892           if (val->lattice_val == CONSTANT)
893             op0 = val->const_val;
894         }
895
896       if (TREE_CODE (op1) == SSA_NAME)
897         {
898           value *val = get_value (op1);
899           if (val->lattice_val == CONSTANT)
900             op1 = val->const_val;
901         }
902
903       retval = nondestructive_fold_binary_to_constant (code,
904                                                        TREE_TYPE (rhs),
905                                                        op0, op1);
906
907       /* If we folded, but did not create an invariant, then we can not
908          use this expression.  */
909       if (retval && ! is_gimple_min_invariant (retval))
910         return NULL;
911       
912       /* If we could not fold the expression, but the arguments are all
913          constants and gimple values, then build and return the new
914          expression. 
915
916          In some cases the new expression is still something we can
917          use as a replacement for an argument.  This happens with
918          NOP conversions of types for example.
919
920          In other cases the new expression can not be used as a
921          replacement for an argument (as it would create non-gimple
922          code).  But the new expression can still be used to derive
923          other constants.  */
924       if (! retval
925           && is_gimple_min_invariant (op0)
926           && is_gimple_min_invariant (op1))
927         return build (code, TREE_TYPE (rhs), op0, op1);
928     }
929
930   /* We may be able to fold away calls to builtin functions if their
931      arguments are constants.  */
932   else if (code == CALL_EXPR
933            && TREE_CODE (TREE_OPERAND (rhs, 0)) == ADDR_EXPR
934            && (TREE_CODE (TREE_OPERAND (TREE_OPERAND (rhs, 0), 0))
935                == FUNCTION_DECL)
936            && DECL_BUILT_IN (TREE_OPERAND (TREE_OPERAND (rhs, 0), 0)))
937     {
938       use_optype uses = STMT_USE_OPS (stmt);
939       if (NUM_USES (uses) != 0)
940         {
941           tree *orig;
942           size_t i;
943
944           /* Preserve the original values of every operand.  */
945           orig = xmalloc (sizeof (tree) * NUM_USES (uses));
946           for (i = 0; i < NUM_USES (uses); i++)
947             orig[i] = USE_OP (uses, i);
948
949           /* Substitute operands with their values and try to fold.  */
950           replace_uses_in (stmt, NULL);
951           retval = fold_builtin (rhs, false);
952
953           /* Restore operands to their original form.  */
954           for (i = 0; i < NUM_USES (uses); i++)
955             SET_USE_OP (uses, i, orig[i]);
956           free (orig);
957         }
958     }
959   else
960     return rhs;
961
962   /* If we got a simplified form, see if we need to convert its type.  */
963   if (retval)
964     return fold_convert (TREE_TYPE (rhs), retval);
965
966   /* No simplification was possible.  */
967   return rhs;
968 }
969
970
971 /* Evaluate statement STMT.  */
972
973 static value
974 evaluate_stmt (tree stmt)
975 {
976   value val;
977   tree simplified;
978   latticevalue likelyvalue = likely_value (stmt);
979
980   /* If the statement is likely to have a CONSTANT result, then try
981      to fold the statement to determine the constant value.  */
982   if (likelyvalue == CONSTANT)
983     simplified = ccp_fold (stmt);
984   /* If the statement is likely to have a VARYING result, then do not
985      bother folding the statement.  */
986   else if (likelyvalue == VARYING)
987     simplified = get_rhs (stmt);
988   /* Otherwise the statement is likely to have an UNDEFINED value and
989      there will be nothing to do.  */
990   else
991     simplified = NULL_TREE;
992
993   if (simplified && is_gimple_min_invariant (simplified))
994     {
995       /* The statement produced a constant value.  */
996       val.lattice_val = CONSTANT;
997       val.const_val = simplified;
998     }
999   else
1000     {
1001       /* The statement produced a nonconstant value.  If the statement
1002          had undefined or virtual operands, then the result of the 
1003          statement should be undefined or virtual respectively.  
1004          Else the result of the statement is VARYING.  */
1005       val.lattice_val = (likelyvalue == UNDEFINED ? UNDEFINED : VARYING);
1006       val.lattice_val = (likelyvalue == UNKNOWN_VAL 
1007                            ? UNKNOWN_VAL : val.lattice_val);
1008       val.const_val = NULL_TREE;
1009     }
1010
1011   return val;
1012 }
1013
1014
1015 /* Visit the assignment statement STMT.  Set the value of its LHS to the
1016    value computed by the RHS and store LHS in *OUTPUT_P.  */
1017
1018 static enum ssa_prop_result
1019 visit_assignment (tree stmt, tree *output_p)
1020 {
1021   value val;
1022   tree lhs, rhs;
1023   vuse_optype vuses;
1024   v_must_def_optype v_must_defs;
1025
1026   lhs = TREE_OPERAND (stmt, 0);
1027   rhs = TREE_OPERAND (stmt, 1);
1028   vuses = STMT_VUSE_OPS (stmt);
1029   v_must_defs = STMT_V_MUST_DEF_OPS (stmt);
1030
1031   gcc_assert (NUM_V_MAY_DEFS (STMT_V_MAY_DEF_OPS (stmt)) == 0);
1032   gcc_assert (NUM_V_MUST_DEFS (v_must_defs) == 1
1033               || TREE_CODE (lhs) == SSA_NAME);
1034
1035   /* We require the SSA version number of the lhs for the value_vector.
1036      Make sure we have it.  */
1037   if (TREE_CODE (lhs) != SSA_NAME)
1038     {
1039       /* If we make it here, then stmt only has one definition:
1040          a V_MUST_DEF.  */
1041       lhs = V_MUST_DEF_RESULT (v_must_defs, 0);
1042     }
1043
1044   if (TREE_CODE (rhs) == SSA_NAME)
1045     {
1046       /* For a simple copy operation, we copy the lattice values.  */
1047       value *nval = get_value (rhs);
1048       val = *nval;
1049     }
1050   else if (DECL_P (rhs) 
1051            && NUM_VUSES (vuses) == 1
1052            && rhs == SSA_NAME_VAR (VUSE_OP (vuses, 0)))
1053     {
1054       /* Same as above, but the rhs is not a gimple register and yet
1055         has a known VUSE.  */
1056       value *nval = get_value (VUSE_OP (vuses, 0));
1057       val = *nval;
1058     }
1059   else
1060     {
1061       /* Evaluate the statement.  */
1062       val = evaluate_stmt (stmt);
1063     }
1064
1065   /* FIXME: Hack.  If this was a definition of a bitfield, we need to widen
1066      the constant value into the type of the destination variable.  This
1067      should not be necessary if GCC represented bitfields properly.  */
1068   {
1069     tree lhs = TREE_OPERAND (stmt, 0);
1070     if (val.lattice_val == CONSTANT
1071         && TREE_CODE (lhs) == COMPONENT_REF
1072         && DECL_BIT_FIELD (TREE_OPERAND (lhs, 1)))
1073       {
1074         tree w = widen_bitfield (val.const_val, TREE_OPERAND (lhs, 1), lhs);
1075
1076         if (w && is_gimple_min_invariant (w))
1077           val.const_val = w;
1078         else
1079           {
1080             val.lattice_val = VARYING;
1081             val.const_val = NULL;
1082           }
1083       }
1084   }
1085
1086   /* If LHS is not a gimple register, then it cannot take on an
1087      UNDEFINED value.  */
1088   if (!is_gimple_reg (SSA_NAME_VAR (lhs)) 
1089       && val.lattice_val == UNDEFINED)
1090     val.lattice_val = UNKNOWN_VAL;      
1091
1092   /* Set the lattice value of the statement's output.  */
1093   if (set_lattice_value (lhs, val))
1094     {
1095       *output_p = lhs;
1096       if (val.lattice_val == VARYING)
1097         return SSA_PROP_VARYING;
1098       else
1099         return SSA_PROP_INTERESTING;
1100     }
1101   else
1102     return SSA_PROP_NOT_INTERESTING;
1103 }
1104
1105
1106 /* Visit the conditional statement STMT.  Return SSA_PROP_INTERESTING
1107    if it can determine which edge will be taken.  Otherwise, return
1108    SSA_PROP_VARYING.  */
1109
1110 static enum ssa_prop_result
1111 visit_cond_stmt (tree stmt, edge *taken_edge_p)
1112 {
1113   value val;
1114   basic_block block;
1115
1116   block = bb_for_stmt (stmt);
1117   val = evaluate_stmt (stmt);
1118
1119   /* Find which edge out of the conditional block will be taken and add it
1120      to the worklist.  If no single edge can be determined statically,
1121      return SSA_PROP_VARYING to feed all the outgoing edges to the
1122      propagation engine.  */
1123   *taken_edge_p = val.const_val ? find_taken_edge (block, val.const_val) : 0;
1124   if (*taken_edge_p)
1125     return SSA_PROP_INTERESTING;
1126   else
1127     return SSA_PROP_VARYING;
1128 }
1129
1130
1131 /* Evaluate statement STMT.  If the statement produces an output value and
1132    its evaluation changes the lattice value of its output, return
1133    SSA_PROP_INTERESTING and set *OUTPUT_P to the SSA_NAME holding the
1134    output value.
1135    
1136    If STMT is a conditional branch and we can determine its truth
1137    value, set *TAKEN_EDGE_P accordingly.  If STMT produces a varying
1138    value, return SSA_PROP_VARYING.  */
1139
1140 static enum ssa_prop_result
1141 ccp_visit_stmt (tree stmt, edge *taken_edge_p, tree *output_p)
1142 {
1143   stmt_ann_t ann;
1144   v_may_def_optype v_may_defs;
1145   v_must_def_optype v_must_defs;
1146   tree def;
1147   ssa_op_iter iter;
1148
1149   if (dump_file && (dump_flags & TDF_DETAILS))
1150     {
1151       fprintf (dump_file, "\nVisiting statement: ");
1152       print_generic_stmt (dump_file, stmt, TDF_SLIM);
1153       fprintf (dump_file, "\n");
1154     }
1155
1156   ann = stmt_ann (stmt);
1157
1158   v_must_defs = V_MUST_DEF_OPS (ann);
1159   v_may_defs = V_MAY_DEF_OPS (ann);
1160   if (TREE_CODE (stmt) == MODIFY_EXPR
1161       && NUM_V_MAY_DEFS (v_may_defs) == 0
1162       && (NUM_V_MUST_DEFS (v_must_defs) == 1
1163           || TREE_CODE (TREE_OPERAND (stmt, 0)) == SSA_NAME))
1164     {
1165       /* If the statement is an assignment that produces a single
1166          output value, evaluate its RHS to see if the lattice value of
1167          its output has changed.  */
1168       return visit_assignment (stmt, output_p);
1169     }
1170   else if (TREE_CODE (stmt) == COND_EXPR || TREE_CODE (stmt) == SWITCH_EXPR)
1171     {
1172       /* If STMT is a conditional branch, see if we can determine
1173          which branch will be taken.  */
1174       return visit_cond_stmt (stmt, taken_edge_p);
1175     }
1176
1177   /* Any other kind of statement is not interesting for constant
1178      propagation and, therefore, not worth simulating.  */
1179   if (dump_file && (dump_flags & TDF_DETAILS))
1180     fprintf (dump_file, "No interesting values produced.  Marked VARYING.\n");
1181
1182   /* Definitions made by statements other than assignments to
1183      SSA_NAMEs represent unknown modifications to their outputs.
1184      Mark them VARYING.  */
1185   FOR_EACH_SSA_TREE_OPERAND (def, stmt, iter, SSA_OP_DEF)
1186     def_to_varying (def);
1187
1188   /* Mark all V_MAY_DEF operands VARYING.  */
1189   FOR_EACH_SSA_TREE_OPERAND (def, stmt, iter, SSA_OP_VMAYDEF)
1190     def_to_varying (def);
1191
1192   return SSA_PROP_VARYING;
1193 }
1194
1195
1196 /* Main entry point for SSA Conditional Constant Propagation.
1197
1198    [ DESCRIBE MAIN ALGORITHM HERE ]  */
1199
1200 static void
1201 execute_ssa_ccp (void)
1202 {
1203   ccp_initialize ();
1204   ssa_propagate (ccp_visit_stmt, ccp_visit_phi_node);
1205   ccp_finalize ();
1206 }
1207
1208
1209 static bool
1210 gate_ccp (void)
1211 {
1212   return flag_tree_ccp != 0;
1213 }
1214
1215
1216 struct tree_opt_pass pass_ccp = 
1217 {
1218   "ccp",                                /* name */
1219   gate_ccp,                             /* gate */
1220   execute_ssa_ccp,                      /* execute */
1221   NULL,                                 /* sub */
1222   NULL,                                 /* next */
1223   0,                                    /* static_pass_number */
1224   TV_TREE_CCP,                          /* tv_id */
1225   PROP_cfg | PROP_ssa | PROP_alias,     /* properties_required */
1226   0,                                    /* properties_provided */
1227   0,                                    /* properties_destroyed */
1228   0,                                    /* todo_flags_start */
1229   TODO_cleanup_cfg | TODO_dump_func | TODO_rename_vars
1230     | TODO_ggc_collect | TODO_verify_ssa
1231     | TODO_verify_stmts,                /* todo_flags_finish */
1232   0                                     /* letter */
1233 };
1234
1235
1236 /* Given a constant value VAL for bitfield FIELD, and a destination
1237    variable VAR, return VAL appropriately widened to fit into VAR.  If
1238    FIELD is wider than HOST_WIDE_INT, NULL is returned.  */
1239
1240 tree
1241 widen_bitfield (tree val, tree field, tree var)
1242 {
1243   unsigned HOST_WIDE_INT var_size, field_size;
1244   tree wide_val;
1245   unsigned HOST_WIDE_INT mask;
1246   unsigned int i;
1247
1248   /* We can only do this if the size of the type and field and VAL are
1249      all constants representable in HOST_WIDE_INT.  */
1250   if (!host_integerp (TYPE_SIZE (TREE_TYPE (var)), 1)
1251       || !host_integerp (DECL_SIZE (field), 1)
1252       || !host_integerp (val, 0))
1253     return NULL_TREE;
1254
1255   var_size = tree_low_cst (TYPE_SIZE (TREE_TYPE (var)), 1);
1256   field_size = tree_low_cst (DECL_SIZE (field), 1);
1257
1258   /* Give up if either the bitfield or the variable are too wide.  */
1259   if (field_size > HOST_BITS_PER_WIDE_INT || var_size > HOST_BITS_PER_WIDE_INT)
1260     return NULL_TREE;
1261
1262   gcc_assert (var_size >= field_size);
1263
1264   /* If the sign bit of the value is not set or the field's type is unsigned,
1265      just mask off the high order bits of the value.  */
1266   if (DECL_UNSIGNED (field)
1267       || !(tree_low_cst (val, 0) & (((HOST_WIDE_INT)1) << (field_size - 1))))
1268     {
1269       /* Zero extension.  Build a mask with the lower 'field_size' bits
1270          set and a BIT_AND_EXPR node to clear the high order bits of
1271          the value.  */
1272       for (i = 0, mask = 0; i < field_size; i++)
1273         mask |= ((HOST_WIDE_INT) 1) << i;
1274
1275       wide_val = build (BIT_AND_EXPR, TREE_TYPE (var), val, 
1276                         fold_convert (TREE_TYPE (var),
1277                                       build_int_cst (NULL_TREE, mask)));
1278     }
1279   else
1280     {
1281       /* Sign extension.  Create a mask with the upper 'field_size'
1282          bits set and a BIT_IOR_EXPR to set the high order bits of the
1283          value.  */
1284       for (i = 0, mask = 0; i < (var_size - field_size); i++)
1285         mask |= ((HOST_WIDE_INT) 1) << (var_size - i - 1);
1286
1287       wide_val = build (BIT_IOR_EXPR, TREE_TYPE (var), val,
1288                         fold_convert (TREE_TYPE (var),
1289                                       build_int_cst (NULL_TREE, mask)));
1290     }
1291
1292   return fold (wide_val);
1293 }
1294
1295
1296 /* A subroutine of fold_stmt_r.  Attempts to fold *(A+O) to A[X].
1297    BASE is an array type.  OFFSET is a byte displacement.  ORIG_TYPE
1298    is the desired result type.  */
1299
1300 static tree
1301 maybe_fold_offset_to_array_ref (tree base, tree offset, tree orig_type)
1302 {
1303   tree min_idx, idx, elt_offset = integer_zero_node;
1304   tree array_type, elt_type, elt_size;
1305
1306   /* If BASE is an ARRAY_REF, we can pick up another offset (this time
1307      measured in units of the size of elements type) from that ARRAY_REF).
1308      We can't do anything if either is variable.
1309
1310      The case we handle here is *(&A[N]+O).  */
1311   if (TREE_CODE (base) == ARRAY_REF)
1312     {
1313       tree low_bound = array_ref_low_bound (base);
1314
1315       elt_offset = TREE_OPERAND (base, 1);
1316       if (TREE_CODE (low_bound) != INTEGER_CST
1317           || TREE_CODE (elt_offset) != INTEGER_CST)
1318         return NULL_TREE;
1319
1320       elt_offset = int_const_binop (MINUS_EXPR, elt_offset, low_bound, 0);
1321       base = TREE_OPERAND (base, 0);
1322     }
1323
1324   /* Ignore stupid user tricks of indexing non-array variables.  */
1325   array_type = TREE_TYPE (base);
1326   if (TREE_CODE (array_type) != ARRAY_TYPE)
1327     return NULL_TREE;
1328   elt_type = TREE_TYPE (array_type);
1329   if (!lang_hooks.types_compatible_p (orig_type, elt_type))
1330     return NULL_TREE;
1331         
1332   /* If OFFSET and ELT_OFFSET are zero, we don't care about the size of the
1333      element type (so we can use the alignment if it's not constant).
1334      Otherwise, compute the offset as an index by using a division.  If the
1335      division isn't exact, then don't do anything.  */
1336   elt_size = TYPE_SIZE_UNIT (elt_type);
1337   if (integer_zerop (offset))
1338     {
1339       if (TREE_CODE (elt_size) != INTEGER_CST)
1340         elt_size = size_int (TYPE_ALIGN (elt_type));
1341
1342       idx = integer_zero_node;
1343     }
1344   else
1345     {
1346       unsigned HOST_WIDE_INT lquo, lrem;
1347       HOST_WIDE_INT hquo, hrem;
1348
1349       if (TREE_CODE (elt_size) != INTEGER_CST
1350           || div_and_round_double (TRUNC_DIV_EXPR, 1,
1351                                    TREE_INT_CST_LOW (offset),
1352                                    TREE_INT_CST_HIGH (offset),
1353                                    TREE_INT_CST_LOW (elt_size),
1354                                    TREE_INT_CST_HIGH (elt_size),
1355                                    &lquo, &hquo, &lrem, &hrem)
1356           || lrem || hrem)
1357         return NULL_TREE;
1358
1359       idx = build_int_cst_wide (NULL_TREE, lquo, hquo);
1360     }
1361
1362   /* Assume the low bound is zero.  If there is a domain type, get the
1363      low bound, if any, convert the index into that type, and add the
1364      low bound.  */
1365   min_idx = integer_zero_node;
1366   if (TYPE_DOMAIN (array_type))
1367     {
1368       if (TYPE_MIN_VALUE (TYPE_DOMAIN (array_type)))
1369         min_idx = TYPE_MIN_VALUE (TYPE_DOMAIN (array_type));
1370       else
1371         min_idx = fold_convert (TYPE_DOMAIN (array_type), min_idx);
1372
1373       if (TREE_CODE (min_idx) != INTEGER_CST)
1374         return NULL_TREE;
1375
1376       idx = fold_convert (TYPE_DOMAIN (array_type), idx);
1377       elt_offset = fold_convert (TYPE_DOMAIN (array_type), elt_offset);
1378     }
1379
1380   if (!integer_zerop (min_idx))
1381     idx = int_const_binop (PLUS_EXPR, idx, min_idx, 0);
1382   if (!integer_zerop (elt_offset))
1383     idx = int_const_binop (PLUS_EXPR, idx, elt_offset, 0);
1384
1385   return build (ARRAY_REF, orig_type, base, idx, min_idx,
1386                 size_int (tree_low_cst (elt_size, 1)
1387                           / (TYPE_ALIGN_UNIT (elt_type))));
1388 }
1389
1390
1391 /* A subroutine of fold_stmt_r.  Attempts to fold *(S+O) to S.X.
1392    BASE is a record type.  OFFSET is a byte displacement.  ORIG_TYPE
1393    is the desired result type.  */
1394 /* ??? This doesn't handle class inheritance.  */
1395
1396 static tree
1397 maybe_fold_offset_to_component_ref (tree record_type, tree base, tree offset,
1398                                     tree orig_type, bool base_is_ptr)
1399 {
1400   tree f, t, field_type, tail_array_field, field_offset;
1401
1402   if (TREE_CODE (record_type) != RECORD_TYPE
1403       && TREE_CODE (record_type) != UNION_TYPE
1404       && TREE_CODE (record_type) != QUAL_UNION_TYPE)
1405     return NULL_TREE;
1406
1407   /* Short-circuit silly cases.  */
1408   if (lang_hooks.types_compatible_p (record_type, orig_type))
1409     return NULL_TREE;
1410
1411   tail_array_field = NULL_TREE;
1412   for (f = TYPE_FIELDS (record_type); f ; f = TREE_CHAIN (f))
1413     {
1414       int cmp;
1415
1416       if (TREE_CODE (f) != FIELD_DECL)
1417         continue;
1418       if (DECL_BIT_FIELD (f))
1419         continue;
1420
1421       field_offset = byte_position (f);
1422       if (TREE_CODE (field_offset) != INTEGER_CST)
1423         continue;
1424
1425       /* ??? Java creates "interesting" fields for representing base classes.
1426          They have no name, and have no context.  With no context, we get into
1427          trouble with nonoverlapping_component_refs_p.  Skip them.  */
1428       if (!DECL_FIELD_CONTEXT (f))
1429         continue;
1430
1431       /* The previous array field isn't at the end.  */
1432       tail_array_field = NULL_TREE;
1433
1434       /* Check to see if this offset overlaps with the field.  */
1435       cmp = tree_int_cst_compare (field_offset, offset);
1436       if (cmp > 0)
1437         continue;
1438
1439       field_type = TREE_TYPE (f);
1440       if (cmp < 0)
1441         {
1442           /* Don't care about offsets into the middle of scalars.  */
1443           if (!AGGREGATE_TYPE_P (field_type))
1444             continue;
1445
1446           /* Check for array at the end of the struct.  This is often
1447              used as for flexible array members.  We should be able to
1448              turn this into an array access anyway.  */
1449           if (TREE_CODE (field_type) == ARRAY_TYPE)
1450             tail_array_field = f;
1451
1452           /* Check the end of the field against the offset.  */
1453           if (!DECL_SIZE_UNIT (f)
1454               || TREE_CODE (DECL_SIZE_UNIT (f)) != INTEGER_CST)
1455             continue;
1456           t = int_const_binop (MINUS_EXPR, offset, DECL_FIELD_OFFSET (f), 1);
1457           if (!tree_int_cst_lt (t, DECL_SIZE_UNIT (f)))
1458             continue;
1459
1460           /* If we matched, then set offset to the displacement into
1461              this field.  */
1462           offset = t;
1463         }
1464
1465       /* Here we exactly match the offset being checked.  If the types match,
1466          then we can return that field.  */
1467       else if (lang_hooks.types_compatible_p (orig_type, field_type))
1468         {
1469           if (base_is_ptr)
1470             base = build1 (INDIRECT_REF, record_type, base);
1471           t = build (COMPONENT_REF, field_type, base, f, NULL_TREE);
1472           return t;
1473         }
1474
1475       /* Don't care about type-punning of scalars.  */
1476       else if (!AGGREGATE_TYPE_P (field_type))
1477         return NULL_TREE;
1478
1479       goto found;
1480     }
1481
1482   if (!tail_array_field)
1483     return NULL_TREE;
1484
1485   f = tail_array_field;
1486   field_type = TREE_TYPE (f);
1487
1488  found:
1489   /* If we get here, we've got an aggregate field, and a possibly 
1490      nonzero offset into them.  Recurse and hope for a valid match.  */
1491   if (base_is_ptr)
1492     base = build1 (INDIRECT_REF, record_type, base);
1493   base = build (COMPONENT_REF, field_type, base, f, NULL_TREE);
1494
1495   t = maybe_fold_offset_to_array_ref (base, offset, orig_type);
1496   if (t)
1497     return t;
1498   return maybe_fold_offset_to_component_ref (field_type, base, offset,
1499                                              orig_type, false);
1500 }
1501
1502
1503 /* A subroutine of fold_stmt_r.  Attempt to simplify *(BASE+OFFSET).
1504    Return the simplified expression, or NULL if nothing could be done.  */
1505
1506 static tree
1507 maybe_fold_stmt_indirect (tree expr, tree base, tree offset)
1508 {
1509   tree t;
1510
1511   /* We may well have constructed a double-nested PLUS_EXPR via multiple
1512      substitutions.  Fold that down to one.  Remove NON_LVALUE_EXPRs that
1513      are sometimes added.  */
1514   base = fold (base);
1515   STRIP_NOPS (base);
1516   TREE_OPERAND (expr, 0) = base;
1517
1518   /* One possibility is that the address reduces to a string constant.  */
1519   t = fold_read_from_constant_string (expr);
1520   if (t)
1521     return t;
1522
1523   /* Add in any offset from a PLUS_EXPR.  */
1524   if (TREE_CODE (base) == PLUS_EXPR)
1525     {
1526       tree offset2;
1527
1528       offset2 = TREE_OPERAND (base, 1);
1529       if (TREE_CODE (offset2) != INTEGER_CST)
1530         return NULL_TREE;
1531       base = TREE_OPERAND (base, 0);
1532
1533       offset = int_const_binop (PLUS_EXPR, offset, offset2, 1);
1534     }
1535
1536   if (TREE_CODE (base) == ADDR_EXPR)
1537     {
1538       /* Strip the ADDR_EXPR.  */
1539       base = TREE_OPERAND (base, 0);
1540
1541       /* Fold away CONST_DECL to its value, if the type is scalar.  */
1542       if (TREE_CODE (base) == CONST_DECL
1543           && is_gimple_min_invariant (DECL_INITIAL (base)))
1544         return DECL_INITIAL (base);
1545
1546       /* Try folding *(&B+O) to B[X].  */
1547       t = maybe_fold_offset_to_array_ref (base, offset, TREE_TYPE (expr));
1548       if (t)
1549         return t;
1550
1551       /* Try folding *(&B+O) to B.X.  */
1552       t = maybe_fold_offset_to_component_ref (TREE_TYPE (base), base, offset,
1553                                               TREE_TYPE (expr), false);
1554       if (t)
1555         return t;
1556
1557       /* Fold *&B to B.  We can only do this if EXPR is the same type
1558          as BASE.  We can't do this if EXPR is the element type of an array
1559          and BASE is the array.  */
1560       if (integer_zerop (offset)
1561           && lang_hooks.types_compatible_p (TREE_TYPE (base),
1562                                             TREE_TYPE (expr)))
1563         return base;
1564     }
1565   else
1566     {
1567       /* We can get here for out-of-range string constant accesses, 
1568          such as "_"[3].  Bail out of the entire substitution search
1569          and arrange for the entire statement to be replaced by a
1570          call to __builtin_trap.  In all likelyhood this will all be
1571          constant-folded away, but in the meantime we can't leave with
1572          something that get_expr_operands can't understand.  */
1573
1574       t = base;
1575       STRIP_NOPS (t);
1576       if (TREE_CODE (t) == ADDR_EXPR
1577           && TREE_CODE (TREE_OPERAND (t, 0)) == STRING_CST)
1578         {
1579           /* FIXME: Except that this causes problems elsewhere with dead
1580              code not being deleted, and we abort in the rtl expanders 
1581              because we failed to remove some ssa_name.  In the meantime,
1582              just return zero.  */
1583           /* FIXME2: This condition should be signaled by
1584              fold_read_from_constant_string directly, rather than 
1585              re-checking for it here.  */
1586           return integer_zero_node;
1587         }
1588
1589       /* Try folding *(B+O) to B->X.  Still an improvement.  */
1590       if (POINTER_TYPE_P (TREE_TYPE (base)))
1591         {
1592           t = maybe_fold_offset_to_component_ref (TREE_TYPE (TREE_TYPE (base)),
1593                                                   base, offset,
1594                                                   TREE_TYPE (expr), true);
1595           if (t)
1596             return t;
1597         }
1598     }
1599
1600   /* Otherwise we had an offset that we could not simplify.  */
1601   return NULL_TREE;
1602 }
1603
1604
1605 /* A subroutine of fold_stmt_r.  EXPR is a PLUS_EXPR.
1606
1607    A quaint feature extant in our address arithmetic is that there
1608    can be hidden type changes here.  The type of the result need
1609    not be the same as the type of the input pointer.
1610
1611    What we're after here is an expression of the form
1612         (T *)(&array + const)
1613    where the cast doesn't actually exist, but is implicit in the
1614    type of the PLUS_EXPR.  We'd like to turn this into
1615         &array[x]
1616    which may be able to propagate further.  */
1617
1618 static tree
1619 maybe_fold_stmt_addition (tree expr)
1620 {
1621   tree op0 = TREE_OPERAND (expr, 0);
1622   tree op1 = TREE_OPERAND (expr, 1);
1623   tree ptr_type = TREE_TYPE (expr);
1624   tree ptd_type;
1625   tree t;
1626   bool subtract = (TREE_CODE (expr) == MINUS_EXPR);
1627
1628   /* We're only interested in pointer arithmetic.  */
1629   if (!POINTER_TYPE_P (ptr_type))
1630     return NULL_TREE;
1631   /* Canonicalize the integral operand to op1.  */
1632   if (INTEGRAL_TYPE_P (TREE_TYPE (op0)))
1633     {
1634       if (subtract)
1635         return NULL_TREE;
1636       t = op0, op0 = op1, op1 = t;
1637     }
1638   /* It had better be a constant.  */
1639   if (TREE_CODE (op1) != INTEGER_CST)
1640     return NULL_TREE;
1641   /* The first operand should be an ADDR_EXPR.  */
1642   if (TREE_CODE (op0) != ADDR_EXPR)
1643     return NULL_TREE;
1644   op0 = TREE_OPERAND (op0, 0);
1645
1646   /* If the first operand is an ARRAY_REF, expand it so that we can fold
1647      the offset into it.  */
1648   while (TREE_CODE (op0) == ARRAY_REF)
1649     {
1650       tree array_obj = TREE_OPERAND (op0, 0);
1651       tree array_idx = TREE_OPERAND (op0, 1);
1652       tree elt_type = TREE_TYPE (op0);
1653       tree elt_size = TYPE_SIZE_UNIT (elt_type);
1654       tree min_idx;
1655
1656       if (TREE_CODE (array_idx) != INTEGER_CST)
1657         break;
1658       if (TREE_CODE (elt_size) != INTEGER_CST)
1659         break;
1660
1661       /* Un-bias the index by the min index of the array type.  */
1662       min_idx = TYPE_DOMAIN (TREE_TYPE (array_obj));
1663       if (min_idx)
1664         {
1665           min_idx = TYPE_MIN_VALUE (min_idx);
1666           if (min_idx)
1667             {
1668               if (TREE_CODE (min_idx) != INTEGER_CST)
1669                 break;
1670
1671               array_idx = convert (TREE_TYPE (min_idx), array_idx);
1672               if (!integer_zerop (min_idx))
1673                 array_idx = int_const_binop (MINUS_EXPR, array_idx,
1674                                              min_idx, 0);
1675             }
1676         }
1677
1678       /* Convert the index to a byte offset.  */
1679       array_idx = convert (sizetype, array_idx);
1680       array_idx = int_const_binop (MULT_EXPR, array_idx, elt_size, 0);
1681
1682       /* Update the operands for the next round, or for folding.  */
1683       /* If we're manipulating unsigned types, then folding into negative
1684          values can produce incorrect results.  Particularly if the type
1685          is smaller than the width of the pointer.  */
1686       if (subtract
1687           && TYPE_UNSIGNED (TREE_TYPE (op1))
1688           && tree_int_cst_lt (array_idx, op1))
1689         return NULL;
1690       op1 = int_const_binop (subtract ? MINUS_EXPR : PLUS_EXPR,
1691                              array_idx, op1, 0);
1692       subtract = false;
1693       op0 = array_obj;
1694     }
1695
1696   /* If we weren't able to fold the subtraction into another array reference,
1697      canonicalize the integer for passing to the array and component ref
1698      simplification functions.  */
1699   if (subtract)
1700     {
1701       if (TYPE_UNSIGNED (TREE_TYPE (op1)))
1702         return NULL;
1703       op1 = fold (build1 (NEGATE_EXPR, TREE_TYPE (op1), op1));
1704       /* ??? In theory fold should always produce another integer.  */
1705       if (TREE_CODE (op1) != INTEGER_CST)
1706         return NULL;
1707     }
1708
1709   ptd_type = TREE_TYPE (ptr_type);
1710
1711   /* At which point we can try some of the same things as for indirects.  */
1712   t = maybe_fold_offset_to_array_ref (op0, op1, ptd_type);
1713   if (!t)
1714     t = maybe_fold_offset_to_component_ref (TREE_TYPE (op0), op0, op1,
1715                                             ptd_type, false);
1716   if (t)
1717     t = build1 (ADDR_EXPR, ptr_type, t);
1718
1719   return t;
1720 }
1721
1722
1723 /* Subroutine of fold_stmt called via walk_tree.  We perform several
1724    simplifications of EXPR_P, mostly having to do with pointer arithmetic.  */
1725
1726 static tree
1727 fold_stmt_r (tree *expr_p, int *walk_subtrees, void *data)
1728 {
1729   bool *changed_p = data;
1730   tree expr = *expr_p, t;
1731
1732   /* ??? It'd be nice if walk_tree had a pre-order option.  */
1733   switch (TREE_CODE (expr))
1734     {
1735     case INDIRECT_REF:
1736       t = walk_tree (&TREE_OPERAND (expr, 0), fold_stmt_r, data, NULL);
1737       if (t)
1738         return t;
1739       *walk_subtrees = 0;
1740
1741       t = maybe_fold_stmt_indirect (expr, TREE_OPERAND (expr, 0),
1742                                     integer_zero_node);
1743       break;
1744
1745       /* ??? Could handle ARRAY_REF here, as a variant of INDIRECT_REF.
1746          We'd only want to bother decomposing an existing ARRAY_REF if
1747          the base array is found to have another offset contained within.
1748          Otherwise we'd be wasting time.  */
1749
1750     case ADDR_EXPR:
1751       t = walk_tree (&TREE_OPERAND (expr, 0), fold_stmt_r, data, NULL);
1752       if (t)
1753         return t;
1754       *walk_subtrees = 0;
1755
1756       /* Set TREE_INVARIANT properly so that the value is properly
1757          considered constant, and so gets propagated as expected.  */
1758       if (*changed_p)
1759         recompute_tree_invarant_for_addr_expr (expr);
1760       return NULL_TREE;
1761
1762     case PLUS_EXPR:
1763     case MINUS_EXPR:
1764       t = walk_tree (&TREE_OPERAND (expr, 0), fold_stmt_r, data, NULL);
1765       if (t)
1766         return t;
1767       t = walk_tree (&TREE_OPERAND (expr, 1), fold_stmt_r, data, NULL);
1768       if (t)
1769         return t;
1770       *walk_subtrees = 0;
1771
1772       t = maybe_fold_stmt_addition (expr);
1773       break;
1774
1775     case COMPONENT_REF:
1776       t = walk_tree (&TREE_OPERAND (expr, 0), fold_stmt_r, data, NULL);
1777       if (t)
1778         return t;
1779       *walk_subtrees = 0;
1780
1781       /* Make sure the FIELD_DECL is actually a field in the type on the lhs.
1782          We've already checked that the records are compatible, so we should
1783          come up with a set of compatible fields.  */
1784       {
1785         tree expr_record = TREE_TYPE (TREE_OPERAND (expr, 0));
1786         tree expr_field = TREE_OPERAND (expr, 1);
1787
1788         if (DECL_FIELD_CONTEXT (expr_field) != TYPE_MAIN_VARIANT (expr_record))
1789           {
1790             expr_field = find_compatible_field (expr_record, expr_field);
1791             TREE_OPERAND (expr, 1) = expr_field;
1792           }
1793       }
1794       break;
1795
1796     default:
1797       return NULL_TREE;
1798     }
1799
1800   if (t)
1801     {
1802       *expr_p = t;
1803       *changed_p = true;
1804     }
1805
1806   return NULL_TREE;
1807 }
1808
1809
1810 /* Return the string length of ARG in LENGTH.  If ARG is an SSA name variable,
1811    follow its use-def chains.  If LENGTH is not NULL and its value is not
1812    equal to the length we determine, or if we are unable to determine the
1813    length, return false.  VISITED is a bitmap of visited variables.  */
1814
1815 static bool
1816 get_strlen (tree arg, tree *length, bitmap visited)
1817 {
1818   tree var, def_stmt, val;
1819   
1820   if (TREE_CODE (arg) != SSA_NAME)
1821     {
1822       val = c_strlen (arg, 1);
1823       if (!val)
1824         return false;
1825
1826       if (*length && simple_cst_equal (val, *length) != 1)
1827         return false;
1828
1829       *length = val;
1830       return true;
1831     }
1832
1833   /* If we were already here, break the infinite cycle.  */
1834   if (bitmap_bit_p (visited, SSA_NAME_VERSION (arg)))
1835     return true;
1836   bitmap_set_bit (visited, SSA_NAME_VERSION (arg));
1837
1838   var = arg;
1839   def_stmt = SSA_NAME_DEF_STMT (var);
1840
1841   switch (TREE_CODE (def_stmt))
1842     {
1843       case MODIFY_EXPR:
1844         {
1845           tree len, rhs;
1846           
1847           /* The RHS of the statement defining VAR must either have a
1848              constant length or come from another SSA_NAME with a constant
1849              length.  */
1850           rhs = TREE_OPERAND (def_stmt, 1);
1851           STRIP_NOPS (rhs);
1852           if (TREE_CODE (rhs) == SSA_NAME)
1853             return get_strlen (rhs, length, visited);
1854
1855           /* See if the RHS is a constant length.  */
1856           len = c_strlen (rhs, 1);
1857           if (len)
1858             {
1859               if (*length && simple_cst_equal (len, *length) != 1)
1860                 return false;
1861
1862               *length = len;
1863               return true;
1864             }
1865
1866           break;
1867         }
1868
1869       case PHI_NODE:
1870         {
1871           /* All the arguments of the PHI node must have the same constant
1872              length.  */
1873           int i;
1874
1875           for (i = 0; i < PHI_NUM_ARGS (def_stmt); i++)
1876             {
1877               tree arg = PHI_ARG_DEF (def_stmt, i);
1878
1879               /* If this PHI has itself as an argument, we cannot
1880                  determine the string length of this argument.  However,
1881                  if we can find a constant string length for the other
1882                  PHI args then we can still be sure that this is a
1883                  constant string length.  So be optimistic and just
1884                  continue with the next argument.  */
1885               if (arg == PHI_RESULT (def_stmt))
1886                 continue;
1887
1888               if (!get_strlen (arg, length, visited))
1889                 return false;
1890             }
1891
1892           return true;
1893         }
1894
1895       default:
1896         break;
1897     }
1898
1899
1900   return false;
1901 }
1902
1903
1904 /* Fold builtin call FN in statement STMT.  If it cannot be folded into a
1905    constant, return NULL_TREE.  Otherwise, return its constant value.  */
1906
1907 static tree
1908 ccp_fold_builtin (tree stmt, tree fn)
1909 {
1910   tree result, strlen_val[2];
1911   tree callee, arglist, a;
1912   int strlen_arg, i;
1913   bitmap visited;
1914   bool ignore;
1915
1916   ignore = TREE_CODE (stmt) != MODIFY_EXPR;
1917
1918   /* First try the generic builtin folder.  If that succeeds, return the
1919      result directly.  */
1920   result = fold_builtin (fn, ignore);
1921   if (result)
1922   {
1923     if (ignore)
1924       STRIP_NOPS (result);
1925     return result;
1926   }
1927
1928   /* Ignore MD builtins.  */
1929   callee = get_callee_fndecl (fn);
1930   if (DECL_BUILT_IN_CLASS (callee) == BUILT_IN_MD)
1931     return NULL_TREE;
1932
1933   /* If the builtin could not be folded, and it has no argument list,
1934      we're done.  */
1935   arglist = TREE_OPERAND (fn, 1);
1936   if (!arglist)
1937     return NULL_TREE;
1938
1939   /* Limit the work only for builtins we know how to simplify.  */
1940   switch (DECL_FUNCTION_CODE (callee))
1941     {
1942     case BUILT_IN_STRLEN:
1943     case BUILT_IN_FPUTS:
1944     case BUILT_IN_FPUTS_UNLOCKED:
1945       strlen_arg = 1;
1946       break;
1947     case BUILT_IN_STRCPY:
1948     case BUILT_IN_STRNCPY:
1949       strlen_arg = 2;
1950       break;
1951     default:
1952       return NULL_TREE;
1953     }
1954
1955   /* Try to use the dataflow information gathered by the CCP process.  */
1956   visited = BITMAP_XMALLOC ();
1957
1958   memset (strlen_val, 0, sizeof (strlen_val));
1959   for (i = 0, a = arglist;
1960        strlen_arg;
1961        i++, strlen_arg >>= 1, a = TREE_CHAIN (a))
1962     if (strlen_arg & 1)
1963       {
1964         bitmap_clear (visited);
1965         if (!get_strlen (TREE_VALUE (a), &strlen_val[i], visited))
1966           strlen_val[i] = NULL_TREE;
1967       }
1968
1969   BITMAP_XFREE (visited);
1970
1971   result = NULL_TREE;
1972   switch (DECL_FUNCTION_CODE (callee))
1973     {
1974     case BUILT_IN_STRLEN:
1975       if (strlen_val[0])
1976         {
1977           tree new = fold_convert (TREE_TYPE (fn), strlen_val[0]);
1978
1979           /* If the result is not a valid gimple value, or not a cast
1980              of a valid gimple value, then we can not use the result.  */
1981           if (is_gimple_val (new)
1982               || (is_gimple_cast (new)
1983                   && is_gimple_val (TREE_OPERAND (new, 0))))
1984             return new;
1985         }
1986       break;
1987
1988     case BUILT_IN_STRCPY:
1989       if (strlen_val[1] && is_gimple_val (strlen_val[1]))
1990         result = fold_builtin_strcpy (fn, strlen_val[1]);
1991       break;
1992
1993     case BUILT_IN_STRNCPY:
1994       if (strlen_val[1] && is_gimple_val (strlen_val[1]))
1995         result = fold_builtin_strncpy (fn, strlen_val[1]);
1996       break;
1997
1998     case BUILT_IN_FPUTS:
1999       result = fold_builtin_fputs (arglist,
2000                                    TREE_CODE (stmt) != MODIFY_EXPR, 0,
2001                                    strlen_val[0]);
2002       break;
2003
2004     case BUILT_IN_FPUTS_UNLOCKED:
2005       result = fold_builtin_fputs (arglist,
2006                                    TREE_CODE (stmt) != MODIFY_EXPR, 1,
2007                                    strlen_val[0]);
2008       break;
2009
2010     default:
2011       gcc_unreachable ();
2012     }
2013
2014   if (result && ignore)
2015     result = fold_ignored_result (result);
2016   return result;
2017 }
2018
2019
2020 /* Fold the statement pointed by STMT_P.  In some cases, this function may
2021    replace the whole statement with a new one.  Returns true iff folding
2022    makes any changes.  */
2023
2024 bool
2025 fold_stmt (tree *stmt_p)
2026 {
2027   tree rhs, result, stmt;
2028   bool changed = false;
2029
2030   stmt = *stmt_p;
2031
2032   /* If we replaced constants and the statement makes pointer dereferences,
2033      then we may need to fold instances of *&VAR into VAR, etc.  */
2034   if (walk_tree (stmt_p, fold_stmt_r, &changed, NULL))
2035     {
2036       *stmt_p
2037         = build_function_call_expr (implicit_built_in_decls[BUILT_IN_TRAP],
2038                                     NULL);
2039       return true;
2040     }
2041
2042   rhs = get_rhs (stmt);
2043   if (!rhs)
2044     return changed;
2045   result = NULL_TREE;
2046
2047   if (TREE_CODE (rhs) == CALL_EXPR)
2048     {
2049       tree callee;
2050
2051       /* Check for builtins that CCP can handle using information not
2052          available in the generic fold routines.  */
2053       callee = get_callee_fndecl (rhs);
2054       if (callee && DECL_BUILT_IN (callee))
2055         result = ccp_fold_builtin (stmt, rhs);
2056       else
2057         {
2058           /* Check for resolvable OBJ_TYPE_REF.  The only sorts we can resolve
2059              here are when we've propagated the address of a decl into the
2060              object slot.  */
2061           /* ??? Should perhaps do this in fold proper.  However, doing it
2062              there requires that we create a new CALL_EXPR, and that requires
2063              copying EH region info to the new node.  Easier to just do it
2064              here where we can just smash the call operand.  */
2065           callee = TREE_OPERAND (rhs, 0);
2066           if (TREE_CODE (callee) == OBJ_TYPE_REF
2067               && lang_hooks.fold_obj_type_ref
2068               && TREE_CODE (OBJ_TYPE_REF_OBJECT (callee)) == ADDR_EXPR
2069               && DECL_P (TREE_OPERAND
2070                          (OBJ_TYPE_REF_OBJECT (callee), 0)))
2071             {
2072               tree t;
2073
2074               /* ??? Caution: Broken ADDR_EXPR semantics means that
2075                  looking at the type of the operand of the addr_expr
2076                  can yield an array type.  See silly exception in
2077                  check_pointer_types_r.  */
2078
2079               t = TREE_TYPE (TREE_TYPE (OBJ_TYPE_REF_OBJECT (callee)));
2080               t = lang_hooks.fold_obj_type_ref (callee, t);
2081               if (t)
2082                 {
2083                   TREE_OPERAND (rhs, 0) = t;
2084                   changed = true;
2085                 }
2086             }
2087         }
2088     }
2089
2090   /* If we couldn't fold the RHS, hand over to the generic fold routines.  */
2091   if (result == NULL_TREE)
2092     result = fold (rhs);
2093
2094   /* Strip away useless type conversions.  Both the NON_LVALUE_EXPR that
2095      may have been added by fold, and "useless" type conversions that might
2096      now be apparent due to propagation.  */
2097   STRIP_USELESS_TYPE_CONVERSION (result);
2098
2099   if (result != rhs)
2100     changed |= set_rhs (stmt_p, result);
2101
2102   return changed;
2103 }
2104
2105 \f
2106 /* Convert EXPR into a GIMPLE value suitable for substitution on the
2107    RHS of an assignment.  Insert the necessary statements before
2108    iterator *SI_P.  */
2109
2110 static tree
2111 convert_to_gimple_builtin (block_stmt_iterator *si_p, tree expr)
2112 {
2113   tree_stmt_iterator ti;
2114   tree stmt = bsi_stmt (*si_p);
2115   tree tmp, stmts = NULL;
2116
2117   push_gimplify_context ();
2118   tmp = get_initialized_tmp_var (expr, &stmts, NULL);
2119   pop_gimplify_context (NULL);
2120
2121   /* The replacement can expose previously unreferenced variables.  */
2122   for (ti = tsi_start (stmts); !tsi_end_p (ti); tsi_next (&ti))
2123     {
2124       find_new_referenced_vars (tsi_stmt_ptr (ti));
2125       mark_new_vars_to_rename (tsi_stmt (ti), vars_to_rename);
2126     }
2127
2128   if (EXPR_HAS_LOCATION (stmt))
2129     annotate_all_with_locus (&stmts, EXPR_LOCATION (stmt));
2130
2131   bsi_insert_before (si_p, stmts, BSI_SAME_STMT);
2132
2133   return tmp;
2134 }
2135
2136
2137 /* A simple pass that attempts to fold all builtin functions.  This pass
2138    is run after we've propagated as many constants as we can.  */
2139
2140 static void
2141 execute_fold_all_builtins (void)
2142 {
2143   bool cfg_changed = false;
2144   basic_block bb;
2145   FOR_EACH_BB (bb)
2146     {
2147       block_stmt_iterator i;
2148       for (i = bsi_start (bb); !bsi_end_p (i); bsi_next (&i))
2149         {
2150           tree *stmtp = bsi_stmt_ptr (i);
2151           tree call = get_rhs (*stmtp);
2152           tree callee, result;
2153
2154           if (!call || TREE_CODE (call) != CALL_EXPR)
2155             continue;
2156           callee = get_callee_fndecl (call);
2157           if (!callee || DECL_BUILT_IN_CLASS (callee) != BUILT_IN_NORMAL)
2158             continue;
2159
2160           result = ccp_fold_builtin (*stmtp, call);
2161           if (!result)
2162             switch (DECL_FUNCTION_CODE (callee))
2163               {
2164               case BUILT_IN_CONSTANT_P:
2165                 /* Resolve __builtin_constant_p.  If it hasn't been
2166                    folded to integer_one_node by now, it's fairly
2167                    certain that the value simply isn't constant.  */
2168                 result = integer_zero_node;
2169                 break;
2170
2171               default:
2172                 continue;
2173               }
2174
2175           if (dump_file && (dump_flags & TDF_DETAILS))
2176             {
2177               fprintf (dump_file, "Simplified\n  ");
2178               print_generic_stmt (dump_file, *stmtp, dump_flags);
2179             }
2180
2181           if (!set_rhs (stmtp, result))
2182             {
2183               result = convert_to_gimple_builtin (&i, result);
2184               if (result && !set_rhs (stmtp, result))
2185                 abort ();
2186             }
2187           modify_stmt (*stmtp);
2188           if (maybe_clean_eh_stmt (*stmtp)
2189               && tree_purge_dead_eh_edges (bb))
2190             cfg_changed = true;
2191
2192           if (dump_file && (dump_flags & TDF_DETAILS))
2193             {
2194               fprintf (dump_file, "to\n  ");
2195               print_generic_stmt (dump_file, *stmtp, dump_flags);
2196               fprintf (dump_file, "\n");
2197             }
2198         }
2199     }
2200
2201   /* Delete unreachable blocks.  */
2202   if (cfg_changed)
2203     cleanup_tree_cfg ();
2204 }
2205
2206
2207 struct tree_opt_pass pass_fold_builtins = 
2208 {
2209   "fab",                                /* name */
2210   NULL,                                 /* gate */
2211   execute_fold_all_builtins,            /* execute */
2212   NULL,                                 /* sub */
2213   NULL,                                 /* next */
2214   0,                                    /* static_pass_number */
2215   0,                                    /* tv_id */
2216   PROP_cfg | PROP_ssa | PROP_alias,     /* properties_required */
2217   0,                                    /* properties_provided */
2218   0,                                    /* properties_destroyed */
2219   0,                                    /* todo_flags_start */
2220   TODO_dump_func
2221     | TODO_verify_ssa
2222     | TODO_rename_vars,                 /* todo_flags_finish */
2223   0                                     /* letter */
2224 };