EnumSet*.class: Regenerate
[official-gcc.git] / gcc / tree-ssa-dom.c
blob7bed1c292d85d37f1bdcdb5c04fafb788c4dc0cf
1 /* SSA Dominator optimizations for trees
2 Copyright (C) 2001, 2002, 2003, 2004, 2005, 2006, 2007
3 Free Software Foundation, Inc.
4 Contributed by Diego Novillo <dnovillo@redhat.com>
6 This file is part of GCC.
8 GCC is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 3, or (at your option)
11 any later version.
13 GCC is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with GCC; see the file COPYING3. If not see
20 <http://www.gnu.org/licenses/>. */
22 #include "config.h"
23 #include "system.h"
24 #include "coretypes.h"
25 #include "tm.h"
26 #include "tree.h"
27 #include "flags.h"
28 #include "rtl.h"
29 #include "tm_p.h"
30 #include "ggc.h"
31 #include "basic-block.h"
32 #include "cfgloop.h"
33 #include "output.h"
34 #include "expr.h"
35 #include "function.h"
36 #include "diagnostic.h"
37 #include "timevar.h"
38 #include "tree-dump.h"
39 #include "tree-flow.h"
40 #include "domwalk.h"
41 #include "real.h"
42 #include "tree-pass.h"
43 #include "tree-ssa-propagate.h"
44 #include "langhooks.h"
45 #include "params.h"
47 /* This file implements optimizations on the dominator tree. */
50 /* Structure for recording edge equivalences as well as any pending
51 edge redirections during the dominator optimizer.
53 Computing and storing the edge equivalences instead of creating
54 them on-demand can save significant amounts of time, particularly
55 for pathological cases involving switch statements.
57 These structures live for a single iteration of the dominator
58 optimizer in the edge's AUX field. At the end of an iteration we
59 free each of these structures and update the AUX field to point
60 to any requested redirection target (the code for updating the
61 CFG and SSA graph for edge redirection expects redirection edge
62 targets to be in the AUX field for each edge. */
64 struct edge_info
66 /* If this edge creates a simple equivalence, the LHS and RHS of
67 the equivalence will be stored here. */
68 tree lhs;
69 tree rhs;
71 /* Traversing an edge may also indicate one or more particular conditions
72 are true or false. The number of recorded conditions can vary, but
73 can be determined by the condition's code. So we have an array
74 and its maximum index rather than use a varray. */
75 tree *cond_equivalences;
76 unsigned int max_cond_equivalences;
80 /* Hash table with expressions made available during the renaming process.
81 When an assignment of the form X_i = EXPR is found, the statement is
82 stored in this table. If the same expression EXPR is later found on the
83 RHS of another statement, it is replaced with X_i (thus performing
84 global redundancy elimination). Similarly as we pass through conditionals
85 we record the conditional itself as having either a true or false value
86 in this table. */
87 static htab_t avail_exprs;
89 /* Stack of available expressions in AVAIL_EXPRs. Each block pushes any
90 expressions it enters into the hash table along with a marker entry
91 (null). When we finish processing the block, we pop off entries and
92 remove the expressions from the global hash table until we hit the
93 marker. */
94 static VEC(tree,heap) *avail_exprs_stack;
96 /* Stack of statements we need to rescan during finalization for newly
97 exposed variables.
99 Statement rescanning must occur after the current block's available
100 expressions are removed from AVAIL_EXPRS. Else we may change the
101 hash code for an expression and be unable to find/remove it from
102 AVAIL_EXPRS. */
103 typedef tree *tree_p;
104 DEF_VEC_P(tree_p);
105 DEF_VEC_ALLOC_P(tree_p,heap);
107 static VEC(tree_p,heap) *stmts_to_rescan;
109 /* Structure for entries in the expression hash table.
111 This requires more memory for the hash table entries, but allows us
112 to avoid creating silly tree nodes and annotations for conditionals,
113 eliminates 2 global hash tables and two block local varrays.
115 It also allows us to reduce the number of hash table lookups we
116 have to perform in lookup_avail_expr and finally it allows us to
117 significantly reduce the number of calls into the hashing routine
118 itself. */
120 struct expr_hash_elt
122 /* The value (lhs) of this expression. */
123 tree lhs;
125 /* The expression (rhs) we want to record. */
126 tree rhs;
128 /* The stmt pointer if this element corresponds to a statement. */
129 tree stmt;
131 /* The hash value for RHS/ann. */
132 hashval_t hash;
135 /* Stack of dest,src pairs that need to be restored during finalization.
137 A NULL entry is used to mark the end of pairs which need to be
138 restored during finalization of this block. */
139 static VEC(tree,heap) *const_and_copies_stack;
141 /* Track whether or not we have changed the control flow graph. */
142 static bool cfg_altered;
144 /* Bitmap of blocks that have had EH statements cleaned. We should
145 remove their dead edges eventually. */
146 static bitmap need_eh_cleanup;
148 /* Statistics for dominator optimizations. */
149 struct opt_stats_d
151 long num_stmts;
152 long num_exprs_considered;
153 long num_re;
154 long num_const_prop;
155 long num_copy_prop;
158 static struct opt_stats_d opt_stats;
160 struct eq_expr_value
162 tree src;
163 tree dst;
166 /* Local functions. */
167 static void optimize_stmt (struct dom_walk_data *,
168 basic_block bb,
169 block_stmt_iterator);
170 static tree lookup_avail_expr (tree, bool);
171 static hashval_t avail_expr_hash (const void *);
172 static hashval_t real_avail_expr_hash (const void *);
173 static int avail_expr_eq (const void *, const void *);
174 static void htab_statistics (FILE *, htab_t);
175 static void record_cond (tree, tree);
176 static void record_const_or_copy (tree, tree);
177 static void record_equality (tree, tree);
178 static void record_equivalences_from_phis (basic_block);
179 static void record_equivalences_from_incoming_edge (basic_block);
180 static bool eliminate_redundant_computations (tree);
181 static void record_equivalences_from_stmt (tree, int, stmt_ann_t);
182 static void dom_thread_across_edge (struct dom_walk_data *, edge);
183 static void dom_opt_finalize_block (struct dom_walk_data *, basic_block);
184 static void dom_opt_initialize_block (struct dom_walk_data *, basic_block);
185 static void propagate_to_outgoing_edges (struct dom_walk_data *, basic_block);
186 static void remove_local_expressions_from_table (void);
187 static void restore_vars_to_original_value (void);
188 static edge single_incoming_edge_ignoring_loop_edges (basic_block);
191 /* Allocate an EDGE_INFO for edge E and attach it to E.
192 Return the new EDGE_INFO structure. */
194 static struct edge_info *
195 allocate_edge_info (edge e)
197 struct edge_info *edge_info;
199 edge_info = XCNEW (struct edge_info);
201 e->aux = edge_info;
202 return edge_info;
205 /* Free all EDGE_INFO structures associated with edges in the CFG.
206 If a particular edge can be threaded, copy the redirection
207 target from the EDGE_INFO structure into the edge's AUX field
208 as required by code to update the CFG and SSA graph for
209 jump threading. */
211 static void
212 free_all_edge_infos (void)
214 basic_block bb;
215 edge_iterator ei;
216 edge e;
218 FOR_EACH_BB (bb)
220 FOR_EACH_EDGE (e, ei, bb->preds)
222 struct edge_info *edge_info = (struct edge_info *) e->aux;
224 if (edge_info)
226 if (edge_info->cond_equivalences)
227 free (edge_info->cond_equivalences);
228 free (edge_info);
229 e->aux = NULL;
235 /* Jump threading, redundancy elimination and const/copy propagation.
237 This pass may expose new symbols that need to be renamed into SSA. For
238 every new symbol exposed, its corresponding bit will be set in
239 VARS_TO_RENAME. */
241 static unsigned int
242 tree_ssa_dominator_optimize (void)
244 struct dom_walk_data walk_data;
245 unsigned int i;
247 memset (&opt_stats, 0, sizeof (opt_stats));
249 /* Create our hash tables. */
250 avail_exprs = htab_create (1024, real_avail_expr_hash, avail_expr_eq, free);
251 avail_exprs_stack = VEC_alloc (tree, heap, 20);
252 const_and_copies_stack = VEC_alloc (tree, heap, 20);
253 stmts_to_rescan = VEC_alloc (tree_p, heap, 20);
254 need_eh_cleanup = BITMAP_ALLOC (NULL);
256 /* Setup callbacks for the generic dominator tree walker. */
257 walk_data.walk_stmts_backward = false;
258 walk_data.dom_direction = CDI_DOMINATORS;
259 walk_data.initialize_block_local_data = NULL;
260 walk_data.before_dom_children_before_stmts = dom_opt_initialize_block;
261 walk_data.before_dom_children_walk_stmts = optimize_stmt;
262 walk_data.before_dom_children_after_stmts = propagate_to_outgoing_edges;
263 walk_data.after_dom_children_before_stmts = NULL;
264 walk_data.after_dom_children_walk_stmts = NULL;
265 walk_data.after_dom_children_after_stmts = dom_opt_finalize_block;
266 /* Right now we only attach a dummy COND_EXPR to the global data pointer.
267 When we attach more stuff we'll need to fill this out with a real
268 structure. */
269 walk_data.global_data = NULL;
270 walk_data.block_local_data_size = 0;
271 walk_data.interesting_blocks = NULL;
273 /* Now initialize the dominator walker. */
274 init_walk_dominator_tree (&walk_data);
276 calculate_dominance_info (CDI_DOMINATORS);
277 cfg_altered = false;
279 /* We need to know loop structures in order to avoid destroying them
280 in jump threading. Note that we still can e.g. thread through loop
281 headers to an exit edge, or through loop header to the loop body, assuming
282 that we update the loop info. */
283 loop_optimizer_init (LOOPS_HAVE_SIMPLE_LATCHES);
285 /* We need accurate information regarding back edges in the CFG
286 for jump threading; this may include back edes that are not part of
287 a single loop. */
288 mark_dfs_back_edges ();
290 /* Recursively walk the dominator tree optimizing statements. */
291 walk_dominator_tree (&walk_data, ENTRY_BLOCK_PTR);
294 block_stmt_iterator bsi;
295 basic_block bb;
296 FOR_EACH_BB (bb)
298 for (bsi = bsi_start (bb); !bsi_end_p (bsi); bsi_next (&bsi))
299 update_stmt_if_modified (bsi_stmt (bsi));
303 /* If we exposed any new variables, go ahead and put them into
304 SSA form now, before we handle jump threading. This simplifies
305 interactions between rewriting of _DECL nodes into SSA form
306 and rewriting SSA_NAME nodes into SSA form after block
307 duplication and CFG manipulation. */
308 update_ssa (TODO_update_ssa);
310 free_all_edge_infos ();
312 /* Thread jumps, creating duplicate blocks as needed. */
313 cfg_altered |= thread_through_all_blocks (first_pass_instance);
315 if (cfg_altered)
316 free_dominance_info (CDI_DOMINATORS);
318 /* Removal of statements may make some EH edges dead. Purge
319 such edges from the CFG as needed. */
320 if (!bitmap_empty_p (need_eh_cleanup))
322 tree_purge_all_dead_eh_edges (need_eh_cleanup);
323 bitmap_zero (need_eh_cleanup);
326 /* Finally, remove everything except invariants in SSA_NAME_VALUE.
328 Long term we will be able to let everything in SSA_NAME_VALUE
329 persist. However, for now, we know this is the safe thing to do. */
330 for (i = 0; i < num_ssa_names; i++)
332 tree name = ssa_name (i);
333 tree value;
335 if (!name)
336 continue;
338 value = SSA_NAME_VALUE (name);
339 if (value && !is_gimple_min_invariant (value))
340 SSA_NAME_VALUE (name) = NULL;
343 /* Debugging dumps. */
344 if (dump_file && (dump_flags & TDF_STATS))
345 dump_dominator_optimization_stats (dump_file);
347 loop_optimizer_finalize ();
349 /* Delete our main hashtable. */
350 htab_delete (avail_exprs);
352 /* And finalize the dominator walker. */
353 fini_walk_dominator_tree (&walk_data);
355 /* Free asserted bitmaps and stacks. */
356 BITMAP_FREE (need_eh_cleanup);
358 VEC_free (tree, heap, avail_exprs_stack);
359 VEC_free (tree, heap, const_and_copies_stack);
360 VEC_free (tree_p, heap, stmts_to_rescan);
361 return 0;
364 static bool
365 gate_dominator (void)
367 return flag_tree_dom != 0;
370 struct tree_opt_pass pass_dominator =
372 "dom", /* name */
373 gate_dominator, /* gate */
374 tree_ssa_dominator_optimize, /* execute */
375 NULL, /* sub */
376 NULL, /* next */
377 0, /* static_pass_number */
378 TV_TREE_SSA_DOMINATOR_OPTS, /* tv_id */
379 PROP_cfg | PROP_ssa | PROP_alias, /* properties_required */
380 0, /* properties_provided */
381 0, /* properties_destroyed */
382 0, /* todo_flags_start */
383 TODO_dump_func
384 | TODO_update_ssa
385 | TODO_cleanup_cfg
386 | TODO_verify_ssa, /* todo_flags_finish */
387 0 /* letter */
391 /* Given a stmt CONDSTMT containing a COND_EXPR, canonicalize the
392 COND_EXPR into a canonical form. */
394 static void
395 canonicalize_comparison (tree condstmt)
397 tree cond = COND_EXPR_COND (condstmt);
398 tree op0;
399 tree op1;
400 enum tree_code code = TREE_CODE (cond);
402 if (!COMPARISON_CLASS_P (cond))
403 return;
405 op0 = TREE_OPERAND (cond, 0);
406 op1 = TREE_OPERAND (cond, 1);
408 /* If it would be profitable to swap the operands, then do so to
409 canonicalize the statement, enabling better optimization.
411 By placing canonicalization of such expressions here we
412 transparently keep statements in canonical form, even
413 when the statement is modified. */
414 if (tree_swap_operands_p (op0, op1, false))
416 /* For relationals we need to swap the operands
417 and change the code. */
418 if (code == LT_EXPR
419 || code == GT_EXPR
420 || code == LE_EXPR
421 || code == GE_EXPR)
423 TREE_SET_CODE (cond, swap_tree_comparison (code));
424 swap_tree_operands (condstmt,
425 &TREE_OPERAND (cond, 0),
426 &TREE_OPERAND (cond, 1));
427 /* If one operand was in the operand cache, but the other is
428 not, because it is a constant, this is a case that the
429 internal updating code of swap_tree_operands can't handle
430 properly. */
431 if (TREE_CODE_CLASS (TREE_CODE (op0))
432 != TREE_CODE_CLASS (TREE_CODE (op1)))
433 update_stmt (condstmt);
438 /* Initialize local stacks for this optimizer and record equivalences
439 upon entry to BB. Equivalences can come from the edge traversed to
440 reach BB or they may come from PHI nodes at the start of BB. */
442 static void
443 dom_opt_initialize_block (struct dom_walk_data *walk_data ATTRIBUTE_UNUSED,
444 basic_block bb)
446 if (dump_file && (dump_flags & TDF_DETAILS))
447 fprintf (dump_file, "\n\nOptimizing block #%d\n\n", bb->index);
449 /* Push a marker on the stacks of local information so that we know how
450 far to unwind when we finalize this block. */
451 VEC_safe_push (tree, heap, avail_exprs_stack, NULL_TREE);
452 VEC_safe_push (tree, heap, const_and_copies_stack, NULL_TREE);
454 record_equivalences_from_incoming_edge (bb);
456 /* PHI nodes can create equivalences too. */
457 record_equivalences_from_phis (bb);
460 /* Given an expression EXPR (a relational expression or a statement),
461 initialize the hash table element pointed to by ELEMENT. */
463 static void
464 initialize_hash_element (tree expr, tree lhs, struct expr_hash_elt *element)
466 /* Hash table elements may be based on conditional expressions or statements.
468 For the former case, we have no annotation and we want to hash the
469 conditional expression. In the latter case we have an annotation and
470 we want to record the expression the statement evaluates. */
471 if (COMPARISON_CLASS_P (expr) || TREE_CODE (expr) == TRUTH_NOT_EXPR)
473 element->stmt = NULL;
474 element->rhs = expr;
476 else if (TREE_CODE (expr) == COND_EXPR)
478 element->stmt = expr;
479 element->rhs = COND_EXPR_COND (expr);
481 else if (TREE_CODE (expr) == SWITCH_EXPR)
483 element->stmt = expr;
484 element->rhs = SWITCH_COND (expr);
486 else if (TREE_CODE (expr) == RETURN_EXPR && TREE_OPERAND (expr, 0))
488 element->stmt = expr;
489 element->rhs = GIMPLE_STMT_OPERAND (TREE_OPERAND (expr, 0), 1);
491 else if (TREE_CODE (expr) == GOTO_EXPR)
493 element->stmt = expr;
494 element->rhs = GOTO_DESTINATION (expr);
496 else
498 element->stmt = expr;
499 element->rhs = GENERIC_TREE_OPERAND (expr, 1);
502 element->lhs = lhs;
503 element->hash = avail_expr_hash (element);
506 /* Remove all the expressions in LOCALS from TABLE, stopping when there are
507 LIMIT entries left in LOCALs. */
509 static void
510 remove_local_expressions_from_table (void)
512 /* Remove all the expressions made available in this block. */
513 while (VEC_length (tree, avail_exprs_stack) > 0)
515 struct expr_hash_elt element;
516 tree expr = VEC_pop (tree, avail_exprs_stack);
518 if (expr == NULL_TREE)
519 break;
521 initialize_hash_element (expr, NULL, &element);
522 htab_remove_elt_with_hash (avail_exprs, &element, element.hash);
526 /* Use the source/dest pairs in CONST_AND_COPIES_STACK to restore
527 CONST_AND_COPIES to its original state, stopping when we hit a
528 NULL marker. */
530 static void
531 restore_vars_to_original_value (void)
533 while (VEC_length (tree, const_and_copies_stack) > 0)
535 tree prev_value, dest;
537 dest = VEC_pop (tree, const_and_copies_stack);
539 if (dest == NULL)
540 break;
542 prev_value = VEC_pop (tree, const_and_copies_stack);
543 SSA_NAME_VALUE (dest) = prev_value;
547 /* A trivial wrapper so that we can present the generic jump
548 threading code with a simple API for simplifying statements. */
549 static tree
550 simplify_stmt_for_jump_threading (tree stmt, tree within_stmt ATTRIBUTE_UNUSED)
552 return lookup_avail_expr (stmt, false);
555 /* Wrapper for common code to attempt to thread an edge. For example,
556 it handles lazily building the dummy condition and the bookkeeping
557 when jump threading is successful. */
559 static void
560 dom_thread_across_edge (struct dom_walk_data *walk_data, edge e)
562 /* If we don't already have a dummy condition, build it now. */
563 if (! walk_data->global_data)
565 tree dummy_cond = build2 (NE_EXPR, boolean_type_node,
566 integer_zero_node, integer_zero_node);
567 dummy_cond = build3 (COND_EXPR, void_type_node, dummy_cond, NULL, NULL);
568 walk_data->global_data = dummy_cond;
571 thread_across_edge ((tree) walk_data->global_data, e, false,
572 &const_and_copies_stack,
573 simplify_stmt_for_jump_threading);
576 /* We have finished processing the dominator children of BB, perform
577 any finalization actions in preparation for leaving this node in
578 the dominator tree. */
580 static void
581 dom_opt_finalize_block (struct dom_walk_data *walk_data, basic_block bb)
583 tree last;
586 /* If we have an outgoing edge to a block with multiple incoming and
587 outgoing edges, then we may be able to thread the edge. ie, we
588 may be able to statically determine which of the outgoing edges
589 will be traversed when the incoming edge from BB is traversed. */
590 if (single_succ_p (bb)
591 && (single_succ_edge (bb)->flags & EDGE_ABNORMAL) == 0
592 && potentially_threadable_block (single_succ (bb)))
594 dom_thread_across_edge (walk_data, single_succ_edge (bb));
596 else if ((last = last_stmt (bb))
597 && TREE_CODE (last) == COND_EXPR
598 && (COMPARISON_CLASS_P (COND_EXPR_COND (last))
599 || TREE_CODE (COND_EXPR_COND (last)) == SSA_NAME)
600 && EDGE_COUNT (bb->succs) == 2
601 && (EDGE_SUCC (bb, 0)->flags & EDGE_ABNORMAL) == 0
602 && (EDGE_SUCC (bb, 1)->flags & EDGE_ABNORMAL) == 0)
604 edge true_edge, false_edge;
606 extract_true_false_edges_from_block (bb, &true_edge, &false_edge);
608 /* Only try to thread the edge if it reaches a target block with
609 more than one predecessor and more than one successor. */
610 if (potentially_threadable_block (true_edge->dest))
612 struct edge_info *edge_info;
613 unsigned int i;
615 /* Push a marker onto the available expression stack so that we
616 unwind any expressions related to the TRUE arm before processing
617 the false arm below. */
618 VEC_safe_push (tree, heap, avail_exprs_stack, NULL_TREE);
619 VEC_safe_push (tree, heap, const_and_copies_stack, NULL_TREE);
621 edge_info = (struct edge_info *) true_edge->aux;
623 /* If we have info associated with this edge, record it into
624 our equivalency tables. */
625 if (edge_info)
627 tree *cond_equivalences = edge_info->cond_equivalences;
628 tree lhs = edge_info->lhs;
629 tree rhs = edge_info->rhs;
631 /* If we have a simple NAME = VALUE equivalency record it. */
632 if (lhs && TREE_CODE (lhs) == SSA_NAME)
633 record_const_or_copy (lhs, rhs);
635 /* If we have 0 = COND or 1 = COND equivalences, record them
636 into our expression hash tables. */
637 if (cond_equivalences)
638 for (i = 0; i < edge_info->max_cond_equivalences; i += 2)
640 tree expr = cond_equivalences[i];
641 tree value = cond_equivalences[i + 1];
643 record_cond (expr, value);
647 dom_thread_across_edge (walk_data, true_edge);
649 /* And restore the various tables to their state before
650 we threaded this edge. */
651 remove_local_expressions_from_table ();
654 /* Similarly for the ELSE arm. */
655 if (potentially_threadable_block (false_edge->dest))
657 struct edge_info *edge_info;
658 unsigned int i;
660 VEC_safe_push (tree, heap, const_and_copies_stack, NULL_TREE);
661 edge_info = (struct edge_info *) false_edge->aux;
663 /* If we have info associated with this edge, record it into
664 our equivalency tables. */
665 if (edge_info)
667 tree *cond_equivalences = edge_info->cond_equivalences;
668 tree lhs = edge_info->lhs;
669 tree rhs = edge_info->rhs;
671 /* If we have a simple NAME = VALUE equivalency record it. */
672 if (lhs && TREE_CODE (lhs) == SSA_NAME)
673 record_const_or_copy (lhs, rhs);
675 /* If we have 0 = COND or 1 = COND equivalences, record them
676 into our expression hash tables. */
677 if (cond_equivalences)
678 for (i = 0; i < edge_info->max_cond_equivalences; i += 2)
680 tree expr = cond_equivalences[i];
681 tree value = cond_equivalences[i + 1];
683 record_cond (expr, value);
687 /* Now thread the edge. */
688 dom_thread_across_edge (walk_data, false_edge);
690 /* No need to remove local expressions from our tables
691 or restore vars to their original value as that will
692 be done immediately below. */
696 remove_local_expressions_from_table ();
697 restore_vars_to_original_value ();
699 /* If we queued any statements to rescan in this block, then
700 go ahead and rescan them now. */
701 while (VEC_length (tree_p, stmts_to_rescan) > 0)
703 tree *stmt_p = VEC_last (tree_p, stmts_to_rescan);
704 tree stmt = *stmt_p;
705 basic_block stmt_bb = bb_for_stmt (stmt);
707 if (stmt_bb != bb)
708 break;
710 VEC_pop (tree_p, stmts_to_rescan);
711 pop_stmt_changes (stmt_p);
715 /* PHI nodes can create equivalences too.
717 Ignoring any alternatives which are the same as the result, if
718 all the alternatives are equal, then the PHI node creates an
719 equivalence. */
721 static void
722 record_equivalences_from_phis (basic_block bb)
724 tree phi;
726 for (phi = phi_nodes (bb); phi; phi = PHI_CHAIN (phi))
728 tree lhs = PHI_RESULT (phi);
729 tree rhs = NULL;
730 int i;
732 for (i = 0; i < PHI_NUM_ARGS (phi); i++)
734 tree t = PHI_ARG_DEF (phi, i);
736 /* Ignore alternatives which are the same as our LHS. Since
737 LHS is a PHI_RESULT, it is known to be a SSA_NAME, so we
738 can simply compare pointers. */
739 if (lhs == t)
740 continue;
742 /* If we have not processed an alternative yet, then set
743 RHS to this alternative. */
744 if (rhs == NULL)
745 rhs = t;
746 /* If we have processed an alternative (stored in RHS), then
747 see if it is equal to this one. If it isn't, then stop
748 the search. */
749 else if (! operand_equal_for_phi_arg_p (rhs, t))
750 break;
753 /* If we had no interesting alternatives, then all the RHS alternatives
754 must have been the same as LHS. */
755 if (!rhs)
756 rhs = lhs;
758 /* If we managed to iterate through each PHI alternative without
759 breaking out of the loop, then we have a PHI which may create
760 a useful equivalence. We do not need to record unwind data for
761 this, since this is a true assignment and not an equivalence
762 inferred from a comparison. All uses of this ssa name are dominated
763 by this assignment, so unwinding just costs time and space. */
764 if (i == PHI_NUM_ARGS (phi)
765 && may_propagate_copy (lhs, rhs))
766 SSA_NAME_VALUE (lhs) = rhs;
770 /* Ignoring loop backedges, if BB has precisely one incoming edge then
771 return that edge. Otherwise return NULL. */
772 static edge
773 single_incoming_edge_ignoring_loop_edges (basic_block bb)
775 edge retval = NULL;
776 edge e;
777 edge_iterator ei;
779 FOR_EACH_EDGE (e, ei, bb->preds)
781 /* A loop back edge can be identified by the destination of
782 the edge dominating the source of the edge. */
783 if (dominated_by_p (CDI_DOMINATORS, e->src, e->dest))
784 continue;
786 /* If we have already seen a non-loop edge, then we must have
787 multiple incoming non-loop edges and thus we return NULL. */
788 if (retval)
789 return NULL;
791 /* This is the first non-loop incoming edge we have found. Record
792 it. */
793 retval = e;
796 return retval;
799 /* Record any equivalences created by the incoming edge to BB. If BB
800 has more than one incoming edge, then no equivalence is created. */
802 static void
803 record_equivalences_from_incoming_edge (basic_block bb)
805 edge e;
806 basic_block parent;
807 struct edge_info *edge_info;
809 /* If our parent block ended with a control statement, then we may be
810 able to record some equivalences based on which outgoing edge from
811 the parent was followed. */
812 parent = get_immediate_dominator (CDI_DOMINATORS, bb);
814 e = single_incoming_edge_ignoring_loop_edges (bb);
816 /* If we had a single incoming edge from our parent block, then enter
817 any data associated with the edge into our tables. */
818 if (e && e->src == parent)
820 unsigned int i;
822 edge_info = (struct edge_info *) e->aux;
824 if (edge_info)
826 tree lhs = edge_info->lhs;
827 tree rhs = edge_info->rhs;
828 tree *cond_equivalences = edge_info->cond_equivalences;
830 if (lhs)
831 record_equality (lhs, rhs);
833 if (cond_equivalences)
835 for (i = 0; i < edge_info->max_cond_equivalences; i += 2)
837 tree expr = cond_equivalences[i];
838 tree value = cond_equivalences[i + 1];
840 record_cond (expr, value);
847 /* Dump SSA statistics on FILE. */
849 void
850 dump_dominator_optimization_stats (FILE *file)
852 long n_exprs;
854 fprintf (file, "Total number of statements: %6ld\n\n",
855 opt_stats.num_stmts);
856 fprintf (file, "Exprs considered for dominator optimizations: %6ld\n",
857 opt_stats.num_exprs_considered);
859 n_exprs = opt_stats.num_exprs_considered;
860 if (n_exprs == 0)
861 n_exprs = 1;
863 fprintf (file, " Redundant expressions eliminated: %6ld (%.0f%%)\n",
864 opt_stats.num_re, PERCENT (opt_stats.num_re,
865 n_exprs));
866 fprintf (file, " Constants propagated: %6ld\n",
867 opt_stats.num_const_prop);
868 fprintf (file, " Copies propagated: %6ld\n",
869 opt_stats.num_copy_prop);
871 fprintf (file, "\nHash table statistics:\n");
873 fprintf (file, " avail_exprs: ");
874 htab_statistics (file, avail_exprs);
878 /* Dump SSA statistics on stderr. */
880 void
881 debug_dominator_optimization_stats (void)
883 dump_dominator_optimization_stats (stderr);
887 /* Dump statistics for the hash table HTAB. */
889 static void
890 htab_statistics (FILE *file, htab_t htab)
892 fprintf (file, "size %ld, %ld elements, %f collision/search ratio\n",
893 (long) htab_size (htab),
894 (long) htab_elements (htab),
895 htab_collisions (htab));
898 /* Enter a statement into the true/false expression hash table indicating
899 that the condition COND has the value VALUE. */
901 static void
902 record_cond (tree cond, tree value)
904 struct expr_hash_elt *element = XCNEW (struct expr_hash_elt);
905 void **slot;
907 initialize_hash_element (cond, value, element);
909 slot = htab_find_slot_with_hash (avail_exprs, (void *)element,
910 element->hash, INSERT);
911 if (*slot == NULL)
913 *slot = (void *) element;
914 VEC_safe_push (tree, heap, avail_exprs_stack, cond);
916 else
917 free (element);
920 /* Build a new conditional using NEW_CODE, OP0 and OP1 and store
921 the new conditional into *p, then store a boolean_true_node
922 into *(p + 1). */
924 static void
925 build_and_record_new_cond (enum tree_code new_code, tree op0, tree op1, tree *p)
927 *p = build2 (new_code, boolean_type_node, op0, op1);
928 p++;
929 *p = boolean_true_node;
932 /* Record that COND is true and INVERTED is false into the edge information
933 structure. Also record that any conditions dominated by COND are true
934 as well.
936 For example, if a < b is true, then a <= b must also be true. */
938 static void
939 record_conditions (struct edge_info *edge_info, tree cond, tree inverted)
941 tree op0, op1;
943 if (!COMPARISON_CLASS_P (cond))
944 return;
946 op0 = TREE_OPERAND (cond, 0);
947 op1 = TREE_OPERAND (cond, 1);
949 switch (TREE_CODE (cond))
951 case LT_EXPR:
952 case GT_EXPR:
953 if (FLOAT_TYPE_P (TREE_TYPE (op0)))
955 edge_info->max_cond_equivalences = 12;
956 edge_info->cond_equivalences = XNEWVEC (tree, 12);
957 build_and_record_new_cond (ORDERED_EXPR, op0, op1,
958 &edge_info->cond_equivalences[8]);
959 build_and_record_new_cond (LTGT_EXPR, op0, op1,
960 &edge_info->cond_equivalences[10]);
962 else
964 edge_info->max_cond_equivalences = 8;
965 edge_info->cond_equivalences = XNEWVEC (tree, 8);
968 build_and_record_new_cond ((TREE_CODE (cond) == LT_EXPR
969 ? LE_EXPR : GE_EXPR),
970 op0, op1, &edge_info->cond_equivalences[4]);
971 build_and_record_new_cond (NE_EXPR, op0, op1,
972 &edge_info->cond_equivalences[6]);
973 break;
975 case GE_EXPR:
976 case LE_EXPR:
977 if (FLOAT_TYPE_P (TREE_TYPE (op0)))
979 edge_info->max_cond_equivalences = 6;
980 edge_info->cond_equivalences = XNEWVEC (tree, 6);
981 build_and_record_new_cond (ORDERED_EXPR, op0, op1,
982 &edge_info->cond_equivalences[4]);
984 else
986 edge_info->max_cond_equivalences = 4;
987 edge_info->cond_equivalences = XNEWVEC (tree, 4);
989 break;
991 case EQ_EXPR:
992 if (FLOAT_TYPE_P (TREE_TYPE (op0)))
994 edge_info->max_cond_equivalences = 10;
995 edge_info->cond_equivalences = XNEWVEC (tree, 10);
996 build_and_record_new_cond (ORDERED_EXPR, op0, op1,
997 &edge_info->cond_equivalences[8]);
999 else
1001 edge_info->max_cond_equivalences = 8;
1002 edge_info->cond_equivalences = XNEWVEC (tree, 8);
1004 build_and_record_new_cond (LE_EXPR, op0, op1,
1005 &edge_info->cond_equivalences[4]);
1006 build_and_record_new_cond (GE_EXPR, op0, op1,
1007 &edge_info->cond_equivalences[6]);
1008 break;
1010 case UNORDERED_EXPR:
1011 edge_info->max_cond_equivalences = 16;
1012 edge_info->cond_equivalences = XNEWVEC (tree, 16);
1013 build_and_record_new_cond (NE_EXPR, op0, op1,
1014 &edge_info->cond_equivalences[4]);
1015 build_and_record_new_cond (UNLE_EXPR, op0, op1,
1016 &edge_info->cond_equivalences[6]);
1017 build_and_record_new_cond (UNGE_EXPR, op0, op1,
1018 &edge_info->cond_equivalences[8]);
1019 build_and_record_new_cond (UNEQ_EXPR, op0, op1,
1020 &edge_info->cond_equivalences[10]);
1021 build_and_record_new_cond (UNLT_EXPR, op0, op1,
1022 &edge_info->cond_equivalences[12]);
1023 build_and_record_new_cond (UNGT_EXPR, op0, op1,
1024 &edge_info->cond_equivalences[14]);
1025 break;
1027 case UNLT_EXPR:
1028 case UNGT_EXPR:
1029 edge_info->max_cond_equivalences = 8;
1030 edge_info->cond_equivalences = XNEWVEC (tree, 8);
1031 build_and_record_new_cond ((TREE_CODE (cond) == UNLT_EXPR
1032 ? UNLE_EXPR : UNGE_EXPR),
1033 op0, op1, &edge_info->cond_equivalences[4]);
1034 build_and_record_new_cond (NE_EXPR, op0, op1,
1035 &edge_info->cond_equivalences[6]);
1036 break;
1038 case UNEQ_EXPR:
1039 edge_info->max_cond_equivalences = 8;
1040 edge_info->cond_equivalences = XNEWVEC (tree, 8);
1041 build_and_record_new_cond (UNLE_EXPR, op0, op1,
1042 &edge_info->cond_equivalences[4]);
1043 build_and_record_new_cond (UNGE_EXPR, op0, op1,
1044 &edge_info->cond_equivalences[6]);
1045 break;
1047 case LTGT_EXPR:
1048 edge_info->max_cond_equivalences = 8;
1049 edge_info->cond_equivalences = XNEWVEC (tree, 8);
1050 build_and_record_new_cond (NE_EXPR, op0, op1,
1051 &edge_info->cond_equivalences[4]);
1052 build_and_record_new_cond (ORDERED_EXPR, op0, op1,
1053 &edge_info->cond_equivalences[6]);
1054 break;
1056 default:
1057 edge_info->max_cond_equivalences = 4;
1058 edge_info->cond_equivalences = XNEWVEC (tree, 4);
1059 break;
1062 /* Now store the original true and false conditions into the first
1063 two slots. */
1064 edge_info->cond_equivalences[0] = cond;
1065 edge_info->cond_equivalences[1] = boolean_true_node;
1066 edge_info->cond_equivalences[2] = inverted;
1067 edge_info->cond_equivalences[3] = boolean_false_node;
1070 /* A helper function for record_const_or_copy and record_equality.
1071 Do the work of recording the value and undo info. */
1073 static void
1074 record_const_or_copy_1 (tree x, tree y, tree prev_x)
1076 SSA_NAME_VALUE (x) = y;
1078 VEC_reserve (tree, heap, const_and_copies_stack, 2);
1079 VEC_quick_push (tree, const_and_copies_stack, prev_x);
1080 VEC_quick_push (tree, const_and_copies_stack, x);
1084 /* Return the loop depth of the basic block of the defining statement of X.
1085 This number should not be treated as absolutely correct because the loop
1086 information may not be completely up-to-date when dom runs. However, it
1087 will be relatively correct, and as more passes are taught to keep loop info
1088 up to date, the result will become more and more accurate. */
1091 loop_depth_of_name (tree x)
1093 tree defstmt;
1094 basic_block defbb;
1096 /* If it's not an SSA_NAME, we have no clue where the definition is. */
1097 if (TREE_CODE (x) != SSA_NAME)
1098 return 0;
1100 /* Otherwise return the loop depth of the defining statement's bb.
1101 Note that there may not actually be a bb for this statement, if the
1102 ssa_name is live on entry. */
1103 defstmt = SSA_NAME_DEF_STMT (x);
1104 defbb = bb_for_stmt (defstmt);
1105 if (!defbb)
1106 return 0;
1108 return defbb->loop_depth;
1112 /* Record that X is equal to Y in const_and_copies. Record undo
1113 information in the block-local vector. */
1115 static void
1116 record_const_or_copy (tree x, tree y)
1118 tree prev_x = SSA_NAME_VALUE (x);
1120 if (TREE_CODE (y) == SSA_NAME)
1122 tree tmp = SSA_NAME_VALUE (y);
1123 if (tmp)
1124 y = tmp;
1127 record_const_or_copy_1 (x, y, prev_x);
1130 /* Similarly, but assume that X and Y are the two operands of an EQ_EXPR.
1131 This constrains the cases in which we may treat this as assignment. */
1133 static void
1134 record_equality (tree x, tree y)
1136 tree prev_x = NULL, prev_y = NULL;
1138 if (TREE_CODE (x) == SSA_NAME)
1139 prev_x = SSA_NAME_VALUE (x);
1140 if (TREE_CODE (y) == SSA_NAME)
1141 prev_y = SSA_NAME_VALUE (y);
1143 /* If one of the previous values is invariant, or invariant in more loops
1144 (by depth), then use that.
1145 Otherwise it doesn't matter which value we choose, just so
1146 long as we canonicalize on one value. */
1147 if (TREE_INVARIANT (y))
1149 else if (TREE_INVARIANT (x) || (loop_depth_of_name (x) <= loop_depth_of_name (y)))
1150 prev_x = x, x = y, y = prev_x, prev_x = prev_y;
1151 else if (prev_x && TREE_INVARIANT (prev_x))
1152 x = y, y = prev_x, prev_x = prev_y;
1153 else if (prev_y && TREE_CODE (prev_y) != VALUE_HANDLE)
1154 y = prev_y;
1156 /* After the swapping, we must have one SSA_NAME. */
1157 if (TREE_CODE (x) != SSA_NAME)
1158 return;
1160 /* For IEEE, -0.0 == 0.0, so we don't necessarily know the sign of a
1161 variable compared against zero. If we're honoring signed zeros,
1162 then we cannot record this value unless we know that the value is
1163 nonzero. */
1164 if (HONOR_SIGNED_ZEROS (TYPE_MODE (TREE_TYPE (x)))
1165 && (TREE_CODE (y) != REAL_CST
1166 || REAL_VALUES_EQUAL (dconst0, TREE_REAL_CST (y))))
1167 return;
1169 record_const_or_copy_1 (x, y, prev_x);
1172 /* Returns true when STMT is a simple iv increment. It detects the
1173 following situation:
1175 i_1 = phi (..., i_2)
1176 i_2 = i_1 +/- ... */
1178 static bool
1179 simple_iv_increment_p (tree stmt)
1181 tree lhs, rhs, preinc, phi;
1182 unsigned i;
1184 if (TREE_CODE (stmt) != GIMPLE_MODIFY_STMT)
1185 return false;
1187 lhs = GIMPLE_STMT_OPERAND (stmt, 0);
1188 if (TREE_CODE (lhs) != SSA_NAME)
1189 return false;
1191 rhs = GIMPLE_STMT_OPERAND (stmt, 1);
1193 if (TREE_CODE (rhs) != PLUS_EXPR
1194 && TREE_CODE (rhs) != MINUS_EXPR)
1195 return false;
1197 preinc = TREE_OPERAND (rhs, 0);
1198 if (TREE_CODE (preinc) != SSA_NAME)
1199 return false;
1201 phi = SSA_NAME_DEF_STMT (preinc);
1202 if (TREE_CODE (phi) != PHI_NODE)
1203 return false;
1205 for (i = 0; i < (unsigned) PHI_NUM_ARGS (phi); i++)
1206 if (PHI_ARG_DEF (phi, i) == lhs)
1207 return true;
1209 return false;
1212 /* CONST_AND_COPIES is a table which maps an SSA_NAME to the current
1213 known value for that SSA_NAME (or NULL if no value is known).
1215 Propagate values from CONST_AND_COPIES into the PHI nodes of the
1216 successors of BB. */
1218 static void
1219 cprop_into_successor_phis (basic_block bb)
1221 edge e;
1222 edge_iterator ei;
1224 FOR_EACH_EDGE (e, ei, bb->succs)
1226 tree phi;
1227 int indx;
1229 /* If this is an abnormal edge, then we do not want to copy propagate
1230 into the PHI alternative associated with this edge. */
1231 if (e->flags & EDGE_ABNORMAL)
1232 continue;
1234 phi = phi_nodes (e->dest);
1235 if (! phi)
1236 continue;
1238 indx = e->dest_idx;
1239 for ( ; phi; phi = PHI_CHAIN (phi))
1241 tree new_val;
1242 use_operand_p orig_p;
1243 tree orig_val;
1245 /* The alternative may be associated with a constant, so verify
1246 it is an SSA_NAME before doing anything with it. */
1247 orig_p = PHI_ARG_DEF_PTR (phi, indx);
1248 orig_val = USE_FROM_PTR (orig_p);
1249 if (TREE_CODE (orig_val) != SSA_NAME)
1250 continue;
1252 /* If we have *ORIG_P in our constant/copy table, then replace
1253 ORIG_P with its value in our constant/copy table. */
1254 new_val = SSA_NAME_VALUE (orig_val);
1255 if (new_val
1256 && new_val != orig_val
1257 && (TREE_CODE (new_val) == SSA_NAME
1258 || is_gimple_min_invariant (new_val))
1259 && may_propagate_copy (orig_val, new_val))
1260 propagate_value (orig_p, new_val);
1265 /* We have finished optimizing BB, record any information implied by
1266 taking a specific outgoing edge from BB. */
1268 static void
1269 record_edge_info (basic_block bb)
1271 block_stmt_iterator bsi = bsi_last (bb);
1272 struct edge_info *edge_info;
1274 if (! bsi_end_p (bsi))
1276 tree stmt = bsi_stmt (bsi);
1278 if (stmt && TREE_CODE (stmt) == SWITCH_EXPR)
1280 tree cond = SWITCH_COND (stmt);
1282 if (TREE_CODE (cond) == SSA_NAME)
1284 tree labels = SWITCH_LABELS (stmt);
1285 int i, n_labels = TREE_VEC_LENGTH (labels);
1286 tree *info = XCNEWVEC (tree, last_basic_block);
1287 edge e;
1288 edge_iterator ei;
1290 for (i = 0; i < n_labels; i++)
1292 tree label = TREE_VEC_ELT (labels, i);
1293 basic_block target_bb = label_to_block (CASE_LABEL (label));
1295 if (CASE_HIGH (label)
1296 || !CASE_LOW (label)
1297 || info[target_bb->index])
1298 info[target_bb->index] = error_mark_node;
1299 else
1300 info[target_bb->index] = label;
1303 FOR_EACH_EDGE (e, ei, bb->succs)
1305 basic_block target_bb = e->dest;
1306 tree node = info[target_bb->index];
1308 if (node != NULL && node != error_mark_node)
1310 tree x = fold_convert (TREE_TYPE (cond), CASE_LOW (node));
1311 edge_info = allocate_edge_info (e);
1312 edge_info->lhs = cond;
1313 edge_info->rhs = x;
1316 free (info);
1320 /* A COND_EXPR may create equivalences too. */
1321 if (stmt && TREE_CODE (stmt) == COND_EXPR)
1323 tree cond = COND_EXPR_COND (stmt);
1324 edge true_edge;
1325 edge false_edge;
1327 extract_true_false_edges_from_block (bb, &true_edge, &false_edge);
1329 /* If the conditional is a single variable 'X', record 'X = 1'
1330 for the true edge and 'X = 0' on the false edge. */
1331 if (SSA_VAR_P (cond))
1333 struct edge_info *edge_info;
1335 edge_info = allocate_edge_info (true_edge);
1336 edge_info->lhs = cond;
1337 edge_info->rhs = constant_boolean_node (1, TREE_TYPE (cond));
1339 edge_info = allocate_edge_info (false_edge);
1340 edge_info->lhs = cond;
1341 edge_info->rhs = constant_boolean_node (0, TREE_TYPE (cond));
1343 /* Equality tests may create one or two equivalences. */
1344 else if (COMPARISON_CLASS_P (cond))
1346 tree op0 = TREE_OPERAND (cond, 0);
1347 tree op1 = TREE_OPERAND (cond, 1);
1349 /* Special case comparing booleans against a constant as we
1350 know the value of OP0 on both arms of the branch. i.e., we
1351 can record an equivalence for OP0 rather than COND. */
1352 if ((TREE_CODE (cond) == EQ_EXPR || TREE_CODE (cond) == NE_EXPR)
1353 && TREE_CODE (op0) == SSA_NAME
1354 && TREE_CODE (TREE_TYPE (op0)) == BOOLEAN_TYPE
1355 && is_gimple_min_invariant (op1))
1357 if (TREE_CODE (cond) == EQ_EXPR)
1359 edge_info = allocate_edge_info (true_edge);
1360 edge_info->lhs = op0;
1361 edge_info->rhs = (integer_zerop (op1)
1362 ? boolean_false_node
1363 : boolean_true_node);
1365 edge_info = allocate_edge_info (false_edge);
1366 edge_info->lhs = op0;
1367 edge_info->rhs = (integer_zerop (op1)
1368 ? boolean_true_node
1369 : boolean_false_node);
1371 else
1373 edge_info = allocate_edge_info (true_edge);
1374 edge_info->lhs = op0;
1375 edge_info->rhs = (integer_zerop (op1)
1376 ? boolean_true_node
1377 : boolean_false_node);
1379 edge_info = allocate_edge_info (false_edge);
1380 edge_info->lhs = op0;
1381 edge_info->rhs = (integer_zerop (op1)
1382 ? boolean_false_node
1383 : boolean_true_node);
1387 else if (is_gimple_min_invariant (op0)
1388 && (TREE_CODE (op1) == SSA_NAME
1389 || is_gimple_min_invariant (op1)))
1391 tree inverted = invert_truthvalue (cond);
1392 struct edge_info *edge_info;
1394 edge_info = allocate_edge_info (true_edge);
1395 record_conditions (edge_info, cond, inverted);
1397 if (TREE_CODE (cond) == EQ_EXPR)
1399 edge_info->lhs = op1;
1400 edge_info->rhs = op0;
1403 edge_info = allocate_edge_info (false_edge);
1404 record_conditions (edge_info, inverted, cond);
1406 if (TREE_CODE (cond) == NE_EXPR)
1408 edge_info->lhs = op1;
1409 edge_info->rhs = op0;
1413 else if (TREE_CODE (op0) == SSA_NAME
1414 && (is_gimple_min_invariant (op1)
1415 || TREE_CODE (op1) == SSA_NAME))
1417 tree inverted = invert_truthvalue (cond);
1418 struct edge_info *edge_info;
1420 edge_info = allocate_edge_info (true_edge);
1421 record_conditions (edge_info, cond, inverted);
1423 if (TREE_CODE (cond) == EQ_EXPR)
1425 edge_info->lhs = op0;
1426 edge_info->rhs = op1;
1429 edge_info = allocate_edge_info (false_edge);
1430 record_conditions (edge_info, inverted, cond);
1432 if (TREE_CODE (cond) == NE_EXPR)
1434 edge_info->lhs = op0;
1435 edge_info->rhs = op1;
1440 /* ??? TRUTH_NOT_EXPR can create an equivalence too. */
1445 /* Propagate information from BB to its outgoing edges.
1447 This can include equivalency information implied by control statements
1448 at the end of BB and const/copy propagation into PHIs in BB's
1449 successor blocks. */
1451 static void
1452 propagate_to_outgoing_edges (struct dom_walk_data *walk_data ATTRIBUTE_UNUSED,
1453 basic_block bb)
1455 record_edge_info (bb);
1456 cprop_into_successor_phis (bb);
1459 /* Search for redundant computations in STMT. If any are found, then
1460 replace them with the variable holding the result of the computation.
1462 If safe, record this expression into the available expression hash
1463 table. */
1465 static bool
1466 eliminate_redundant_computations (tree stmt)
1468 tree *expr_p, def = NULL_TREE;
1469 bool insert = true;
1470 tree cached_lhs;
1471 bool retval = false;
1472 bool modify_expr_p = false;
1474 if (TREE_CODE (stmt) == GIMPLE_MODIFY_STMT)
1475 def = GIMPLE_STMT_OPERAND (stmt, 0);
1477 /* Certain expressions on the RHS can be optimized away, but can not
1478 themselves be entered into the hash tables. */
1479 if (! def
1480 || TREE_CODE (def) != SSA_NAME
1481 || SSA_NAME_OCCURS_IN_ABNORMAL_PHI (def)
1482 || !ZERO_SSA_OPERANDS (stmt, SSA_OP_VDEF)
1483 /* Do not record equivalences for increments of ivs. This would create
1484 overlapping live ranges for a very questionable gain. */
1485 || simple_iv_increment_p (stmt))
1486 insert = false;
1488 /* Check if the expression has been computed before. */
1489 cached_lhs = lookup_avail_expr (stmt, insert);
1491 opt_stats.num_exprs_considered++;
1493 /* Get a pointer to the expression we are trying to optimize. */
1494 if (TREE_CODE (stmt) == COND_EXPR)
1495 expr_p = &COND_EXPR_COND (stmt);
1496 else if (TREE_CODE (stmt) == SWITCH_EXPR)
1497 expr_p = &SWITCH_COND (stmt);
1498 else if (TREE_CODE (stmt) == RETURN_EXPR && TREE_OPERAND (stmt, 0))
1500 expr_p = &GIMPLE_STMT_OPERAND (TREE_OPERAND (stmt, 0), 1);
1501 modify_expr_p = true;
1503 else
1505 expr_p = &GENERIC_TREE_OPERAND (stmt, 1);
1506 modify_expr_p = true;
1509 /* It is safe to ignore types here since we have already done
1510 type checking in the hashing and equality routines. In fact
1511 type checking here merely gets in the way of constant
1512 propagation. Also, make sure that it is safe to propagate
1513 CACHED_LHS into *EXPR_P. */
1514 if (cached_lhs
1515 && ((TREE_CODE (cached_lhs) != SSA_NAME
1516 && (modify_expr_p
1517 || useless_type_conversion_p (TREE_TYPE (*expr_p),
1518 TREE_TYPE (cached_lhs))))
1519 || may_propagate_copy (*expr_p, cached_lhs)))
1521 if (dump_file && (dump_flags & TDF_DETAILS))
1523 fprintf (dump_file, " Replaced redundant expr '");
1524 print_generic_expr (dump_file, *expr_p, dump_flags);
1525 fprintf (dump_file, "' with '");
1526 print_generic_expr (dump_file, cached_lhs, dump_flags);
1527 fprintf (dump_file, "'\n");
1530 opt_stats.num_re++;
1532 #if defined ENABLE_CHECKING
1533 gcc_assert (TREE_CODE (cached_lhs) == SSA_NAME
1534 || is_gimple_min_invariant (cached_lhs));
1535 #endif
1537 if (TREE_CODE (cached_lhs) == ADDR_EXPR
1538 || (POINTER_TYPE_P (TREE_TYPE (*expr_p))
1539 && is_gimple_min_invariant (cached_lhs)))
1540 retval = true;
1542 if (modify_expr_p
1543 && !useless_type_conversion_p (TREE_TYPE (*expr_p),
1544 TREE_TYPE (cached_lhs)))
1545 cached_lhs = fold_convert (TREE_TYPE (*expr_p), cached_lhs);
1547 propagate_tree_value (expr_p, cached_lhs);
1548 mark_stmt_modified (stmt);
1550 return retval;
1553 /* STMT, a GIMPLE_MODIFY_STMT, may create certain equivalences, in either
1554 the available expressions table or the const_and_copies table.
1555 Detect and record those equivalences. */
1557 static void
1558 record_equivalences_from_stmt (tree stmt, int may_optimize_p, stmt_ann_t ann)
1560 tree lhs = GIMPLE_STMT_OPERAND (stmt, 0);
1561 enum tree_code lhs_code = TREE_CODE (lhs);
1563 if (lhs_code == SSA_NAME)
1565 tree rhs = GIMPLE_STMT_OPERAND (stmt, 1);
1567 /* Strip away any useless type conversions. */
1568 STRIP_USELESS_TYPE_CONVERSION (rhs);
1570 /* If the RHS of the assignment is a constant or another variable that
1571 may be propagated, register it in the CONST_AND_COPIES table. We
1572 do not need to record unwind data for this, since this is a true
1573 assignment and not an equivalence inferred from a comparison. All
1574 uses of this ssa name are dominated by this assignment, so unwinding
1575 just costs time and space. */
1576 if (may_optimize_p
1577 && (TREE_CODE (rhs) == SSA_NAME
1578 || is_gimple_min_invariant (rhs)))
1579 SSA_NAME_VALUE (lhs) = rhs;
1582 /* A memory store, even an aliased store, creates a useful
1583 equivalence. By exchanging the LHS and RHS, creating suitable
1584 vops and recording the result in the available expression table,
1585 we may be able to expose more redundant loads. */
1586 if (!ann->has_volatile_ops
1587 && stmt_references_memory_p (stmt)
1588 && (TREE_CODE (GIMPLE_STMT_OPERAND (stmt, 1)) == SSA_NAME
1589 || is_gimple_min_invariant (GIMPLE_STMT_OPERAND (stmt, 1)))
1590 && !is_gimple_reg (lhs))
1592 tree rhs = GIMPLE_STMT_OPERAND (stmt, 1);
1593 tree new_stmt;
1595 /* FIXME: If the LHS of the assignment is a bitfield and the RHS
1596 is a constant, we need to adjust the constant to fit into the
1597 type of the LHS. If the LHS is a bitfield and the RHS is not
1598 a constant, then we can not record any equivalences for this
1599 statement since we would need to represent the widening or
1600 narrowing of RHS. This fixes gcc.c-torture/execute/921016-1.c
1601 and should not be necessary if GCC represented bitfields
1602 properly. */
1603 if (lhs_code == COMPONENT_REF
1604 && DECL_BIT_FIELD (TREE_OPERAND (lhs, 1)))
1606 if (TREE_CONSTANT (rhs))
1607 rhs = widen_bitfield (rhs, TREE_OPERAND (lhs, 1), lhs);
1608 else
1609 rhs = NULL;
1611 /* If the value overflowed, then we can not use this equivalence. */
1612 if (rhs && ! is_gimple_min_invariant (rhs))
1613 rhs = NULL;
1616 if (rhs)
1618 /* Build a new statement with the RHS and LHS exchanged. */
1619 new_stmt = build_gimple_modify_stmt (rhs, lhs);
1621 create_ssa_artificial_load_stmt (new_stmt, stmt);
1623 /* Finally enter the statement into the available expression
1624 table. */
1625 lookup_avail_expr (new_stmt, true);
1630 /* Replace *OP_P in STMT with any known equivalent value for *OP_P from
1631 CONST_AND_COPIES. */
1633 static bool
1634 cprop_operand (tree stmt, use_operand_p op_p)
1636 bool may_have_exposed_new_symbols = false;
1637 tree val;
1638 tree op = USE_FROM_PTR (op_p);
1640 /* If the operand has a known constant value or it is known to be a
1641 copy of some other variable, use the value or copy stored in
1642 CONST_AND_COPIES. */
1643 val = SSA_NAME_VALUE (op);
1644 if (val && val != op && TREE_CODE (val) != VALUE_HANDLE)
1646 tree op_type, val_type;
1648 /* Do not change the base variable in the virtual operand
1649 tables. That would make it impossible to reconstruct
1650 the renamed virtual operand if we later modify this
1651 statement. Also only allow the new value to be an SSA_NAME
1652 for propagation into virtual operands. */
1653 if (!is_gimple_reg (op)
1654 && (TREE_CODE (val) != SSA_NAME
1655 || is_gimple_reg (val)
1656 || get_virtual_var (val) != get_virtual_var (op)))
1657 return false;
1659 /* Do not replace hard register operands in asm statements. */
1660 if (TREE_CODE (stmt) == ASM_EXPR
1661 && !may_propagate_copy_into_asm (op))
1662 return false;
1664 /* Get the toplevel type of each operand. */
1665 op_type = TREE_TYPE (op);
1666 val_type = TREE_TYPE (val);
1668 /* While both types are pointers, get the type of the object
1669 pointed to. */
1670 while (POINTER_TYPE_P (op_type) && POINTER_TYPE_P (val_type))
1672 op_type = TREE_TYPE (op_type);
1673 val_type = TREE_TYPE (val_type);
1676 /* Make sure underlying types match before propagating a constant by
1677 converting the constant to the proper type. Note that convert may
1678 return a non-gimple expression, in which case we ignore this
1679 propagation opportunity. */
1680 if (TREE_CODE (val) != SSA_NAME)
1682 if (!useless_type_conversion_p (op_type, val_type))
1684 val = fold_convert (TREE_TYPE (op), val);
1685 if (!is_gimple_min_invariant (val))
1686 return false;
1690 /* Certain operands are not allowed to be copy propagated due
1691 to their interaction with exception handling and some GCC
1692 extensions. */
1693 else if (!may_propagate_copy (op, val))
1694 return false;
1696 /* Do not propagate copies if the propagated value is at a deeper loop
1697 depth than the propagatee. Otherwise, this may move loop variant
1698 variables outside of their loops and prevent coalescing
1699 opportunities. If the value was loop invariant, it will be hoisted
1700 by LICM and exposed for copy propagation. */
1701 if (loop_depth_of_name (val) > loop_depth_of_name (op))
1702 return false;
1704 /* Dump details. */
1705 if (dump_file && (dump_flags & TDF_DETAILS))
1707 fprintf (dump_file, " Replaced '");
1708 print_generic_expr (dump_file, op, dump_flags);
1709 fprintf (dump_file, "' with %s '",
1710 (TREE_CODE (val) != SSA_NAME ? "constant" : "variable"));
1711 print_generic_expr (dump_file, val, dump_flags);
1712 fprintf (dump_file, "'\n");
1715 /* If VAL is an ADDR_EXPR or a constant of pointer type, note
1716 that we may have exposed a new symbol for SSA renaming. */
1717 if (TREE_CODE (val) == ADDR_EXPR
1718 || (POINTER_TYPE_P (TREE_TYPE (op))
1719 && is_gimple_min_invariant (val)))
1720 may_have_exposed_new_symbols = true;
1722 if (TREE_CODE (val) != SSA_NAME)
1723 opt_stats.num_const_prop++;
1724 else
1725 opt_stats.num_copy_prop++;
1727 propagate_value (op_p, val);
1729 /* And note that we modified this statement. This is now
1730 safe, even if we changed virtual operands since we will
1731 rescan the statement and rewrite its operands again. */
1732 mark_stmt_modified (stmt);
1734 return may_have_exposed_new_symbols;
1737 /* CONST_AND_COPIES is a table which maps an SSA_NAME to the current
1738 known value for that SSA_NAME (or NULL if no value is known).
1740 Propagate values from CONST_AND_COPIES into the uses, vuses and
1741 vdef_ops of STMT. */
1743 static bool
1744 cprop_into_stmt (tree stmt)
1746 bool may_have_exposed_new_symbols = false;
1747 use_operand_p op_p;
1748 ssa_op_iter iter;
1750 FOR_EACH_SSA_USE_OPERAND (op_p, stmt, iter, SSA_OP_ALL_USES)
1752 if (TREE_CODE (USE_FROM_PTR (op_p)) == SSA_NAME)
1753 may_have_exposed_new_symbols |= cprop_operand (stmt, op_p);
1756 return may_have_exposed_new_symbols;
1760 /* Optimize the statement pointed to by iterator SI.
1762 We try to perform some simplistic global redundancy elimination and
1763 constant propagation:
1765 1- To detect global redundancy, we keep track of expressions that have
1766 been computed in this block and its dominators. If we find that the
1767 same expression is computed more than once, we eliminate repeated
1768 computations by using the target of the first one.
1770 2- Constant values and copy assignments. This is used to do very
1771 simplistic constant and copy propagation. When a constant or copy
1772 assignment is found, we map the value on the RHS of the assignment to
1773 the variable in the LHS in the CONST_AND_COPIES table. */
1775 static void
1776 optimize_stmt (struct dom_walk_data *walk_data ATTRIBUTE_UNUSED,
1777 basic_block bb, block_stmt_iterator si)
1779 stmt_ann_t ann;
1780 tree stmt, old_stmt;
1781 bool may_optimize_p;
1782 bool may_have_exposed_new_symbols = false;
1784 old_stmt = stmt = bsi_stmt (si);
1786 if (TREE_CODE (stmt) == COND_EXPR)
1787 canonicalize_comparison (stmt);
1789 update_stmt_if_modified (stmt);
1790 ann = stmt_ann (stmt);
1791 opt_stats.num_stmts++;
1792 may_have_exposed_new_symbols = false;
1793 push_stmt_changes (bsi_stmt_ptr (si));
1795 if (dump_file && (dump_flags & TDF_DETAILS))
1797 fprintf (dump_file, "Optimizing statement ");
1798 print_generic_stmt (dump_file, stmt, TDF_SLIM);
1801 /* Const/copy propagate into USES, VUSES and the RHS of VDEFs. */
1802 may_have_exposed_new_symbols = cprop_into_stmt (stmt);
1804 /* If the statement has been modified with constant replacements,
1805 fold its RHS before checking for redundant computations. */
1806 if (ann->modified)
1808 tree rhs;
1810 /* Try to fold the statement making sure that STMT is kept
1811 up to date. */
1812 if (fold_stmt (bsi_stmt_ptr (si)))
1814 stmt = bsi_stmt (si);
1815 ann = stmt_ann (stmt);
1817 if (dump_file && (dump_flags & TDF_DETAILS))
1819 fprintf (dump_file, " Folded to: ");
1820 print_generic_stmt (dump_file, stmt, TDF_SLIM);
1824 rhs = get_rhs (stmt);
1825 if (rhs && TREE_CODE (rhs) == ADDR_EXPR)
1826 recompute_tree_invariant_for_addr_expr (rhs);
1828 /* Constant/copy propagation above may change the set of
1829 virtual operands associated with this statement. Folding
1830 may remove the need for some virtual operands.
1832 Indicate we will need to rescan and rewrite the statement. */
1833 may_have_exposed_new_symbols = true;
1836 /* Check for redundant computations. Do this optimization only
1837 for assignments that have no volatile ops and conditionals. */
1838 may_optimize_p = (!ann->has_volatile_ops
1839 && ((TREE_CODE (stmt) == RETURN_EXPR
1840 && TREE_OPERAND (stmt, 0)
1841 && TREE_CODE (TREE_OPERAND (stmt, 0))
1842 == GIMPLE_MODIFY_STMT
1843 && ! (TREE_SIDE_EFFECTS
1844 (GIMPLE_STMT_OPERAND
1845 (TREE_OPERAND (stmt, 0), 1))))
1846 || (TREE_CODE (stmt) == GIMPLE_MODIFY_STMT
1847 && ! TREE_SIDE_EFFECTS (GIMPLE_STMT_OPERAND (stmt,
1848 1)))
1849 || TREE_CODE (stmt) == COND_EXPR
1850 || TREE_CODE (stmt) == SWITCH_EXPR));
1852 if (may_optimize_p)
1853 may_have_exposed_new_symbols |= eliminate_redundant_computations (stmt);
1855 /* Record any additional equivalences created by this statement. */
1856 if (TREE_CODE (stmt) == GIMPLE_MODIFY_STMT)
1857 record_equivalences_from_stmt (stmt, may_optimize_p, ann);
1859 /* If STMT is a COND_EXPR and it was modified, then we may know
1860 where it goes. If that is the case, then mark the CFG as altered.
1862 This will cause us to later call remove_unreachable_blocks and
1863 cleanup_tree_cfg when it is safe to do so. It is not safe to
1864 clean things up here since removal of edges and such can trigger
1865 the removal of PHI nodes, which in turn can release SSA_NAMEs to
1866 the manager.
1868 That's all fine and good, except that once SSA_NAMEs are released
1869 to the manager, we must not call create_ssa_name until all references
1870 to released SSA_NAMEs have been eliminated.
1872 All references to the deleted SSA_NAMEs can not be eliminated until
1873 we remove unreachable blocks.
1875 We can not remove unreachable blocks until after we have completed
1876 any queued jump threading.
1878 We can not complete any queued jump threads until we have taken
1879 appropriate variables out of SSA form. Taking variables out of
1880 SSA form can call create_ssa_name and thus we lose.
1882 Ultimately I suspect we're going to need to change the interface
1883 into the SSA_NAME manager. */
1884 if (ann->modified)
1886 tree val = NULL;
1888 if (TREE_CODE (stmt) == COND_EXPR)
1889 val = COND_EXPR_COND (stmt);
1890 else if (TREE_CODE (stmt) == SWITCH_EXPR)
1891 val = SWITCH_COND (stmt);
1893 if (val && TREE_CODE (val) == INTEGER_CST && find_taken_edge (bb, val))
1894 cfg_altered = true;
1896 /* If we simplified a statement in such a way as to be shown that it
1897 cannot trap, update the eh information and the cfg to match. */
1898 if (maybe_clean_or_replace_eh_stmt (old_stmt, stmt))
1900 bitmap_set_bit (need_eh_cleanup, bb->index);
1901 if (dump_file && (dump_flags & TDF_DETAILS))
1902 fprintf (dump_file, " Flagged to clear EH edges.\n");
1906 if (may_have_exposed_new_symbols)
1908 /* Queue the statement to be re-scanned after all the
1909 AVAIL_EXPRS have been processed. The change buffer stack for
1910 all the pushed statements will be processed when this queue
1911 is emptied. */
1912 VEC_safe_push (tree_p, heap, stmts_to_rescan, bsi_stmt_ptr (si));
1914 else
1916 /* Otherwise, just discard the recently pushed change buffer. If
1917 not, the STMTS_TO_RESCAN queue will get out of synch with the
1918 change buffer stack. */
1919 discard_stmt_changes (bsi_stmt_ptr (si));
1923 /* Search for an existing instance of STMT in the AVAIL_EXPRS table. If
1924 found, return its LHS. Otherwise insert STMT in the table and return
1925 NULL_TREE.
1927 Also, when an expression is first inserted in the AVAIL_EXPRS table, it
1928 is also added to the stack pointed to by BLOCK_AVAIL_EXPRS_P, so that they
1929 can be removed when we finish processing this block and its children.
1931 NOTE: This function assumes that STMT is a GIMPLE_MODIFY_STMT node that
1932 contains no CALL_EXPR on its RHS and makes no volatile nor
1933 aliased references. */
1935 static tree
1936 lookup_avail_expr (tree stmt, bool insert)
1938 void **slot;
1939 tree lhs;
1940 tree temp;
1941 struct expr_hash_elt *element = XNEW (struct expr_hash_elt);
1943 lhs = TREE_CODE (stmt) == GIMPLE_MODIFY_STMT
1944 ? GIMPLE_STMT_OPERAND (stmt, 0) : NULL;
1946 initialize_hash_element (stmt, lhs, element);
1948 /* Don't bother remembering constant assignments and copy operations.
1949 Constants and copy operations are handled by the constant/copy propagator
1950 in optimize_stmt. */
1951 if (TREE_CODE (element->rhs) == SSA_NAME
1952 || is_gimple_min_invariant (element->rhs))
1954 free (element);
1955 return NULL_TREE;
1958 /* Finally try to find the expression in the main expression hash table. */
1959 slot = htab_find_slot_with_hash (avail_exprs, element, element->hash,
1960 (insert ? INSERT : NO_INSERT));
1961 if (slot == NULL)
1963 free (element);
1964 return NULL_TREE;
1967 if (*slot == NULL)
1969 *slot = (void *) element;
1970 VEC_safe_push (tree, heap, avail_exprs_stack,
1971 stmt ? stmt : element->rhs);
1972 return NULL_TREE;
1975 /* Extract the LHS of the assignment so that it can be used as the current
1976 definition of another variable. */
1977 lhs = ((struct expr_hash_elt *)*slot)->lhs;
1979 /* See if the LHS appears in the CONST_AND_COPIES table. If it does, then
1980 use the value from the const_and_copies table. */
1981 if (TREE_CODE (lhs) == SSA_NAME)
1983 temp = SSA_NAME_VALUE (lhs);
1984 if (temp && TREE_CODE (temp) != VALUE_HANDLE)
1985 lhs = temp;
1988 free (element);
1989 return lhs;
1992 /* Hashing and equality functions for AVAIL_EXPRS. The table stores
1993 GIMPLE_MODIFY_STMT statements. We compute a value number for expressions
1994 using the code of the expression and the SSA numbers of its operands. */
1996 static hashval_t
1997 avail_expr_hash (const void *p)
1999 tree stmt = ((const struct expr_hash_elt *)p)->stmt;
2000 tree rhs = ((const struct expr_hash_elt *)p)->rhs;
2001 tree vuse;
2002 ssa_op_iter iter;
2003 hashval_t val = 0;
2005 /* iterative_hash_expr knows how to deal with any expression and
2006 deals with commutative operators as well, so just use it instead
2007 of duplicating such complexities here. */
2008 val = iterative_hash_expr (rhs, val);
2010 /* If the hash table entry is not associated with a statement, then we
2011 can just hash the expression and not worry about virtual operands
2012 and such. */
2013 if (!stmt || !stmt_ann (stmt))
2014 return val;
2016 /* Add the SSA version numbers of every vuse operand. This is important
2017 because compound variables like arrays are not renamed in the
2018 operands. Rather, the rename is done on the virtual variable
2019 representing all the elements of the array. */
2020 FOR_EACH_SSA_TREE_OPERAND (vuse, stmt, iter, SSA_OP_VUSE)
2021 val = iterative_hash_expr (vuse, val);
2023 return val;
2026 static hashval_t
2027 real_avail_expr_hash (const void *p)
2029 return ((const struct expr_hash_elt *)p)->hash;
2032 static int
2033 avail_expr_eq (const void *p1, const void *p2)
2035 tree stmt1 = ((const struct expr_hash_elt *)p1)->stmt;
2036 tree rhs1 = ((const struct expr_hash_elt *)p1)->rhs;
2037 tree stmt2 = ((const struct expr_hash_elt *)p2)->stmt;
2038 tree rhs2 = ((const struct expr_hash_elt *)p2)->rhs;
2040 /* If they are the same physical expression, return true. */
2041 if (rhs1 == rhs2 && stmt1 == stmt2)
2042 return true;
2044 /* If their codes are not equal, then quit now. */
2045 if (TREE_CODE (rhs1) != TREE_CODE (rhs2))
2046 return false;
2048 /* In case of a collision, both RHS have to be identical and have the
2049 same VUSE operands. */
2050 if (types_compatible_p (TREE_TYPE (rhs1), TREE_TYPE (rhs2))
2051 && operand_equal_p (rhs1, rhs2, OEP_PURE_SAME))
2053 bool ret = compare_ssa_operands_equal (stmt1, stmt2, SSA_OP_VUSE);
2054 gcc_assert (!ret || ((const struct expr_hash_elt *)p1)->hash
2055 == ((const struct expr_hash_elt *)p2)->hash);
2056 return ret;
2059 return false;
2062 /* PHI-ONLY copy and constant propagation. This pass is meant to clean
2063 up degenerate PHIs created by or exposed by jump threading. */
2065 /* Given PHI, return its RHS if the PHI is a degenerate, otherwise return
2066 NULL. */
2068 static tree
2069 degenerate_phi_result (tree phi)
2071 tree lhs = PHI_RESULT (phi);
2072 tree val = NULL;
2073 int i;
2075 /* Ignoring arguments which are the same as LHS, if all the remaining
2076 arguments are the same, then the PHI is a degenerate and has the
2077 value of that common argument. */
2078 for (i = 0; i < PHI_NUM_ARGS (phi); i++)
2080 tree arg = PHI_ARG_DEF (phi, i);
2082 if (arg == lhs)
2083 continue;
2084 else if (!val)
2085 val = arg;
2086 else if (!operand_equal_p (arg, val, 0))
2087 break;
2089 return (i == PHI_NUM_ARGS (phi) ? val : NULL);
2092 /* Given a tree node T, which is either a PHI_NODE or GIMPLE_MODIFY_STMT,
2093 remove it from the IL. */
2095 static void
2096 remove_stmt_or_phi (tree t)
2098 if (TREE_CODE (t) == PHI_NODE)
2099 remove_phi_node (t, NULL, true);
2100 else
2102 block_stmt_iterator bsi = bsi_for_stmt (t);
2103 bsi_remove (&bsi, true);
2104 release_defs (t);
2108 /* Given a tree node T, which is either a PHI_NODE or GIMPLE_MODIFY_STMT,
2109 return the "rhs" of the node, in the case of a non-degenerate
2110 PHI, NULL is returned. */
2112 static tree
2113 get_rhs_or_phi_arg (tree t)
2115 if (TREE_CODE (t) == PHI_NODE)
2116 return degenerate_phi_result (t);
2117 else if (TREE_CODE (t) == GIMPLE_MODIFY_STMT)
2118 return GIMPLE_STMT_OPERAND (t, 1);
2119 gcc_unreachable ();
2123 /* Given a tree node T, which is either a PHI_NODE or a GIMPLE_MODIFY_STMT,
2124 return the "lhs" of the node. */
2126 static tree
2127 get_lhs_or_phi_result (tree t)
2129 if (TREE_CODE (t) == PHI_NODE)
2130 return PHI_RESULT (t);
2131 else if (TREE_CODE (t) == GIMPLE_MODIFY_STMT)
2132 return GIMPLE_STMT_OPERAND (t, 0);
2133 gcc_unreachable ();
2136 /* Propagate RHS into all uses of LHS (when possible).
2138 RHS and LHS are derived from STMT, which is passed in solely so
2139 that we can remove it if propagation is successful.
2141 When propagating into a PHI node or into a statement which turns
2142 into a trivial copy or constant initialization, set the
2143 appropriate bit in INTERESTING_NAMEs so that we will visit those
2144 nodes as well in an effort to pick up secondary optimization
2145 opportunities. */
2147 static void
2148 propagate_rhs_into_lhs (tree stmt, tree lhs, tree rhs, bitmap interesting_names)
2150 /* First verify that propagation is valid and isn't going to move a
2151 loop variant variable outside its loop. */
2152 if (! SSA_NAME_OCCURS_IN_ABNORMAL_PHI (lhs)
2153 && (TREE_CODE (rhs) != SSA_NAME
2154 || ! SSA_NAME_OCCURS_IN_ABNORMAL_PHI (rhs))
2155 && may_propagate_copy (lhs, rhs)
2156 && loop_depth_of_name (lhs) >= loop_depth_of_name (rhs))
2158 use_operand_p use_p;
2159 imm_use_iterator iter;
2160 tree use_stmt;
2161 bool all = true;
2163 /* Dump details. */
2164 if (dump_file && (dump_flags & TDF_DETAILS))
2166 fprintf (dump_file, " Replacing '");
2167 print_generic_expr (dump_file, lhs, dump_flags);
2168 fprintf (dump_file, "' with %s '",
2169 (TREE_CODE (rhs) != SSA_NAME ? "constant" : "variable"));
2170 print_generic_expr (dump_file, rhs, dump_flags);
2171 fprintf (dump_file, "'\n");
2174 /* Walk over every use of LHS and try to replace the use with RHS.
2175 At this point the only reason why such a propagation would not
2176 be successful would be if the use occurs in an ASM_EXPR. */
2177 FOR_EACH_IMM_USE_STMT (use_stmt, iter, lhs)
2180 /* It's not always safe to propagate into an ASM_EXPR. */
2181 if (TREE_CODE (use_stmt) == ASM_EXPR
2182 && ! may_propagate_copy_into_asm (lhs))
2184 all = false;
2185 continue;
2188 /* Dump details. */
2189 if (dump_file && (dump_flags & TDF_DETAILS))
2191 fprintf (dump_file, " Original statement:");
2192 print_generic_expr (dump_file, use_stmt, dump_flags);
2193 fprintf (dump_file, "\n");
2196 push_stmt_changes (&use_stmt);
2198 /* Propagate the RHS into this use of the LHS. */
2199 FOR_EACH_IMM_USE_ON_STMT (use_p, iter)
2200 propagate_value (use_p, rhs);
2202 /* Special cases to avoid useless calls into the folding
2203 routines, operand scanning, etc.
2205 First, propagation into a PHI may cause the PHI to become
2206 a degenerate, so mark the PHI as interesting. No other
2207 actions are necessary.
2209 Second, if we're propagating a virtual operand and the
2210 propagation does not change the underlying _DECL node for
2211 the virtual operand, then no further actions are necessary. */
2212 if (TREE_CODE (use_stmt) == PHI_NODE
2213 || (! is_gimple_reg (lhs)
2214 && TREE_CODE (rhs) == SSA_NAME
2215 && SSA_NAME_VAR (lhs) == SSA_NAME_VAR (rhs)))
2217 /* Dump details. */
2218 if (dump_file && (dump_flags & TDF_DETAILS))
2220 fprintf (dump_file, " Updated statement:");
2221 print_generic_expr (dump_file, use_stmt, dump_flags);
2222 fprintf (dump_file, "\n");
2225 /* Propagation into a PHI may expose new degenerate PHIs,
2226 so mark the result of the PHI as interesting. */
2227 if (TREE_CODE (use_stmt) == PHI_NODE)
2229 tree result = get_lhs_or_phi_result (use_stmt);
2230 bitmap_set_bit (interesting_names, SSA_NAME_VERSION (result));
2233 discard_stmt_changes (&use_stmt);
2234 continue;
2237 /* From this point onward we are propagating into a
2238 real statement. Folding may (or may not) be possible,
2239 we may expose new operands, expose dead EH edges,
2240 etc. */
2241 fold_stmt_inplace (use_stmt);
2243 /* Sometimes propagation can expose new operands to the
2244 renamer. Note this will call update_stmt at the
2245 appropriate time. */
2246 pop_stmt_changes (&use_stmt);
2248 /* Dump details. */
2249 if (dump_file && (dump_flags & TDF_DETAILS))
2251 fprintf (dump_file, " Updated statement:");
2252 print_generic_expr (dump_file, use_stmt, dump_flags);
2253 fprintf (dump_file, "\n");
2256 /* If we replaced a variable index with a constant, then
2257 we would need to update the invariant flag for ADDR_EXPRs. */
2258 if (TREE_CODE (use_stmt) == GIMPLE_MODIFY_STMT
2259 && TREE_CODE (GIMPLE_STMT_OPERAND (use_stmt, 1)) == ADDR_EXPR)
2260 recompute_tree_invariant_for_addr_expr
2261 (GIMPLE_STMT_OPERAND (use_stmt, 1));
2263 /* If we cleaned up EH information from the statement,
2264 mark its containing block as needing EH cleanups. */
2265 if (maybe_clean_or_replace_eh_stmt (use_stmt, use_stmt))
2267 bitmap_set_bit (need_eh_cleanup, bb_for_stmt (use_stmt)->index);
2268 if (dump_file && (dump_flags & TDF_DETAILS))
2269 fprintf (dump_file, " Flagged to clear EH edges.\n");
2272 /* Propagation may expose new trivial copy/constant propagation
2273 opportunities. */
2274 if (TREE_CODE (use_stmt) == GIMPLE_MODIFY_STMT
2275 && TREE_CODE (GIMPLE_STMT_OPERAND (use_stmt, 0)) == SSA_NAME
2276 && (TREE_CODE (GIMPLE_STMT_OPERAND (use_stmt, 1)) == SSA_NAME
2277 || is_gimple_min_invariant (GIMPLE_STMT_OPERAND (use_stmt,
2278 1))))
2280 tree result = get_lhs_or_phi_result (use_stmt);
2281 bitmap_set_bit (interesting_names, SSA_NAME_VERSION (result));
2284 /* Propagation into these nodes may make certain edges in
2285 the CFG unexecutable. We want to identify them as PHI nodes
2286 at the destination of those unexecutable edges may become
2287 degenerates. */
2288 else if (TREE_CODE (use_stmt) == COND_EXPR
2289 || TREE_CODE (use_stmt) == SWITCH_EXPR
2290 || TREE_CODE (use_stmt) == GOTO_EXPR)
2292 tree val;
2294 if (TREE_CODE (use_stmt) == COND_EXPR)
2295 val = COND_EXPR_COND (use_stmt);
2296 else if (TREE_CODE (use_stmt) == SWITCH_EXPR)
2297 val = SWITCH_COND (use_stmt);
2298 else
2299 val = GOTO_DESTINATION (use_stmt);
2301 if (is_gimple_min_invariant (val))
2303 basic_block bb = bb_for_stmt (use_stmt);
2304 edge te = find_taken_edge (bb, val);
2305 edge_iterator ei;
2306 edge e;
2307 block_stmt_iterator bsi;
2309 /* Remove all outgoing edges except TE. */
2310 for (ei = ei_start (bb->succs); (e = ei_safe_edge (ei));)
2312 if (e != te)
2314 tree phi;
2316 /* Mark all the PHI nodes at the destination of
2317 the unexecutable edge as interesting. */
2318 for (phi = phi_nodes (e->dest);
2319 phi;
2320 phi = PHI_CHAIN (phi))
2322 tree result = PHI_RESULT (phi);
2323 int version = SSA_NAME_VERSION (result);
2325 bitmap_set_bit (interesting_names, version);
2328 te->probability += e->probability;
2330 te->count += e->count;
2331 remove_edge (e);
2332 cfg_altered = true;
2334 else
2335 ei_next (&ei);
2338 bsi = bsi_last (bb_for_stmt (use_stmt));
2339 bsi_remove (&bsi, true);
2341 /* And fixup the flags on the single remaining edge. */
2342 te->flags &= ~(EDGE_TRUE_VALUE | EDGE_FALSE_VALUE);
2343 te->flags &= ~EDGE_ABNORMAL;
2344 te->flags |= EDGE_FALLTHRU;
2345 if (te->probability > REG_BR_PROB_BASE)
2346 te->probability = REG_BR_PROB_BASE;
2351 /* Ensure there is nothing else to do. */
2352 gcc_assert (!all || has_zero_uses (lhs));
2354 /* If we were able to propagate away all uses of LHS, then
2355 we can remove STMT. */
2356 if (all)
2357 remove_stmt_or_phi (stmt);
2361 /* T is either a PHI node (potentially a degenerate PHI node) or
2362 a statement that is a trivial copy or constant initialization.
2364 Attempt to eliminate T by propagating its RHS into all uses of
2365 its LHS. This may in turn set new bits in INTERESTING_NAMES
2366 for nodes we want to revisit later.
2368 All exit paths should clear INTERESTING_NAMES for the result
2369 of T. */
2371 static void
2372 eliminate_const_or_copy (tree t, bitmap interesting_names)
2374 tree lhs = get_lhs_or_phi_result (t);
2375 tree rhs;
2376 int version = SSA_NAME_VERSION (lhs);
2378 /* If the LHS of this statement or PHI has no uses, then we can
2379 just eliminate it. This can occur if, for example, the PHI
2380 was created by block duplication due to threading and its only
2381 use was in the conditional at the end of the block which was
2382 deleted. */
2383 if (has_zero_uses (lhs))
2385 bitmap_clear_bit (interesting_names, version);
2386 remove_stmt_or_phi (t);
2387 return;
2390 /* Get the RHS of the assignment or PHI node if the PHI is a
2391 degenerate. */
2392 rhs = get_rhs_or_phi_arg (t);
2393 if (!rhs)
2395 bitmap_clear_bit (interesting_names, version);
2396 return;
2399 propagate_rhs_into_lhs (t, lhs, rhs, interesting_names);
2401 /* Note that T may well have been deleted by now, so do
2402 not access it, instead use the saved version # to clear
2403 T's entry in the worklist. */
2404 bitmap_clear_bit (interesting_names, version);
2407 /* The first phase in degenerate PHI elimination.
2409 Eliminate the degenerate PHIs in BB, then recurse on the
2410 dominator children of BB. */
2412 static void
2413 eliminate_degenerate_phis_1 (basic_block bb, bitmap interesting_names)
2415 tree phi, next;
2416 basic_block son;
2418 for (phi = phi_nodes (bb); phi; phi = next)
2420 next = PHI_CHAIN (phi);
2421 eliminate_const_or_copy (phi, interesting_names);
2424 /* Recurse into the dominator children of BB. */
2425 for (son = first_dom_son (CDI_DOMINATORS, bb);
2426 son;
2427 son = next_dom_son (CDI_DOMINATORS, son))
2428 eliminate_degenerate_phis_1 (son, interesting_names);
2432 /* A very simple pass to eliminate degenerate PHI nodes from the
2433 IL. This is meant to be fast enough to be able to be run several
2434 times in the optimization pipeline.
2436 Certain optimizations, particularly those which duplicate blocks
2437 or remove edges from the CFG can create or expose PHIs which are
2438 trivial copies or constant initializations.
2440 While we could pick up these optimizations in DOM or with the
2441 combination of copy-prop and CCP, those solutions are far too
2442 heavy-weight for our needs.
2444 This implementation has two phases so that we can efficiently
2445 eliminate the first order degenerate PHIs and second order
2446 degenerate PHIs.
2448 The first phase performs a dominator walk to identify and eliminate
2449 the vast majority of the degenerate PHIs. When a degenerate PHI
2450 is identified and eliminated any affected statements or PHIs
2451 are put on a worklist.
2453 The second phase eliminates degenerate PHIs and trivial copies
2454 or constant initializations using the worklist. This is how we
2455 pick up the secondary optimization opportunities with minimal
2456 cost. */
2458 static unsigned int
2459 eliminate_degenerate_phis (void)
2461 bitmap interesting_names;
2462 bitmap interesting_names1;
2464 /* Bitmap of blocks which need EH information updated. We can not
2465 update it on-the-fly as doing so invalidates the dominator tree. */
2466 need_eh_cleanup = BITMAP_ALLOC (NULL);
2468 /* INTERESTING_NAMES is effectively our worklist, indexed by
2469 SSA_NAME_VERSION.
2471 A set bit indicates that the statement or PHI node which
2472 defines the SSA_NAME should be (re)examined to determine if
2473 it has become a degenerate PHI or trivial const/copy propagation
2474 opportunity.
2476 Experiments have show we generally get better compilation
2477 time behavior with bitmaps rather than sbitmaps. */
2478 interesting_names = BITMAP_ALLOC (NULL);
2479 interesting_names1 = BITMAP_ALLOC (NULL);
2481 calculate_dominance_info (CDI_DOMINATORS);
2482 cfg_altered = false;
2484 /* First phase. Eliminate degenerate PHIs via a dominator
2485 walk of the CFG.
2487 Experiments have indicated that we generally get better
2488 compile-time behavior by visiting blocks in the first
2489 phase in dominator order. Presumably this is because walking
2490 in dominator order leaves fewer PHIs for later examination
2491 by the worklist phase. */
2492 eliminate_degenerate_phis_1 (ENTRY_BLOCK_PTR, interesting_names);
2494 /* Second phase. Eliminate second order degenerate PHIs as well
2495 as trivial copies or constant initializations identified by
2496 the first phase or this phase. Basically we keep iterating
2497 until our set of INTERESTING_NAMEs is empty. */
2498 while (!bitmap_empty_p (interesting_names))
2500 unsigned int i;
2501 bitmap_iterator bi;
2503 /* EXECUTE_IF_SET_IN_BITMAP does not like its bitmap
2504 changed during the loop. Copy it to another bitmap and
2505 use that. */
2506 bitmap_copy (interesting_names1, interesting_names);
2508 EXECUTE_IF_SET_IN_BITMAP (interesting_names1, 0, i, bi)
2510 tree name = ssa_name (i);
2512 /* Ignore SSA_NAMEs that have been released because
2513 their defining statement was deleted (unreachable). */
2514 if (name)
2515 eliminate_const_or_copy (SSA_NAME_DEF_STMT (ssa_name (i)),
2516 interesting_names);
2520 if (cfg_altered)
2521 free_dominance_info (CDI_DOMINATORS);
2523 /* Propagation of const and copies may make some EH edges dead. Purge
2524 such edges from the CFG as needed. */
2525 if (!bitmap_empty_p (need_eh_cleanup))
2527 tree_purge_all_dead_eh_edges (need_eh_cleanup);
2528 BITMAP_FREE (need_eh_cleanup);
2531 BITMAP_FREE (interesting_names);
2532 BITMAP_FREE (interesting_names1);
2533 return 0;
2536 struct tree_opt_pass pass_phi_only_cprop =
2538 "phicprop", /* name */
2539 gate_dominator, /* gate */
2540 eliminate_degenerate_phis, /* execute */
2541 NULL, /* sub */
2542 NULL, /* next */
2543 0, /* static_pass_number */
2544 TV_TREE_PHI_CPROP, /* tv_id */
2545 PROP_cfg | PROP_ssa | PROP_alias, /* properties_required */
2546 0, /* properties_provided */
2547 0, /* properties_destroyed */
2548 0, /* todo_flags_start */
2549 TODO_cleanup_cfg
2550 | TODO_dump_func
2551 | TODO_ggc_collect
2552 | TODO_verify_ssa
2553 | TODO_verify_stmts
2554 | TODO_update_ssa, /* todo_flags_finish */
2555 0 /* letter */