OSDN Git Service

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