OSDN Git Service

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