OSDN Git Service

Merge from gomp-branch.
[pf3gnuchains/gcc-fork.git] / gcc / tree-ssa-dom.c
1 /* SSA Dominator optimizations for trees
2    Copyright (C) 2001, 2002, 2003, 2004, 2005 Free Software Foundation, Inc.
3    Contributed by Diego Novillo <dnovillo@redhat.com>
4
5 This file is part of GCC.
6
7 GCC is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2, or (at your option)
10 any later version.
11
12 GCC is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING.  If not, write to
19 the Free Software Foundation, 51 Franklin Street, Fifth Floor,
20 Boston, MA 02110-1301, USA.  */
21
22 #include "config.h"
23 #include "system.h"
24 #include "coretypes.h"
25 #include "tm.h"
26 #include "tree.h"
27 #include "flags.h"
28 #include "rtl.h"
29 #include "tm_p.h"
30 #include "ggc.h"
31 #include "basic-block.h"
32 #include "cfgloop.h"
33 #include "output.h"
34 #include "expr.h"
35 #include "function.h"
36 #include "diagnostic.h"
37 #include "timevar.h"
38 #include "tree-dump.h"
39 #include "tree-flow.h"
40 #include "domwalk.h"
41 #include "real.h"
42 #include "tree-pass.h"
43 #include "tree-ssa-propagate.h"
44 #include "langhooks.h"
45 #include "params.h"
46
47 /* This file implements optimizations on the dominator tree.  */
48
49
50 /* Structure for recording edge equivalences as well as any pending
51    edge redirections during the dominator optimizer.
52
53    Computing and storing the edge equivalences instead of creating
54    them on-demand can save significant amounts of time, particularly
55    for pathological cases involving switch statements.  
56
57    These structures live for a single iteration of the dominator
58    optimizer in the edge's AUX field.  At the end of an iteration we
59    free each of these structures and update the AUX field to point
60    to any requested redirection target (the code for updating the
61    CFG and SSA graph for edge redirection expects redirection edge
62    targets to be in the AUX field for each edge.  */
63
64 struct edge_info
65 {
66   /* If this edge creates a simple equivalence, the LHS and RHS of
67      the equivalence will be stored here.  */
68   tree lhs;
69   tree rhs;
70
71   /* Traversing an edge may also indicate one or more particular conditions
72      are true or false.  The number of recorded conditions can vary, but
73      can be determined by the condition's code.  So we have an array
74      and its maximum index rather than use a varray.  */
75   tree *cond_equivalences;
76   unsigned int max_cond_equivalences;
77
78   /* If we can thread this edge this field records the new target.  */
79   edge redirection_target;
80 };
81
82
83 /* Hash table with expressions made available during the renaming process.
84    When an assignment of the form X_i = EXPR is found, the statement is
85    stored in this table.  If the same expression EXPR is later found on the
86    RHS of another statement, it is replaced with X_i (thus performing
87    global redundancy elimination).  Similarly as we pass through conditionals
88    we record the conditional itself as having either a true or false value
89    in this table.  */
90 static htab_t avail_exprs;
91
92 /* Stack of available expressions in AVAIL_EXPRs.  Each block pushes any
93    expressions it enters into the hash table along with a marker entry
94    (null).  When we finish processing the block, we pop off entries and
95    remove the expressions from the global hash table until we hit the
96    marker.  */
97 static VEC(tree,heap) *avail_exprs_stack;
98
99 /* Stack of statements we need to rescan during finalization for newly
100    exposed variables.
101
102    Statement rescanning must occur after the current block's available
103    expressions are removed from AVAIL_EXPRS.  Else we may change the
104    hash code for an expression and be unable to find/remove it from
105    AVAIL_EXPRS.  */
106 static VEC(tree,heap) *stmts_to_rescan;
107
108 /* Structure for entries in the expression hash table.
109
110    This requires more memory for the hash table entries, but allows us
111    to avoid creating silly tree nodes and annotations for conditionals,
112    eliminates 2 global hash tables and two block local varrays.
113    
114    It also allows us to reduce the number of hash table lookups we
115    have to perform in lookup_avail_expr and finally it allows us to
116    significantly reduce the number of calls into the hashing routine
117    itself.  */
118
119 struct expr_hash_elt
120 {
121   /* The value (lhs) of this expression.  */
122   tree lhs;
123
124   /* The expression (rhs) we want to record.  */
125   tree rhs;
126
127   /* The stmt pointer if this element corresponds to a statement.  */
128   tree stmt;
129
130   /* The hash value for RHS/ann.  */
131   hashval_t hash;
132 };
133
134 /* Stack of dest,src pairs that need to be restored during finalization.
135
136    A NULL entry is used to mark the end of pairs which need to be
137    restored during finalization of this block.  */
138 static VEC(tree,heap) *const_and_copies_stack;
139
140 /* Bitmap of SSA_NAMEs known to have a nonzero value, even if we do not
141    know their exact value.  */
142 static bitmap nonzero_vars;
143
144 /* Bitmap of blocks that are scheduled to be threaded through.  This
145    is used to communicate with thread_through_blocks.  */
146 static bitmap threaded_blocks;
147
148 /* Stack of SSA_NAMEs which need their NONZERO_VARS property cleared
149    when the current block is finalized. 
150
151    A NULL entry is used to mark the end of names needing their 
152    entry in NONZERO_VARS cleared during finalization of this block.  */
153 static VEC(tree,heap) *nonzero_vars_stack;
154
155 /* Track whether or not we have changed the control flow graph.  */
156 static bool cfg_altered;
157
158 /* Bitmap of blocks that have had EH statements cleaned.  We should
159    remove their dead edges eventually.  */
160 static bitmap need_eh_cleanup;
161
162 /* Statistics for dominator optimizations.  */
163 struct opt_stats_d
164 {
165   long num_stmts;
166   long num_exprs_considered;
167   long num_re;
168   long num_const_prop;
169   long num_copy_prop;
170   long num_iterations;
171 };
172
173 static struct opt_stats_d opt_stats;
174
175 /* Value range propagation record.  Each time we encounter a conditional
176    of the form SSA_NAME COND CONST we create a new vrp_element to record
177    how the condition affects the possible values SSA_NAME may have.
178
179    Each record contains the condition tested (COND), and the range of
180    values the variable may legitimately have if COND is true.  Note the
181    range of values may be a smaller range than COND specifies if we have
182    recorded other ranges for this variable.  Each record also contains the
183    block in which the range was recorded for invalidation purposes.
184
185    Note that the current known range is computed lazily.  This allows us
186    to avoid the overhead of computing ranges which are never queried.
187
188    When we encounter a conditional, we look for records which constrain
189    the SSA_NAME used in the condition.  In some cases those records allow
190    us to determine the condition's result at compile time.  In other cases
191    they may allow us to simplify the condition.
192
193    We also use value ranges to do things like transform signed div/mod
194    operations into unsigned div/mod or to simplify ABS_EXPRs. 
195
196    Simple experiments have shown these optimizations to not be all that
197    useful on switch statements (much to my surprise).  So switch statement
198    optimizations are not performed.
199
200    Note carefully we do not propagate information through each statement
201    in the block.  i.e., if we know variable X has a value defined of
202    [0, 25] and we encounter Y = X + 1, we do not track a value range
203    for Y (which would be [1, 26] if we cared).  Similarly we do not
204    constrain values as we encounter narrowing typecasts, etc.  */
205
206 struct vrp_element
207 {
208   /* The highest and lowest values the variable in COND may contain when
209      COND is true.  Note this may not necessarily be the same values
210      tested by COND if the same variable was used in earlier conditionals. 
211
212      Note this is computed lazily and thus can be NULL indicating that
213      the values have not been computed yet.  */
214   tree low;
215   tree high;
216
217   /* The actual conditional we recorded.  This is needed since we compute
218      ranges lazily.  */
219   tree cond;
220
221   /* The basic block where this record was created.  We use this to determine
222      when to remove records.  */
223   basic_block bb;
224 };
225
226 /* A hash table holding value range records (VRP_ELEMENTs) for a given
227    SSA_NAME.  We used to use a varray indexed by SSA_NAME_VERSION, but
228    that gets awful wasteful, particularly since the density objects
229    with useful information is very low.  */
230 static htab_t vrp_data;
231
232 typedef struct vrp_element *vrp_element_p;
233
234 DEF_VEC_P(vrp_element_p);
235 DEF_VEC_ALLOC_P(vrp_element_p,heap);
236
237 /* An entry in the VRP_DATA hash table.  We record the variable and a
238    varray of VRP_ELEMENT records associated with that variable.  */
239 struct vrp_hash_elt
240 {
241   tree var;
242   VEC(vrp_element_p,heap) *records;
243 };
244
245 /* Array of variables which have their values constrained by operations
246    in this basic block.  We use this during finalization to know
247    which variables need their VRP data updated.  */
248
249 /* Stack of SSA_NAMEs which had their values constrained by operations
250    in this basic block.  During finalization of this block we use this
251    list to determine which variables need their VRP data updated.
252
253    A NULL entry marks the end of the SSA_NAMEs associated with this block.  */
254 static VEC(tree,heap) *vrp_variables_stack;
255
256 struct eq_expr_value
257 {
258   tree src;
259   tree dst;
260 };
261
262 /* Local functions.  */
263 static void optimize_stmt (struct dom_walk_data *, 
264                            basic_block bb,
265                            block_stmt_iterator);
266 static tree lookup_avail_expr (tree, bool);
267 static hashval_t vrp_hash (const void *);
268 static int vrp_eq (const void *, const void *);
269 static hashval_t avail_expr_hash (const void *);
270 static hashval_t real_avail_expr_hash (const void *);
271 static int avail_expr_eq (const void *, const void *);
272 static void htab_statistics (FILE *, htab_t);
273 static void record_cond (tree, tree);
274 static void record_const_or_copy (tree, tree);
275 static void record_equality (tree, tree);
276 static tree simplify_cond_and_lookup_avail_expr (tree, stmt_ann_t, int);
277 static tree find_equivalent_equality_comparison (tree);
278 static void record_range (tree, basic_block);
279 static bool extract_range_from_cond (tree, tree *, tree *, int *);
280 static void record_equivalences_from_phis (basic_block);
281 static void record_equivalences_from_incoming_edge (basic_block);
282 static bool eliminate_redundant_computations (tree, stmt_ann_t);
283 static void record_equivalences_from_stmt (tree, int, stmt_ann_t);
284 static void thread_across_edge (struct dom_walk_data *, edge);
285 static void dom_opt_finalize_block (struct dom_walk_data *, basic_block);
286 static void dom_opt_initialize_block (struct dom_walk_data *, basic_block);
287 static void propagate_to_outgoing_edges (struct dom_walk_data *, basic_block);
288 static void remove_local_expressions_from_table (void);
289 static void restore_vars_to_original_value (void);
290 static edge single_incoming_edge_ignoring_loop_edges (basic_block);
291 static void restore_nonzero_vars_to_original_value (void);
292 static inline bool unsafe_associative_fp_binop (tree);
293
294
295 /* Local version of fold that doesn't introduce cruft.  */
296
297 static tree
298 local_fold (tree t)
299 {
300   t = fold (t);
301
302   /* Strip away useless type conversions.  Both the NON_LVALUE_EXPR that
303      may have been added by fold, and "useless" type conversions that might
304      now be apparent due to propagation.  */
305   STRIP_USELESS_TYPE_CONVERSION (t);
306
307   return t;
308 }
309
310 /* Allocate an EDGE_INFO for edge E and attach it to E.
311    Return the new EDGE_INFO structure.  */
312
313 static struct edge_info *
314 allocate_edge_info (edge e)
315 {
316   struct edge_info *edge_info;
317
318   edge_info = XCNEW (struct edge_info);
319
320   e->aux = edge_info;
321   return edge_info;
322 }
323
324 /* Free all EDGE_INFO structures associated with edges in the CFG.
325    If a particular edge can be threaded, copy the redirection
326    target from the EDGE_INFO structure into the edge's AUX field
327    as required by code to update the CFG and SSA graph for
328    jump threading.  */
329
330 static void
331 free_all_edge_infos (void)
332 {
333   basic_block bb;
334   edge_iterator ei;
335   edge e;
336
337   FOR_EACH_BB (bb)
338     {
339       FOR_EACH_EDGE (e, ei, bb->preds)
340         {
341          struct edge_info *edge_info = (struct edge_info *) e->aux;
342
343           if (edge_info)
344             {
345               e->aux = edge_info->redirection_target;
346               if (edge_info->cond_equivalences)
347                 free (edge_info->cond_equivalences);
348               free (edge_info);
349             }
350         }
351     }
352 }
353
354 /* Free an instance of vrp_hash_elt.  */
355
356 static void
357 vrp_free (void *data)
358 {
359   struct vrp_hash_elt *elt = (struct vrp_hash_elt *) data;
360   struct VEC(vrp_element_p,heap) **vrp_elt = &elt->records;
361
362   VEC_free (vrp_element_p, heap, *vrp_elt);
363   free (elt);
364 }
365
366 /* Jump threading, redundancy elimination and const/copy propagation. 
367
368    This pass may expose new symbols that need to be renamed into SSA.  For
369    every new symbol exposed, its corresponding bit will be set in
370    VARS_TO_RENAME.  */
371
372 static void
373 tree_ssa_dominator_optimize (void)
374 {
375   struct dom_walk_data walk_data;
376   unsigned int i;
377   struct loops loops_info;
378
379   memset (&opt_stats, 0, sizeof (opt_stats));
380
381   /* Create our hash tables.  */
382   avail_exprs = htab_create (1024, real_avail_expr_hash, avail_expr_eq, free);
383   vrp_data = htab_create (ceil_log2 (num_ssa_names), vrp_hash, vrp_eq,
384                           vrp_free);
385   avail_exprs_stack = VEC_alloc (tree, heap, 20);
386   const_and_copies_stack = VEC_alloc (tree, heap, 20);
387   nonzero_vars_stack = VEC_alloc (tree, heap, 20);
388   vrp_variables_stack = VEC_alloc (tree, heap, 20);
389   stmts_to_rescan = VEC_alloc (tree, heap, 20);
390   nonzero_vars = BITMAP_ALLOC (NULL);
391   threaded_blocks = BITMAP_ALLOC (NULL);
392   need_eh_cleanup = BITMAP_ALLOC (NULL);
393
394   /* Setup callbacks for the generic dominator tree walker.  */
395   walk_data.walk_stmts_backward = false;
396   walk_data.dom_direction = CDI_DOMINATORS;
397   walk_data.initialize_block_local_data = NULL;
398   walk_data.before_dom_children_before_stmts = dom_opt_initialize_block;
399   walk_data.before_dom_children_walk_stmts = optimize_stmt;
400   walk_data.before_dom_children_after_stmts = propagate_to_outgoing_edges;
401   walk_data.after_dom_children_before_stmts = NULL;
402   walk_data.after_dom_children_walk_stmts = NULL;
403   walk_data.after_dom_children_after_stmts = dom_opt_finalize_block;
404   /* Right now we only attach a dummy COND_EXPR to the global data pointer.
405      When we attach more stuff we'll need to fill this out with a real
406      structure.  */
407   walk_data.global_data = NULL;
408   walk_data.block_local_data_size = 0;
409   walk_data.interesting_blocks = NULL;
410
411   /* Now initialize the dominator walker.  */
412   init_walk_dominator_tree (&walk_data);
413
414   calculate_dominance_info (CDI_DOMINATORS);
415
416   /* We need to know which edges exit loops so that we can
417      aggressively thread through loop headers to an exit
418      edge.  */
419   flow_loops_find (&loops_info);
420   mark_loop_exit_edges (&loops_info);
421   flow_loops_free (&loops_info);
422
423   /* Clean up the CFG so that any forwarder blocks created by loop
424      canonicalization are removed.  */
425   cleanup_tree_cfg ();
426   calculate_dominance_info (CDI_DOMINATORS);
427
428   /* If we prove certain blocks are unreachable, then we want to
429      repeat the dominator optimization process as PHI nodes may
430      have turned into copies which allows better propagation of
431      values.  So we repeat until we do not identify any new unreachable
432      blocks.  */
433   do
434     {
435       /* Optimize the dominator tree.  */
436       cfg_altered = false;
437
438       /* We need accurate information regarding back edges in the CFG
439          for jump threading.  */
440       mark_dfs_back_edges ();
441
442       /* Recursively walk the dominator tree optimizing statements.  */
443       walk_dominator_tree (&walk_data, ENTRY_BLOCK_PTR);
444
445       {
446         block_stmt_iterator bsi;
447         basic_block bb;
448         FOR_EACH_BB (bb)
449           {
450             for (bsi = bsi_start (bb); !bsi_end_p (bsi); bsi_next (&bsi))
451               {
452                 update_stmt_if_modified (bsi_stmt (bsi));
453               }
454           }
455       }
456
457       /* If we exposed any new variables, go ahead and put them into
458          SSA form now, before we handle jump threading.  This simplifies
459          interactions between rewriting of _DECL nodes into SSA form
460          and rewriting SSA_NAME nodes into SSA form after block
461          duplication and CFG manipulation.  */
462       update_ssa (TODO_update_ssa);
463
464       free_all_edge_infos ();
465
466       /* Thread jumps, creating duplicate blocks as needed.  */
467       cfg_altered |= thread_through_all_blocks (threaded_blocks);
468
469       /* Removal of statements may make some EH edges dead.  Purge
470          such edges from the CFG as needed.  */
471       if (!bitmap_empty_p (need_eh_cleanup))
472         {
473           cfg_altered |= tree_purge_all_dead_eh_edges (need_eh_cleanup);
474           bitmap_zero (need_eh_cleanup);
475         }
476
477       if (cfg_altered)
478         free_dominance_info (CDI_DOMINATORS);
479
480       /* Only iterate if we threaded jumps AND the CFG cleanup did
481          something interesting.  Other cases generate far fewer
482          optimization opportunities and thus are not worth another
483          full DOM iteration.  */
484       cfg_altered &= cleanup_tree_cfg ();
485
486       if (rediscover_loops_after_threading)
487         {
488           /* Rerun basic loop analysis to discover any newly
489              created loops and update the set of exit edges.  */
490           rediscover_loops_after_threading = false;
491           flow_loops_find (&loops_info);
492           mark_loop_exit_edges (&loops_info);
493           flow_loops_free (&loops_info);
494
495           /* Remove any forwarder blocks inserted by loop
496              header canonicalization.  */
497           cleanup_tree_cfg ();
498         }
499
500       calculate_dominance_info (CDI_DOMINATORS);
501
502       update_ssa (TODO_update_ssa);
503
504       /* Reinitialize the various tables.  */
505       bitmap_clear (nonzero_vars);
506       bitmap_clear (threaded_blocks);
507       htab_empty (avail_exprs);
508       htab_empty (vrp_data);
509
510       /* Finally, remove everything except invariants in SSA_NAME_VALUE.
511
512          This must be done before we iterate as we might have a
513          reference to an SSA_NAME which was removed by the call to
514          update_ssa.
515
516          Long term we will be able to let everything in SSA_NAME_VALUE
517          persist.  However, for now, we know this is the safe thing to do.  */
518       for (i = 0; i < num_ssa_names; i++)
519         {
520           tree name = ssa_name (i);
521           tree value;
522
523           if (!name)
524             continue;
525
526           value = SSA_NAME_VALUE (name);
527           if (value && !is_gimple_min_invariant (value))
528             SSA_NAME_VALUE (name) = NULL;
529         }
530
531       opt_stats.num_iterations++;
532     }
533   while (optimize > 1 && cfg_altered);
534
535   /* Debugging dumps.  */
536   if (dump_file && (dump_flags & TDF_STATS))
537     dump_dominator_optimization_stats (dump_file);
538
539   /* We emptied the hash table earlier, now delete it completely.  */
540   htab_delete (avail_exprs);
541   htab_delete (vrp_data);
542
543   /* It is not necessary to clear CURRDEFS, REDIRECTION_EDGES, VRP_DATA,
544      CONST_AND_COPIES, and NONZERO_VARS as they all get cleared at the bottom
545      of the do-while loop above.  */
546
547   /* And finalize the dominator walker.  */
548   fini_walk_dominator_tree (&walk_data);
549
550   /* Free nonzero_vars.  */
551   BITMAP_FREE (nonzero_vars);
552   BITMAP_FREE (threaded_blocks);
553   BITMAP_FREE (need_eh_cleanup);
554   
555   VEC_free (tree, heap, avail_exprs_stack);
556   VEC_free (tree, heap, const_and_copies_stack);
557   VEC_free (tree, heap, nonzero_vars_stack);
558   VEC_free (tree, heap, vrp_variables_stack);
559   VEC_free (tree, heap, stmts_to_rescan);
560 }
561
562 static bool
563 gate_dominator (void)
564 {
565   return flag_tree_dom != 0;
566 }
567
568 struct tree_opt_pass pass_dominator = 
569 {
570   "dom",                                /* name */
571   gate_dominator,                       /* gate */
572   tree_ssa_dominator_optimize,          /* execute */
573   NULL,                                 /* sub */
574   NULL,                                 /* next */
575   0,                                    /* static_pass_number */
576   TV_TREE_SSA_DOMINATOR_OPTS,           /* tv_id */
577   PROP_cfg | PROP_ssa | PROP_alias,     /* properties_required */
578   0,                                    /* properties_provided */
579   0,                                    /* properties_destroyed */
580   0,                                    /* todo_flags_start */
581   TODO_dump_func
582     | TODO_update_ssa
583     | TODO_verify_ssa,                  /* todo_flags_finish */
584   0                                     /* letter */
585 };
586
587
588 /* Given a stmt CONDSTMT containing a COND_EXPR, canonicalize the
589    COND_EXPR into a canonical form.  */
590
591 static void
592 canonicalize_comparison (tree condstmt)
593 {
594   tree cond = COND_EXPR_COND (condstmt);
595   tree op0;
596   tree op1;
597   enum tree_code code = TREE_CODE (cond);
598
599   if (!COMPARISON_CLASS_P (cond))
600     return;
601
602   op0 = TREE_OPERAND (cond, 0);
603   op1 = TREE_OPERAND (cond, 1);
604
605   /* If it would be profitable to swap the operands, then do so to
606      canonicalize the statement, enabling better optimization.
607
608      By placing canonicalization of such expressions here we
609      transparently keep statements in canonical form, even
610      when the statement is modified.  */
611   if (tree_swap_operands_p (op0, op1, false))
612     {
613       /* For relationals we need to swap the operands
614          and change the code.  */
615       if (code == LT_EXPR
616           || code == GT_EXPR
617           || code == LE_EXPR
618           || code == GE_EXPR)
619         {
620           TREE_SET_CODE (cond, swap_tree_comparison (code));
621           swap_tree_operands (condstmt,
622                               &TREE_OPERAND (cond, 0),
623                               &TREE_OPERAND (cond, 1));
624           /* If one operand was in the operand cache, but the other is
625              not, because it is a constant, this is a case that the
626              internal updating code of swap_tree_operands can't handle
627              properly.  */
628           if (TREE_CODE_CLASS (TREE_CODE (op0)) 
629               != TREE_CODE_CLASS (TREE_CODE (op1)))
630             update_stmt (condstmt);
631         }
632     }
633 }
634 /* We are exiting E->src, see if E->dest ends with a conditional
635    jump which has a known value when reached via E. 
636
637    Special care is necessary if E is a back edge in the CFG as we
638    will have already recorded equivalences for E->dest into our
639    various tables, including the result of the conditional at
640    the end of E->dest.  Threading opportunities are severely
641    limited in that case to avoid short-circuiting the loop
642    incorrectly.
643
644    Note it is quite common for the first block inside a loop to
645    end with a conditional which is either always true or always
646    false when reached via the loop backedge.  Thus we do not want
647    to blindly disable threading across a loop backedge.  */
648
649 static void
650 thread_across_edge (struct dom_walk_data *walk_data, edge e)
651 {
652   block_stmt_iterator bsi;
653   tree stmt = NULL;
654   tree phi;
655   int stmt_count = 0;
656   int max_stmt_count;
657
658
659   /* If E->dest does not end with a conditional, then there is
660      nothing to do.  */
661   bsi = bsi_last (e->dest);
662   if (bsi_end_p (bsi)
663       || ! bsi_stmt (bsi)
664       || (TREE_CODE (bsi_stmt (bsi)) != COND_EXPR
665           && TREE_CODE (bsi_stmt (bsi)) != GOTO_EXPR
666           && TREE_CODE (bsi_stmt (bsi)) != SWITCH_EXPR))
667     return;
668
669   /* The basic idea here is to use whatever knowledge we have
670      from our dominator walk to simplify statements in E->dest,
671      with the ultimate goal being to simplify the conditional
672      at the end of E->dest.
673
674      Note that we must undo any changes we make to the underlying
675      statements as the simplifications we are making are control
676      flow sensitive (ie, the simplifications are valid when we 
677      traverse E, but may not be valid on other paths to E->dest.  */
678      
679   /* Each PHI creates a temporary equivalence, record them.  Again
680      these are context sensitive equivalences and will be removed
681      by our caller.  */
682   for (phi = phi_nodes (e->dest); phi; phi = PHI_CHAIN (phi))
683     {
684       tree src = PHI_ARG_DEF_FROM_EDGE (phi, e);
685       tree dst = PHI_RESULT (phi);
686
687       /* Do not include virtual PHIs in our statement count as
688          they never generate code.  */
689       if (is_gimple_reg (dst))
690         stmt_count++;
691
692       /* If the desired argument is not the same as this PHI's result 
693          and it is set by a PHI in E->dest, then we can not thread
694          through E->dest.  */
695       if (src != dst
696           && TREE_CODE (src) == SSA_NAME
697           && TREE_CODE (SSA_NAME_DEF_STMT (src)) == PHI_NODE
698           && bb_for_stmt (SSA_NAME_DEF_STMT (src)) == e->dest)
699         return;
700
701       record_const_or_copy (dst, src);
702     }
703
704   /* Try to simplify each statement in E->dest, ultimately leading to
705      a simplification of the COND_EXPR at the end of E->dest.
706
707      We might consider marking just those statements which ultimately
708      feed the COND_EXPR.  It's not clear if the overhead of bookkeeping
709      would be recovered by trying to simplify fewer statements.
710
711      If we are able to simplify a statement into the form
712      SSA_NAME = (SSA_NAME | gimple invariant), then we can record
713      a context sensitive equivalency which may help us simplify
714      later statements in E->dest. 
715
716      Failure to simplify into the form above merely means that the
717      statement provides no equivalences to help simplify later
718      statements.  This does not prevent threading through E->dest.  */
719   max_stmt_count = PARAM_VALUE (PARAM_MAX_JUMP_THREAD_DUPLICATION_STMTS);
720   for (bsi = bsi_start (e->dest); ! bsi_end_p (bsi); bsi_next (&bsi))
721     {
722       tree cached_lhs = NULL;
723
724       stmt = bsi_stmt (bsi);
725
726       /* Ignore empty statements and labels.  */
727       if (IS_EMPTY_STMT (stmt) || TREE_CODE (stmt) == LABEL_EXPR)
728         continue;
729
730       /* If duplicating this block is going to cause too much code
731          expansion, then do not thread through this block.  */
732       stmt_count++;
733       if (stmt_count > max_stmt_count)
734         return;
735
736       /* Safely handle threading across loop backedges.  This is
737          over conservative, but still allows us to capture the
738          majority of the cases where we can thread across a loop
739          backedge.  */
740       if ((e->flags & EDGE_DFS_BACK) != 0
741           && TREE_CODE (stmt) != COND_EXPR
742           && TREE_CODE (stmt) != SWITCH_EXPR)
743         return;
744
745       /* If the statement has volatile operands, then we assume we
746          can not thread through this block.  This is overly
747          conservative in some ways.  */
748       if (TREE_CODE (stmt) == ASM_EXPR && ASM_VOLATILE_P (stmt))
749         return;
750
751       /* If this is not a MODIFY_EXPR which sets an SSA_NAME to a new
752          value, then do not try to simplify this statement as it will
753          not simplify in any way that is helpful for jump threading.  */
754       if (TREE_CODE (stmt) != MODIFY_EXPR
755           || TREE_CODE (TREE_OPERAND (stmt, 0)) != SSA_NAME)
756         continue;
757
758       /* At this point we have a statement which assigns an RHS to an
759          SSA_VAR on the LHS.  We want to try and simplify this statement
760          to expose more context sensitive equivalences which in turn may
761          allow us to simplify the condition at the end of the loop.  */
762       if (TREE_CODE (TREE_OPERAND (stmt, 1)) == SSA_NAME)
763         cached_lhs = TREE_OPERAND (stmt, 1);
764       else
765         {
766           /* Copy the operands.  */
767           tree *copy, pre_fold_expr;
768           ssa_op_iter iter;
769           use_operand_p use_p;
770           unsigned int num, i = 0;
771
772           num = NUM_SSA_OPERANDS (stmt, (SSA_OP_USE | SSA_OP_VUSE));
773           copy = XCNEWVEC (tree, num);
774
775           /* Make a copy of the uses & vuses into USES_COPY, then cprop into
776              the operands.  */
777           FOR_EACH_SSA_USE_OPERAND (use_p, stmt, iter, SSA_OP_USE | SSA_OP_VUSE)
778             {
779               tree tmp = NULL;
780               tree use = USE_FROM_PTR (use_p);
781
782               copy[i++] = use;
783               if (TREE_CODE (use) == SSA_NAME)
784                 tmp = SSA_NAME_VALUE (use);
785               if (tmp && TREE_CODE (tmp) != VALUE_HANDLE)
786                 SET_USE (use_p, tmp);
787             }
788
789           /* Try to fold/lookup the new expression.  Inserting the
790              expression into the hash table is unlikely to help
791              Sadly, we have to handle conditional assignments specially
792              here, because fold expects all the operands of an expression
793              to be folded before the expression itself is folded, but we
794              can't just substitute the folded condition here.  */
795           if (TREE_CODE (TREE_OPERAND (stmt, 1)) == COND_EXPR)
796             {
797               tree cond = COND_EXPR_COND (TREE_OPERAND (stmt, 1));
798               cond = fold (cond);
799               if (cond == boolean_true_node)
800                 pre_fold_expr = COND_EXPR_THEN (TREE_OPERAND (stmt, 1));
801               else if (cond == boolean_false_node)
802                 pre_fold_expr = COND_EXPR_ELSE (TREE_OPERAND (stmt, 1));
803               else
804                 pre_fold_expr = TREE_OPERAND (stmt, 1);
805             }
806           else
807             pre_fold_expr = TREE_OPERAND (stmt, 1);
808
809           if (pre_fold_expr)
810             {
811               cached_lhs = fold (pre_fold_expr);
812               if (TREE_CODE (cached_lhs) != SSA_NAME
813                   && !is_gimple_min_invariant (cached_lhs))
814                 cached_lhs = lookup_avail_expr (stmt, false);
815             }
816
817           /* Restore the statement's original uses/defs.  */
818           i = 0;
819           FOR_EACH_SSA_USE_OPERAND (use_p, stmt, iter, SSA_OP_USE | SSA_OP_VUSE)
820             SET_USE (use_p, copy[i++]);
821
822           free (copy);
823         }
824
825       /* Record the context sensitive equivalence if we were able
826          to simplify this statement.  */
827       if (cached_lhs
828           && (TREE_CODE (cached_lhs) == SSA_NAME
829               || is_gimple_min_invariant (cached_lhs)))
830         record_const_or_copy (TREE_OPERAND (stmt, 0), cached_lhs);
831     }
832
833   /* If we stopped at a COND_EXPR or SWITCH_EXPR, see if we know which arm
834      will be taken.  */
835   if (stmt
836       && (TREE_CODE (stmt) == COND_EXPR
837           || TREE_CODE (stmt) == GOTO_EXPR
838           || TREE_CODE (stmt) == SWITCH_EXPR))
839     {
840       tree cond, cached_lhs;
841
842       /* Now temporarily cprop the operands and try to find the resulting
843          expression in the hash tables.  */
844       if (TREE_CODE (stmt) == COND_EXPR)
845         {
846           canonicalize_comparison (stmt);
847           cond = COND_EXPR_COND (stmt);
848         }
849       else if (TREE_CODE (stmt) == GOTO_EXPR)
850         cond = GOTO_DESTINATION (stmt);
851       else
852         cond = SWITCH_COND (stmt);
853
854       if (COMPARISON_CLASS_P (cond))
855         {
856           tree dummy_cond, op0, op1;
857           enum tree_code cond_code;
858
859           op0 = TREE_OPERAND (cond, 0);
860           op1 = TREE_OPERAND (cond, 1);
861           cond_code = TREE_CODE (cond);
862
863           /* Get the current value of both operands.  */
864           if (TREE_CODE (op0) == SSA_NAME)
865             {
866               tree tmp = SSA_NAME_VALUE (op0);
867               if (tmp && TREE_CODE (tmp) != VALUE_HANDLE)
868                 op0 = tmp;
869             }
870
871           if (TREE_CODE (op1) == SSA_NAME)
872             {
873               tree tmp = SSA_NAME_VALUE (op1);
874               if (tmp && TREE_CODE (tmp) != VALUE_HANDLE)
875                 op1 = tmp;
876             }
877
878           /* Stuff the operator and operands into our dummy conditional
879              expression, creating the dummy conditional if necessary.  */
880           dummy_cond = (tree) walk_data->global_data;
881           if (! dummy_cond)
882             {
883               dummy_cond = build2 (cond_code, boolean_type_node, op0, op1);
884               dummy_cond = build3 (COND_EXPR, void_type_node,
885                                    dummy_cond, NULL_TREE, NULL_TREE);
886               walk_data->global_data = dummy_cond;
887             }
888           else
889             {
890               TREE_SET_CODE (COND_EXPR_COND (dummy_cond), cond_code);
891               TREE_OPERAND (COND_EXPR_COND (dummy_cond), 0) = op0;
892               TREE_OPERAND (COND_EXPR_COND (dummy_cond), 1) = op1;
893             }
894
895           /* We absolutely do not care about any type conversions
896              we only care about a zero/nonzero value.  */
897           cached_lhs = fold (COND_EXPR_COND (dummy_cond));
898           while (TREE_CODE (cached_lhs) == NOP_EXPR
899                  || TREE_CODE (cached_lhs) == CONVERT_EXPR
900                  || TREE_CODE (cached_lhs) == NON_LVALUE_EXPR)
901             cached_lhs = TREE_OPERAND (cached_lhs, 0);
902             
903           if (! is_gimple_min_invariant (cached_lhs))
904             {
905               cached_lhs = lookup_avail_expr (dummy_cond, false);
906               if (!cached_lhs || ! is_gimple_min_invariant (cached_lhs))
907                 cached_lhs = simplify_cond_and_lookup_avail_expr (dummy_cond,
908                                                                   NULL,
909                                                                   false);
910             }
911         }
912       /* We can have conditionals which just test the state of a
913          variable rather than use a relational operator.  These are
914          simpler to handle.  */
915       else if (TREE_CODE (cond) == SSA_NAME)
916         {
917           cached_lhs = cond;
918           cached_lhs = SSA_NAME_VALUE (cached_lhs);
919           if (cached_lhs && ! is_gimple_min_invariant (cached_lhs))
920             cached_lhs = NULL;
921         }
922       else
923         cached_lhs = lookup_avail_expr (stmt, false);
924
925       if (cached_lhs)
926         {
927           edge taken_edge = find_taken_edge (e->dest, cached_lhs);
928           basic_block dest = (taken_edge ? taken_edge->dest : NULL);
929
930           if (dest == e->dest)
931             return;
932
933           /* If we have a known destination for the conditional, then
934              we can perform this optimization, which saves at least one
935              conditional jump each time it applies since we get to
936              bypass the conditional at our original destination.  */
937           if (dest)
938             {
939               struct edge_info *edge_info;
940
941               if (e->aux)
942                 edge_info = (struct edge_info *) e->aux;
943               else
944                 edge_info = allocate_edge_info (e);
945               edge_info->redirection_target = taken_edge;
946               bitmap_set_bit (threaded_blocks, e->dest->index);
947             }
948         }
949     }
950 }
951
952
953 /* Initialize local stacks for this optimizer and record equivalences
954    upon entry to BB.  Equivalences can come from the edge traversed to
955    reach BB or they may come from PHI nodes at the start of BB.  */
956
957 static void
958 dom_opt_initialize_block (struct dom_walk_data *walk_data ATTRIBUTE_UNUSED,
959                           basic_block bb)
960 {
961   if (dump_file && (dump_flags & TDF_DETAILS))
962     fprintf (dump_file, "\n\nOptimizing block #%d\n\n", bb->index);
963
964   /* Push a marker on the stacks of local information so that we know how
965      far to unwind when we finalize this block.  */
966   VEC_safe_push (tree, heap, avail_exprs_stack, NULL_TREE);
967   VEC_safe_push (tree, heap, const_and_copies_stack, NULL_TREE);
968   VEC_safe_push (tree, heap, nonzero_vars_stack, NULL_TREE);
969   VEC_safe_push (tree, heap, vrp_variables_stack, NULL_TREE);
970
971   record_equivalences_from_incoming_edge (bb);
972
973   /* PHI nodes can create equivalences too.  */
974   record_equivalences_from_phis (bb);
975 }
976
977 /* Given an expression EXPR (a relational expression or a statement), 
978    initialize the hash table element pointed to by ELEMENT.  */
979
980 static void
981 initialize_hash_element (tree expr, tree lhs, struct expr_hash_elt *element)
982 {
983   /* Hash table elements may be based on conditional expressions or statements.
984
985      For the former case, we have no annotation and we want to hash the
986      conditional expression.  In the latter case we have an annotation and
987      we want to record the expression the statement evaluates.  */
988   if (COMPARISON_CLASS_P (expr) || TREE_CODE (expr) == TRUTH_NOT_EXPR)
989     {
990       element->stmt = NULL;
991       element->rhs = expr;
992     }
993   else if (TREE_CODE (expr) == COND_EXPR)
994     {
995       element->stmt = expr;
996       element->rhs = COND_EXPR_COND (expr);
997     }
998   else if (TREE_CODE (expr) == SWITCH_EXPR)
999     {
1000       element->stmt = expr;
1001       element->rhs = SWITCH_COND (expr);
1002     }
1003   else if (TREE_CODE (expr) == RETURN_EXPR && TREE_OPERAND (expr, 0))
1004     {
1005       element->stmt = expr;
1006       element->rhs = TREE_OPERAND (TREE_OPERAND (expr, 0), 1);
1007     }
1008   else if (TREE_CODE (expr) == GOTO_EXPR)
1009     {
1010       element->stmt = expr;
1011       element->rhs = GOTO_DESTINATION (expr);
1012     }
1013   else
1014     {
1015       element->stmt = expr;
1016       element->rhs = TREE_OPERAND (expr, 1);
1017     }
1018
1019   element->lhs = lhs;
1020   element->hash = avail_expr_hash (element);
1021 }
1022
1023 /* Remove all the expressions in LOCALS from TABLE, stopping when there are
1024    LIMIT entries left in LOCALs.  */
1025
1026 static void
1027 remove_local_expressions_from_table (void)
1028 {
1029   /* Remove all the expressions made available in this block.  */
1030   while (VEC_length (tree, avail_exprs_stack) > 0)
1031     {
1032       struct expr_hash_elt element;
1033       tree expr = VEC_pop (tree, avail_exprs_stack);
1034
1035       if (expr == NULL_TREE)
1036         break;
1037
1038       initialize_hash_element (expr, NULL, &element);
1039       htab_remove_elt_with_hash (avail_exprs, &element, element.hash);
1040     }
1041 }
1042
1043 /* Use the SSA_NAMES in LOCALS to restore TABLE to its original
1044    state, stopping when there are LIMIT entries left in LOCALs.  */
1045
1046 static void
1047 restore_nonzero_vars_to_original_value (void)
1048 {
1049   while (VEC_length (tree, nonzero_vars_stack) > 0)
1050     {
1051       tree name = VEC_pop (tree, nonzero_vars_stack);
1052
1053       if (name == NULL)
1054         break;
1055
1056       bitmap_clear_bit (nonzero_vars, SSA_NAME_VERSION (name));
1057     }
1058 }
1059
1060 /* Use the source/dest pairs in CONST_AND_COPIES_STACK to restore
1061    CONST_AND_COPIES to its original state, stopping when we hit a
1062    NULL marker.  */
1063
1064 static void
1065 restore_vars_to_original_value (void)
1066 {
1067   while (VEC_length (tree, const_and_copies_stack) > 0)
1068     {
1069       tree prev_value, dest;
1070
1071       dest = VEC_pop (tree, const_and_copies_stack);
1072
1073       if (dest == NULL)
1074         break;
1075
1076       prev_value = VEC_pop (tree, const_and_copies_stack);
1077       SSA_NAME_VALUE (dest) =  prev_value;
1078     }
1079 }
1080
1081 /* We have finished processing the dominator children of BB, perform
1082    any finalization actions in preparation for leaving this node in
1083    the dominator tree.  */
1084
1085 static void
1086 dom_opt_finalize_block (struct dom_walk_data *walk_data, basic_block bb)
1087 {
1088   tree last;
1089
1090   /* If we have an outgoing edge to a block with multiple incoming and
1091      outgoing edges, then we may be able to thread the edge.  ie, we
1092      may be able to statically determine which of the outgoing edges
1093      will be traversed when the incoming edge from BB is traversed.  */
1094   if (single_succ_p (bb)
1095       && (single_succ_edge (bb)->flags & EDGE_ABNORMAL) == 0
1096       && !single_pred_p (single_succ (bb))
1097       && !single_succ_p (single_succ (bb)))
1098         
1099     {
1100       thread_across_edge (walk_data, single_succ_edge (bb));
1101     }
1102   else if ((last = last_stmt (bb))
1103            && TREE_CODE (last) == COND_EXPR
1104            && (COMPARISON_CLASS_P (COND_EXPR_COND (last))
1105                || TREE_CODE (COND_EXPR_COND (last)) == SSA_NAME)
1106            && EDGE_COUNT (bb->succs) == 2
1107            && (EDGE_SUCC (bb, 0)->flags & EDGE_ABNORMAL) == 0
1108            && (EDGE_SUCC (bb, 1)->flags & EDGE_ABNORMAL) == 0)
1109     {
1110       edge true_edge, false_edge;
1111
1112       extract_true_false_edges_from_block (bb, &true_edge, &false_edge);
1113
1114       /* Only try to thread the edge if it reaches a target block with
1115          more than one predecessor and more than one successor.  */
1116       if (!single_pred_p (true_edge->dest) && !single_succ_p (true_edge->dest))
1117         {
1118           struct edge_info *edge_info;
1119           unsigned int i;
1120
1121           /* Push a marker onto the available expression stack so that we
1122              unwind any expressions related to the TRUE arm before processing
1123              the false arm below.  */
1124           VEC_safe_push (tree, heap, avail_exprs_stack, NULL_TREE);
1125           VEC_safe_push (tree, heap, const_and_copies_stack, NULL_TREE);
1126
1127           edge_info = (struct edge_info *) true_edge->aux;
1128
1129           /* If we have info associated with this edge, record it into
1130              our equivalency tables.  */
1131           if (edge_info)
1132             {
1133               tree *cond_equivalences = edge_info->cond_equivalences;
1134               tree lhs = edge_info->lhs;
1135               tree rhs = edge_info->rhs;
1136
1137               /* If we have a simple NAME = VALUE equivalency record it.  */
1138               if (lhs && TREE_CODE (lhs) == SSA_NAME)
1139                 record_const_or_copy (lhs, rhs);
1140
1141               /* If we have 0 = COND or 1 = COND equivalences, record them
1142                  into our expression hash tables.  */
1143               if (cond_equivalences)
1144                 for (i = 0; i < edge_info->max_cond_equivalences; i += 2)
1145                   {
1146                     tree expr = cond_equivalences[i];
1147                     tree value = cond_equivalences[i + 1];
1148
1149                     record_cond (expr, value);
1150                   }
1151             }
1152
1153           /* Now thread the edge.  */
1154           thread_across_edge (walk_data, true_edge);
1155
1156           /* And restore the various tables to their state before
1157              we threaded this edge.  */
1158           remove_local_expressions_from_table ();
1159           restore_vars_to_original_value ();
1160         }
1161
1162       /* Similarly for the ELSE arm.  */
1163       if (!single_pred_p (false_edge->dest) && !single_succ_p (false_edge->dest))
1164         {
1165           struct edge_info *edge_info;
1166           unsigned int i;
1167
1168           edge_info = (struct edge_info *) false_edge->aux;
1169
1170           /* If we have info associated with this edge, record it into
1171              our equivalency tables.  */
1172           if (edge_info)
1173             {
1174               tree *cond_equivalences = edge_info->cond_equivalences;
1175               tree lhs = edge_info->lhs;
1176               tree rhs = edge_info->rhs;
1177
1178               /* If we have a simple NAME = VALUE equivalency record it.  */
1179               if (lhs && TREE_CODE (lhs) == SSA_NAME)
1180                 record_const_or_copy (lhs, rhs);
1181
1182               /* If we have 0 = COND or 1 = COND equivalences, record them
1183                  into our expression hash tables.  */
1184               if (cond_equivalences)
1185                 for (i = 0; i < edge_info->max_cond_equivalences; i += 2)
1186                   {
1187                     tree expr = cond_equivalences[i];
1188                     tree value = cond_equivalences[i + 1];
1189
1190                     record_cond (expr, value);
1191                   }
1192             }
1193
1194           thread_across_edge (walk_data, false_edge);
1195
1196           /* No need to remove local expressions from our tables
1197              or restore vars to their original value as that will
1198              be done immediately below.  */
1199         }
1200     }
1201
1202   remove_local_expressions_from_table ();
1203   restore_nonzero_vars_to_original_value ();
1204   restore_vars_to_original_value ();
1205
1206   /* Remove VRP records associated with this basic block.  They are no
1207      longer valid.
1208
1209      To be efficient, we note which variables have had their values
1210      constrained in this block.  So walk over each variable in the
1211      VRP_VARIABLEs array.  */
1212   while (VEC_length (tree, vrp_variables_stack) > 0)
1213     {
1214       tree var = VEC_pop (tree, vrp_variables_stack);
1215       struct vrp_hash_elt vrp_hash_elt, *vrp_hash_elt_p;
1216       void **slot;
1217
1218       /* Each variable has a stack of value range records.  We want to
1219          invalidate those associated with our basic block.  So we walk
1220          the array backwards popping off records associated with our
1221          block.  Once we hit a record not associated with our block
1222          we are done.  */
1223       VEC(vrp_element_p,heap) **var_vrp_records;
1224
1225       if (var == NULL)
1226         break;
1227
1228       vrp_hash_elt.var = var;
1229       vrp_hash_elt.records = NULL;
1230
1231       slot = htab_find_slot (vrp_data, &vrp_hash_elt, NO_INSERT);
1232
1233       vrp_hash_elt_p = (struct vrp_hash_elt *) *slot;
1234       var_vrp_records = &vrp_hash_elt_p->records;
1235
1236       while (VEC_length (vrp_element_p, *var_vrp_records) > 0)
1237         {
1238           struct vrp_element *element
1239             = VEC_last (vrp_element_p, *var_vrp_records);
1240
1241           if (element->bb != bb)
1242             break;
1243   
1244           VEC_pop (vrp_element_p, *var_vrp_records);
1245         }
1246     }
1247
1248   /* If we queued any statements to rescan in this block, then
1249      go ahead and rescan them now.  */
1250   while (VEC_length (tree, stmts_to_rescan) > 0)
1251     {
1252       tree stmt = VEC_last (tree, stmts_to_rescan);
1253       basic_block stmt_bb = bb_for_stmt (stmt);
1254
1255       if (stmt_bb != bb)
1256         break;
1257
1258       VEC_pop (tree, stmts_to_rescan);
1259       mark_new_vars_to_rename (stmt);
1260     }
1261 }
1262
1263 /* PHI nodes can create equivalences too.
1264
1265    Ignoring any alternatives which are the same as the result, if
1266    all the alternatives are equal, then the PHI node creates an
1267    equivalence.
1268
1269    Additionally, if all the PHI alternatives are known to have a nonzero
1270    value, then the result of this PHI is known to have a nonzero value,
1271    even if we do not know its exact value.  */
1272
1273 static void
1274 record_equivalences_from_phis (basic_block bb)
1275 {
1276   tree phi;
1277
1278   for (phi = phi_nodes (bb); phi; phi = PHI_CHAIN (phi))
1279     {
1280       tree lhs = PHI_RESULT (phi);
1281       tree rhs = NULL;
1282       int i;
1283
1284       for (i = 0; i < PHI_NUM_ARGS (phi); i++)
1285         {
1286           tree t = PHI_ARG_DEF (phi, i);
1287
1288           /* Ignore alternatives which are the same as our LHS.  Since
1289              LHS is a PHI_RESULT, it is known to be a SSA_NAME, so we
1290              can simply compare pointers.  */
1291           if (lhs == t)
1292             continue;
1293
1294           /* If we have not processed an alternative yet, then set
1295              RHS to this alternative.  */
1296           if (rhs == NULL)
1297             rhs = t;
1298           /* If we have processed an alternative (stored in RHS), then
1299              see if it is equal to this one.  If it isn't, then stop
1300              the search.  */
1301           else if (! operand_equal_for_phi_arg_p (rhs, t))
1302             break;
1303         }
1304
1305       /* If we had no interesting alternatives, then all the RHS alternatives
1306          must have been the same as LHS.  */
1307       if (!rhs)
1308         rhs = lhs;
1309
1310       /* If we managed to iterate through each PHI alternative without
1311          breaking out of the loop, then we have a PHI which may create
1312          a useful equivalence.  We do not need to record unwind data for
1313          this, since this is a true assignment and not an equivalence
1314          inferred from a comparison.  All uses of this ssa name are dominated
1315          by this assignment, so unwinding just costs time and space.  */
1316       if (i == PHI_NUM_ARGS (phi)
1317           && may_propagate_copy (lhs, rhs))
1318         SSA_NAME_VALUE (lhs) = rhs;
1319
1320       /* Now see if we know anything about the nonzero property for the
1321          result of this PHI.  */
1322       for (i = 0; i < PHI_NUM_ARGS (phi); i++)
1323         {
1324           if (!PHI_ARG_NONZERO (phi, i))
1325             break;
1326         }
1327
1328       if (i == PHI_NUM_ARGS (phi))
1329         bitmap_set_bit (nonzero_vars, SSA_NAME_VERSION (PHI_RESULT (phi)));
1330     }
1331 }
1332
1333 /* Ignoring loop backedges, if BB has precisely one incoming edge then
1334    return that edge.  Otherwise return NULL.  */
1335 static edge
1336 single_incoming_edge_ignoring_loop_edges (basic_block bb)
1337 {
1338   edge retval = NULL;
1339   edge e;
1340   edge_iterator ei;
1341
1342   FOR_EACH_EDGE (e, ei, bb->preds)
1343     {
1344       /* A loop back edge can be identified by the destination of
1345          the edge dominating the source of the edge.  */
1346       if (dominated_by_p (CDI_DOMINATORS, e->src, e->dest))
1347         continue;
1348
1349       /* If we have already seen a non-loop edge, then we must have
1350          multiple incoming non-loop edges and thus we return NULL.  */
1351       if (retval)
1352         return NULL;
1353
1354       /* This is the first non-loop incoming edge we have found.  Record
1355          it.  */
1356       retval = e;
1357     }
1358
1359   return retval;
1360 }
1361
1362 /* Record any equivalences created by the incoming edge to BB.  If BB
1363    has more than one incoming edge, then no equivalence is created.  */
1364
1365 static void
1366 record_equivalences_from_incoming_edge (basic_block bb)
1367 {
1368   edge e;
1369   basic_block parent;
1370   struct edge_info *edge_info;
1371
1372   /* If our parent block ended with a control statement, then we may be
1373      able to record some equivalences based on which outgoing edge from
1374      the parent was followed.  */
1375   parent = get_immediate_dominator (CDI_DOMINATORS, bb);
1376
1377   e = single_incoming_edge_ignoring_loop_edges (bb);
1378
1379   /* If we had a single incoming edge from our parent block, then enter
1380      any data associated with the edge into our tables.  */
1381   if (e && e->src == parent)
1382     {
1383       unsigned int i;
1384
1385       edge_info = (struct edge_info *) e->aux;
1386
1387       if (edge_info)
1388         {
1389           tree lhs = edge_info->lhs;
1390           tree rhs = edge_info->rhs;
1391           tree *cond_equivalences = edge_info->cond_equivalences;
1392
1393           if (lhs)
1394             record_equality (lhs, rhs);
1395
1396           if (cond_equivalences)
1397             {
1398               bool recorded_range = false;
1399               for (i = 0; i < edge_info->max_cond_equivalences; i += 2)
1400                 {
1401                   tree expr = cond_equivalences[i];
1402                   tree value = cond_equivalences[i + 1];
1403
1404                   record_cond (expr, value);
1405
1406                   /* For the first true equivalence, record range
1407                      information.  We only do this for the first
1408                      true equivalence as it should dominate any
1409                      later true equivalences.  */
1410                   if (! recorded_range 
1411                       && COMPARISON_CLASS_P (expr)
1412                       && value == boolean_true_node
1413                       && TREE_CONSTANT (TREE_OPERAND (expr, 1)))
1414                     {
1415                       record_range (expr, bb);
1416                       recorded_range = true;
1417                     }
1418                 }
1419             }
1420         }
1421     }
1422 }
1423
1424 /* Dump SSA statistics on FILE.  */
1425
1426 void
1427 dump_dominator_optimization_stats (FILE *file)
1428 {
1429   long n_exprs;
1430
1431   fprintf (file, "Total number of statements:                   %6ld\n\n",
1432            opt_stats.num_stmts);
1433   fprintf (file, "Exprs considered for dominator optimizations: %6ld\n",
1434            opt_stats.num_exprs_considered);
1435
1436   n_exprs = opt_stats.num_exprs_considered;
1437   if (n_exprs == 0)
1438     n_exprs = 1;
1439
1440   fprintf (file, "    Redundant expressions eliminated:         %6ld (%.0f%%)\n",
1441            opt_stats.num_re, PERCENT (opt_stats.num_re,
1442                                       n_exprs));
1443   fprintf (file, "    Constants propagated:                     %6ld\n",
1444            opt_stats.num_const_prop);
1445   fprintf (file, "    Copies propagated:                        %6ld\n",
1446            opt_stats.num_copy_prop);
1447
1448   fprintf (file, "\nTotal number of DOM iterations:             %6ld\n",
1449            opt_stats.num_iterations);
1450
1451   fprintf (file, "\nHash table statistics:\n");
1452
1453   fprintf (file, "    avail_exprs: ");
1454   htab_statistics (file, avail_exprs);
1455 }
1456
1457
1458 /* Dump SSA statistics on stderr.  */
1459
1460 void
1461 debug_dominator_optimization_stats (void)
1462 {
1463   dump_dominator_optimization_stats (stderr);
1464 }
1465
1466
1467 /* Dump statistics for the hash table HTAB.  */
1468
1469 static void
1470 htab_statistics (FILE *file, htab_t htab)
1471 {
1472   fprintf (file, "size %ld, %ld elements, %f collision/search ratio\n",
1473            (long) htab_size (htab),
1474            (long) htab_elements (htab),
1475            htab_collisions (htab));
1476 }
1477
1478 /* Record the fact that VAR has a nonzero value, though we may not know
1479    its exact value.  Note that if VAR is already known to have a nonzero
1480    value, then we do nothing.  */
1481
1482 static void
1483 record_var_is_nonzero (tree var)
1484 {
1485   int indx = SSA_NAME_VERSION (var);
1486
1487   if (bitmap_bit_p (nonzero_vars, indx))
1488     return;
1489
1490   /* Mark it in the global table.  */
1491   bitmap_set_bit (nonzero_vars, indx);
1492
1493   /* Record this SSA_NAME so that we can reset the global table
1494      when we leave this block.  */
1495   VEC_safe_push (tree, heap, nonzero_vars_stack, var);
1496 }
1497
1498 /* Enter a statement into the true/false expression hash table indicating
1499    that the condition COND has the value VALUE.  */
1500
1501 static void
1502 record_cond (tree cond, tree value)
1503 {
1504   struct expr_hash_elt *element = XCNEW (struct expr_hash_elt);
1505   void **slot;
1506
1507   initialize_hash_element (cond, value, element);
1508
1509   slot = htab_find_slot_with_hash (avail_exprs, (void *)element,
1510                                    element->hash, INSERT);
1511   if (*slot == NULL)
1512     {
1513       *slot = (void *) element;
1514       VEC_safe_push (tree, heap, avail_exprs_stack, cond);
1515     }
1516   else
1517     free (element);
1518 }
1519
1520 /* Build a new conditional using NEW_CODE, OP0 and OP1 and store
1521    the new conditional into *p, then store a boolean_true_node
1522    into *(p + 1).  */
1523    
1524 static void
1525 build_and_record_new_cond (enum tree_code new_code, tree op0, tree op1, tree *p)
1526 {
1527   *p = build2 (new_code, boolean_type_node, op0, op1);
1528   p++;
1529   *p = boolean_true_node;
1530 }
1531
1532 /* Record that COND is true and INVERTED is false into the edge information
1533    structure.  Also record that any conditions dominated by COND are true
1534    as well.
1535
1536    For example, if a < b is true, then a <= b must also be true.  */
1537
1538 static void
1539 record_conditions (struct edge_info *edge_info, tree cond, tree inverted)
1540 {
1541   tree op0, op1;
1542
1543   if (!COMPARISON_CLASS_P (cond))
1544     return;
1545
1546   op0 = TREE_OPERAND (cond, 0);
1547   op1 = TREE_OPERAND (cond, 1);
1548
1549   switch (TREE_CODE (cond))
1550     {
1551     case LT_EXPR:
1552     case GT_EXPR:
1553       edge_info->max_cond_equivalences = 12;
1554       edge_info->cond_equivalences = XNEWVEC (tree, 12);
1555       build_and_record_new_cond ((TREE_CODE (cond) == LT_EXPR
1556                                   ? LE_EXPR : GE_EXPR),
1557                                  op0, op1, &edge_info->cond_equivalences[4]);
1558       build_and_record_new_cond (ORDERED_EXPR, op0, op1,
1559                                  &edge_info->cond_equivalences[6]);
1560       build_and_record_new_cond (NE_EXPR, op0, op1,
1561                                  &edge_info->cond_equivalences[8]);
1562       build_and_record_new_cond (LTGT_EXPR, op0, op1,
1563                                  &edge_info->cond_equivalences[10]);
1564       break;
1565
1566     case GE_EXPR:
1567     case LE_EXPR:
1568       edge_info->max_cond_equivalences = 6;
1569       edge_info->cond_equivalences = XNEWVEC (tree, 6);
1570       build_and_record_new_cond (ORDERED_EXPR, op0, op1,
1571                                  &edge_info->cond_equivalences[4]);
1572       break;
1573
1574     case EQ_EXPR:
1575       edge_info->max_cond_equivalences = 10;
1576       edge_info->cond_equivalences = XNEWVEC (tree, 10);
1577       build_and_record_new_cond (ORDERED_EXPR, op0, op1,
1578                                  &edge_info->cond_equivalences[4]);
1579       build_and_record_new_cond (LE_EXPR, op0, op1,
1580                                  &edge_info->cond_equivalences[6]);
1581       build_and_record_new_cond (GE_EXPR, op0, op1,
1582                                  &edge_info->cond_equivalences[8]);
1583       break;
1584
1585     case UNORDERED_EXPR:
1586       edge_info->max_cond_equivalences = 16;
1587       edge_info->cond_equivalences = XNEWVEC (tree, 16);
1588       build_and_record_new_cond (NE_EXPR, op0, op1,
1589                                  &edge_info->cond_equivalences[4]);
1590       build_and_record_new_cond (UNLE_EXPR, op0, op1,
1591                                  &edge_info->cond_equivalences[6]);
1592       build_and_record_new_cond (UNGE_EXPR, op0, op1,
1593                                  &edge_info->cond_equivalences[8]);
1594       build_and_record_new_cond (UNEQ_EXPR, op0, op1,
1595                                  &edge_info->cond_equivalences[10]);
1596       build_and_record_new_cond (UNLT_EXPR, op0, op1,
1597                                  &edge_info->cond_equivalences[12]);
1598       build_and_record_new_cond (UNGT_EXPR, op0, op1,
1599                                  &edge_info->cond_equivalences[14]);
1600       break;
1601
1602     case UNLT_EXPR:
1603     case UNGT_EXPR:
1604       edge_info->max_cond_equivalences = 8;
1605       edge_info->cond_equivalences = XNEWVEC (tree, 8);
1606       build_and_record_new_cond ((TREE_CODE (cond) == UNLT_EXPR
1607                                   ? UNLE_EXPR : UNGE_EXPR),
1608                                  op0, op1, &edge_info->cond_equivalences[4]);
1609       build_and_record_new_cond (NE_EXPR, op0, op1,
1610                                  &edge_info->cond_equivalences[6]);
1611       break;
1612
1613     case UNEQ_EXPR:
1614       edge_info->max_cond_equivalences = 8;
1615       edge_info->cond_equivalences = XNEWVEC (tree, 8);
1616       build_and_record_new_cond (UNLE_EXPR, op0, op1,
1617                                  &edge_info->cond_equivalences[4]);
1618       build_and_record_new_cond (UNGE_EXPR, op0, op1,
1619                                  &edge_info->cond_equivalences[6]);
1620       break;
1621
1622     case LTGT_EXPR:
1623       edge_info->max_cond_equivalences = 8;
1624       edge_info->cond_equivalences = XNEWVEC (tree, 8);
1625       build_and_record_new_cond (NE_EXPR, op0, op1,
1626                                  &edge_info->cond_equivalences[4]);
1627       build_and_record_new_cond (ORDERED_EXPR, op0, op1,
1628                                  &edge_info->cond_equivalences[6]);
1629       break;
1630
1631     default:
1632       edge_info->max_cond_equivalences = 4;
1633       edge_info->cond_equivalences = XNEWVEC (tree, 4);
1634       break;
1635     }
1636
1637   /* Now store the original true and false conditions into the first
1638      two slots.  */
1639   edge_info->cond_equivalences[0] = cond;
1640   edge_info->cond_equivalences[1] = boolean_true_node;
1641   edge_info->cond_equivalences[2] = inverted;
1642   edge_info->cond_equivalences[3] = boolean_false_node;
1643 }
1644
1645 /* A helper function for record_const_or_copy and record_equality.
1646    Do the work of recording the value and undo info.  */
1647
1648 static void
1649 record_const_or_copy_1 (tree x, tree y, tree prev_x)
1650 {
1651   SSA_NAME_VALUE (x) = y;
1652
1653   VEC_reserve (tree, heap, const_and_copies_stack, 2);
1654   VEC_quick_push (tree, const_and_copies_stack, prev_x);
1655   VEC_quick_push (tree, const_and_copies_stack, x);
1656 }
1657
1658
1659 /* Return the loop depth of the basic block of the defining statement of X.
1660    This number should not be treated as absolutely correct because the loop
1661    information may not be completely up-to-date when dom runs.  However, it
1662    will be relatively correct, and as more passes are taught to keep loop info
1663    up to date, the result will become more and more accurate.  */
1664
1665 int
1666 loop_depth_of_name (tree x)
1667 {
1668   tree defstmt;
1669   basic_block defbb;
1670
1671   /* If it's not an SSA_NAME, we have no clue where the definition is.  */
1672   if (TREE_CODE (x) != SSA_NAME)
1673     return 0;
1674
1675   /* Otherwise return the loop depth of the defining statement's bb.
1676      Note that there may not actually be a bb for this statement, if the
1677      ssa_name is live on entry.  */
1678   defstmt = SSA_NAME_DEF_STMT (x);
1679   defbb = bb_for_stmt (defstmt);
1680   if (!defbb)
1681     return 0;
1682
1683   return defbb->loop_depth;
1684 }
1685
1686
1687 /* Record that X is equal to Y in const_and_copies.  Record undo
1688    information in the block-local vector.  */
1689
1690 static void
1691 record_const_or_copy (tree x, tree y)
1692 {
1693   tree prev_x = SSA_NAME_VALUE (x);
1694
1695   if (TREE_CODE (y) == SSA_NAME)
1696     {
1697       tree tmp = SSA_NAME_VALUE (y);
1698       if (tmp)
1699         y = tmp;
1700     }
1701
1702   record_const_or_copy_1 (x, y, prev_x);
1703 }
1704
1705 /* Similarly, but assume that X and Y are the two operands of an EQ_EXPR.
1706    This constrains the cases in which we may treat this as assignment.  */
1707
1708 static void
1709 record_equality (tree x, tree y)
1710 {
1711   tree prev_x = NULL, prev_y = NULL;
1712
1713   if (TREE_CODE (x) == SSA_NAME)
1714     prev_x = SSA_NAME_VALUE (x);
1715   if (TREE_CODE (y) == SSA_NAME)
1716     prev_y = SSA_NAME_VALUE (y);
1717
1718   /* If one of the previous values is invariant, or invariant in more loops
1719      (by depth), then use that.
1720      Otherwise it doesn't matter which value we choose, just so
1721      long as we canonicalize on one value.  */
1722   if (TREE_INVARIANT (y))
1723     ;
1724   else if (TREE_INVARIANT (x) || (loop_depth_of_name (x) <= loop_depth_of_name (y)))
1725     prev_x = x, x = y, y = prev_x, prev_x = prev_y;
1726   else if (prev_x && TREE_INVARIANT (prev_x))
1727     x = y, y = prev_x, prev_x = prev_y;
1728   else if (prev_y && TREE_CODE (prev_y) != VALUE_HANDLE)
1729     y = prev_y;
1730
1731   /* After the swapping, we must have one SSA_NAME.  */
1732   if (TREE_CODE (x) != SSA_NAME)
1733     return;
1734
1735   /* For IEEE, -0.0 == 0.0, so we don't necessarily know the sign of a
1736      variable compared against zero.  If we're honoring signed zeros,
1737      then we cannot record this value unless we know that the value is
1738      nonzero.  */
1739   if (HONOR_SIGNED_ZEROS (TYPE_MODE (TREE_TYPE (x)))
1740       && (TREE_CODE (y) != REAL_CST
1741           || REAL_VALUES_EQUAL (dconst0, TREE_REAL_CST (y))))
1742     return;
1743
1744   record_const_or_copy_1 (x, y, prev_x);
1745 }
1746
1747 /* Return true, if it is ok to do folding of an associative expression.
1748    EXP is the tree for the associative expression.  */ 
1749
1750 static inline bool
1751 unsafe_associative_fp_binop (tree exp)
1752 {
1753   enum tree_code code = TREE_CODE (exp);
1754   return !(!flag_unsafe_math_optimizations
1755            && (code == MULT_EXPR || code == PLUS_EXPR
1756                || code == MINUS_EXPR)
1757            && FLOAT_TYPE_P (TREE_TYPE (exp)));
1758 }
1759
1760 /* Returns true when STMT is a simple iv increment.  It detects the
1761    following situation:
1762    
1763    i_1 = phi (..., i_2)
1764    i_2 = i_1 +/- ...  */
1765
1766 static bool
1767 simple_iv_increment_p (tree stmt)
1768 {
1769   tree lhs, rhs, preinc, phi;
1770   unsigned i;
1771
1772   if (TREE_CODE (stmt) != MODIFY_EXPR)
1773     return false;
1774
1775   lhs = TREE_OPERAND (stmt, 0);
1776   if (TREE_CODE (lhs) != SSA_NAME)
1777     return false;
1778
1779   rhs = TREE_OPERAND (stmt, 1);
1780
1781   if (TREE_CODE (rhs) != PLUS_EXPR
1782       && TREE_CODE (rhs) != MINUS_EXPR)
1783     return false;
1784
1785   preinc = TREE_OPERAND (rhs, 0);
1786   if (TREE_CODE (preinc) != SSA_NAME)
1787     return false;
1788
1789   phi = SSA_NAME_DEF_STMT (preinc);
1790   if (TREE_CODE (phi) != PHI_NODE)
1791     return false;
1792
1793   for (i = 0; i < (unsigned) PHI_NUM_ARGS (phi); i++)
1794     if (PHI_ARG_DEF (phi, i) == lhs)
1795       return true;
1796
1797   return false;
1798 }
1799
1800 /* COND is a condition of the form:
1801
1802      x == const or x != const
1803
1804    Look back to x's defining statement and see if x is defined as
1805
1806      x = (type) y;
1807
1808    If const is unchanged if we convert it to type, then we can build
1809    the equivalent expression:
1810
1811
1812       y == const or y != const
1813
1814    Which may allow further optimizations.
1815
1816    Return the equivalent comparison or NULL if no such equivalent comparison
1817    was found.  */
1818
1819 static tree
1820 find_equivalent_equality_comparison (tree cond)
1821 {
1822   tree op0 = TREE_OPERAND (cond, 0);
1823   tree op1 = TREE_OPERAND (cond, 1);
1824   tree def_stmt = SSA_NAME_DEF_STMT (op0);
1825
1826   /* OP0 might have been a parameter, so first make sure it
1827      was defined by a MODIFY_EXPR.  */
1828   if (def_stmt && TREE_CODE (def_stmt) == MODIFY_EXPR)
1829     {
1830       tree def_rhs = TREE_OPERAND (def_stmt, 1);
1831
1832
1833       /* If either operand to the comparison is a pointer to
1834          a function, then we can not apply this optimization
1835          as some targets require function pointers to be
1836          canonicalized and in this case this optimization would
1837          eliminate a necessary canonicalization.  */
1838       if ((POINTER_TYPE_P (TREE_TYPE (op0))
1839            && TREE_CODE (TREE_TYPE (TREE_TYPE (op0))) == FUNCTION_TYPE)
1840           || (POINTER_TYPE_P (TREE_TYPE (op1))
1841               && TREE_CODE (TREE_TYPE (TREE_TYPE (op1))) == FUNCTION_TYPE))
1842         return NULL;
1843               
1844       /* Now make sure the RHS of the MODIFY_EXPR is a typecast.  */
1845       if ((TREE_CODE (def_rhs) == NOP_EXPR
1846            || TREE_CODE (def_rhs) == CONVERT_EXPR)
1847           && TREE_CODE (TREE_OPERAND (def_rhs, 0)) == SSA_NAME)
1848         {
1849           tree def_rhs_inner = TREE_OPERAND (def_rhs, 0);
1850           tree def_rhs_inner_type = TREE_TYPE (def_rhs_inner);
1851           tree new;
1852
1853           if (TYPE_PRECISION (def_rhs_inner_type)
1854               > TYPE_PRECISION (TREE_TYPE (def_rhs)))
1855             return NULL;
1856
1857           /* If the inner type of the conversion is a pointer to
1858              a function, then we can not apply this optimization
1859              as some targets require function pointers to be
1860              canonicalized.  This optimization would result in
1861              canonicalization of the pointer when it was not originally
1862              needed/intended.  */
1863           if (POINTER_TYPE_P (def_rhs_inner_type)
1864               && TREE_CODE (TREE_TYPE (def_rhs_inner_type)) == FUNCTION_TYPE)
1865             return NULL;
1866
1867           /* What we want to prove is that if we convert OP1 to
1868              the type of the object inside the NOP_EXPR that the
1869              result is still equivalent to SRC. 
1870
1871              If that is true, the build and return new equivalent
1872              condition which uses the source of the typecast and the
1873              new constant (which has only changed its type).  */
1874           new = build1 (TREE_CODE (def_rhs), def_rhs_inner_type, op1);
1875           new = local_fold (new);
1876           if (is_gimple_val (new) && tree_int_cst_equal (new, op1))
1877             return build2 (TREE_CODE (cond), TREE_TYPE (cond),
1878                            def_rhs_inner, new);
1879         }
1880     }
1881   return NULL;
1882 }
1883
1884 /* STMT is a COND_EXPR for which we could not trivially determine its
1885    result.  This routine attempts to find equivalent forms of the
1886    condition which we may be able to optimize better.  It also 
1887    uses simple value range propagation to optimize conditionals.  */
1888
1889 static tree
1890 simplify_cond_and_lookup_avail_expr (tree stmt,
1891                                      stmt_ann_t ann,
1892                                      int insert)
1893 {
1894   tree cond = COND_EXPR_COND (stmt);
1895
1896   if (COMPARISON_CLASS_P (cond))
1897     {
1898       tree op0 = TREE_OPERAND (cond, 0);
1899       tree op1 = TREE_OPERAND (cond, 1);
1900
1901       if (TREE_CODE (op0) == SSA_NAME && is_gimple_min_invariant (op1))
1902         {
1903           int limit;
1904           tree low, high, cond_low, cond_high;
1905           int lowequal, highequal, swapped, no_overlap, subset, cond_inverted;
1906           VEC(vrp_element_p,heap) **vrp_records;
1907           struct vrp_element *element;
1908           struct vrp_hash_elt vrp_hash_elt, *vrp_hash_elt_p;
1909           void **slot;
1910
1911           /* First see if we have test of an SSA_NAME against a constant
1912              where the SSA_NAME is defined by an earlier typecast which
1913              is irrelevant when performing tests against the given
1914              constant.  */
1915           if (TREE_CODE (cond) == EQ_EXPR || TREE_CODE (cond) == NE_EXPR)
1916             {
1917               tree new_cond = find_equivalent_equality_comparison (cond);
1918
1919               if (new_cond)
1920                 {
1921                   /* Update the statement to use the new equivalent
1922                      condition.  */
1923                   COND_EXPR_COND (stmt) = new_cond;
1924
1925                   /* If this is not a real stmt, ann will be NULL and we
1926                      avoid processing the operands.  */
1927                   if (ann)
1928                     mark_stmt_modified (stmt);
1929
1930                   /* Lookup the condition and return its known value if it
1931                      exists.  */
1932                   new_cond = lookup_avail_expr (stmt, insert);
1933                   if (new_cond)
1934                     return new_cond;
1935
1936                   /* The operands have changed, so update op0 and op1.  */
1937                   op0 = TREE_OPERAND (cond, 0);
1938                   op1 = TREE_OPERAND (cond, 1);
1939                 }
1940             }
1941
1942           /* Consult the value range records for this variable (if they exist)
1943              to see if we can eliminate or simplify this conditional. 
1944
1945              Note two tests are necessary to determine no records exist.
1946              First we have to see if the virtual array exists, if it 
1947              exists, then we have to check its active size. 
1948
1949              Also note the vast majority of conditionals are not testing
1950              a variable which has had its range constrained by an earlier
1951              conditional.  So this filter avoids a lot of unnecessary work.  */
1952           vrp_hash_elt.var = op0;
1953           vrp_hash_elt.records = NULL;
1954           slot = htab_find_slot (vrp_data, &vrp_hash_elt, NO_INSERT);
1955           if (slot == NULL)
1956             return NULL;
1957
1958           vrp_hash_elt_p = (struct vrp_hash_elt *) *slot;
1959           vrp_records = &vrp_hash_elt_p->records;
1960
1961           limit = VEC_length (vrp_element_p, *vrp_records);
1962
1963           /* If we have no value range records for this variable, or we are
1964              unable to extract a range for this condition, then there is
1965              nothing to do.  */
1966           if (limit == 0
1967               || ! extract_range_from_cond (cond, &cond_high,
1968                                             &cond_low, &cond_inverted))
1969             return NULL;
1970
1971           /* We really want to avoid unnecessary computations of range
1972              info.  So all ranges are computed lazily; this avoids a
1973              lot of unnecessary work.  i.e., we record the conditional,
1974              but do not process how it constrains the variable's 
1975              potential values until we know that processing the condition
1976              could be helpful.
1977
1978              However, we do not want to have to walk a potentially long
1979              list of ranges, nor do we want to compute a variable's
1980              range more than once for a given path.
1981
1982              Luckily, each time we encounter a conditional that can not
1983              be otherwise optimized we will end up here and we will
1984              compute the necessary range information for the variable
1985              used in this condition.
1986
1987              Thus you can conclude that there will never be more than one
1988              conditional associated with a variable which has not been
1989              processed.  So we never need to merge more than one new
1990              conditional into the current range. 
1991
1992              These properties also help us avoid unnecessary work.  */
1993            element = VEC_last (vrp_element_p, *vrp_records);
1994
1995           if (element->high && element->low)
1996             {
1997               /* The last element has been processed, so there is no range
1998                  merging to do, we can simply use the high/low values
1999                  recorded in the last element.  */
2000               low = element->low;
2001               high = element->high;
2002             }
2003           else
2004             {
2005               tree tmp_high, tmp_low;
2006               int dummy;
2007
2008               /* The last element has not been processed.  Process it now.
2009                  record_range should ensure for cond inverted is not set.
2010                  This call can only fail if cond is x < min or x > max,
2011                  which fold should have optimized into false.
2012                  If that doesn't happen, just pretend all values are
2013                  in the range.  */
2014               if (! extract_range_from_cond (element->cond, &tmp_high,
2015                                              &tmp_low, &dummy))
2016                 gcc_unreachable ();
2017               else
2018                 gcc_assert (dummy == 0);
2019
2020               /* If this is the only element, then no merging is necessary, 
2021                  the high/low values from extract_range_from_cond are all
2022                  we need.  */
2023               if (limit == 1)
2024                 {
2025                   low = tmp_low;
2026                   high = tmp_high;
2027                 }
2028               else
2029                 {
2030                   /* Get the high/low value from the previous element.  */
2031                   struct vrp_element *prev
2032                     = VEC_index (vrp_element_p, *vrp_records, limit - 2);
2033                   low = prev->low;
2034                   high = prev->high;
2035
2036                   /* Merge in this element's range with the range from the
2037                      previous element.
2038
2039                      The low value for the merged range is the maximum of
2040                      the previous low value and the low value of this record.
2041
2042                      Similarly the high value for the merged range is the
2043                      minimum of the previous high value and the high value of
2044                      this record.  */
2045                   low = (low && tree_int_cst_compare (low, tmp_low) == 1
2046                          ? low : tmp_low);
2047                   high = (high && tree_int_cst_compare (high, tmp_high) == -1
2048                           ? high : tmp_high);
2049                 }
2050
2051               /* And record the computed range.  */
2052               element->low = low;
2053               element->high = high;
2054
2055             }
2056
2057           /* After we have constrained this variable's potential values,
2058              we try to determine the result of the given conditional.
2059
2060              To simplify later tests, first determine if the current
2061              low value is the same low value as the conditional.
2062              Similarly for the current high value and the high value
2063              for the conditional.  */
2064           lowequal = tree_int_cst_equal (low, cond_low);
2065           highequal = tree_int_cst_equal (high, cond_high);
2066
2067           if (lowequal && highequal)
2068             return (cond_inverted ? boolean_false_node : boolean_true_node);
2069
2070           /* To simplify the overlap/subset tests below we may want
2071              to swap the two ranges so that the larger of the two
2072              ranges occurs "first".  */
2073           swapped = 0;
2074           if (tree_int_cst_compare (low, cond_low) == 1
2075               || (lowequal 
2076                   && tree_int_cst_compare (cond_high, high) == 1))
2077             {
2078               tree temp;
2079
2080               swapped = 1;
2081               temp = low;
2082               low = cond_low;
2083               cond_low = temp;
2084               temp = high;
2085               high = cond_high;
2086               cond_high = temp;
2087             }
2088
2089           /* Now determine if there is no overlap in the ranges
2090              or if the second range is a subset of the first range.  */
2091           no_overlap = tree_int_cst_lt (high, cond_low);
2092           subset = tree_int_cst_compare (cond_high, high) != 1;
2093
2094           /* If there was no overlap in the ranges, then this conditional
2095              always has a false value (unless we had to invert this
2096              conditional, in which case it always has a true value).  */
2097           if (no_overlap)
2098             return (cond_inverted ? boolean_true_node : boolean_false_node);
2099
2100           /* If the current range is a subset of the condition's range,
2101              then this conditional always has a true value (unless we
2102              had to invert this conditional, in which case it always
2103              has a true value).  */
2104           if (subset && swapped)
2105             return (cond_inverted ? boolean_false_node : boolean_true_node);
2106
2107           /* We were unable to determine the result of the conditional.
2108              However, we may be able to simplify the conditional.  First
2109              merge the ranges in the same manner as range merging above.  */
2110           low = tree_int_cst_compare (low, cond_low) == 1 ? low : cond_low;
2111           high = tree_int_cst_compare (high, cond_high) == -1 ? high : cond_high;
2112           
2113           /* If the range has converged to a single point, then turn this
2114              into an equality comparison.  */
2115           if (TREE_CODE (cond) != EQ_EXPR
2116               && TREE_CODE (cond) != NE_EXPR
2117               && tree_int_cst_equal (low, high))
2118             {
2119               TREE_SET_CODE (cond, EQ_EXPR);
2120               TREE_OPERAND (cond, 1) = high;
2121             }
2122         }
2123     }
2124   return 0;
2125 }
2126
2127 /* CONST_AND_COPIES is a table which maps an SSA_NAME to the current
2128    known value for that SSA_NAME (or NULL if no value is known).  
2129
2130    NONZERO_VARS is the set SSA_NAMES known to have a nonzero value,
2131    even if we don't know their precise value.
2132
2133    Propagate values from CONST_AND_COPIES and NONZERO_VARS into the PHI
2134    nodes of the successors of BB.  */
2135
2136 static void
2137 cprop_into_successor_phis (basic_block bb, bitmap nonzero_vars)
2138 {
2139   edge e;
2140   edge_iterator ei;
2141
2142   FOR_EACH_EDGE (e, ei, bb->succs)
2143     {
2144       tree phi;
2145       int indx;
2146
2147       /* If this is an abnormal edge, then we do not want to copy propagate
2148          into the PHI alternative associated with this edge.  */
2149       if (e->flags & EDGE_ABNORMAL)
2150         continue;
2151
2152       phi = phi_nodes (e->dest);
2153       if (! phi)
2154         continue;
2155
2156       indx = e->dest_idx;
2157       for ( ; phi; phi = PHI_CHAIN (phi))
2158         {
2159           tree new;
2160           use_operand_p orig_p;
2161           tree orig;
2162
2163           /* The alternative may be associated with a constant, so verify
2164              it is an SSA_NAME before doing anything with it.  */
2165           orig_p = PHI_ARG_DEF_PTR (phi, indx);
2166           orig = USE_FROM_PTR (orig_p);
2167           if (TREE_CODE (orig) != SSA_NAME)
2168             continue;
2169
2170           /* If the alternative is known to have a nonzero value, record
2171              that fact in the PHI node itself for future use.  */
2172           if (bitmap_bit_p (nonzero_vars, SSA_NAME_VERSION (orig)))
2173             PHI_ARG_NONZERO (phi, indx) = true;
2174
2175           /* If we have *ORIG_P in our constant/copy table, then replace
2176              ORIG_P with its value in our constant/copy table.  */
2177           new = SSA_NAME_VALUE (orig);
2178           if (new
2179               && new != orig
2180               && (TREE_CODE (new) == SSA_NAME
2181                   || is_gimple_min_invariant (new))
2182               && may_propagate_copy (orig, new))
2183             propagate_value (orig_p, new);
2184         }
2185     }
2186 }
2187
2188 /* We have finished optimizing BB, record any information implied by
2189    taking a specific outgoing edge from BB.  */
2190
2191 static void
2192 record_edge_info (basic_block bb)
2193 {
2194   block_stmt_iterator bsi = bsi_last (bb);
2195   struct edge_info *edge_info;
2196
2197   if (! bsi_end_p (bsi))
2198     {
2199       tree stmt = bsi_stmt (bsi);
2200
2201       if (stmt && TREE_CODE (stmt) == SWITCH_EXPR)
2202         {
2203           tree cond = SWITCH_COND (stmt);
2204
2205           if (TREE_CODE (cond) == SSA_NAME)
2206             {
2207               tree labels = SWITCH_LABELS (stmt);
2208               int i, n_labels = TREE_VEC_LENGTH (labels);
2209               tree *info = XCNEWVEC (tree, last_basic_block);
2210               edge e;
2211               edge_iterator ei;
2212
2213               for (i = 0; i < n_labels; i++)
2214                 {
2215                   tree label = TREE_VEC_ELT (labels, i);
2216                   basic_block target_bb = label_to_block (CASE_LABEL (label));
2217
2218                   if (CASE_HIGH (label)
2219                       || !CASE_LOW (label)
2220                       || info[target_bb->index])
2221                     info[target_bb->index] = error_mark_node;
2222                   else
2223                     info[target_bb->index] = label;
2224                 }
2225
2226               FOR_EACH_EDGE (e, ei, bb->succs)
2227                 {
2228                   basic_block target_bb = e->dest;
2229                   tree node = info[target_bb->index];
2230
2231                   if (node != NULL && node != error_mark_node)
2232                     {
2233                       tree x = fold_convert (TREE_TYPE (cond), CASE_LOW (node));
2234                       edge_info = allocate_edge_info (e);
2235                       edge_info->lhs = cond;
2236                       edge_info->rhs = x;
2237                     }
2238                 }
2239               free (info);
2240             }
2241         }
2242
2243       /* A COND_EXPR may create equivalences too.  */
2244       if (stmt && TREE_CODE (stmt) == COND_EXPR)
2245         {
2246           tree cond = COND_EXPR_COND (stmt);
2247           edge true_edge;
2248           edge false_edge;
2249
2250           extract_true_false_edges_from_block (bb, &true_edge, &false_edge);
2251
2252           /* If the conditional is a single variable 'X', record 'X = 1'
2253              for the true edge and 'X = 0' on the false edge.  */
2254           if (SSA_VAR_P (cond))
2255             {
2256               struct edge_info *edge_info;
2257
2258               edge_info = allocate_edge_info (true_edge);
2259               edge_info->lhs = cond;
2260               edge_info->rhs = constant_boolean_node (1, TREE_TYPE (cond));
2261
2262               edge_info = allocate_edge_info (false_edge);
2263               edge_info->lhs = cond;
2264               edge_info->rhs = constant_boolean_node (0, TREE_TYPE (cond));
2265             }
2266           /* Equality tests may create one or two equivalences.  */
2267           else if (COMPARISON_CLASS_P (cond))
2268             {
2269               tree op0 = TREE_OPERAND (cond, 0);
2270               tree op1 = TREE_OPERAND (cond, 1);
2271
2272               /* Special case comparing booleans against a constant as we
2273                  know the value of OP0 on both arms of the branch.  i.e., we
2274                  can record an equivalence for OP0 rather than COND.  */
2275               if ((TREE_CODE (cond) == EQ_EXPR || TREE_CODE (cond) == NE_EXPR)
2276                   && TREE_CODE (op0) == SSA_NAME
2277                   && TREE_CODE (TREE_TYPE (op0)) == BOOLEAN_TYPE
2278                   && is_gimple_min_invariant (op1))
2279                 {
2280                   if (TREE_CODE (cond) == EQ_EXPR)
2281                     {
2282                       edge_info = allocate_edge_info (true_edge);
2283                       edge_info->lhs = op0;
2284                       edge_info->rhs = (integer_zerop (op1)
2285                                             ? boolean_false_node
2286                                             : boolean_true_node);
2287
2288                       edge_info = allocate_edge_info (false_edge);
2289                       edge_info->lhs = op0;
2290                       edge_info->rhs = (integer_zerop (op1)
2291                                             ? boolean_true_node
2292                                             : boolean_false_node);
2293                     }
2294                   else
2295                     {
2296                       edge_info = allocate_edge_info (true_edge);
2297                       edge_info->lhs = op0;
2298                       edge_info->rhs = (integer_zerop (op1)
2299                                             ? boolean_true_node
2300                                             : boolean_false_node);
2301
2302                       edge_info = allocate_edge_info (false_edge);
2303                       edge_info->lhs = op0;
2304                       edge_info->rhs = (integer_zerop (op1)
2305                                             ? boolean_false_node
2306                                             : boolean_true_node);
2307                     }
2308                 }
2309
2310               else if (is_gimple_min_invariant (op0)
2311                        && (TREE_CODE (op1) == SSA_NAME
2312                            || is_gimple_min_invariant (op1)))
2313                 {
2314                   tree inverted = invert_truthvalue (cond);
2315                   struct edge_info *edge_info;
2316
2317                   edge_info = allocate_edge_info (true_edge);
2318                   record_conditions (edge_info, cond, inverted);
2319
2320                   if (TREE_CODE (cond) == EQ_EXPR)
2321                     {
2322                       edge_info->lhs = op1;
2323                       edge_info->rhs = op0;
2324                     }
2325
2326                   edge_info = allocate_edge_info (false_edge);
2327                   record_conditions (edge_info, inverted, cond);
2328
2329                   if (TREE_CODE (cond) == NE_EXPR)
2330                     {
2331                       edge_info->lhs = op1;
2332                       edge_info->rhs = op0;
2333                     }
2334                 }
2335
2336               else if (TREE_CODE (op0) == SSA_NAME
2337                        && (is_gimple_min_invariant (op1)
2338                            || TREE_CODE (op1) == SSA_NAME))
2339                 {
2340                   tree inverted = invert_truthvalue (cond);
2341                   struct edge_info *edge_info;
2342
2343                   edge_info = allocate_edge_info (true_edge);
2344                   record_conditions (edge_info, cond, inverted);
2345
2346                   if (TREE_CODE (cond) == EQ_EXPR)
2347                     {
2348                       edge_info->lhs = op0;
2349                       edge_info->rhs = op1;
2350                     }
2351
2352                   edge_info = allocate_edge_info (false_edge);
2353                   record_conditions (edge_info, inverted, cond);
2354
2355                   if (TREE_CODE (cond) == NE_EXPR)
2356                     {
2357                       edge_info->lhs = op0;
2358                       edge_info->rhs = op1;
2359                     }
2360                 }
2361             }
2362
2363           /* ??? TRUTH_NOT_EXPR can create an equivalence too.  */
2364         }
2365     }
2366 }
2367
2368 /* Propagate information from BB to its outgoing edges.
2369
2370    This can include equivalency information implied by control statements
2371    at the end of BB and const/copy propagation into PHIs in BB's
2372    successor blocks.  */
2373
2374 static void
2375 propagate_to_outgoing_edges (struct dom_walk_data *walk_data ATTRIBUTE_UNUSED,
2376                              basic_block bb)
2377 {
2378   record_edge_info (bb);
2379   cprop_into_successor_phis (bb, nonzero_vars);
2380 }
2381
2382 /* Search for redundant computations in STMT.  If any are found, then
2383    replace them with the variable holding the result of the computation.
2384
2385    If safe, record this expression into the available expression hash
2386    table.  */
2387
2388 static bool
2389 eliminate_redundant_computations (tree stmt, stmt_ann_t ann)
2390 {
2391   tree *expr_p, def = NULL_TREE;
2392   bool insert = true;
2393   tree cached_lhs;
2394   bool retval = false;
2395   bool modify_expr_p = false;
2396
2397   if (TREE_CODE (stmt) == MODIFY_EXPR)
2398     def = TREE_OPERAND (stmt, 0);
2399
2400   /* Certain expressions on the RHS can be optimized away, but can not
2401      themselves be entered into the hash tables.  */
2402   if (! def
2403       || TREE_CODE (def) != SSA_NAME
2404       || SSA_NAME_OCCURS_IN_ABNORMAL_PHI (def)
2405       || !ZERO_SSA_OPERANDS (stmt, SSA_OP_VMAYDEF)
2406       /* Do not record equivalences for increments of ivs.  This would create
2407          overlapping live ranges for a very questionable gain.  */
2408       || simple_iv_increment_p (stmt))
2409     insert = false;
2410
2411   /* Check if the expression has been computed before.  */
2412   cached_lhs = lookup_avail_expr (stmt, insert);
2413
2414   /* If this is a COND_EXPR and we did not find its expression in
2415      the hash table, simplify the condition and try again.  */
2416   if (! cached_lhs && TREE_CODE (stmt) == COND_EXPR)
2417     cached_lhs = simplify_cond_and_lookup_avail_expr (stmt, ann, insert);
2418
2419   opt_stats.num_exprs_considered++;
2420
2421   /* Get a pointer to the expression we are trying to optimize.  */
2422   if (TREE_CODE (stmt) == COND_EXPR)
2423     expr_p = &COND_EXPR_COND (stmt);
2424   else if (TREE_CODE (stmt) == SWITCH_EXPR)
2425     expr_p = &SWITCH_COND (stmt);
2426   else if (TREE_CODE (stmt) == RETURN_EXPR && TREE_OPERAND (stmt, 0))
2427     {
2428       expr_p = &TREE_OPERAND (TREE_OPERAND (stmt, 0), 1);
2429       modify_expr_p = true;
2430     }
2431   else
2432     {
2433       expr_p = &TREE_OPERAND (stmt, 1);
2434       modify_expr_p = true;
2435     }
2436
2437   /* It is safe to ignore types here since we have already done
2438      type checking in the hashing and equality routines.  In fact
2439      type checking here merely gets in the way of constant
2440      propagation.  Also, make sure that it is safe to propagate
2441      CACHED_LHS into *EXPR_P.  */
2442   if (cached_lhs
2443       && ((TREE_CODE (cached_lhs) != SSA_NAME
2444            && (modify_expr_p
2445                || tree_ssa_useless_type_conversion_1 (TREE_TYPE (*expr_p),
2446                                                       TREE_TYPE (cached_lhs))))
2447           || may_propagate_copy (*expr_p, cached_lhs)))
2448     {
2449       if (dump_file && (dump_flags & TDF_DETAILS))
2450         {
2451           fprintf (dump_file, "  Replaced redundant expr '");
2452           print_generic_expr (dump_file, *expr_p, dump_flags);
2453           fprintf (dump_file, "' with '");
2454           print_generic_expr (dump_file, cached_lhs, dump_flags);
2455            fprintf (dump_file, "'\n");
2456         }
2457
2458       opt_stats.num_re++;
2459
2460 #if defined ENABLE_CHECKING
2461       gcc_assert (TREE_CODE (cached_lhs) == SSA_NAME
2462                   || is_gimple_min_invariant (cached_lhs));
2463 #endif
2464
2465       if (TREE_CODE (cached_lhs) == ADDR_EXPR
2466           || (POINTER_TYPE_P (TREE_TYPE (*expr_p))
2467               && is_gimple_min_invariant (cached_lhs)))
2468         retval = true;
2469       
2470       if (modify_expr_p
2471           && !tree_ssa_useless_type_conversion_1 (TREE_TYPE (*expr_p),
2472                                                   TREE_TYPE (cached_lhs)))
2473         cached_lhs = fold_convert (TREE_TYPE (*expr_p), cached_lhs);
2474
2475       propagate_tree_value (expr_p, cached_lhs);
2476       mark_stmt_modified (stmt);
2477     }
2478   return retval;
2479 }
2480
2481 /* STMT, a MODIFY_EXPR, may create certain equivalences, in either
2482    the available expressions table or the const_and_copies table.
2483    Detect and record those equivalences.  */
2484
2485 static void
2486 record_equivalences_from_stmt (tree stmt,
2487                                int may_optimize_p,
2488                                stmt_ann_t ann)
2489 {
2490   tree lhs = TREE_OPERAND (stmt, 0);
2491   enum tree_code lhs_code = TREE_CODE (lhs);
2492   int i;
2493
2494   if (lhs_code == SSA_NAME)
2495     {
2496       tree rhs = TREE_OPERAND (stmt, 1);
2497
2498       /* Strip away any useless type conversions.  */
2499       STRIP_USELESS_TYPE_CONVERSION (rhs);
2500
2501       /* If the RHS of the assignment is a constant or another variable that
2502          may be propagated, register it in the CONST_AND_COPIES table.  We
2503          do not need to record unwind data for this, since this is a true
2504          assignment and not an equivalence inferred from a comparison.  All
2505          uses of this ssa name are dominated by this assignment, so unwinding
2506          just costs time and space.  */
2507       if (may_optimize_p
2508           && (TREE_CODE (rhs) == SSA_NAME
2509               || is_gimple_min_invariant (rhs)))
2510         SSA_NAME_VALUE (lhs) = rhs;
2511
2512       if (tree_expr_nonzero_p (rhs))
2513         record_var_is_nonzero (lhs);
2514     }
2515
2516   /* Look at both sides for pointer dereferences.  If we find one, then
2517      the pointer must be nonnull and we can enter that equivalence into
2518      the hash tables.  */
2519   if (flag_delete_null_pointer_checks)
2520     for (i = 0; i < 2; i++)
2521       {
2522         tree t = TREE_OPERAND (stmt, i);
2523
2524         /* Strip away any COMPONENT_REFs.  */
2525         while (TREE_CODE (t) == COMPONENT_REF)
2526           t = TREE_OPERAND (t, 0);
2527
2528         /* Now see if this is a pointer dereference.  */
2529         if (INDIRECT_REF_P (t))
2530           {
2531             tree op = TREE_OPERAND (t, 0);
2532
2533             /* If the pointer is a SSA variable, then enter new
2534                equivalences into the hash table.  */
2535             while (TREE_CODE (op) == SSA_NAME)
2536               {
2537                 tree def = SSA_NAME_DEF_STMT (op);
2538
2539                 record_var_is_nonzero (op);
2540
2541                 /* And walk up the USE-DEF chains noting other SSA_NAMEs
2542                    which are known to have a nonzero value.  */
2543                 if (def
2544                     && TREE_CODE (def) == MODIFY_EXPR
2545                     && TREE_CODE (TREE_OPERAND (def, 1)) == NOP_EXPR)
2546                   op = TREE_OPERAND (TREE_OPERAND (def, 1), 0);
2547                 else
2548                   break;
2549               }
2550           }
2551       }
2552
2553   /* A memory store, even an aliased store, creates a useful
2554      equivalence.  By exchanging the LHS and RHS, creating suitable
2555      vops and recording the result in the available expression table,
2556      we may be able to expose more redundant loads.  */
2557   if (!ann->has_volatile_ops
2558       && (TREE_CODE (TREE_OPERAND (stmt, 1)) == SSA_NAME
2559           || is_gimple_min_invariant (TREE_OPERAND (stmt, 1)))
2560       && !is_gimple_reg (lhs))
2561     {
2562       tree rhs = TREE_OPERAND (stmt, 1);
2563       tree new;
2564
2565       /* FIXME: If the LHS of the assignment is a bitfield and the RHS
2566          is a constant, we need to adjust the constant to fit into the
2567          type of the LHS.  If the LHS is a bitfield and the RHS is not
2568          a constant, then we can not record any equivalences for this
2569          statement since we would need to represent the widening or
2570          narrowing of RHS.  This fixes gcc.c-torture/execute/921016-1.c
2571          and should not be necessary if GCC represented bitfields
2572          properly.  */
2573       if (lhs_code == COMPONENT_REF
2574           && DECL_BIT_FIELD (TREE_OPERAND (lhs, 1)))
2575         {
2576           if (TREE_CONSTANT (rhs))
2577             rhs = widen_bitfield (rhs, TREE_OPERAND (lhs, 1), lhs);
2578           else
2579             rhs = NULL;
2580
2581           /* If the value overflowed, then we can not use this equivalence.  */
2582           if (rhs && ! is_gimple_min_invariant (rhs))
2583             rhs = NULL;
2584         }
2585
2586       if (rhs)
2587         {
2588           /* Build a new statement with the RHS and LHS exchanged.  */
2589           new = build2 (MODIFY_EXPR, TREE_TYPE (stmt), rhs, lhs);
2590
2591           create_ssa_artficial_load_stmt (new, stmt);
2592
2593           /* Finally enter the statement into the available expression
2594              table.  */
2595           lookup_avail_expr (new, true);
2596         }
2597     }
2598 }
2599
2600 /* Replace *OP_P in STMT with any known equivalent value for *OP_P from
2601    CONST_AND_COPIES.  */
2602
2603 static bool
2604 cprop_operand (tree stmt, use_operand_p op_p)
2605 {
2606   bool may_have_exposed_new_symbols = false;
2607   tree val;
2608   tree op = USE_FROM_PTR (op_p);
2609
2610   /* If the operand has a known constant value or it is known to be a
2611      copy of some other variable, use the value or copy stored in
2612      CONST_AND_COPIES.  */
2613   val = SSA_NAME_VALUE (op);
2614   if (val && val != op && TREE_CODE (val) != VALUE_HANDLE)
2615     {
2616       tree op_type, val_type;
2617
2618       /* Do not change the base variable in the virtual operand
2619          tables.  That would make it impossible to reconstruct
2620          the renamed virtual operand if we later modify this
2621          statement.  Also only allow the new value to be an SSA_NAME
2622          for propagation into virtual operands.  */
2623       if (!is_gimple_reg (op)
2624           && (TREE_CODE (val) != SSA_NAME
2625               || is_gimple_reg (val)
2626               || get_virtual_var (val) != get_virtual_var (op)))
2627         return false;
2628
2629       /* Do not replace hard register operands in asm statements.  */
2630       if (TREE_CODE (stmt) == ASM_EXPR
2631           && !may_propagate_copy_into_asm (op))
2632         return false;
2633
2634       /* Get the toplevel type of each operand.  */
2635       op_type = TREE_TYPE (op);
2636       val_type = TREE_TYPE (val);
2637
2638       /* While both types are pointers, get the type of the object
2639          pointed to.  */
2640       while (POINTER_TYPE_P (op_type) && POINTER_TYPE_P (val_type))
2641         {
2642           op_type = TREE_TYPE (op_type);
2643           val_type = TREE_TYPE (val_type);
2644         }
2645
2646       /* Make sure underlying types match before propagating a constant by
2647          converting the constant to the proper type.  Note that convert may
2648          return a non-gimple expression, in which case we ignore this
2649          propagation opportunity.  */
2650       if (TREE_CODE (val) != SSA_NAME)
2651         {
2652           if (!lang_hooks.types_compatible_p (op_type, val_type))
2653             {
2654               val = fold_convert (TREE_TYPE (op), val);
2655               if (!is_gimple_min_invariant (val))
2656                 return false;
2657             }
2658         }
2659
2660       /* Certain operands are not allowed to be copy propagated due
2661          to their interaction with exception handling and some GCC
2662          extensions.  */
2663       else if (!may_propagate_copy (op, val))
2664         return false;
2665       
2666       /* Do not propagate copies if the propagated value is at a deeper loop
2667          depth than the propagatee.  Otherwise, this may move loop variant
2668          variables outside of their loops and prevent coalescing
2669          opportunities.  If the value was loop invariant, it will be hoisted
2670          by LICM and exposed for copy propagation.  */
2671       if (loop_depth_of_name (val) > loop_depth_of_name (op))
2672         return false;
2673
2674       /* Dump details.  */
2675       if (dump_file && (dump_flags & TDF_DETAILS))
2676         {
2677           fprintf (dump_file, "  Replaced '");
2678           print_generic_expr (dump_file, op, dump_flags);
2679           fprintf (dump_file, "' with %s '",
2680                    (TREE_CODE (val) != SSA_NAME ? "constant" : "variable"));
2681           print_generic_expr (dump_file, val, dump_flags);
2682           fprintf (dump_file, "'\n");
2683         }
2684
2685       /* If VAL is an ADDR_EXPR or a constant of pointer type, note
2686          that we may have exposed a new symbol for SSA renaming.  */
2687       if (TREE_CODE (val) == ADDR_EXPR
2688           || (POINTER_TYPE_P (TREE_TYPE (op))
2689               && is_gimple_min_invariant (val)))
2690         may_have_exposed_new_symbols = true;
2691
2692       if (TREE_CODE (val) != SSA_NAME)
2693         opt_stats.num_const_prop++;
2694       else
2695         opt_stats.num_copy_prop++;
2696
2697       propagate_value (op_p, val);
2698
2699       /* And note that we modified this statement.  This is now
2700          safe, even if we changed virtual operands since we will
2701          rescan the statement and rewrite its operands again.  */
2702       mark_stmt_modified (stmt);
2703     }
2704   return may_have_exposed_new_symbols;
2705 }
2706
2707 /* CONST_AND_COPIES is a table which maps an SSA_NAME to the current
2708    known value for that SSA_NAME (or NULL if no value is known).  
2709
2710    Propagate values from CONST_AND_COPIES into the uses, vuses and
2711    v_may_def_ops of STMT.  */
2712
2713 static bool
2714 cprop_into_stmt (tree stmt)
2715 {
2716   bool may_have_exposed_new_symbols = false;
2717   use_operand_p op_p;
2718   ssa_op_iter iter;
2719
2720   FOR_EACH_SSA_USE_OPERAND (op_p, stmt, iter, SSA_OP_ALL_USES)
2721     {
2722       if (TREE_CODE (USE_FROM_PTR (op_p)) == SSA_NAME)
2723         may_have_exposed_new_symbols |= cprop_operand (stmt, op_p);
2724     }
2725
2726   return may_have_exposed_new_symbols;
2727 }
2728
2729
2730 /* Optimize the statement pointed to by iterator SI.
2731    
2732    We try to perform some simplistic global redundancy elimination and
2733    constant propagation:
2734
2735    1- To detect global redundancy, we keep track of expressions that have
2736       been computed in this block and its dominators.  If we find that the
2737       same expression is computed more than once, we eliminate repeated
2738       computations by using the target of the first one.
2739
2740    2- Constant values and copy assignments.  This is used to do very
2741       simplistic constant and copy propagation.  When a constant or copy
2742       assignment is found, we map the value on the RHS of the assignment to
2743       the variable in the LHS in the CONST_AND_COPIES table.  */
2744
2745 static void
2746 optimize_stmt (struct dom_walk_data *walk_data ATTRIBUTE_UNUSED,
2747                basic_block bb, block_stmt_iterator si)
2748 {
2749   stmt_ann_t ann;
2750   tree stmt, old_stmt;
2751   bool may_optimize_p;
2752   bool may_have_exposed_new_symbols = false;
2753
2754   old_stmt = stmt = bsi_stmt (si);
2755   
2756   if (TREE_CODE (stmt) == COND_EXPR)
2757     canonicalize_comparison (stmt);
2758   
2759   update_stmt_if_modified (stmt);
2760   ann = stmt_ann (stmt);
2761   opt_stats.num_stmts++;
2762   may_have_exposed_new_symbols = false;
2763
2764   if (dump_file && (dump_flags & TDF_DETAILS))
2765     {
2766       fprintf (dump_file, "Optimizing statement ");
2767       print_generic_stmt (dump_file, stmt, TDF_SLIM);
2768     }
2769
2770   /* Const/copy propagate into USES, VUSES and the RHS of V_MAY_DEFs.  */
2771   may_have_exposed_new_symbols = cprop_into_stmt (stmt);
2772
2773   /* If the statement has been modified with constant replacements,
2774      fold its RHS before checking for redundant computations.  */
2775   if (ann->modified)
2776     {
2777       tree rhs;
2778
2779       /* Try to fold the statement making sure that STMT is kept
2780          up to date.  */
2781       if (fold_stmt (bsi_stmt_ptr (si)))
2782         {
2783           stmt = bsi_stmt (si);
2784           ann = stmt_ann (stmt);
2785
2786           if (dump_file && (dump_flags & TDF_DETAILS))
2787             {
2788               fprintf (dump_file, "  Folded to: ");
2789               print_generic_stmt (dump_file, stmt, TDF_SLIM);
2790             }
2791         }
2792
2793       rhs = get_rhs (stmt);
2794       if (rhs && TREE_CODE (rhs) == ADDR_EXPR)
2795         recompute_tree_invariant_for_addr_expr (rhs);
2796
2797       /* Constant/copy propagation above may change the set of 
2798          virtual operands associated with this statement.  Folding
2799          may remove the need for some virtual operands.
2800
2801          Indicate we will need to rescan and rewrite the statement.  */
2802       may_have_exposed_new_symbols = true;
2803     }
2804
2805   /* Check for redundant computations.  Do this optimization only
2806      for assignments that have no volatile ops and conditionals.  */
2807   may_optimize_p = (!ann->has_volatile_ops
2808                     && ((TREE_CODE (stmt) == RETURN_EXPR
2809                          && TREE_OPERAND (stmt, 0)
2810                          && TREE_CODE (TREE_OPERAND (stmt, 0)) == MODIFY_EXPR
2811                          && ! (TREE_SIDE_EFFECTS
2812                                (TREE_OPERAND (TREE_OPERAND (stmt, 0), 1))))
2813                         || (TREE_CODE (stmt) == MODIFY_EXPR
2814                             && ! TREE_SIDE_EFFECTS (TREE_OPERAND (stmt, 1)))
2815                         || TREE_CODE (stmt) == COND_EXPR
2816                         || TREE_CODE (stmt) == SWITCH_EXPR));
2817
2818   if (may_optimize_p)
2819     may_have_exposed_new_symbols
2820       |= eliminate_redundant_computations (stmt, ann);
2821
2822   /* Record any additional equivalences created by this statement.  */
2823   if (TREE_CODE (stmt) == MODIFY_EXPR)
2824     record_equivalences_from_stmt (stmt,
2825                                    may_optimize_p,
2826                                    ann);
2827
2828   /* If STMT is a COND_EXPR and it was modified, then we may know
2829      where it goes.  If that is the case, then mark the CFG as altered.
2830
2831      This will cause us to later call remove_unreachable_blocks and
2832      cleanup_tree_cfg when it is safe to do so.  It is not safe to 
2833      clean things up here since removal of edges and such can trigger
2834      the removal of PHI nodes, which in turn can release SSA_NAMEs to
2835      the manager.
2836
2837      That's all fine and good, except that once SSA_NAMEs are released
2838      to the manager, we must not call create_ssa_name until all references
2839      to released SSA_NAMEs have been eliminated.
2840
2841      All references to the deleted SSA_NAMEs can not be eliminated until
2842      we remove unreachable blocks.
2843
2844      We can not remove unreachable blocks until after we have completed
2845      any queued jump threading.
2846
2847      We can not complete any queued jump threads until we have taken
2848      appropriate variables out of SSA form.  Taking variables out of
2849      SSA form can call create_ssa_name and thus we lose.
2850
2851      Ultimately I suspect we're going to need to change the interface
2852      into the SSA_NAME manager.  */
2853
2854   if (ann->modified)
2855     {
2856       tree val = NULL;
2857
2858       if (TREE_CODE (stmt) == COND_EXPR)
2859         val = COND_EXPR_COND (stmt);
2860       else if (TREE_CODE (stmt) == SWITCH_EXPR)
2861         val = SWITCH_COND (stmt);
2862
2863       if (val && TREE_CODE (val) == INTEGER_CST && find_taken_edge (bb, val))
2864         cfg_altered = true;
2865
2866       /* If we simplified a statement in such a way as to be shown that it
2867          cannot trap, update the eh information and the cfg to match.  */
2868       if (maybe_clean_or_replace_eh_stmt (old_stmt, stmt))
2869         {
2870           bitmap_set_bit (need_eh_cleanup, bb->index);
2871           if (dump_file && (dump_flags & TDF_DETAILS))
2872             fprintf (dump_file, "  Flagged to clear EH edges.\n");
2873         }
2874     }
2875
2876   if (may_have_exposed_new_symbols)
2877     VEC_safe_push (tree, heap, stmts_to_rescan, bsi_stmt (si));
2878 }
2879
2880 /* Search for an existing instance of STMT in the AVAIL_EXPRS table.  If
2881    found, return its LHS. Otherwise insert STMT in the table and return
2882    NULL_TREE.
2883
2884    Also, when an expression is first inserted in the AVAIL_EXPRS table, it
2885    is also added to the stack pointed to by BLOCK_AVAIL_EXPRS_P, so that they
2886    can be removed when we finish processing this block and its children.
2887
2888    NOTE: This function assumes that STMT is a MODIFY_EXPR node that
2889    contains no CALL_EXPR on its RHS and makes no volatile nor
2890    aliased references.  */
2891
2892 static tree
2893 lookup_avail_expr (tree stmt, bool insert)
2894 {
2895   void **slot;
2896   tree lhs;
2897   tree temp;
2898   struct expr_hash_elt *element = XNEW (struct expr_hash_elt);
2899
2900   lhs = TREE_CODE (stmt) == MODIFY_EXPR ? TREE_OPERAND (stmt, 0) : NULL;
2901
2902   initialize_hash_element (stmt, lhs, element);
2903
2904   /* Don't bother remembering constant assignments and copy operations.
2905      Constants and copy operations are handled by the constant/copy propagator
2906      in optimize_stmt.  */
2907   if (TREE_CODE (element->rhs) == SSA_NAME
2908       || is_gimple_min_invariant (element->rhs))
2909     {
2910       free (element);
2911       return NULL_TREE;
2912     }
2913
2914   /* If this is an equality test against zero, see if we have recorded a
2915      nonzero value for the variable in question.  */
2916   if ((TREE_CODE (element->rhs) == EQ_EXPR
2917        || TREE_CODE  (element->rhs) == NE_EXPR)
2918       && TREE_CODE (TREE_OPERAND (element->rhs, 0)) == SSA_NAME
2919       && integer_zerop (TREE_OPERAND (element->rhs, 1)))
2920     {
2921       int indx = SSA_NAME_VERSION (TREE_OPERAND (element->rhs, 0));
2922
2923       if (bitmap_bit_p (nonzero_vars, indx))
2924         {
2925           tree t = element->rhs;
2926           free (element);
2927           return constant_boolean_node (TREE_CODE (t) != EQ_EXPR,
2928                                         TREE_TYPE (t));
2929         }
2930     }
2931
2932   /* Finally try to find the expression in the main expression hash table.  */
2933   slot = htab_find_slot_with_hash (avail_exprs, element, element->hash,
2934                                    (insert ? INSERT : NO_INSERT));
2935   if (slot == NULL)
2936     {
2937       free (element);
2938       return NULL_TREE;
2939     }
2940
2941   if (*slot == NULL)
2942     {
2943       *slot = (void *) element;
2944       VEC_safe_push (tree, heap, avail_exprs_stack,
2945                      stmt ? stmt : element->rhs);
2946       return NULL_TREE;
2947     }
2948
2949   /* Extract the LHS of the assignment so that it can be used as the current
2950      definition of another variable.  */
2951   lhs = ((struct expr_hash_elt *)*slot)->lhs;
2952
2953   /* See if the LHS appears in the CONST_AND_COPIES table.  If it does, then
2954      use the value from the const_and_copies table.  */
2955   if (TREE_CODE (lhs) == SSA_NAME)
2956     {
2957       temp = SSA_NAME_VALUE (lhs);
2958       if (temp && TREE_CODE (temp) != VALUE_HANDLE)
2959         lhs = temp;
2960     }
2961
2962   free (element);
2963   return lhs;
2964 }
2965
2966 /* Given a condition COND, record into HI_P, LO_P and INVERTED_P the
2967    range of values that result in the conditional having a true value.
2968
2969    Return true if we are successful in extracting a range from COND and
2970    false if we are unsuccessful.  */
2971
2972 static bool
2973 extract_range_from_cond (tree cond, tree *hi_p, tree *lo_p, int *inverted_p)
2974 {
2975   tree op1 = TREE_OPERAND (cond, 1);
2976   tree high, low, type;
2977   int inverted;
2978
2979   type = TREE_TYPE (op1);
2980
2981   /* Experiments have shown that it's rarely, if ever useful to
2982      record ranges for enumerations.  Presumably this is due to
2983      the fact that they're rarely used directly.  They are typically
2984      cast into an integer type and used that way.  */
2985   if (TREE_CODE (type) != INTEGER_TYPE)
2986     return 0;
2987
2988   switch (TREE_CODE (cond))
2989     {
2990     case EQ_EXPR:
2991       high = low = op1;
2992       inverted = 0;
2993       break;
2994
2995     case NE_EXPR:
2996       high = low = op1;
2997       inverted = 1;
2998       break;
2999
3000     case GE_EXPR:
3001       low = op1;
3002
3003       /* Get the highest value of the type.  If not a constant, use that
3004          of its base type, if it has one.  */
3005       high = TYPE_MAX_VALUE (type);
3006       if (TREE_CODE (high) != INTEGER_CST && TREE_TYPE (type))
3007         high = TYPE_MAX_VALUE (TREE_TYPE (type));
3008       inverted = 0;
3009       break;
3010
3011     case GT_EXPR:
3012       high = TYPE_MAX_VALUE (type);
3013       if (TREE_CODE (high) != INTEGER_CST && TREE_TYPE (type))
3014         high = TYPE_MAX_VALUE (TREE_TYPE (type));
3015       if (!tree_int_cst_lt (op1, high))
3016         return 0;
3017       low = int_const_binop (PLUS_EXPR, op1, integer_one_node, 1);
3018       inverted = 0;
3019       break;
3020
3021     case LE_EXPR:
3022       high = op1;
3023       low = TYPE_MIN_VALUE (type);
3024       if (TREE_CODE (low) != INTEGER_CST && TREE_TYPE (type))
3025         low = TYPE_MIN_VALUE (TREE_TYPE (type));
3026       inverted = 0;
3027       break;
3028
3029     case LT_EXPR:
3030       low = TYPE_MIN_VALUE (type);
3031       if (TREE_CODE (low) != INTEGER_CST && TREE_TYPE (type))
3032         low = TYPE_MIN_VALUE (TREE_TYPE (type));
3033       if (!tree_int_cst_lt (low, op1))
3034         return 0;
3035       high = int_const_binop (MINUS_EXPR, op1, integer_one_node, 1);
3036       inverted = 0;
3037       break;
3038
3039     default:
3040       return 0;
3041     }
3042
3043   *hi_p = high;
3044   *lo_p = low;
3045   *inverted_p = inverted;
3046   return 1;
3047 }
3048
3049 /* Record a range created by COND for basic block BB.  */
3050
3051 static void
3052 record_range (tree cond, basic_block bb)
3053 {
3054   enum tree_code code = TREE_CODE (cond);
3055
3056   /* We explicitly ignore NE_EXPRs and all the unordered comparisons.
3057      They rarely allow for meaningful range optimizations and significantly
3058      complicate the implementation.  */
3059   if ((code == LT_EXPR || code == LE_EXPR || code == GT_EXPR
3060        || code == GE_EXPR || code == EQ_EXPR)
3061       && TREE_CODE (TREE_TYPE (TREE_OPERAND (cond, 1))) == INTEGER_TYPE)
3062     {
3063       struct vrp_hash_elt *vrp_hash_elt;
3064       struct vrp_element *element;
3065       VEC(vrp_element_p,heap) **vrp_records_p;
3066       void **slot;
3067
3068
3069       vrp_hash_elt = XNEW (struct vrp_hash_elt);
3070       vrp_hash_elt->var = TREE_OPERAND (cond, 0);
3071       vrp_hash_elt->records = NULL;
3072       slot = htab_find_slot (vrp_data, vrp_hash_elt, INSERT);
3073
3074       if (*slot == NULL)
3075         *slot = (void *) vrp_hash_elt;
3076       else
3077         vrp_free (vrp_hash_elt);
3078
3079       vrp_hash_elt = (struct vrp_hash_elt *) *slot;
3080       vrp_records_p = &vrp_hash_elt->records;
3081
3082       element = GGC_NEW (struct vrp_element);
3083       element->low = NULL;
3084       element->high = NULL;
3085       element->cond = cond;
3086       element->bb = bb;
3087
3088       VEC_safe_push (vrp_element_p, heap, *vrp_records_p, element);
3089       VEC_safe_push (tree, heap, vrp_variables_stack, TREE_OPERAND (cond, 0));
3090     }
3091 }
3092
3093 /* Hashing and equality functions for VRP_DATA.
3094
3095    Since this hash table is addressed by SSA_NAMEs, we can hash on
3096    their version number and equality can be determined with a 
3097    pointer comparison.  */
3098
3099 static hashval_t
3100 vrp_hash (const void *p)
3101 {
3102   tree var = ((struct vrp_hash_elt *)p)->var;
3103
3104   return SSA_NAME_VERSION (var);
3105 }
3106
3107 static int
3108 vrp_eq (const void *p1, const void *p2)
3109 {
3110   tree var1 = ((struct vrp_hash_elt *)p1)->var;
3111   tree var2 = ((struct vrp_hash_elt *)p2)->var;
3112
3113   return var1 == var2;
3114 }
3115
3116 /* Hashing and equality functions for AVAIL_EXPRS.  The table stores
3117    MODIFY_EXPR statements.  We compute a value number for expressions using
3118    the code of the expression and the SSA numbers of its operands.  */
3119
3120 static hashval_t
3121 avail_expr_hash (const void *p)
3122 {
3123   tree stmt = ((struct expr_hash_elt *)p)->stmt;
3124   tree rhs = ((struct expr_hash_elt *)p)->rhs;
3125   tree vuse;
3126   ssa_op_iter iter;
3127   hashval_t val = 0;
3128
3129   /* iterative_hash_expr knows how to deal with any expression and
3130      deals with commutative operators as well, so just use it instead
3131      of duplicating such complexities here.  */
3132   val = iterative_hash_expr (rhs, val);
3133
3134   /* If the hash table entry is not associated with a statement, then we
3135      can just hash the expression and not worry about virtual operands
3136      and such.  */
3137   if (!stmt || !stmt_ann (stmt))
3138     return val;
3139
3140   /* Add the SSA version numbers of every vuse operand.  This is important
3141      because compound variables like arrays are not renamed in the
3142      operands.  Rather, the rename is done on the virtual variable
3143      representing all the elements of the array.  */
3144   FOR_EACH_SSA_TREE_OPERAND (vuse, stmt, iter, SSA_OP_VUSE)
3145     val = iterative_hash_expr (vuse, val);
3146
3147   return val;
3148 }
3149
3150 static hashval_t
3151 real_avail_expr_hash (const void *p)
3152 {
3153   return ((const struct expr_hash_elt *)p)->hash;
3154 }
3155
3156 static int
3157 avail_expr_eq (const void *p1, const void *p2)
3158 {
3159   tree stmt1 = ((struct expr_hash_elt *)p1)->stmt;
3160   tree rhs1 = ((struct expr_hash_elt *)p1)->rhs;
3161   tree stmt2 = ((struct expr_hash_elt *)p2)->stmt;
3162   tree rhs2 = ((struct expr_hash_elt *)p2)->rhs;
3163
3164   /* If they are the same physical expression, return true.  */
3165   if (rhs1 == rhs2 && stmt1 == stmt2)
3166     return true;
3167
3168   /* If their codes are not equal, then quit now.  */
3169   if (TREE_CODE (rhs1) != TREE_CODE (rhs2))
3170     return false;
3171
3172   /* In case of a collision, both RHS have to be identical and have the
3173      same VUSE operands.  */
3174   if ((TREE_TYPE (rhs1) == TREE_TYPE (rhs2)
3175        || lang_hooks.types_compatible_p (TREE_TYPE (rhs1), TREE_TYPE (rhs2)))
3176       && operand_equal_p (rhs1, rhs2, OEP_PURE_SAME))
3177     {
3178       bool ret = compare_ssa_operands_equal (stmt1, stmt2, SSA_OP_VUSE);
3179       gcc_assert (!ret || ((struct expr_hash_elt *)p1)->hash
3180                   == ((struct expr_hash_elt *)p2)->hash);
3181       return ret;
3182     }
3183
3184   return false;
3185 }