OSDN Git Service

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