OSDN Git Service

2004-09-23 Frank Ch. Eigler <fche@redhat.com>
[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_EQUIV (var)
140       && is_gimple_min_invariant (SSA_NAME_EQUIV (var)))
141     {
142       val.lattice_val = CONSTANT;
143       val.const_val = SSA_NAME_EQUIV (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       value *val = get_value (USE_FROM_PTR (use));
458
459       if (val->lattice_val == CONSTANT)
460         {
461           SET_USE (use, val->const_val);
462           replaced = true;
463           if (POINTER_TYPE_P (TREE_TYPE (USE_FROM_PTR (use))) 
464               && replaced_addresses_p)
465             *replaced_addresses_p = true;
466         }
467     }
468
469   return replaced;
470 }
471
472
473 /* Replace the VUSE references in statement STMT with its immediate reaching
474    definition.  Return true if the reference was replaced.  If
475    REPLACED_ADDRESSES_P is given, it will be set to true if an address
476    constant was replaced.  */
477
478 static bool
479 replace_vuse_in (tree stmt, bool *replaced_addresses_p)
480 {
481   bool replaced = false;
482   vuse_optype vuses;
483   use_operand_p vuse;
484   value *val;
485
486   if (replaced_addresses_p)
487     *replaced_addresses_p = false;
488
489   get_stmt_operands (stmt);
490
491   vuses = STMT_VUSE_OPS (stmt);
492
493   if (NUM_VUSES (vuses) != 1)
494     return false;
495
496   vuse = VUSE_OP_PTR (vuses, 0);
497   val = get_value (USE_FROM_PTR (vuse));
498
499   if (val->lattice_val == CONSTANT
500       && TREE_CODE (stmt) == MODIFY_EXPR
501       && DECL_P (TREE_OPERAND (stmt, 1))
502       && TREE_OPERAND (stmt, 1) == SSA_NAME_VAR (USE_FROM_PTR (vuse)))
503     {
504       TREE_OPERAND (stmt, 1) = val->const_val;
505       replaced = true;
506       if (POINTER_TYPE_P (TREE_TYPE (USE_FROM_PTR (vuse))) 
507           && replaced_addresses_p)
508         *replaced_addresses_p = true;
509     }
510
511   return replaced;
512 }
513
514
515 /* Perform final substitution and folding.  After this pass the program
516    should still be in SSA form.  */
517
518 static void
519 substitute_and_fold (void)
520 {
521   basic_block bb;
522   unsigned int i;
523
524   if (dump_file && (dump_flags & TDF_DETAILS))
525     fprintf (dump_file,
526              "\nSubstituing constants and folding statements\n\n");
527
528   /* Substitute constants in every statement of every basic block.  */
529   FOR_EACH_BB (bb)
530     {
531       block_stmt_iterator i;
532       tree phi;
533
534       /* Propagate our known constants into PHI nodes.  */
535       for (phi = phi_nodes (bb); phi; phi = PHI_CHAIN (phi))
536         {
537           int i;
538
539           for (i = 0; i < PHI_NUM_ARGS (phi); i++)
540             {
541               value *new_val;
542               use_operand_p orig_p = PHI_ARG_DEF_PTR (phi, i);
543               tree orig = USE_FROM_PTR (orig_p);
544
545               if (! SSA_VAR_P (orig))
546                 break;
547
548               new_val = get_value (orig);
549               if (new_val->lattice_val == CONSTANT
550                   && may_propagate_copy (orig, new_val->const_val))
551                 SET_USE (orig_p, new_val->const_val);
552             }
553         }
554
555       for (i = bsi_start (bb); !bsi_end_p (i); bsi_next (&i))
556         {
557           bool replaced_address;
558           tree stmt = bsi_stmt (i);
559
560           /* Skip statements that have been folded already.  */
561           if (stmt_modified_p (stmt) || !is_exec_stmt (stmt))
562             continue;
563
564           /* Replace the statement with its folded version and mark it
565              folded.  */
566           if (dump_file && (dump_flags & TDF_DETAILS))
567             {
568               fprintf (dump_file, "Line %d: replaced ", get_lineno (stmt));
569               print_generic_stmt (dump_file, stmt, TDF_SLIM);
570             }
571
572           if (replace_uses_in (stmt, &replaced_address)
573               || replace_vuse_in (stmt, &replaced_address))
574             {
575               bool changed = fold_stmt (bsi_stmt_ptr (i));
576               stmt = bsi_stmt(i);
577               /* If we folded a builtin function, we'll likely
578                  need to rename VDEFs.  */
579               if (replaced_address || changed)
580                 {
581                   mark_new_vars_to_rename (stmt, vars_to_rename);
582                   if (maybe_clean_eh_stmt (stmt))
583                     tree_purge_dead_eh_edges (bb);
584                 }
585               else
586                 modify_stmt (stmt);
587             }
588
589           if (dump_file && (dump_flags & TDF_DETAILS))
590             {
591               fprintf (dump_file, " with ");
592               print_generic_stmt (dump_file, stmt, TDF_SLIM);
593               fprintf (dump_file, "\n");
594             }
595         }
596     }
597
598   /* And transfer what we learned from VALUE_VECTOR into the
599      SSA_NAMEs themselves.  This probably isn't terribly important
600      since we probably constant propagated the values to their
601      use sites above.  */
602   for (i = 0; i < num_ssa_names; i++)
603     {
604       tree name = ssa_name (i);
605       value *value;
606
607       if (!name)
608         continue;
609
610       value = get_value (name);
611       if (value->lattice_val == CONSTANT
612           && is_gimple_reg (name)
613           && is_gimple_min_invariant (value->const_val))
614         SET_SSA_NAME_EQUIV (name, value->const_val)
615     }
616 }
617
618
619 /* Free allocated storage.  */
620
621 static void
622 ccp_finalize (void)
623 {
624   /* Perform substitutions based on the known constant values.  */
625   substitute_and_fold ();
626
627   /* Now cleanup any unreachable code.  */
628   cleanup_tree_cfg ();
629
630   free (value_vector);
631 }
632
633
634
635 /* Compute the meet operator between VAL1 and VAL2:
636
637                 any  M UNDEFINED     = any
638                 any  M VARYING       = VARYING
639                 any  M UNKNOWN_VAL   = UNKNOWN_VAL
640                 Ci   M Cj            = Ci       if (i == j)
641                 Ci   M Cj            = VARYING  if (i != j)  */
642 static value
643 ccp_lattice_meet (value val1, value val2)
644 {
645   value result;
646
647   /* any M UNDEFINED = any.  */
648   if (val1.lattice_val == UNDEFINED)
649     return val2;
650   else if (val2.lattice_val == UNDEFINED)
651     return val1;
652
653   /* any M VARYING = VARYING.  */
654   if (val1.lattice_val == VARYING || val2.lattice_val == VARYING)
655     {
656       result.lattice_val = VARYING;
657       result.const_val = NULL_TREE;
658       return result;
659     }
660
661   /* any M UNKNOWN_VAL = UNKNOWN_VAL.  */
662   if (val1.lattice_val == UNKNOWN_VAL 
663       || val2.lattice_val == UNKNOWN_VAL)
664     {
665       result.lattice_val = UNKNOWN_VAL;
666       result.const_val = NULL_TREE;
667       return result;
668     }
669
670   /* Ci M Cj = Ci       if (i == j)
671      Ci M Cj = VARYING  if (i != j)  */
672   if (simple_cst_equal (val1.const_val, val2.const_val) == 1)
673     {
674       result.lattice_val = CONSTANT;
675       result.const_val = val1.const_val;
676     }
677   else
678     {
679       result.lattice_val = VARYING;
680       result.const_val = NULL_TREE;
681     }
682
683   return result;
684 }
685
686
687 /* Loop through the PHI_NODE's parameters for BLOCK and compare their
688    lattice values to determine PHI_NODE's lattice value.  The value of a
689    PHI node is determined calling ccp_lattice_meet() with all the arguments
690    of the PHI node that are incoming via executable edges.  */
691
692 static enum ssa_prop_result
693 ccp_visit_phi_node (tree phi)
694 {
695   value new_val, *old_val;
696   int i;
697
698   if (dump_file && (dump_flags & TDF_DETAILS))
699     {
700       fprintf (dump_file, "\nVisiting PHI node: ");
701       print_generic_expr (dump_file, phi, dump_flags);
702     }
703
704   old_val = get_value (PHI_RESULT (phi));
705   switch (old_val->lattice_val)
706     {
707     case VARYING:
708       return SSA_PROP_NOT_INTERESTING;
709
710     case CONSTANT:
711       new_val = *old_val;
712       break;
713
714     case UNKNOWN_VAL:
715       /* To avoid the default value of UNKNOWN_VAL overriding
716          that of its possible constant arguments, temporarily
717          set the PHI node's default lattice value to be 
718          UNDEFINED.  If the PHI node's old value was UNKNOWN_VAL and
719          the new value is UNDEFINED, then we prevent the invalid
720          transition by not calling set_lattice_value.  */
721       new_val.lattice_val = UNDEFINED;
722       new_val.const_val = NULL_TREE;
723       break;
724
725     case UNDEFINED:
726     case UNINITIALIZED:
727       new_val.lattice_val = UNDEFINED;
728       new_val.const_val = NULL_TREE;
729       break;
730
731     default:
732       gcc_unreachable ();
733     }
734
735   for (i = 0; i < PHI_NUM_ARGS (phi); i++)
736     {
737       /* Compute the meet operator over all the PHI arguments.  */
738       edge e = PHI_ARG_EDGE (phi, i);
739
740       if (dump_file && (dump_flags & TDF_DETAILS))
741         {
742           fprintf (dump_file,
743               "\n    Argument #%d (%d -> %d %sexecutable)\n",
744               i, e->src->index, e->dest->index,
745               (e->flags & EDGE_EXECUTABLE) ? "" : "not ");
746         }
747
748       /* If the incoming edge is executable, Compute the meet operator for
749          the existing value of the PHI node and the current PHI argument.  */
750       if (e->flags & EDGE_EXECUTABLE)
751         {
752           tree rdef = PHI_ARG_DEF (phi, i);
753           value *rdef_val, val;
754
755           if (is_gimple_min_invariant (rdef))
756             {
757               val.lattice_val = CONSTANT;
758               val.const_val = rdef;
759               rdef_val = &val;
760             }
761           else
762             rdef_val = get_value (rdef);
763
764           new_val = ccp_lattice_meet (new_val, *rdef_val);
765
766           if (dump_file && (dump_flags & TDF_DETAILS))
767             {
768               fprintf (dump_file, "\t");
769               print_generic_expr (dump_file, rdef, dump_flags);
770               dump_lattice_value (dump_file, "\tValue: ", *rdef_val);
771               fprintf (dump_file, "\n");
772             }
773
774           if (new_val.lattice_val == VARYING)
775             break;
776         }
777     }
778
779   if (dump_file && (dump_flags & TDF_DETAILS))
780     {
781       dump_lattice_value (dump_file, "\n    PHI node value: ", new_val);
782       fprintf (dump_file, "\n\n");
783     }
784
785   /* Check for an invalid change from UNKNOWN_VAL to UNDEFINED.  */
786   if (old_val->lattice_val == UNKNOWN_VAL
787       && new_val.lattice_val == UNDEFINED)
788     return SSA_PROP_NOT_INTERESTING;
789
790   /* Otherwise, make the transition to the new value.  */
791   if (set_lattice_value (PHI_RESULT (phi), new_val))
792     {
793       if (new_val.lattice_val == VARYING)
794         return SSA_PROP_VARYING;
795       else
796         return SSA_PROP_INTERESTING;
797     }
798   else
799     return SSA_PROP_NOT_INTERESTING;
800 }
801
802
803 /* CCP specific front-end to the non-destructive constant folding
804    routines.
805
806    Attempt to simplify the RHS of STMT knowing that one or more
807    operands are constants.
808
809    If simplification is possible, return the simplified RHS,
810    otherwise return the original RHS.  */
811
812 static tree
813 ccp_fold (tree stmt)
814 {
815   tree rhs = get_rhs (stmt);
816   enum tree_code code = TREE_CODE (rhs);
817   enum tree_code_class kind = TREE_CODE_CLASS (code);
818   tree retval = NULL_TREE;
819   vuse_optype vuses;
820   
821   vuses = STMT_VUSE_OPS (stmt);
822
823   /* If the RHS is just a variable, then that variable must now have
824      a constant value that we can return directly.  */
825   if (TREE_CODE (rhs) == SSA_NAME)
826     return get_value (rhs)->const_val;
827   else if (DECL_P (rhs) 
828            && NUM_VUSES (vuses) == 1
829            && rhs == SSA_NAME_VAR (VUSE_OP (vuses, 0)))
830     return get_value (VUSE_OP (vuses, 0))->const_val;
831
832   /* Unary operators.  Note that we know the single operand must
833      be a constant.  So this should almost always return a
834      simplified RHS.  */
835   if (kind == tcc_unary)
836     {
837       /* Handle unary operators which can appear in GIMPLE form.  */
838       tree op0 = TREE_OPERAND (rhs, 0);
839
840       /* Simplify the operand down to a constant.  */
841       if (TREE_CODE (op0) == SSA_NAME)
842         {
843           value *val = get_value (op0);
844           if (val->lattice_val == CONSTANT)
845             op0 = get_value (op0)->const_val;
846         }
847
848       retval = nondestructive_fold_unary_to_constant (code,
849                                                       TREE_TYPE (rhs),
850                                                       op0);
851
852       /* If we folded, but did not create an invariant, then we can not
853          use this expression.  */
854       if (retval && ! is_gimple_min_invariant (retval))
855         return NULL;
856
857       /* If we could not fold the expression, but the arguments are all
858          constants and gimple values, then build and return the new
859          expression. 
860
861          In some cases the new expression is still something we can
862          use as a replacement for an argument.  This happens with
863          NOP conversions of types for example.
864
865          In other cases the new expression can not be used as a
866          replacement for an argument (as it would create non-gimple
867          code).  But the new expression can still be used to derive
868          other constants.  */
869       if (! retval && is_gimple_min_invariant (op0))
870         return build1 (code, TREE_TYPE (rhs), op0);
871     }
872
873   /* Binary and comparison operators.  We know one or both of the
874      operands are constants.  */
875   else if (kind == tcc_binary
876            || kind == tcc_comparison
877            || code == TRUTH_AND_EXPR
878            || code == TRUTH_OR_EXPR
879            || code == TRUTH_XOR_EXPR)
880     {
881       /* Handle binary and comparison operators that can appear in
882          GIMPLE form.  */
883       tree op0 = TREE_OPERAND (rhs, 0);
884       tree op1 = TREE_OPERAND (rhs, 1);
885
886       /* Simplify the operands down to constants when appropriate.  */
887       if (TREE_CODE (op0) == SSA_NAME)
888         {
889           value *val = get_value (op0);
890           if (val->lattice_val == CONSTANT)
891             op0 = val->const_val;
892         }
893
894       if (TREE_CODE (op1) == SSA_NAME)
895         {
896           value *val = get_value (op1);
897           if (val->lattice_val == CONSTANT)
898             op1 = val->const_val;
899         }
900
901       retval = nondestructive_fold_binary_to_constant (code,
902                                                        TREE_TYPE (rhs),
903                                                        op0, op1);
904
905       /* If we folded, but did not create an invariant, then we can not
906          use this expression.  */
907       if (retval && ! is_gimple_min_invariant (retval))
908         return NULL;
909       
910       /* If we could not fold the expression, but the arguments are all
911          constants and gimple values, then build and return the new
912          expression. 
913
914          In some cases the new expression is still something we can
915          use as a replacement for an argument.  This happens with
916          NOP conversions of types for example.
917
918          In other cases the new expression can not be used as a
919          replacement for an argument (as it would create non-gimple
920          code).  But the new expression can still be used to derive
921          other constants.  */
922       if (! retval
923           && is_gimple_min_invariant (op0)
924           && is_gimple_min_invariant (op1))
925         return build (code, TREE_TYPE (rhs), op0, op1);
926     }
927
928   /* We may be able to fold away calls to builtin functions if their
929      arguments are constants.  */
930   else if (code == CALL_EXPR
931            && TREE_CODE (TREE_OPERAND (rhs, 0)) == ADDR_EXPR
932            && (TREE_CODE (TREE_OPERAND (TREE_OPERAND (rhs, 0), 0))
933                == FUNCTION_DECL)
934            && DECL_BUILT_IN (TREE_OPERAND (TREE_OPERAND (rhs, 0), 0)))
935     {
936       use_optype uses = STMT_USE_OPS (stmt);
937       if (NUM_USES (uses) != 0)
938         {
939           tree *orig;
940           size_t i;
941
942           /* Preserve the original values of every operand.  */
943           orig = xmalloc (sizeof (tree) * NUM_USES (uses));
944           for (i = 0; i < NUM_USES (uses); i++)
945             orig[i] = USE_OP (uses, i);
946
947           /* Substitute operands with their values and try to fold.  */
948           replace_uses_in (stmt, NULL);
949           retval = fold_builtin (rhs, false);
950
951           /* Restore operands to their original form.  */
952           for (i = 0; i < NUM_USES (uses); i++)
953             SET_USE_OP (uses, i, orig[i]);
954           free (orig);
955         }
956     }
957   else
958     return rhs;
959
960   /* If we got a simplified form, see if we need to convert its type.  */
961   if (retval)
962     return fold_convert (TREE_TYPE (rhs), retval);
963
964   /* No simplification was possible.  */
965   return rhs;
966 }
967
968
969 /* Evaluate statement STMT.  */
970
971 static value
972 evaluate_stmt (tree stmt)
973 {
974   value val;
975   tree simplified;
976   latticevalue likelyvalue = likely_value (stmt);
977
978   /* If the statement is likely to have a CONSTANT result, then try
979      to fold the statement to determine the constant value.  */
980   if (likelyvalue == CONSTANT)
981     simplified = ccp_fold (stmt);
982   /* If the statement is likely to have a VARYING result, then do not
983      bother folding the statement.  */
984   else if (likelyvalue == VARYING)
985     simplified = get_rhs (stmt);
986   /* Otherwise the statement is likely to have an UNDEFINED value and
987      there will be nothing to do.  */
988   else
989     simplified = NULL_TREE;
990
991   if (simplified && is_gimple_min_invariant (simplified))
992     {
993       /* The statement produced a constant value.  */
994       val.lattice_val = CONSTANT;
995       val.const_val = simplified;
996     }
997   else
998     {
999       /* The statement produced a nonconstant value.  If the statement
1000          had undefined or virtual operands, then the result of the 
1001          statement should be undefined or virtual respectively.  
1002          Else the result of the statement is VARYING.  */
1003       val.lattice_val = (likelyvalue == UNDEFINED ? UNDEFINED : VARYING);
1004       val.lattice_val = (likelyvalue == UNKNOWN_VAL 
1005                            ? UNKNOWN_VAL : val.lattice_val);
1006       val.const_val = NULL_TREE;
1007     }
1008
1009   return val;
1010 }
1011
1012
1013 /* Visit the assignment statement STMT.  Set the value of its LHS to the
1014    value computed by the RHS and store LHS in *OUTPUT_P.  */
1015
1016 static enum ssa_prop_result
1017 visit_assignment (tree stmt, tree *output_p)
1018 {
1019   value val;
1020   tree lhs, rhs;
1021   vuse_optype vuses;
1022   v_must_def_optype v_must_defs;
1023
1024   lhs = TREE_OPERAND (stmt, 0);
1025   rhs = TREE_OPERAND (stmt, 1);
1026   vuses = STMT_VUSE_OPS (stmt);
1027   v_must_defs = STMT_V_MUST_DEF_OPS (stmt);
1028
1029   gcc_assert (NUM_V_MAY_DEFS (STMT_V_MAY_DEF_OPS (stmt)) == 0);
1030   gcc_assert (NUM_V_MUST_DEFS (v_must_defs) == 1
1031               || TREE_CODE (lhs) == SSA_NAME);
1032
1033   /* We require the SSA version number of the lhs for the value_vector.
1034      Make sure we have it.  */
1035   if (TREE_CODE (lhs) != SSA_NAME)
1036     {
1037       /* If we make it here, then stmt only has one definition:
1038          a V_MUST_DEF.  */
1039       lhs = V_MUST_DEF_OP (v_must_defs, 0);
1040     }
1041
1042   if (TREE_CODE (rhs) == SSA_NAME)
1043     {
1044       /* For a simple copy operation, we copy the lattice values.  */
1045       value *nval = get_value (rhs);
1046       val = *nval;
1047     }
1048   else if (DECL_P (rhs) 
1049            && NUM_VUSES (vuses) == 1
1050            && rhs == SSA_NAME_VAR (VUSE_OP (vuses, 0)))
1051     {
1052       /* Same as above, but the rhs is not a gimple register and yet
1053         has a known VUSE.  */
1054       value *nval = get_value (VUSE_OP (vuses, 0));
1055       val = *nval;
1056     }
1057   else
1058     {
1059       /* Evaluate the statement.  */
1060       val = evaluate_stmt (stmt);
1061     }
1062
1063   /* FIXME: Hack.  If this was a definition of a bitfield, we need to widen
1064      the constant value into the type of the destination variable.  This
1065      should not be necessary if GCC represented bitfields properly.  */
1066   {
1067     tree lhs = TREE_OPERAND (stmt, 0);
1068     if (val.lattice_val == CONSTANT
1069         && TREE_CODE (lhs) == COMPONENT_REF
1070         && DECL_BIT_FIELD (TREE_OPERAND (lhs, 1)))
1071       {
1072         tree w = widen_bitfield (val.const_val, TREE_OPERAND (lhs, 1), lhs);
1073
1074         if (w && is_gimple_min_invariant (w))
1075           val.const_val = w;
1076         else
1077           {
1078             val.lattice_val = VARYING;
1079             val.const_val = NULL;
1080           }
1081       }
1082   }
1083
1084   /* If LHS is not a gimple register, then it cannot take on an
1085      UNDEFINED value.  */
1086   if (!is_gimple_reg (SSA_NAME_VAR (lhs)) 
1087       && val.lattice_val == UNDEFINED)
1088     val.lattice_val = UNKNOWN_VAL;      
1089
1090   /* Set the lattice value of the statement's output.  */
1091   if (set_lattice_value (lhs, val))
1092     {
1093       *output_p = lhs;
1094       if (val.lattice_val == VARYING)
1095         return SSA_PROP_VARYING;
1096       else
1097         return SSA_PROP_INTERESTING;
1098     }
1099   else
1100     return SSA_PROP_NOT_INTERESTING;
1101 }
1102
1103
1104 /* Visit the conditional statement STMT.  Return SSA_PROP_INTERESTING
1105    if it can determine which edge will be taken.  Otherwise, return
1106    SSA_PROP_VARYING.  */
1107
1108 static enum ssa_prop_result
1109 visit_cond_stmt (tree stmt, edge *taken_edge_p)
1110 {
1111   value val;
1112   basic_block block;
1113
1114   block = bb_for_stmt (stmt);
1115   val = evaluate_stmt (stmt);
1116
1117   /* Find which edge out of the conditional block will be taken and add it
1118      to the worklist.  If no single edge can be determined statically,
1119      return SSA_PROP_VARYING to feed all the outgoing edges to the
1120      propagation engine.  */
1121   *taken_edge_p = find_taken_edge (block, val.const_val);
1122   if (*taken_edge_p)
1123     return SSA_PROP_INTERESTING;
1124   else
1125     return SSA_PROP_VARYING;
1126 }
1127
1128
1129 /* Evaluate statement STMT.  If the statement produces an output value and
1130    its evaluation changes the lattice value of its output, return
1131    SSA_PROP_INTERESTING and set *OUTPUT_P to the SSA_NAME holding the
1132    output value.
1133    
1134    If STMT is a conditional branch and we can determine its truth
1135    value, set *TAKEN_EDGE_P accordingly.  If STMT produces a varying
1136    value, return SSA_PROP_VARYING.  */
1137
1138 static enum ssa_prop_result
1139 ccp_visit_stmt (tree stmt, edge *taken_edge_p, tree *output_p)
1140 {
1141   stmt_ann_t ann;
1142   v_may_def_optype v_may_defs;
1143   v_must_def_optype v_must_defs;
1144   tree def;
1145   ssa_op_iter iter;
1146
1147   if (dump_file && (dump_flags & TDF_DETAILS))
1148     {
1149       fprintf (dump_file, "\nVisiting statement: ");
1150       print_generic_stmt (dump_file, stmt, TDF_SLIM);
1151       fprintf (dump_file, "\n");
1152     }
1153
1154   ann = stmt_ann (stmt);
1155
1156   v_must_defs = V_MUST_DEF_OPS (ann);
1157   v_may_defs = V_MAY_DEF_OPS (ann);
1158   if (TREE_CODE (stmt) == MODIFY_EXPR
1159       && NUM_V_MAY_DEFS (v_may_defs) == 0
1160       && (NUM_V_MUST_DEFS (v_must_defs) == 1
1161           || TREE_CODE (TREE_OPERAND (stmt, 0)) == SSA_NAME))
1162     {
1163       /* If the statement is an assignment that produces a single
1164          output value, evaluate its RHS to see if the lattice value of
1165          its output has changed.  */
1166       return visit_assignment (stmt, output_p);
1167     }
1168   else if (TREE_CODE (stmt) == COND_EXPR || TREE_CODE (stmt) == SWITCH_EXPR)
1169     {
1170       /* If STMT is a conditional branch, see if we can determine
1171          which branch will be taken.  */
1172       return visit_cond_stmt (stmt, taken_edge_p);
1173     }
1174
1175   /* Any other kind of statement is not interesting for constant
1176      propagation and, therefore, not worth simulating.  */
1177   if (dump_file && (dump_flags & TDF_DETAILS))
1178     fprintf (dump_file, "No interesting values produced.  Marked VARYING.\n");
1179
1180   /* Definitions made by statements other than assignments to
1181      SSA_NAMEs represent unknown modifications to their outputs.
1182      Mark them VARYING.  */
1183   FOR_EACH_SSA_TREE_OPERAND (def, stmt, iter, SSA_OP_DEF)
1184     def_to_varying (def);
1185
1186   /* Mark all V_MAY_DEF operands VARYING.  */
1187   FOR_EACH_SSA_TREE_OPERAND (def, stmt, iter, SSA_OP_VMAYDEF)
1188     def_to_varying (def);
1189
1190   return SSA_PROP_VARYING;
1191 }
1192
1193
1194 /* Main entry point for SSA Conditional Constant Propagation.
1195
1196    [ DESCRIBE MAIN ALGORITHM HERE ]  */
1197
1198 static void
1199 execute_ssa_ccp (void)
1200 {
1201   ccp_initialize ();
1202   ssa_propagate (ccp_visit_stmt, ccp_visit_phi_node);
1203   ccp_finalize ();
1204 }
1205
1206
1207 static bool
1208 gate_ccp (void)
1209 {
1210   return flag_tree_ccp != 0;
1211 }
1212
1213
1214 struct tree_opt_pass pass_ccp = 
1215 {
1216   "ccp",                                /* name */
1217   gate_ccp,                             /* gate */
1218   execute_ssa_ccp,                      /* execute */
1219   NULL,                                 /* sub */
1220   NULL,                                 /* next */
1221   0,                                    /* static_pass_number */
1222   TV_TREE_CCP,                          /* tv_id */
1223   PROP_cfg | PROP_ssa | PROP_alias,     /* properties_required */
1224   0,                                    /* properties_provided */
1225   0,                                    /* properties_destroyed */
1226   0,                                    /* todo_flags_start */
1227   TODO_dump_func | TODO_rename_vars
1228     | TODO_ggc_collect | TODO_verify_ssa
1229     | TODO_verify_stmts,                /* todo_flags_finish */
1230   0                                     /* letter */
1231 };
1232
1233
1234 /* Given a constant value VAL for bitfield FIELD, and a destination
1235    variable VAR, return VAL appropriately widened to fit into VAR.  If
1236    FIELD is wider than HOST_WIDE_INT, NULL is returned.  */
1237
1238 tree
1239 widen_bitfield (tree val, tree field, tree var)
1240 {
1241   unsigned HOST_WIDE_INT var_size, field_size;
1242   tree wide_val;
1243   unsigned HOST_WIDE_INT mask;
1244   unsigned int i;
1245
1246   /* We can only do this if the size of the type and field and VAL are
1247      all constants representable in HOST_WIDE_INT.  */
1248   if (!host_integerp (TYPE_SIZE (TREE_TYPE (var)), 1)
1249       || !host_integerp (DECL_SIZE (field), 1)
1250       || !host_integerp (val, 0))
1251     return NULL_TREE;
1252
1253   var_size = tree_low_cst (TYPE_SIZE (TREE_TYPE (var)), 1);
1254   field_size = tree_low_cst (DECL_SIZE (field), 1);
1255
1256   /* Give up if either the bitfield or the variable are too wide.  */
1257   if (field_size > HOST_BITS_PER_WIDE_INT || var_size > HOST_BITS_PER_WIDE_INT)
1258     return NULL_TREE;
1259
1260   gcc_assert (var_size >= field_size);
1261
1262   /* If the sign bit of the value is not set or the field's type is unsigned,
1263      just mask off the high order bits of the value.  */
1264   if (DECL_UNSIGNED (field)
1265       || !(tree_low_cst (val, 0) & (((HOST_WIDE_INT)1) << (field_size - 1))))
1266     {
1267       /* Zero extension.  Build a mask with the lower 'field_size' bits
1268          set and a BIT_AND_EXPR node to clear the high order bits of
1269          the value.  */
1270       for (i = 0, mask = 0; i < field_size; i++)
1271         mask |= ((HOST_WIDE_INT) 1) << i;
1272
1273       wide_val = build (BIT_AND_EXPR, TREE_TYPE (var), val, 
1274                         fold_convert (TREE_TYPE (var),
1275                                       build_int_cst (NULL_TREE, mask)));
1276     }
1277   else
1278     {
1279       /* Sign extension.  Create a mask with the upper 'field_size'
1280          bits set and a BIT_IOR_EXPR to set the high order bits of the
1281          value.  */
1282       for (i = 0, mask = 0; i < (var_size - field_size); i++)
1283         mask |= ((HOST_WIDE_INT) 1) << (var_size - i - 1);
1284
1285       wide_val = build (BIT_IOR_EXPR, TREE_TYPE (var), val,
1286                         fold_convert (TREE_TYPE (var),
1287                                       build_int_cst (NULL_TREE, mask)));
1288     }
1289
1290   return fold (wide_val);
1291 }
1292
1293
1294 /* A subroutine of fold_stmt_r.  Attempts to fold *(A+O) to A[X].
1295    BASE is an array type.  OFFSET is a byte displacement.  ORIG_TYPE
1296    is the desired result type.  */
1297
1298 static tree
1299 maybe_fold_offset_to_array_ref (tree base, tree offset, tree orig_type)
1300 {
1301   tree min_idx, idx, elt_offset = integer_zero_node;
1302   tree array_type, elt_type, elt_size;
1303
1304   /* If BASE is an ARRAY_REF, we can pick up another offset (this time
1305      measured in units of the size of elements type) from that ARRAY_REF).
1306      We can't do anything if either is variable.
1307
1308      The case we handle here is *(&A[N]+O).  */
1309   if (TREE_CODE (base) == ARRAY_REF)
1310     {
1311       tree low_bound = array_ref_low_bound (base);
1312
1313       elt_offset = TREE_OPERAND (base, 1);
1314       if (TREE_CODE (low_bound) != INTEGER_CST
1315           || TREE_CODE (elt_offset) != INTEGER_CST)
1316         return NULL_TREE;
1317
1318       elt_offset = int_const_binop (MINUS_EXPR, elt_offset, low_bound, 0);
1319       base = TREE_OPERAND (base, 0);
1320     }
1321
1322   /* Ignore stupid user tricks of indexing non-array variables.  */
1323   array_type = TREE_TYPE (base);
1324   if (TREE_CODE (array_type) != ARRAY_TYPE)
1325     return NULL_TREE;
1326   elt_type = TREE_TYPE (array_type);
1327   if (!lang_hooks.types_compatible_p (orig_type, elt_type))
1328     return NULL_TREE;
1329         
1330   /* If OFFSET and ELT_OFFSET are zero, we don't care about the size of the
1331      element type (so we can use the alignment if it's not constant).
1332      Otherwise, compute the offset as an index by using a division.  If the
1333      division isn't exact, then don't do anything.  */
1334   elt_size = TYPE_SIZE_UNIT (elt_type);
1335   if (integer_zerop (offset))
1336     {
1337       if (TREE_CODE (elt_size) != INTEGER_CST)
1338         elt_size = size_int (TYPE_ALIGN (elt_type));
1339
1340       idx = integer_zero_node;
1341     }
1342   else
1343     {
1344       unsigned HOST_WIDE_INT lquo, lrem;
1345       HOST_WIDE_INT hquo, hrem;
1346
1347       if (TREE_CODE (elt_size) != INTEGER_CST
1348           || div_and_round_double (TRUNC_DIV_EXPR, 1,
1349                                    TREE_INT_CST_LOW (offset),
1350                                    TREE_INT_CST_HIGH (offset),
1351                                    TREE_INT_CST_LOW (elt_size),
1352                                    TREE_INT_CST_HIGH (elt_size),
1353                                    &lquo, &hquo, &lrem, &hrem)
1354           || lrem || hrem)
1355         return NULL_TREE;
1356
1357       idx = build_int_cst_wide (NULL_TREE, lquo, hquo);
1358     }
1359
1360   /* Assume the low bound is zero.  If there is a domain type, get the
1361      low bound, if any, convert the index into that type, and add the
1362      low bound.  */
1363   min_idx = integer_zero_node;
1364   if (TYPE_DOMAIN (array_type))
1365     {
1366       if (TYPE_MIN_VALUE (TYPE_DOMAIN (array_type)))
1367         min_idx = TYPE_MIN_VALUE (TYPE_DOMAIN (array_type));
1368       else
1369         min_idx = fold_convert (TYPE_DOMAIN (array_type), min_idx);
1370
1371       if (TREE_CODE (min_idx) != INTEGER_CST)
1372         return NULL_TREE;
1373
1374       idx = fold_convert (TYPE_DOMAIN (array_type), idx);
1375       elt_offset = fold_convert (TYPE_DOMAIN (array_type), elt_offset);
1376     }
1377
1378   if (!integer_zerop (min_idx))
1379     idx = int_const_binop (PLUS_EXPR, idx, min_idx, 0);
1380   if (!integer_zerop (elt_offset))
1381     idx = int_const_binop (PLUS_EXPR, idx, elt_offset, 0);
1382
1383   return build (ARRAY_REF, orig_type, base, idx, min_idx,
1384                 size_int (tree_low_cst (elt_size, 1)
1385                           / (TYPE_ALIGN_UNIT (elt_type))));
1386 }
1387
1388
1389 /* A subroutine of fold_stmt_r.  Attempts to fold *(S+O) to S.X.
1390    BASE is a record type.  OFFSET is a byte displacement.  ORIG_TYPE
1391    is the desired result type.  */
1392 /* ??? This doesn't handle class inheritance.  */
1393
1394 static tree
1395 maybe_fold_offset_to_component_ref (tree record_type, tree base, tree offset,
1396                                     tree orig_type, bool base_is_ptr)
1397 {
1398   tree f, t, field_type, tail_array_field;
1399
1400   if (TREE_CODE (record_type) != RECORD_TYPE
1401       && TREE_CODE (record_type) != UNION_TYPE
1402       && TREE_CODE (record_type) != QUAL_UNION_TYPE)
1403     return NULL_TREE;
1404
1405   /* Short-circuit silly cases.  */
1406   if (lang_hooks.types_compatible_p (record_type, orig_type))
1407     return NULL_TREE;
1408
1409   tail_array_field = NULL_TREE;
1410   for (f = TYPE_FIELDS (record_type); f ; f = TREE_CHAIN (f))
1411     {
1412       int cmp;
1413
1414       if (TREE_CODE (f) != FIELD_DECL)
1415         continue;
1416       if (DECL_BIT_FIELD (f))
1417         continue;
1418       if (TREE_CODE (DECL_FIELD_OFFSET (f)) != INTEGER_CST)
1419         continue;
1420
1421       /* ??? Java creates "interesting" fields for representing base classes.
1422          They have no name, and have no context.  With no context, we get into
1423          trouble with nonoverlapping_component_refs_p.  Skip them.  */
1424       if (!DECL_FIELD_CONTEXT (f))
1425         continue;
1426
1427       /* The previous array field isn't at the end.  */
1428       tail_array_field = NULL_TREE;
1429
1430       /* Check to see if this offset overlaps with the field.  */
1431       cmp = tree_int_cst_compare (DECL_FIELD_OFFSET (f), offset);
1432       if (cmp > 0)
1433         continue;
1434
1435       field_type = TREE_TYPE (f);
1436       if (cmp < 0)
1437         {
1438           /* Don't care about offsets into the middle of scalars.  */
1439           if (!AGGREGATE_TYPE_P (field_type))
1440             continue;
1441
1442           /* Check for array at the end of the struct.  This is often
1443              used as for flexible array members.  We should be able to
1444              turn this into an array access anyway.  */
1445           if (TREE_CODE (field_type) == ARRAY_TYPE)
1446             tail_array_field = f;
1447
1448           /* Check the end of the field against the offset.  */
1449           if (!DECL_SIZE_UNIT (f)
1450               || TREE_CODE (DECL_SIZE_UNIT (f)) != INTEGER_CST)
1451             continue;
1452           t = int_const_binop (MINUS_EXPR, offset, DECL_FIELD_OFFSET (f), 1);
1453           if (!tree_int_cst_lt (t, DECL_SIZE_UNIT (f)))
1454             continue;
1455
1456           /* If we matched, then set offset to the displacement into
1457              this field.  */
1458           offset = t;
1459         }
1460
1461       /* Here we exactly match the offset being checked.  If the types match,
1462          then we can return that field.  */
1463       else if (lang_hooks.types_compatible_p (orig_type, field_type))
1464         {
1465           if (base_is_ptr)
1466             base = build1 (INDIRECT_REF, record_type, base);
1467           t = build (COMPONENT_REF, field_type, base, f, NULL_TREE);
1468           return t;
1469         }
1470
1471       /* Don't care about type-punning of scalars.  */
1472       else if (!AGGREGATE_TYPE_P (field_type))
1473         return NULL_TREE;
1474
1475       goto found;
1476     }
1477
1478   if (!tail_array_field)
1479     return NULL_TREE;
1480
1481   f = tail_array_field;
1482   field_type = TREE_TYPE (f);
1483
1484  found:
1485   /* If we get here, we've got an aggregate field, and a possibly 
1486      nonzero offset into them.  Recurse and hope for a valid match.  */
1487   if (base_is_ptr)
1488     base = build1 (INDIRECT_REF, record_type, base);
1489   base = build (COMPONENT_REF, field_type, base, f, NULL_TREE);
1490
1491   t = maybe_fold_offset_to_array_ref (base, offset, orig_type);
1492   if (t)
1493     return t;
1494   return maybe_fold_offset_to_component_ref (field_type, base, offset,
1495                                              orig_type, false);
1496 }
1497
1498
1499 /* A subroutine of fold_stmt_r.  Attempt to simplify *(BASE+OFFSET).
1500    Return the simplified expression, or NULL if nothing could be done.  */
1501
1502 static tree
1503 maybe_fold_stmt_indirect (tree expr, tree base, tree offset)
1504 {
1505   tree t;
1506
1507   /* We may well have constructed a double-nested PLUS_EXPR via multiple
1508      substitutions.  Fold that down to one.  Remove NON_LVALUE_EXPRs that
1509      are sometimes added.  */
1510   base = fold (base);
1511   STRIP_NOPS (base);
1512   TREE_OPERAND (expr, 0) = base;
1513
1514   /* One possibility is that the address reduces to a string constant.  */
1515   t = fold_read_from_constant_string (expr);
1516   if (t)
1517     return t;
1518
1519   /* Add in any offset from a PLUS_EXPR.  */
1520   if (TREE_CODE (base) == PLUS_EXPR)
1521     {
1522       tree offset2;
1523
1524       offset2 = TREE_OPERAND (base, 1);
1525       if (TREE_CODE (offset2) != INTEGER_CST)
1526         return NULL_TREE;
1527       base = TREE_OPERAND (base, 0);
1528
1529       offset = int_const_binop (PLUS_EXPR, offset, offset2, 1);
1530     }
1531
1532   if (TREE_CODE (base) == ADDR_EXPR)
1533     {
1534       /* Strip the ADDR_EXPR.  */
1535       base = TREE_OPERAND (base, 0);
1536
1537       /* Fold away CONST_DECL to its value, if the type is scalar.  */
1538       if (TREE_CODE (base) == CONST_DECL
1539           && is_gimple_min_invariant (DECL_INITIAL (base)))
1540         return DECL_INITIAL (base);
1541
1542       /* Try folding *(&B+O) to B[X].  */
1543       t = maybe_fold_offset_to_array_ref (base, offset, TREE_TYPE (expr));
1544       if (t)
1545         return t;
1546
1547       /* Try folding *(&B+O) to B.X.  */
1548       t = maybe_fold_offset_to_component_ref (TREE_TYPE (base), base, offset,
1549                                               TREE_TYPE (expr), false);
1550       if (t)
1551         return t;
1552
1553       /* Fold *&B to B.  We can only do this if EXPR is the same type
1554          as BASE.  We can't do this if EXPR is the element type of an array
1555          and BASE is the array.  */
1556       if (integer_zerop (offset)
1557           && lang_hooks.types_compatible_p (TREE_TYPE (base),
1558                                             TREE_TYPE (expr)))
1559         return base;
1560     }
1561   else
1562     {
1563       /* We can get here for out-of-range string constant accesses, 
1564          such as "_"[3].  Bail out of the entire substitution search
1565          and arrange for the entire statement to be replaced by a
1566          call to __builtin_trap.  In all likelyhood this will all be
1567          constant-folded away, but in the meantime we can't leave with
1568          something that get_expr_operands can't understand.  */
1569
1570       t = base;
1571       STRIP_NOPS (t);
1572       if (TREE_CODE (t) == ADDR_EXPR
1573           && TREE_CODE (TREE_OPERAND (t, 0)) == STRING_CST)
1574         {
1575           /* FIXME: Except that this causes problems elsewhere with dead
1576              code not being deleted, and we abort in the rtl expanders 
1577              because we failed to remove some ssa_name.  In the meantime,
1578              just return zero.  */
1579           /* FIXME2: This condition should be signaled by
1580              fold_read_from_constant_string directly, rather than 
1581              re-checking for it here.  */
1582           return integer_zero_node;
1583         }
1584
1585       /* Try folding *(B+O) to B->X.  Still an improvement.  */
1586       if (POINTER_TYPE_P (TREE_TYPE (base)))
1587         {
1588           t = maybe_fold_offset_to_component_ref (TREE_TYPE (TREE_TYPE (base)),
1589                                                   base, offset,
1590                                                   TREE_TYPE (expr), true);
1591           if (t)
1592             return t;
1593         }
1594     }
1595
1596   /* Otherwise we had an offset that we could not simplify.  */
1597   return NULL_TREE;
1598 }
1599
1600
1601 /* A subroutine of fold_stmt_r.  EXPR is a PLUS_EXPR.
1602
1603    A quaint feature extant in our address arithmetic is that there
1604    can be hidden type changes here.  The type of the result need
1605    not be the same as the type of the input pointer.
1606
1607    What we're after here is an expression of the form
1608         (T *)(&array + const)
1609    where the cast doesn't actually exist, but is implicit in the
1610    type of the PLUS_EXPR.  We'd like to turn this into
1611         &array[x]
1612    which may be able to propagate further.  */
1613
1614 static tree
1615 maybe_fold_stmt_addition (tree expr)
1616 {
1617   tree op0 = TREE_OPERAND (expr, 0);
1618   tree op1 = TREE_OPERAND (expr, 1);
1619   tree ptr_type = TREE_TYPE (expr);
1620   tree ptd_type;
1621   tree t;
1622   bool subtract = (TREE_CODE (expr) == MINUS_EXPR);
1623
1624   /* We're only interested in pointer arithmetic.  */
1625   if (!POINTER_TYPE_P (ptr_type))
1626     return NULL_TREE;
1627   /* Canonicalize the integral operand to op1.  */
1628   if (INTEGRAL_TYPE_P (TREE_TYPE (op0)))
1629     {
1630       if (subtract)
1631         return NULL_TREE;
1632       t = op0, op0 = op1, op1 = t;
1633     }
1634   /* It had better be a constant.  */
1635   if (TREE_CODE (op1) != INTEGER_CST)
1636     return NULL_TREE;
1637   /* The first operand should be an ADDR_EXPR.  */
1638   if (TREE_CODE (op0) != ADDR_EXPR)
1639     return NULL_TREE;
1640   op0 = TREE_OPERAND (op0, 0);
1641
1642   /* If the first operand is an ARRAY_REF, expand it so that we can fold
1643      the offset into it.  */
1644   while (TREE_CODE (op0) == ARRAY_REF)
1645     {
1646       tree array_obj = TREE_OPERAND (op0, 0);
1647       tree array_idx = TREE_OPERAND (op0, 1);
1648       tree elt_type = TREE_TYPE (op0);
1649       tree elt_size = TYPE_SIZE_UNIT (elt_type);
1650       tree min_idx;
1651
1652       if (TREE_CODE (array_idx) != INTEGER_CST)
1653         break;
1654       if (TREE_CODE (elt_size) != INTEGER_CST)
1655         break;
1656
1657       /* Un-bias the index by the min index of the array type.  */
1658       min_idx = TYPE_DOMAIN (TREE_TYPE (array_obj));
1659       if (min_idx)
1660         {
1661           min_idx = TYPE_MIN_VALUE (min_idx);
1662           if (min_idx)
1663             {
1664               if (TREE_CODE (min_idx) != INTEGER_CST)
1665                 break;
1666
1667               array_idx = convert (TREE_TYPE (min_idx), array_idx);
1668               if (!integer_zerop (min_idx))
1669                 array_idx = int_const_binop (MINUS_EXPR, array_idx,
1670                                              min_idx, 0);
1671             }
1672         }
1673
1674       /* Convert the index to a byte offset.  */
1675       array_idx = convert (sizetype, array_idx);
1676       array_idx = int_const_binop (MULT_EXPR, array_idx, elt_size, 0);
1677
1678       /* Update the operands for the next round, or for folding.  */
1679       /* If we're manipulating unsigned types, then folding into negative
1680          values can produce incorrect results.  Particularly if the type
1681          is smaller than the width of the pointer.  */
1682       if (subtract
1683           && TYPE_UNSIGNED (TREE_TYPE (op1))
1684           && tree_int_cst_lt (array_idx, op1))
1685         return NULL;
1686       op1 = int_const_binop (subtract ? MINUS_EXPR : PLUS_EXPR,
1687                              array_idx, op1, 0);
1688       subtract = false;
1689       op0 = array_obj;
1690     }
1691
1692   /* If we weren't able to fold the subtraction into another array reference,
1693      canonicalize the integer for passing to the array and component ref
1694      simplification functions.  */
1695   if (subtract)
1696     {
1697       if (TYPE_UNSIGNED (TREE_TYPE (op1)))
1698         return NULL;
1699       op1 = fold (build1 (NEGATE_EXPR, TREE_TYPE (op1), op1));
1700       /* ??? In theory fold should always produce another integer.  */
1701       if (TREE_CODE (op1) != INTEGER_CST)
1702         return NULL;
1703     }
1704
1705   ptd_type = TREE_TYPE (ptr_type);
1706
1707   /* At which point we can try some of the same things as for indirects.  */
1708   t = maybe_fold_offset_to_array_ref (op0, op1, ptd_type);
1709   if (!t)
1710     t = maybe_fold_offset_to_component_ref (TREE_TYPE (op0), op0, op1,
1711                                             ptd_type, false);
1712   if (t)
1713     t = build1 (ADDR_EXPR, ptr_type, t);
1714
1715   return t;
1716 }
1717
1718
1719 /* Subroutine of fold_stmt called via walk_tree.  We perform several
1720    simplifications of EXPR_P, mostly having to do with pointer arithmetic.  */
1721
1722 static tree
1723 fold_stmt_r (tree *expr_p, int *walk_subtrees, void *data)
1724 {
1725   bool *changed_p = data;
1726   tree expr = *expr_p, t;
1727
1728   /* ??? It'd be nice if walk_tree had a pre-order option.  */
1729   switch (TREE_CODE (expr))
1730     {
1731     case INDIRECT_REF:
1732       t = walk_tree (&TREE_OPERAND (expr, 0), fold_stmt_r, data, NULL);
1733       if (t)
1734         return t;
1735       *walk_subtrees = 0;
1736
1737       t = maybe_fold_stmt_indirect (expr, TREE_OPERAND (expr, 0),
1738                                     integer_zero_node);
1739       break;
1740
1741       /* ??? Could handle ARRAY_REF here, as a variant of INDIRECT_REF.
1742          We'd only want to bother decomposing an existing ARRAY_REF if
1743          the base array is found to have another offset contained within.
1744          Otherwise we'd be wasting time.  */
1745
1746     case ADDR_EXPR:
1747       t = walk_tree (&TREE_OPERAND (expr, 0), fold_stmt_r, data, NULL);
1748       if (t)
1749         return t;
1750       *walk_subtrees = 0;
1751
1752       /* Set TREE_INVARIANT properly so that the value is properly
1753          considered constant, and so gets propagated as expected.  */
1754       if (*changed_p)
1755         recompute_tree_invarant_for_addr_expr (expr);
1756       return NULL_TREE;
1757
1758     case PLUS_EXPR:
1759     case MINUS_EXPR:
1760       t = walk_tree (&TREE_OPERAND (expr, 0), fold_stmt_r, data, NULL);
1761       if (t)
1762         return t;
1763       t = walk_tree (&TREE_OPERAND (expr, 1), fold_stmt_r, data, NULL);
1764       if (t)
1765         return t;
1766       *walk_subtrees = 0;
1767
1768       t = maybe_fold_stmt_addition (expr);
1769       break;
1770
1771     case COMPONENT_REF:
1772       t = walk_tree (&TREE_OPERAND (expr, 0), fold_stmt_r, data, NULL);
1773       if (t)
1774         return t;
1775       *walk_subtrees = 0;
1776
1777       /* Make sure the FIELD_DECL is actually a field in the type on the lhs.
1778          We've already checked that the records are compatible, so we should
1779          come up with a set of compatible fields.  */
1780       {
1781         tree expr_record = TREE_TYPE (TREE_OPERAND (expr, 0));
1782         tree expr_field = TREE_OPERAND (expr, 1);
1783
1784         if (DECL_FIELD_CONTEXT (expr_field) != TYPE_MAIN_VARIANT (expr_record))
1785           {
1786             expr_field = find_compatible_field (expr_record, expr_field);
1787             TREE_OPERAND (expr, 1) = expr_field;
1788           }
1789       }
1790       break;
1791
1792     default:
1793       return NULL_TREE;
1794     }
1795
1796   if (t)
1797     {
1798       *expr_p = t;
1799       *changed_p = true;
1800     }
1801
1802   return NULL_TREE;
1803 }
1804
1805
1806 /* Return the string length of ARG in LENGTH.  If ARG is an SSA name variable,
1807    follow its use-def chains.  If LENGTH is not NULL and its value is not
1808    equal to the length we determine, or if we are unable to determine the
1809    length, return false.  VISITED is a bitmap of visited variables.  */
1810
1811 static bool
1812 get_strlen (tree arg, tree *length, bitmap visited)
1813 {
1814   tree var, def_stmt, val;
1815   
1816   if (TREE_CODE (arg) != SSA_NAME)
1817     {
1818       val = c_strlen (arg, 1);
1819       if (!val)
1820         return false;
1821
1822       if (*length && simple_cst_equal (val, *length) != 1)
1823         return false;
1824
1825       *length = val;
1826       return true;
1827     }
1828
1829   /* If we were already here, break the infinite cycle.  */
1830   if (bitmap_bit_p (visited, SSA_NAME_VERSION (arg)))
1831     return true;
1832   bitmap_set_bit (visited, SSA_NAME_VERSION (arg));
1833
1834   var = arg;
1835   def_stmt = SSA_NAME_DEF_STMT (var);
1836
1837   switch (TREE_CODE (def_stmt))
1838     {
1839       case MODIFY_EXPR:
1840         {
1841           tree len, rhs;
1842           
1843           /* The RHS of the statement defining VAR must either have a
1844              constant length or come from another SSA_NAME with a constant
1845              length.  */
1846           rhs = TREE_OPERAND (def_stmt, 1);
1847           STRIP_NOPS (rhs);
1848           if (TREE_CODE (rhs) == SSA_NAME)
1849             return get_strlen (rhs, length, visited);
1850
1851           /* See if the RHS is a constant length.  */
1852           len = c_strlen (rhs, 1);
1853           if (len)
1854             {
1855               if (*length && simple_cst_equal (len, *length) != 1)
1856                 return false;
1857
1858               *length = len;
1859               return true;
1860             }
1861
1862           break;
1863         }
1864
1865       case PHI_NODE:
1866         {
1867           /* All the arguments of the PHI node must have the same constant
1868              length.  */
1869           int i;
1870
1871           for (i = 0; i < PHI_NUM_ARGS (def_stmt); i++)
1872             {
1873               tree arg = PHI_ARG_DEF (def_stmt, i);
1874
1875               /* If this PHI has itself as an argument, we cannot
1876                  determine the string length of this argument.  However,
1877                  if we can find a constant string length for the other
1878                  PHI args then we can still be sure that this is a
1879                  constant string length.  So be optimistic and just
1880                  continue with the next argument.  */
1881               if (arg == PHI_RESULT (def_stmt))
1882                 continue;
1883
1884               if (!get_strlen (arg, length, visited))
1885                 return false;
1886             }
1887
1888           return true;
1889         }
1890
1891       default:
1892         break;
1893     }
1894
1895
1896   return false;
1897 }
1898
1899
1900 /* Fold builtin call FN in statement STMT.  If it cannot be folded into a
1901    constant, return NULL_TREE.  Otherwise, return its constant value.  */
1902
1903 static tree
1904 ccp_fold_builtin (tree stmt, tree fn)
1905 {
1906   tree result, strlen_val[2];
1907   tree callee, arglist, a;
1908   int strlen_arg, i;
1909   bitmap visited;
1910   bool ignore;
1911
1912   ignore = TREE_CODE (stmt) != MODIFY_EXPR;
1913
1914   /* First try the generic builtin folder.  If that succeeds, return the
1915      result directly.  */
1916   result = fold_builtin (fn, ignore);
1917   if (result)
1918   {
1919     if (ignore)
1920       STRIP_NOPS (result);
1921     return result;
1922   }
1923
1924   /* Ignore MD builtins.  */
1925   callee = get_callee_fndecl (fn);
1926   if (DECL_BUILT_IN_CLASS (callee) == BUILT_IN_MD)
1927     return NULL_TREE;
1928
1929   /* If the builtin could not be folded, and it has no argument list,
1930      we're done.  */
1931   arglist = TREE_OPERAND (fn, 1);
1932   if (!arglist)
1933     return NULL_TREE;
1934
1935   /* Limit the work only for builtins we know how to simplify.  */
1936   switch (DECL_FUNCTION_CODE (callee))
1937     {
1938     case BUILT_IN_STRLEN:
1939     case BUILT_IN_FPUTS:
1940     case BUILT_IN_FPUTS_UNLOCKED:
1941       strlen_arg = 1;
1942       break;
1943     case BUILT_IN_STRCPY:
1944     case BUILT_IN_STRNCPY:
1945       strlen_arg = 2;
1946       break;
1947     default:
1948       return NULL_TREE;
1949     }
1950
1951   /* Try to use the dataflow information gathered by the CCP process.  */
1952   visited = BITMAP_XMALLOC ();
1953
1954   memset (strlen_val, 0, sizeof (strlen_val));
1955   for (i = 0, a = arglist;
1956        strlen_arg;
1957        i++, strlen_arg >>= 1, a = TREE_CHAIN (a))
1958     if (strlen_arg & 1)
1959       {
1960         bitmap_clear (visited);
1961         if (!get_strlen (TREE_VALUE (a), &strlen_val[i], visited))
1962           strlen_val[i] = NULL_TREE;
1963       }
1964
1965   BITMAP_XFREE (visited);
1966
1967   result = NULL_TREE;
1968   switch (DECL_FUNCTION_CODE (callee))
1969     {
1970     case BUILT_IN_STRLEN:
1971       if (strlen_val[0])
1972         {
1973           tree new = fold_convert (TREE_TYPE (fn), strlen_val[0]);
1974
1975           /* If the result is not a valid gimple value, or not a cast
1976              of a valid gimple value, then we can not use the result.  */
1977           if (is_gimple_val (new)
1978               || (is_gimple_cast (new)
1979                   && is_gimple_val (TREE_OPERAND (new, 0))))
1980             return new;
1981         }
1982       break;
1983
1984     case BUILT_IN_STRCPY:
1985       if (strlen_val[1] && is_gimple_val (strlen_val[1]))
1986         result = fold_builtin_strcpy (fn, strlen_val[1]);
1987       break;
1988
1989     case BUILT_IN_STRNCPY:
1990       if (strlen_val[1] && is_gimple_val (strlen_val[1]))
1991         result = fold_builtin_strncpy (fn, strlen_val[1]);
1992       break;
1993
1994     case BUILT_IN_FPUTS:
1995       result = fold_builtin_fputs (arglist,
1996                                    TREE_CODE (stmt) != MODIFY_EXPR, 0,
1997                                    strlen_val[0]);
1998       break;
1999
2000     case BUILT_IN_FPUTS_UNLOCKED:
2001       result = fold_builtin_fputs (arglist,
2002                                    TREE_CODE (stmt) != MODIFY_EXPR, 1,
2003                                    strlen_val[0]);
2004       break;
2005
2006     default:
2007       gcc_unreachable ();
2008     }
2009
2010   if (result && ignore)
2011     result = fold_ignored_result (result);
2012   return result;
2013 }
2014
2015
2016 /* Fold the statement pointed by STMT_P.  In some cases, this function may
2017    replace the whole statement with a new one.  Returns true iff folding
2018    makes any changes.  */
2019
2020 bool
2021 fold_stmt (tree *stmt_p)
2022 {
2023   tree rhs, result, stmt;
2024   bool changed = false;
2025
2026   stmt = *stmt_p;
2027
2028   /* If we replaced constants and the statement makes pointer dereferences,
2029      then we may need to fold instances of *&VAR into VAR, etc.  */
2030   if (walk_tree (stmt_p, fold_stmt_r, &changed, NULL))
2031     {
2032       *stmt_p
2033         = build_function_call_expr (implicit_built_in_decls[BUILT_IN_TRAP],
2034                                     NULL);
2035       return true;
2036     }
2037
2038   rhs = get_rhs (stmt);
2039   if (!rhs)
2040     return changed;
2041   result = NULL_TREE;
2042
2043   if (TREE_CODE (rhs) == CALL_EXPR)
2044     {
2045       tree callee;
2046
2047       /* Check for builtins that CCP can handle using information not
2048          available in the generic fold routines.  */
2049       callee = get_callee_fndecl (rhs);
2050       if (callee && DECL_BUILT_IN (callee))
2051         result = ccp_fold_builtin (stmt, rhs);
2052       else
2053         {
2054           /* Check for resolvable OBJ_TYPE_REF.  The only sorts we can resolve
2055              here are when we've propagated the address of a decl into the
2056              object slot.  */
2057           /* ??? Should perhaps do this in fold proper.  However, doing it
2058              there requires that we create a new CALL_EXPR, and that requires
2059              copying EH region info to the new node.  Easier to just do it
2060              here where we can just smash the call operand.  */
2061           callee = TREE_OPERAND (rhs, 0);
2062           if (TREE_CODE (callee) == OBJ_TYPE_REF
2063               && lang_hooks.fold_obj_type_ref
2064               && TREE_CODE (OBJ_TYPE_REF_OBJECT (callee)) == ADDR_EXPR
2065               && DECL_P (TREE_OPERAND
2066                          (OBJ_TYPE_REF_OBJECT (callee), 0)))
2067             {
2068               tree t;
2069
2070               /* ??? Caution: Broken ADDR_EXPR semantics means that
2071                  looking at the type of the operand of the addr_expr
2072                  can yield an array type.  See silly exception in
2073                  check_pointer_types_r.  */
2074
2075               t = TREE_TYPE (TREE_TYPE (OBJ_TYPE_REF_OBJECT (callee)));
2076               t = lang_hooks.fold_obj_type_ref (callee, t);
2077               if (t)
2078                 {
2079                   TREE_OPERAND (rhs, 0) = t;
2080                   changed = true;
2081                 }
2082             }
2083         }
2084     }
2085
2086   /* If we couldn't fold the RHS, hand over to the generic fold routines.  */
2087   if (result == NULL_TREE)
2088     result = fold (rhs);
2089
2090   /* Strip away useless type conversions.  Both the NON_LVALUE_EXPR that
2091      may have been added by fold, and "useless" type conversions that might
2092      now be apparent due to propagation.  */
2093   STRIP_USELESS_TYPE_CONVERSION (result);
2094
2095   if (result != rhs)
2096     changed |= set_rhs (stmt_p, result);
2097
2098   return changed;
2099 }
2100
2101 \f
2102 /* A simple pass that attempts to fold all builtin functions.  This pass
2103    is run after we've propagated as many constants as we can.  */
2104
2105 static void
2106 execute_fold_all_builtins (void)
2107 {
2108   basic_block bb;
2109   FOR_EACH_BB (bb)
2110     {
2111       block_stmt_iterator i;
2112       for (i = bsi_start (bb); !bsi_end_p (i); bsi_next (&i))
2113         {
2114           tree *stmtp = bsi_stmt_ptr (i);
2115           tree call = get_rhs (*stmtp);
2116           tree callee, result;
2117
2118           if (!call || TREE_CODE (call) != CALL_EXPR)
2119             continue;
2120           callee = get_callee_fndecl (call);
2121           if (!callee || DECL_BUILT_IN_CLASS (callee) != BUILT_IN_NORMAL)
2122             continue;
2123
2124           result = ccp_fold_builtin (*stmtp, call);
2125           if (!result)
2126             switch (DECL_FUNCTION_CODE (callee))
2127               {
2128               case BUILT_IN_CONSTANT_P:
2129                 /* Resolve __builtin_constant_p.  If it hasn't been
2130                    folded to integer_one_node by now, it's fairly
2131                    certain that the value simply isn't constant.  */
2132                 result = integer_zero_node;
2133                 break;
2134
2135               default:
2136                 continue;
2137               }
2138
2139           if (dump_file && (dump_flags & TDF_DETAILS))
2140             {
2141               fprintf (dump_file, "Simplified\n  ");
2142               print_generic_stmt (dump_file, *stmtp, dump_flags);
2143             }
2144
2145           if (set_rhs (stmtp, result))
2146             modify_stmt (*stmtp);
2147
2148           if (dump_file && (dump_flags & TDF_DETAILS))
2149             {
2150               fprintf (dump_file, "to\n  ");
2151               print_generic_stmt (dump_file, *stmtp, dump_flags);
2152               fprintf (dump_file, "\n");
2153             }
2154         }
2155     }
2156 }
2157
2158
2159 struct tree_opt_pass pass_fold_builtins = 
2160 {
2161   "fab",                                /* name */
2162   NULL,                                 /* gate */
2163   execute_fold_all_builtins,            /* execute */
2164   NULL,                                 /* sub */
2165   NULL,                                 /* next */
2166   0,                                    /* static_pass_number */
2167   0,                                    /* tv_id */
2168   PROP_cfg | PROP_ssa | PROP_alias,     /* properties_required */
2169   0,                                    /* properties_provided */
2170   0,                                    /* properties_destroyed */
2171   0,                                    /* todo_flags_start */
2172   TODO_dump_func | TODO_verify_ssa,     /* todo_flags_finish */
2173   0                                     /* letter */
2174 };