2007-05-06 Jerry DeLisle <jvdelisle@gcc.gnu.org>
[official-gcc.git] / gcc / tree-ssa-dom.c
blob6e1387f715724f2621ce23fa2e25853e6ee55a39
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 2, 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 COPYING. If not, write to
20 the Free Software Foundation, 51 Franklin Street, Fifth Floor,
21 Boston, MA 02110-1301, USA. */
23 #include "config.h"
24 #include "system.h"
25 #include "coretypes.h"
26 #include "tm.h"
27 #include "tree.h"
28 #include "flags.h"
29 #include "rtl.h"
30 #include "tm_p.h"
31 #include "ggc.h"
32 #include "basic-block.h"
33 #include "cfgloop.h"
34 #include "output.h"
35 #include "expr.h"
36 #include "function.h"
37 #include "diagnostic.h"
38 #include "timevar.h"
39 #include "tree-dump.h"
40 #include "tree-flow.h"
41 #include "domwalk.h"
42 #include "real.h"
43 #include "tree-pass.h"
44 #include "tree-ssa-propagate.h"
45 #include "langhooks.h"
46 #include "params.h"
48 /* This file implements optimizations on the dominator tree. */
51 /* Structure for recording edge equivalences as well as any pending
52 edge redirections during the dominator optimizer.
54 Computing and storing the edge equivalences instead of creating
55 them on-demand can save significant amounts of time, particularly
56 for pathological cases involving switch statements.
58 These structures live for a single iteration of the dominator
59 optimizer in the edge's AUX field. At the end of an iteration we
60 free each of these structures and update the AUX field to point
61 to any requested redirection target (the code for updating the
62 CFG and SSA graph for edge redirection expects redirection edge
63 targets to be in the AUX field for each edge. */
65 struct edge_info
67 /* If this edge creates a simple equivalence, the LHS and RHS of
68 the equivalence will be stored here. */
69 tree lhs;
70 tree rhs;
72 /* Traversing an edge may also indicate one or more particular conditions
73 are true or false. The number of recorded conditions can vary, but
74 can be determined by the condition's code. So we have an array
75 and its maximum index rather than use a varray. */
76 tree *cond_equivalences;
77 unsigned int max_cond_equivalences;
81 /* Hash table with expressions made available during the renaming process.
82 When an assignment of the form X_i = EXPR is found, the statement is
83 stored in this table. If the same expression EXPR is later found on the
84 RHS of another statement, it is replaced with X_i (thus performing
85 global redundancy elimination). Similarly as we pass through conditionals
86 we record the conditional itself as having either a true or false value
87 in this table. */
88 static htab_t avail_exprs;
90 /* Stack of available expressions in AVAIL_EXPRs. Each block pushes any
91 expressions it enters into the hash table along with a marker entry
92 (null). When we finish processing the block, we pop off entries and
93 remove the expressions from the global hash table until we hit the
94 marker. */
95 static VEC(tree,heap) *avail_exprs_stack;
97 /* Stack of statements we need to rescan during finalization for newly
98 exposed variables.
100 Statement rescanning must occur after the current block's available
101 expressions are removed from AVAIL_EXPRS. Else we may change the
102 hash code for an expression and be unable to find/remove it from
103 AVAIL_EXPRS. */
104 typedef tree *tree_p;
105 DEF_VEC_P(tree_p);
106 DEF_VEC_ALLOC_P(tree_p,heap);
108 static VEC(tree_p,heap) *stmts_to_rescan;
110 /* Structure for entries in the expression hash table.
112 This requires more memory for the hash table entries, but allows us
113 to avoid creating silly tree nodes and annotations for conditionals,
114 eliminates 2 global hash tables and two block local varrays.
116 It also allows us to reduce the number of hash table lookups we
117 have to perform in lookup_avail_expr and finally it allows us to
118 significantly reduce the number of calls into the hashing routine
119 itself. */
121 struct expr_hash_elt
123 /* The value (lhs) of this expression. */
124 tree lhs;
126 /* The expression (rhs) we want to record. */
127 tree rhs;
129 /* The stmt pointer if this element corresponds to a statement. */
130 tree stmt;
132 /* The hash value for RHS/ann. */
133 hashval_t hash;
136 /* Stack of dest,src pairs that need to be restored during finalization.
138 A NULL entry is used to mark the end of pairs which need to be
139 restored during finalization of this block. */
140 static VEC(tree,heap) *const_and_copies_stack;
142 /* Track whether or not we have changed the control flow graph. */
143 static bool cfg_altered;
145 /* Bitmap of blocks that have had EH statements cleaned. We should
146 remove their dead edges eventually. */
147 static bitmap need_eh_cleanup;
149 /* Statistics for dominator optimizations. */
150 struct opt_stats_d
152 long num_stmts;
153 long num_exprs_considered;
154 long num_re;
155 long num_const_prop;
156 long num_copy_prop;
159 static struct opt_stats_d opt_stats;
161 struct eq_expr_value
163 tree src;
164 tree dst;
167 /* Local functions. */
168 static void optimize_stmt (struct dom_walk_data *,
169 basic_block bb,
170 block_stmt_iterator);
171 static tree lookup_avail_expr (tree, bool);
172 static hashval_t avail_expr_hash (const void *);
173 static hashval_t real_avail_expr_hash (const void *);
174 static int avail_expr_eq (const void *, const void *);
175 static void htab_statistics (FILE *, htab_t);
176 static void record_cond (tree, tree);
177 static void record_const_or_copy (tree, tree);
178 static void record_equality (tree, tree);
179 static void record_equivalences_from_phis (basic_block);
180 static void record_equivalences_from_incoming_edge (basic_block);
181 static bool eliminate_redundant_computations (tree);
182 static void record_equivalences_from_stmt (tree, int, stmt_ann_t);
183 static void dom_thread_across_edge (struct dom_walk_data *, edge);
184 static void dom_opt_finalize_block (struct dom_walk_data *, basic_block);
185 static void dom_opt_initialize_block (struct dom_walk_data *, basic_block);
186 static void propagate_to_outgoing_edges (struct dom_walk_data *, basic_block);
187 static void remove_local_expressions_from_table (void);
188 static void restore_vars_to_original_value (void);
189 static edge single_incoming_edge_ignoring_loop_edges (basic_block);
192 /* Allocate an EDGE_INFO for edge E and attach it to E.
193 Return the new EDGE_INFO structure. */
195 static struct edge_info *
196 allocate_edge_info (edge e)
198 struct edge_info *edge_info;
200 edge_info = XCNEW (struct edge_info);
202 e->aux = edge_info;
203 return edge_info;
206 /* Free all EDGE_INFO structures associated with edges in the CFG.
207 If a particular edge can be threaded, copy the redirection
208 target from the EDGE_INFO structure into the edge's AUX field
209 as required by code to update the CFG and SSA graph for
210 jump threading. */
212 static void
213 free_all_edge_infos (void)
215 basic_block bb;
216 edge_iterator ei;
217 edge e;
219 FOR_EACH_BB (bb)
221 FOR_EACH_EDGE (e, ei, bb->preds)
223 struct edge_info *edge_info = (struct edge_info *) e->aux;
225 if (edge_info)
227 if (edge_info->cond_equivalences)
228 free (edge_info->cond_equivalences);
229 free (edge_info);
230 e->aux = NULL;
236 /* Jump threading, redundancy elimination and const/copy propagation.
238 This pass may expose new symbols that need to be renamed into SSA. For
239 every new symbol exposed, its corresponding bit will be set in
240 VARS_TO_RENAME. */
242 static unsigned int
243 tree_ssa_dominator_optimize (void)
245 struct dom_walk_data walk_data;
246 unsigned int i;
248 memset (&opt_stats, 0, sizeof (opt_stats));
250 /* Create our hash tables. */
251 avail_exprs = htab_create (1024, real_avail_expr_hash, avail_expr_eq, free);
252 avail_exprs_stack = VEC_alloc (tree, heap, 20);
253 const_and_copies_stack = VEC_alloc (tree, heap, 20);
254 stmts_to_rescan = VEC_alloc (tree_p, heap, 20);
255 need_eh_cleanup = BITMAP_ALLOC (NULL);
257 /* Setup callbacks for the generic dominator tree walker. */
258 walk_data.walk_stmts_backward = false;
259 walk_data.dom_direction = CDI_DOMINATORS;
260 walk_data.initialize_block_local_data = NULL;
261 walk_data.before_dom_children_before_stmts = dom_opt_initialize_block;
262 walk_data.before_dom_children_walk_stmts = optimize_stmt;
263 walk_data.before_dom_children_after_stmts = propagate_to_outgoing_edges;
264 walk_data.after_dom_children_before_stmts = NULL;
265 walk_data.after_dom_children_walk_stmts = NULL;
266 walk_data.after_dom_children_after_stmts = dom_opt_finalize_block;
267 /* Right now we only attach a dummy COND_EXPR to the global data pointer.
268 When we attach more stuff we'll need to fill this out with a real
269 structure. */
270 walk_data.global_data = NULL;
271 walk_data.block_local_data_size = 0;
272 walk_data.interesting_blocks = NULL;
274 /* Now initialize the dominator walker. */
275 init_walk_dominator_tree (&walk_data);
277 calculate_dominance_info (CDI_DOMINATORS);
279 /* We need to know which edges exit loops so that we can
280 aggressively thread through loop headers to an exit
281 edge. */
282 loop_optimizer_init (AVOID_CFG_MODIFICATIONS);
283 if (current_loops)
285 mark_loop_exit_edges ();
286 loop_optimizer_finalize ();
289 /* Clean up the CFG so that any forwarder blocks created by loop
290 canonicalization are removed. */
291 cleanup_tree_cfg ();
292 calculate_dominance_info (CDI_DOMINATORS);
294 /* We need accurate information regarding back edges in the CFG
295 for jump threading. */
296 mark_dfs_back_edges ();
298 /* Recursively walk the dominator tree optimizing statements. */
299 walk_dominator_tree (&walk_data, ENTRY_BLOCK_PTR);
302 block_stmt_iterator bsi;
303 basic_block bb;
304 FOR_EACH_BB (bb)
306 for (bsi = bsi_start (bb); !bsi_end_p (bsi); bsi_next (&bsi))
307 update_stmt_if_modified (bsi_stmt (bsi));
311 /* If we exposed any new variables, go ahead and put them into
312 SSA form now, before we handle jump threading. This simplifies
313 interactions between rewriting of _DECL nodes into SSA form
314 and rewriting SSA_NAME nodes into SSA form after block
315 duplication and CFG manipulation. */
316 update_ssa (TODO_update_ssa);
318 free_all_edge_infos ();
320 /* Thread jumps, creating duplicate blocks as needed. */
321 cfg_altered |= thread_through_all_blocks ();
323 /* Removal of statements may make some EH edges dead. Purge
324 such edges from the CFG as needed. */
325 if (!bitmap_empty_p (need_eh_cleanup))
327 cfg_altered |= tree_purge_all_dead_eh_edges (need_eh_cleanup);
328 bitmap_zero (need_eh_cleanup);
331 if (cfg_altered)
332 free_dominance_info (CDI_DOMINATORS);
334 /* Finally, remove everything except invariants in SSA_NAME_VALUE.
336 Long term we will be able to let everything in SSA_NAME_VALUE
337 persist. However, for now, we know this is the safe thing to do. */
338 for (i = 0; i < num_ssa_names; i++)
340 tree name = ssa_name (i);
341 tree value;
343 if (!name)
344 continue;
346 value = SSA_NAME_VALUE (name);
347 if (value && !is_gimple_min_invariant (value))
348 SSA_NAME_VALUE (name) = NULL;
351 /* Debugging dumps. */
352 if (dump_file && (dump_flags & TDF_STATS))
353 dump_dominator_optimization_stats (dump_file);
355 /* Delete our main hashtable. */
356 htab_delete (avail_exprs);
358 /* And finalize the dominator walker. */
359 fini_walk_dominator_tree (&walk_data);
361 /* Free asserted bitmaps and stacks. */
362 BITMAP_FREE (need_eh_cleanup);
364 VEC_free (tree, heap, avail_exprs_stack);
365 VEC_free (tree, heap, const_and_copies_stack);
366 VEC_free (tree_p, heap, stmts_to_rescan);
367 return 0;
370 static bool
371 gate_dominator (void)
373 return flag_tree_dom != 0;
376 struct tree_opt_pass pass_dominator =
378 "dom", /* name */
379 gate_dominator, /* gate */
380 tree_ssa_dominator_optimize, /* execute */
381 NULL, /* sub */
382 NULL, /* next */
383 0, /* static_pass_number */
384 TV_TREE_SSA_DOMINATOR_OPTS, /* tv_id */
385 PROP_cfg | PROP_ssa | PROP_alias, /* properties_required */
386 0, /* properties_provided */
387 0, /* properties_destroyed */
388 0, /* todo_flags_start */
389 TODO_dump_func
390 | TODO_update_ssa
391 | TODO_cleanup_cfg
392 | TODO_verify_ssa, /* todo_flags_finish */
393 0 /* letter */
397 /* Given a stmt CONDSTMT containing a COND_EXPR, canonicalize the
398 COND_EXPR into a canonical form. */
400 static void
401 canonicalize_comparison (tree condstmt)
403 tree cond = COND_EXPR_COND (condstmt);
404 tree op0;
405 tree op1;
406 enum tree_code code = TREE_CODE (cond);
408 if (!COMPARISON_CLASS_P (cond))
409 return;
411 op0 = TREE_OPERAND (cond, 0);
412 op1 = TREE_OPERAND (cond, 1);
414 /* If it would be profitable to swap the operands, then do so to
415 canonicalize the statement, enabling better optimization.
417 By placing canonicalization of such expressions here we
418 transparently keep statements in canonical form, even
419 when the statement is modified. */
420 if (tree_swap_operands_p (op0, op1, false))
422 /* For relationals we need to swap the operands
423 and change the code. */
424 if (code == LT_EXPR
425 || code == GT_EXPR
426 || code == LE_EXPR
427 || code == GE_EXPR)
429 TREE_SET_CODE (cond, swap_tree_comparison (code));
430 swap_tree_operands (condstmt,
431 &TREE_OPERAND (cond, 0),
432 &TREE_OPERAND (cond, 1));
433 /* If one operand was in the operand cache, but the other is
434 not, because it is a constant, this is a case that the
435 internal updating code of swap_tree_operands can't handle
436 properly. */
437 if (TREE_CODE_CLASS (TREE_CODE (op0))
438 != TREE_CODE_CLASS (TREE_CODE (op1)))
439 update_stmt (condstmt);
444 /* Initialize local stacks for this optimizer and record equivalences
445 upon entry to BB. Equivalences can come from the edge traversed to
446 reach BB or they may come from PHI nodes at the start of BB. */
448 static void
449 dom_opt_initialize_block (struct dom_walk_data *walk_data ATTRIBUTE_UNUSED,
450 basic_block bb)
452 if (dump_file && (dump_flags & TDF_DETAILS))
453 fprintf (dump_file, "\n\nOptimizing block #%d\n\n", bb->index);
455 /* Push a marker on the stacks of local information so that we know how
456 far to unwind when we finalize this block. */
457 VEC_safe_push (tree, heap, avail_exprs_stack, NULL_TREE);
458 VEC_safe_push (tree, heap, const_and_copies_stack, NULL_TREE);
460 record_equivalences_from_incoming_edge (bb);
462 /* PHI nodes can create equivalences too. */
463 record_equivalences_from_phis (bb);
466 /* Given an expression EXPR (a relational expression or a statement),
467 initialize the hash table element pointed to by ELEMENT. */
469 static void
470 initialize_hash_element (tree expr, tree lhs, struct expr_hash_elt *element)
472 /* Hash table elements may be based on conditional expressions or statements.
474 For the former case, we have no annotation and we want to hash the
475 conditional expression. In the latter case we have an annotation and
476 we want to record the expression the statement evaluates. */
477 if (COMPARISON_CLASS_P (expr) || TREE_CODE (expr) == TRUTH_NOT_EXPR)
479 element->stmt = NULL;
480 element->rhs = expr;
482 else if (TREE_CODE (expr) == COND_EXPR)
484 element->stmt = expr;
485 element->rhs = COND_EXPR_COND (expr);
487 else if (TREE_CODE (expr) == SWITCH_EXPR)
489 element->stmt = expr;
490 element->rhs = SWITCH_COND (expr);
492 else if (TREE_CODE (expr) == RETURN_EXPR && TREE_OPERAND (expr, 0))
494 element->stmt = expr;
495 element->rhs = GIMPLE_STMT_OPERAND (TREE_OPERAND (expr, 0), 1);
497 else if (TREE_CODE (expr) == GOTO_EXPR)
499 element->stmt = expr;
500 element->rhs = GOTO_DESTINATION (expr);
502 else
504 element->stmt = expr;
505 element->rhs = GENERIC_TREE_OPERAND (expr, 1);
508 element->lhs = lhs;
509 element->hash = avail_expr_hash (element);
512 /* Remove all the expressions in LOCALS from TABLE, stopping when there are
513 LIMIT entries left in LOCALs. */
515 static void
516 remove_local_expressions_from_table (void)
518 /* Remove all the expressions made available in this block. */
519 while (VEC_length (tree, avail_exprs_stack) > 0)
521 struct expr_hash_elt element;
522 tree expr = VEC_pop (tree, avail_exprs_stack);
524 if (expr == NULL_TREE)
525 break;
527 initialize_hash_element (expr, NULL, &element);
528 htab_remove_elt_with_hash (avail_exprs, &element, element.hash);
532 /* Use the source/dest pairs in CONST_AND_COPIES_STACK to restore
533 CONST_AND_COPIES to its original state, stopping when we hit a
534 NULL marker. */
536 static void
537 restore_vars_to_original_value (void)
539 while (VEC_length (tree, const_and_copies_stack) > 0)
541 tree prev_value, dest;
543 dest = VEC_pop (tree, const_and_copies_stack);
545 if (dest == NULL)
546 break;
548 prev_value = VEC_pop (tree, const_and_copies_stack);
549 SSA_NAME_VALUE (dest) = prev_value;
553 /* A trivial wrapper so that we can present the generic jump
554 threading code with a simple API for simplifying statements. */
555 static tree
556 simplify_stmt_for_jump_threading (tree stmt, tree within_stmt ATTRIBUTE_UNUSED)
558 return lookup_avail_expr (stmt, false);
561 /* Wrapper for common code to attempt to thread an edge. For example,
562 it handles lazily building the dummy condition and the bookkeeping
563 when jump threading is successful. */
565 static void
566 dom_thread_across_edge (struct dom_walk_data *walk_data, edge e)
568 /* If we don't already have a dummy condition, build it now. */
569 if (! walk_data->global_data)
571 tree dummy_cond = build2 (NE_EXPR, boolean_type_node,
572 integer_zero_node, integer_zero_node);
573 dummy_cond = build3 (COND_EXPR, void_type_node, dummy_cond, NULL, NULL);
574 walk_data->global_data = dummy_cond;
577 thread_across_edge (walk_data->global_data, e, false,
578 &const_and_copies_stack,
579 simplify_stmt_for_jump_threading);
582 /* We have finished processing the dominator children of BB, perform
583 any finalization actions in preparation for leaving this node in
584 the dominator tree. */
586 static void
587 dom_opt_finalize_block (struct dom_walk_data *walk_data, basic_block bb)
589 tree last;
592 /* If we have an outgoing edge to a block with multiple incoming and
593 outgoing edges, then we may be able to thread the edge. ie, we
594 may be able to statically determine which of the outgoing edges
595 will be traversed when the incoming edge from BB is traversed. */
596 if (single_succ_p (bb)
597 && (single_succ_edge (bb)->flags & EDGE_ABNORMAL) == 0
598 && potentially_threadable_block (single_succ (bb)))
600 dom_thread_across_edge (walk_data, single_succ_edge (bb));
602 else if ((last = last_stmt (bb))
603 && TREE_CODE (last) == COND_EXPR
604 && (COMPARISON_CLASS_P (COND_EXPR_COND (last))
605 || TREE_CODE (COND_EXPR_COND (last)) == SSA_NAME)
606 && EDGE_COUNT (bb->succs) == 2
607 && (EDGE_SUCC (bb, 0)->flags & EDGE_ABNORMAL) == 0
608 && (EDGE_SUCC (bb, 1)->flags & EDGE_ABNORMAL) == 0)
610 edge true_edge, false_edge;
612 extract_true_false_edges_from_block (bb, &true_edge, &false_edge);
614 /* Only try to thread the edge if it reaches a target block with
615 more than one predecessor and more than one successor. */
616 if (potentially_threadable_block (true_edge->dest))
618 struct edge_info *edge_info;
619 unsigned int i;
621 /* Push a marker onto the available expression stack so that we
622 unwind any expressions related to the TRUE arm before processing
623 the false arm below. */
624 VEC_safe_push (tree, heap, avail_exprs_stack, NULL_TREE);
625 VEC_safe_push (tree, heap, const_and_copies_stack, NULL_TREE);
627 edge_info = (struct edge_info *) true_edge->aux;
629 /* If we have info associated with this edge, record it into
630 our equivalency tables. */
631 if (edge_info)
633 tree *cond_equivalences = edge_info->cond_equivalences;
634 tree lhs = edge_info->lhs;
635 tree rhs = edge_info->rhs;
637 /* If we have a simple NAME = VALUE equivalency record it. */
638 if (lhs && TREE_CODE (lhs) == SSA_NAME)
639 record_const_or_copy (lhs, rhs);
641 /* If we have 0 = COND or 1 = COND equivalences, record them
642 into our expression hash tables. */
643 if (cond_equivalences)
644 for (i = 0; i < edge_info->max_cond_equivalences; i += 2)
646 tree expr = cond_equivalences[i];
647 tree value = cond_equivalences[i + 1];
649 record_cond (expr, value);
653 dom_thread_across_edge (walk_data, true_edge);
655 /* And restore the various tables to their state before
656 we threaded this edge. */
657 remove_local_expressions_from_table ();
660 /* Similarly for the ELSE arm. */
661 if (potentially_threadable_block (false_edge->dest))
663 struct edge_info *edge_info;
664 unsigned int i;
666 VEC_safe_push (tree, heap, const_and_copies_stack, NULL_TREE);
667 edge_info = (struct edge_info *) false_edge->aux;
669 /* If we have info associated with this edge, record it into
670 our equivalency tables. */
671 if (edge_info)
673 tree *cond_equivalences = edge_info->cond_equivalences;
674 tree lhs = edge_info->lhs;
675 tree rhs = edge_info->rhs;
677 /* If we have a simple NAME = VALUE equivalency record it. */
678 if (lhs && TREE_CODE (lhs) == SSA_NAME)
679 record_const_or_copy (lhs, rhs);
681 /* If we have 0 = COND or 1 = COND equivalences, record them
682 into our expression hash tables. */
683 if (cond_equivalences)
684 for (i = 0; i < edge_info->max_cond_equivalences; i += 2)
686 tree expr = cond_equivalences[i];
687 tree value = cond_equivalences[i + 1];
689 record_cond (expr, value);
693 /* Now thread the edge. */
694 dom_thread_across_edge (walk_data, false_edge);
696 /* No need to remove local expressions from our tables
697 or restore vars to their original value as that will
698 be done immediately below. */
702 remove_local_expressions_from_table ();
703 restore_vars_to_original_value ();
705 /* If we queued any statements to rescan in this block, then
706 go ahead and rescan them now. */
707 while (VEC_length (tree_p, stmts_to_rescan) > 0)
709 tree *stmt_p = VEC_last (tree_p, stmts_to_rescan);
710 tree stmt = *stmt_p;
711 basic_block stmt_bb = bb_for_stmt (stmt);
713 if (stmt_bb != bb)
714 break;
716 VEC_pop (tree_p, stmts_to_rescan);
717 pop_stmt_changes (stmt_p);
721 /* PHI nodes can create equivalences too.
723 Ignoring any alternatives which are the same as the result, if
724 all the alternatives are equal, then the PHI node creates an
725 equivalence. */
727 static void
728 record_equivalences_from_phis (basic_block bb)
730 tree phi;
732 for (phi = phi_nodes (bb); phi; phi = PHI_CHAIN (phi))
734 tree lhs = PHI_RESULT (phi);
735 tree rhs = NULL;
736 int i;
738 for (i = 0; i < PHI_NUM_ARGS (phi); i++)
740 tree t = PHI_ARG_DEF (phi, i);
742 /* Ignore alternatives which are the same as our LHS. Since
743 LHS is a PHI_RESULT, it is known to be a SSA_NAME, so we
744 can simply compare pointers. */
745 if (lhs == t)
746 continue;
748 /* If we have not processed an alternative yet, then set
749 RHS to this alternative. */
750 if (rhs == NULL)
751 rhs = t;
752 /* If we have processed an alternative (stored in RHS), then
753 see if it is equal to this one. If it isn't, then stop
754 the search. */
755 else if (! operand_equal_for_phi_arg_p (rhs, t))
756 break;
759 /* If we had no interesting alternatives, then all the RHS alternatives
760 must have been the same as LHS. */
761 if (!rhs)
762 rhs = lhs;
764 /* If we managed to iterate through each PHI alternative without
765 breaking out of the loop, then we have a PHI which may create
766 a useful equivalence. We do not need to record unwind data for
767 this, since this is a true assignment and not an equivalence
768 inferred from a comparison. All uses of this ssa name are dominated
769 by this assignment, so unwinding just costs time and space. */
770 if (i == PHI_NUM_ARGS (phi)
771 && may_propagate_copy (lhs, rhs))
772 SSA_NAME_VALUE (lhs) = rhs;
776 /* Ignoring loop backedges, if BB has precisely one incoming edge then
777 return that edge. Otherwise return NULL. */
778 static edge
779 single_incoming_edge_ignoring_loop_edges (basic_block bb)
781 edge retval = NULL;
782 edge e;
783 edge_iterator ei;
785 FOR_EACH_EDGE (e, ei, bb->preds)
787 /* A loop back edge can be identified by the destination of
788 the edge dominating the source of the edge. */
789 if (dominated_by_p (CDI_DOMINATORS, e->src, e->dest))
790 continue;
792 /* If we have already seen a non-loop edge, then we must have
793 multiple incoming non-loop edges and thus we return NULL. */
794 if (retval)
795 return NULL;
797 /* This is the first non-loop incoming edge we have found. Record
798 it. */
799 retval = e;
802 return retval;
805 /* Record any equivalences created by the incoming edge to BB. If BB
806 has more than one incoming edge, then no equivalence is created. */
808 static void
809 record_equivalences_from_incoming_edge (basic_block bb)
811 edge e;
812 basic_block parent;
813 struct edge_info *edge_info;
815 /* If our parent block ended with a control statement, then we may be
816 able to record some equivalences based on which outgoing edge from
817 the parent was followed. */
818 parent = get_immediate_dominator (CDI_DOMINATORS, bb);
820 e = single_incoming_edge_ignoring_loop_edges (bb);
822 /* If we had a single incoming edge from our parent block, then enter
823 any data associated with the edge into our tables. */
824 if (e && e->src == parent)
826 unsigned int i;
828 edge_info = (struct edge_info *) e->aux;
830 if (edge_info)
832 tree lhs = edge_info->lhs;
833 tree rhs = edge_info->rhs;
834 tree *cond_equivalences = edge_info->cond_equivalences;
836 if (lhs)
837 record_equality (lhs, rhs);
839 if (cond_equivalences)
841 for (i = 0; i < edge_info->max_cond_equivalences; i += 2)
843 tree expr = cond_equivalences[i];
844 tree value = cond_equivalences[i + 1];
846 record_cond (expr, value);
853 /* Dump SSA statistics on FILE. */
855 void
856 dump_dominator_optimization_stats (FILE *file)
858 long n_exprs;
860 fprintf (file, "Total number of statements: %6ld\n\n",
861 opt_stats.num_stmts);
862 fprintf (file, "Exprs considered for dominator optimizations: %6ld\n",
863 opt_stats.num_exprs_considered);
865 n_exprs = opt_stats.num_exprs_considered;
866 if (n_exprs == 0)
867 n_exprs = 1;
869 fprintf (file, " Redundant expressions eliminated: %6ld (%.0f%%)\n",
870 opt_stats.num_re, PERCENT (opt_stats.num_re,
871 n_exprs));
872 fprintf (file, " Constants propagated: %6ld\n",
873 opt_stats.num_const_prop);
874 fprintf (file, " Copies propagated: %6ld\n",
875 opt_stats.num_copy_prop);
877 fprintf (file, "\nHash table statistics:\n");
879 fprintf (file, " avail_exprs: ");
880 htab_statistics (file, avail_exprs);
884 /* Dump SSA statistics on stderr. */
886 void
887 debug_dominator_optimization_stats (void)
889 dump_dominator_optimization_stats (stderr);
893 /* Dump statistics for the hash table HTAB. */
895 static void
896 htab_statistics (FILE *file, htab_t htab)
898 fprintf (file, "size %ld, %ld elements, %f collision/search ratio\n",
899 (long) htab_size (htab),
900 (long) htab_elements (htab),
901 htab_collisions (htab));
904 /* Enter a statement into the true/false expression hash table indicating
905 that the condition COND has the value VALUE. */
907 static void
908 record_cond (tree cond, tree value)
910 struct expr_hash_elt *element = XCNEW (struct expr_hash_elt);
911 void **slot;
913 initialize_hash_element (cond, value, element);
915 slot = htab_find_slot_with_hash (avail_exprs, (void *)element,
916 element->hash, INSERT);
917 if (*slot == NULL)
919 *slot = (void *) element;
920 VEC_safe_push (tree, heap, avail_exprs_stack, cond);
922 else
923 free (element);
926 /* Build a new conditional using NEW_CODE, OP0 and OP1 and store
927 the new conditional into *p, then store a boolean_true_node
928 into *(p + 1). */
930 static void
931 build_and_record_new_cond (enum tree_code new_code, tree op0, tree op1, tree *p)
933 *p = build2 (new_code, boolean_type_node, op0, op1);
934 p++;
935 *p = boolean_true_node;
938 /* Record that COND is true and INVERTED is false into the edge information
939 structure. Also record that any conditions dominated by COND are true
940 as well.
942 For example, if a < b is true, then a <= b must also be true. */
944 static void
945 record_conditions (struct edge_info *edge_info, tree cond, tree inverted)
947 tree op0, op1;
949 if (!COMPARISON_CLASS_P (cond))
950 return;
952 op0 = TREE_OPERAND (cond, 0);
953 op1 = TREE_OPERAND (cond, 1);
955 switch (TREE_CODE (cond))
957 case LT_EXPR:
958 case GT_EXPR:
959 if (FLOAT_TYPE_P (TREE_TYPE (op0)))
961 edge_info->max_cond_equivalences = 12;
962 edge_info->cond_equivalences = XNEWVEC (tree, 12);
963 build_and_record_new_cond (ORDERED_EXPR, op0, op1,
964 &edge_info->cond_equivalences[8]);
965 build_and_record_new_cond (LTGT_EXPR, op0, op1,
966 &edge_info->cond_equivalences[10]);
968 else
970 edge_info->max_cond_equivalences = 8;
971 edge_info->cond_equivalences = XNEWVEC (tree, 8);
974 build_and_record_new_cond ((TREE_CODE (cond) == LT_EXPR
975 ? LE_EXPR : GE_EXPR),
976 op0, op1, &edge_info->cond_equivalences[4]);
977 build_and_record_new_cond (NE_EXPR, op0, op1,
978 &edge_info->cond_equivalences[6]);
979 break;
981 case GE_EXPR:
982 case LE_EXPR:
983 if (FLOAT_TYPE_P (TREE_TYPE (op0)))
985 edge_info->max_cond_equivalences = 6;
986 edge_info->cond_equivalences = XNEWVEC (tree, 6);
987 build_and_record_new_cond (ORDERED_EXPR, op0, op1,
988 &edge_info->cond_equivalences[4]);
990 else
992 edge_info->max_cond_equivalences = 4;
993 edge_info->cond_equivalences = XNEWVEC (tree, 4);
995 break;
997 case EQ_EXPR:
998 if (FLOAT_TYPE_P (TREE_TYPE (op0)))
1000 edge_info->max_cond_equivalences = 10;
1001 edge_info->cond_equivalences = XNEWVEC (tree, 10);
1002 build_and_record_new_cond (ORDERED_EXPR, op0, op1,
1003 &edge_info->cond_equivalences[8]);
1005 else
1007 edge_info->max_cond_equivalences = 8;
1008 edge_info->cond_equivalences = XNEWVEC (tree, 8);
1010 build_and_record_new_cond (LE_EXPR, op0, op1,
1011 &edge_info->cond_equivalences[4]);
1012 build_and_record_new_cond (GE_EXPR, op0, op1,
1013 &edge_info->cond_equivalences[6]);
1014 break;
1016 case UNORDERED_EXPR:
1017 edge_info->max_cond_equivalences = 16;
1018 edge_info->cond_equivalences = XNEWVEC (tree, 16);
1019 build_and_record_new_cond (NE_EXPR, op0, op1,
1020 &edge_info->cond_equivalences[4]);
1021 build_and_record_new_cond (UNLE_EXPR, op0, op1,
1022 &edge_info->cond_equivalences[6]);
1023 build_and_record_new_cond (UNGE_EXPR, op0, op1,
1024 &edge_info->cond_equivalences[8]);
1025 build_and_record_new_cond (UNEQ_EXPR, op0, op1,
1026 &edge_info->cond_equivalences[10]);
1027 build_and_record_new_cond (UNLT_EXPR, op0, op1,
1028 &edge_info->cond_equivalences[12]);
1029 build_and_record_new_cond (UNGT_EXPR, op0, op1,
1030 &edge_info->cond_equivalences[14]);
1031 break;
1033 case UNLT_EXPR:
1034 case UNGT_EXPR:
1035 edge_info->max_cond_equivalences = 8;
1036 edge_info->cond_equivalences = XNEWVEC (tree, 8);
1037 build_and_record_new_cond ((TREE_CODE (cond) == UNLT_EXPR
1038 ? UNLE_EXPR : UNGE_EXPR),
1039 op0, op1, &edge_info->cond_equivalences[4]);
1040 build_and_record_new_cond (NE_EXPR, op0, op1,
1041 &edge_info->cond_equivalences[6]);
1042 break;
1044 case UNEQ_EXPR:
1045 edge_info->max_cond_equivalences = 8;
1046 edge_info->cond_equivalences = XNEWVEC (tree, 8);
1047 build_and_record_new_cond (UNLE_EXPR, op0, op1,
1048 &edge_info->cond_equivalences[4]);
1049 build_and_record_new_cond (UNGE_EXPR, op0, op1,
1050 &edge_info->cond_equivalences[6]);
1051 break;
1053 case LTGT_EXPR:
1054 edge_info->max_cond_equivalences = 8;
1055 edge_info->cond_equivalences = XNEWVEC (tree, 8);
1056 build_and_record_new_cond (NE_EXPR, op0, op1,
1057 &edge_info->cond_equivalences[4]);
1058 build_and_record_new_cond (ORDERED_EXPR, op0, op1,
1059 &edge_info->cond_equivalences[6]);
1060 break;
1062 default:
1063 edge_info->max_cond_equivalences = 4;
1064 edge_info->cond_equivalences = XNEWVEC (tree, 4);
1065 break;
1068 /* Now store the original true and false conditions into the first
1069 two slots. */
1070 edge_info->cond_equivalences[0] = cond;
1071 edge_info->cond_equivalences[1] = boolean_true_node;
1072 edge_info->cond_equivalences[2] = inverted;
1073 edge_info->cond_equivalences[3] = boolean_false_node;
1076 /* A helper function for record_const_or_copy and record_equality.
1077 Do the work of recording the value and undo info. */
1079 static void
1080 record_const_or_copy_1 (tree x, tree y, tree prev_x)
1082 SSA_NAME_VALUE (x) = y;
1084 VEC_reserve (tree, heap, const_and_copies_stack, 2);
1085 VEC_quick_push (tree, const_and_copies_stack, prev_x);
1086 VEC_quick_push (tree, const_and_copies_stack, x);
1090 /* Return the loop depth of the basic block of the defining statement of X.
1091 This number should not be treated as absolutely correct because the loop
1092 information may not be completely up-to-date when dom runs. However, it
1093 will be relatively correct, and as more passes are taught to keep loop info
1094 up to date, the result will become more and more accurate. */
1097 loop_depth_of_name (tree x)
1099 tree defstmt;
1100 basic_block defbb;
1102 /* If it's not an SSA_NAME, we have no clue where the definition is. */
1103 if (TREE_CODE (x) != SSA_NAME)
1104 return 0;
1106 /* Otherwise return the loop depth of the defining statement's bb.
1107 Note that there may not actually be a bb for this statement, if the
1108 ssa_name is live on entry. */
1109 defstmt = SSA_NAME_DEF_STMT (x);
1110 defbb = bb_for_stmt (defstmt);
1111 if (!defbb)
1112 return 0;
1114 return defbb->loop_depth;
1118 /* Record that X is equal to Y in const_and_copies. Record undo
1119 information in the block-local vector. */
1121 static void
1122 record_const_or_copy (tree x, tree y)
1124 tree prev_x = SSA_NAME_VALUE (x);
1126 if (TREE_CODE (y) == SSA_NAME)
1128 tree tmp = SSA_NAME_VALUE (y);
1129 if (tmp)
1130 y = tmp;
1133 record_const_or_copy_1 (x, y, prev_x);
1136 /* Similarly, but assume that X and Y are the two operands of an EQ_EXPR.
1137 This constrains the cases in which we may treat this as assignment. */
1139 static void
1140 record_equality (tree x, tree y)
1142 tree prev_x = NULL, prev_y = NULL;
1144 if (TREE_CODE (x) == SSA_NAME)
1145 prev_x = SSA_NAME_VALUE (x);
1146 if (TREE_CODE (y) == SSA_NAME)
1147 prev_y = SSA_NAME_VALUE (y);
1149 /* If one of the previous values is invariant, or invariant in more loops
1150 (by depth), then use that.
1151 Otherwise it doesn't matter which value we choose, just so
1152 long as we canonicalize on one value. */
1153 if (TREE_INVARIANT (y))
1155 else if (TREE_INVARIANT (x) || (loop_depth_of_name (x) <= loop_depth_of_name (y)))
1156 prev_x = x, x = y, y = prev_x, prev_x = prev_y;
1157 else if (prev_x && TREE_INVARIANT (prev_x))
1158 x = y, y = prev_x, prev_x = prev_y;
1159 else if (prev_y && TREE_CODE (prev_y) != VALUE_HANDLE)
1160 y = prev_y;
1162 /* After the swapping, we must have one SSA_NAME. */
1163 if (TREE_CODE (x) != SSA_NAME)
1164 return;
1166 /* For IEEE, -0.0 == 0.0, so we don't necessarily know the sign of a
1167 variable compared against zero. If we're honoring signed zeros,
1168 then we cannot record this value unless we know that the value is
1169 nonzero. */
1170 if (HONOR_SIGNED_ZEROS (TYPE_MODE (TREE_TYPE (x)))
1171 && (TREE_CODE (y) != REAL_CST
1172 || REAL_VALUES_EQUAL (dconst0, TREE_REAL_CST (y))))
1173 return;
1175 record_const_or_copy_1 (x, y, prev_x);
1178 /* Returns true when STMT is a simple iv increment. It detects the
1179 following situation:
1181 i_1 = phi (..., i_2)
1182 i_2 = i_1 +/- ... */
1184 static bool
1185 simple_iv_increment_p (tree stmt)
1187 tree lhs, rhs, preinc, phi;
1188 unsigned i;
1190 if (TREE_CODE (stmt) != GIMPLE_MODIFY_STMT)
1191 return false;
1193 lhs = GIMPLE_STMT_OPERAND (stmt, 0);
1194 if (TREE_CODE (lhs) != SSA_NAME)
1195 return false;
1197 rhs = GIMPLE_STMT_OPERAND (stmt, 1);
1199 if (TREE_CODE (rhs) != PLUS_EXPR
1200 && TREE_CODE (rhs) != MINUS_EXPR)
1201 return false;
1203 preinc = TREE_OPERAND (rhs, 0);
1204 if (TREE_CODE (preinc) != SSA_NAME)
1205 return false;
1207 phi = SSA_NAME_DEF_STMT (preinc);
1208 if (TREE_CODE (phi) != PHI_NODE)
1209 return false;
1211 for (i = 0; i < (unsigned) PHI_NUM_ARGS (phi); i++)
1212 if (PHI_ARG_DEF (phi, i) == lhs)
1213 return true;
1215 return false;
1218 /* CONST_AND_COPIES is a table which maps an SSA_NAME to the current
1219 known value for that SSA_NAME (or NULL if no value is known).
1221 Propagate values from CONST_AND_COPIES into the PHI nodes of the
1222 successors of BB. */
1224 static void
1225 cprop_into_successor_phis (basic_block bb)
1227 edge e;
1228 edge_iterator ei;
1230 FOR_EACH_EDGE (e, ei, bb->succs)
1232 tree phi;
1233 int indx;
1235 /* If this is an abnormal edge, then we do not want to copy propagate
1236 into the PHI alternative associated with this edge. */
1237 if (e->flags & EDGE_ABNORMAL)
1238 continue;
1240 phi = phi_nodes (e->dest);
1241 if (! phi)
1242 continue;
1244 indx = e->dest_idx;
1245 for ( ; phi; phi = PHI_CHAIN (phi))
1247 tree new;
1248 use_operand_p orig_p;
1249 tree orig;
1251 /* The alternative may be associated with a constant, so verify
1252 it is an SSA_NAME before doing anything with it. */
1253 orig_p = PHI_ARG_DEF_PTR (phi, indx);
1254 orig = USE_FROM_PTR (orig_p);
1255 if (TREE_CODE (orig) != SSA_NAME)
1256 continue;
1258 /* If we have *ORIG_P in our constant/copy table, then replace
1259 ORIG_P with its value in our constant/copy table. */
1260 new = SSA_NAME_VALUE (orig);
1261 if (new
1262 && new != orig
1263 && (TREE_CODE (new) == SSA_NAME
1264 || is_gimple_min_invariant (new))
1265 && may_propagate_copy (orig, new))
1266 propagate_value (orig_p, new);
1271 /* We have finished optimizing BB, record any information implied by
1272 taking a specific outgoing edge from BB. */
1274 static void
1275 record_edge_info (basic_block bb)
1277 block_stmt_iterator bsi = bsi_last (bb);
1278 struct edge_info *edge_info;
1280 if (! bsi_end_p (bsi))
1282 tree stmt = bsi_stmt (bsi);
1284 if (stmt && TREE_CODE (stmt) == SWITCH_EXPR)
1286 tree cond = SWITCH_COND (stmt);
1288 if (TREE_CODE (cond) == SSA_NAME)
1290 tree labels = SWITCH_LABELS (stmt);
1291 int i, n_labels = TREE_VEC_LENGTH (labels);
1292 tree *info = XCNEWVEC (tree, last_basic_block);
1293 edge e;
1294 edge_iterator ei;
1296 for (i = 0; i < n_labels; i++)
1298 tree label = TREE_VEC_ELT (labels, i);
1299 basic_block target_bb = label_to_block (CASE_LABEL (label));
1301 if (CASE_HIGH (label)
1302 || !CASE_LOW (label)
1303 || info[target_bb->index])
1304 info[target_bb->index] = error_mark_node;
1305 else
1306 info[target_bb->index] = label;
1309 FOR_EACH_EDGE (e, ei, bb->succs)
1311 basic_block target_bb = e->dest;
1312 tree node = info[target_bb->index];
1314 if (node != NULL && node != error_mark_node)
1316 tree x = fold_convert (TREE_TYPE (cond), CASE_LOW (node));
1317 edge_info = allocate_edge_info (e);
1318 edge_info->lhs = cond;
1319 edge_info->rhs = x;
1322 free (info);
1326 /* A COND_EXPR may create equivalences too. */
1327 if (stmt && TREE_CODE (stmt) == COND_EXPR)
1329 tree cond = COND_EXPR_COND (stmt);
1330 edge true_edge;
1331 edge false_edge;
1333 extract_true_false_edges_from_block (bb, &true_edge, &false_edge);
1335 /* If the conditional is a single variable 'X', record 'X = 1'
1336 for the true edge and 'X = 0' on the false edge. */
1337 if (SSA_VAR_P (cond))
1339 struct edge_info *edge_info;
1341 edge_info = allocate_edge_info (true_edge);
1342 edge_info->lhs = cond;
1343 edge_info->rhs = constant_boolean_node (1, TREE_TYPE (cond));
1345 edge_info = allocate_edge_info (false_edge);
1346 edge_info->lhs = cond;
1347 edge_info->rhs = constant_boolean_node (0, TREE_TYPE (cond));
1349 /* Equality tests may create one or two equivalences. */
1350 else if (COMPARISON_CLASS_P (cond))
1352 tree op0 = TREE_OPERAND (cond, 0);
1353 tree op1 = TREE_OPERAND (cond, 1);
1355 /* Special case comparing booleans against a constant as we
1356 know the value of OP0 on both arms of the branch. i.e., we
1357 can record an equivalence for OP0 rather than COND. */
1358 if ((TREE_CODE (cond) == EQ_EXPR || TREE_CODE (cond) == NE_EXPR)
1359 && TREE_CODE (op0) == SSA_NAME
1360 && TREE_CODE (TREE_TYPE (op0)) == BOOLEAN_TYPE
1361 && is_gimple_min_invariant (op1))
1363 if (TREE_CODE (cond) == EQ_EXPR)
1365 edge_info = allocate_edge_info (true_edge);
1366 edge_info->lhs = op0;
1367 edge_info->rhs = (integer_zerop (op1)
1368 ? boolean_false_node
1369 : boolean_true_node);
1371 edge_info = allocate_edge_info (false_edge);
1372 edge_info->lhs = op0;
1373 edge_info->rhs = (integer_zerop (op1)
1374 ? boolean_true_node
1375 : boolean_false_node);
1377 else
1379 edge_info = allocate_edge_info (true_edge);
1380 edge_info->lhs = op0;
1381 edge_info->rhs = (integer_zerop (op1)
1382 ? boolean_true_node
1383 : boolean_false_node);
1385 edge_info = allocate_edge_info (false_edge);
1386 edge_info->lhs = op0;
1387 edge_info->rhs = (integer_zerop (op1)
1388 ? boolean_false_node
1389 : boolean_true_node);
1393 else if (is_gimple_min_invariant (op0)
1394 && (TREE_CODE (op1) == SSA_NAME
1395 || is_gimple_min_invariant (op1)))
1397 tree inverted = invert_truthvalue (cond);
1398 struct edge_info *edge_info;
1400 edge_info = allocate_edge_info (true_edge);
1401 record_conditions (edge_info, cond, inverted);
1403 if (TREE_CODE (cond) == EQ_EXPR)
1405 edge_info->lhs = op1;
1406 edge_info->rhs = op0;
1409 edge_info = allocate_edge_info (false_edge);
1410 record_conditions (edge_info, inverted, cond);
1412 if (TREE_CODE (cond) == NE_EXPR)
1414 edge_info->lhs = op1;
1415 edge_info->rhs = op0;
1419 else if (TREE_CODE (op0) == SSA_NAME
1420 && (is_gimple_min_invariant (op1)
1421 || TREE_CODE (op1) == SSA_NAME))
1423 tree inverted = invert_truthvalue (cond);
1424 struct edge_info *edge_info;
1426 edge_info = allocate_edge_info (true_edge);
1427 record_conditions (edge_info, cond, inverted);
1429 if (TREE_CODE (cond) == EQ_EXPR)
1431 edge_info->lhs = op0;
1432 edge_info->rhs = op1;
1435 edge_info = allocate_edge_info (false_edge);
1436 record_conditions (edge_info, inverted, cond);
1438 if (TREE_CODE (cond) == NE_EXPR)
1440 edge_info->lhs = op0;
1441 edge_info->rhs = op1;
1446 /* ??? TRUTH_NOT_EXPR can create an equivalence too. */
1451 /* Propagate information from BB to its outgoing edges.
1453 This can include equivalency information implied by control statements
1454 at the end of BB and const/copy propagation into PHIs in BB's
1455 successor blocks. */
1457 static void
1458 propagate_to_outgoing_edges (struct dom_walk_data *walk_data ATTRIBUTE_UNUSED,
1459 basic_block bb)
1461 record_edge_info (bb);
1462 cprop_into_successor_phis (bb);
1465 /* Search for redundant computations in STMT. If any are found, then
1466 replace them with the variable holding the result of the computation.
1468 If safe, record this expression into the available expression hash
1469 table. */
1471 static bool
1472 eliminate_redundant_computations (tree stmt)
1474 tree *expr_p, def = NULL_TREE;
1475 bool insert = true;
1476 tree cached_lhs;
1477 bool retval = false;
1478 bool modify_expr_p = false;
1480 if (TREE_CODE (stmt) == GIMPLE_MODIFY_STMT)
1481 def = GIMPLE_STMT_OPERAND (stmt, 0);
1483 /* Certain expressions on the RHS can be optimized away, but can not
1484 themselves be entered into the hash tables. */
1485 if (! def
1486 || TREE_CODE (def) != SSA_NAME
1487 || SSA_NAME_OCCURS_IN_ABNORMAL_PHI (def)
1488 || !ZERO_SSA_OPERANDS (stmt, SSA_OP_VDEF)
1489 /* Do not record equivalences for increments of ivs. This would create
1490 overlapping live ranges for a very questionable gain. */
1491 || simple_iv_increment_p (stmt))
1492 insert = false;
1494 /* Check if the expression has been computed before. */
1495 cached_lhs = lookup_avail_expr (stmt, insert);
1497 opt_stats.num_exprs_considered++;
1499 /* Get a pointer to the expression we are trying to optimize. */
1500 if (TREE_CODE (stmt) == COND_EXPR)
1501 expr_p = &COND_EXPR_COND (stmt);
1502 else if (TREE_CODE (stmt) == SWITCH_EXPR)
1503 expr_p = &SWITCH_COND (stmt);
1504 else if (TREE_CODE (stmt) == RETURN_EXPR && TREE_OPERAND (stmt, 0))
1506 expr_p = &GIMPLE_STMT_OPERAND (TREE_OPERAND (stmt, 0), 1);
1507 modify_expr_p = true;
1509 else
1511 expr_p = &GENERIC_TREE_OPERAND (stmt, 1);
1512 modify_expr_p = true;
1515 /* It is safe to ignore types here since we have already done
1516 type checking in the hashing and equality routines. In fact
1517 type checking here merely gets in the way of constant
1518 propagation. Also, make sure that it is safe to propagate
1519 CACHED_LHS into *EXPR_P. */
1520 if (cached_lhs
1521 && ((TREE_CODE (cached_lhs) != SSA_NAME
1522 && (modify_expr_p
1523 || tree_ssa_useless_type_conversion_1 (TREE_TYPE (*expr_p),
1524 TREE_TYPE (cached_lhs))))
1525 || may_propagate_copy (*expr_p, cached_lhs)))
1527 if (dump_file && (dump_flags & TDF_DETAILS))
1529 fprintf (dump_file, " Replaced redundant expr '");
1530 print_generic_expr (dump_file, *expr_p, dump_flags);
1531 fprintf (dump_file, "' with '");
1532 print_generic_expr (dump_file, cached_lhs, dump_flags);
1533 fprintf (dump_file, "'\n");
1536 opt_stats.num_re++;
1538 #if defined ENABLE_CHECKING
1539 gcc_assert (TREE_CODE (cached_lhs) == SSA_NAME
1540 || is_gimple_min_invariant (cached_lhs));
1541 #endif
1543 if (TREE_CODE (cached_lhs) == ADDR_EXPR
1544 || (POINTER_TYPE_P (TREE_TYPE (*expr_p))
1545 && is_gimple_min_invariant (cached_lhs)))
1546 retval = true;
1548 if (modify_expr_p
1549 && !tree_ssa_useless_type_conversion_1 (TREE_TYPE (*expr_p),
1550 TREE_TYPE (cached_lhs)))
1551 cached_lhs = fold_convert (TREE_TYPE (*expr_p), cached_lhs);
1553 propagate_tree_value (expr_p, cached_lhs);
1554 mark_stmt_modified (stmt);
1556 return retval;
1559 /* STMT, a GIMPLE_MODIFY_STMT, may create certain equivalences, in either
1560 the available expressions table or the const_and_copies table.
1561 Detect and record those equivalences. */
1563 static void
1564 record_equivalences_from_stmt (tree stmt, int may_optimize_p, stmt_ann_t ann)
1566 tree lhs = GIMPLE_STMT_OPERAND (stmt, 0);
1567 enum tree_code lhs_code = TREE_CODE (lhs);
1569 if (lhs_code == SSA_NAME)
1571 tree rhs = GIMPLE_STMT_OPERAND (stmt, 1);
1573 /* Strip away any useless type conversions. */
1574 STRIP_USELESS_TYPE_CONVERSION (rhs);
1576 /* If the RHS of the assignment is a constant or another variable that
1577 may be propagated, register it in the CONST_AND_COPIES table. We
1578 do not need to record unwind data for this, since this is a true
1579 assignment and not an equivalence inferred from a comparison. All
1580 uses of this ssa name are dominated by this assignment, so unwinding
1581 just costs time and space. */
1582 if (may_optimize_p
1583 && (TREE_CODE (rhs) == SSA_NAME
1584 || is_gimple_min_invariant (rhs)))
1585 SSA_NAME_VALUE (lhs) = rhs;
1588 /* A memory store, even an aliased store, creates a useful
1589 equivalence. By exchanging the LHS and RHS, creating suitable
1590 vops and recording the result in the available expression table,
1591 we may be able to expose more redundant loads. */
1592 if (!ann->has_volatile_ops
1593 && stmt_references_memory_p (stmt)
1594 && (TREE_CODE (GIMPLE_STMT_OPERAND (stmt, 1)) == SSA_NAME
1595 || is_gimple_min_invariant (GIMPLE_STMT_OPERAND (stmt, 1)))
1596 && !is_gimple_reg (lhs))
1598 tree rhs = GIMPLE_STMT_OPERAND (stmt, 1);
1599 tree new;
1601 /* FIXME: If the LHS of the assignment is a bitfield and the RHS
1602 is a constant, we need to adjust the constant to fit into the
1603 type of the LHS. If the LHS is a bitfield and the RHS is not
1604 a constant, then we can not record any equivalences for this
1605 statement since we would need to represent the widening or
1606 narrowing of RHS. This fixes gcc.c-torture/execute/921016-1.c
1607 and should not be necessary if GCC represented bitfields
1608 properly. */
1609 if (lhs_code == COMPONENT_REF
1610 && DECL_BIT_FIELD (TREE_OPERAND (lhs, 1)))
1612 if (TREE_CONSTANT (rhs))
1613 rhs = widen_bitfield (rhs, TREE_OPERAND (lhs, 1), lhs);
1614 else
1615 rhs = NULL;
1617 /* If the value overflowed, then we can not use this equivalence. */
1618 if (rhs && ! is_gimple_min_invariant (rhs))
1619 rhs = NULL;
1622 if (rhs)
1624 /* Build a new statement with the RHS and LHS exchanged. */
1625 new = build_gimple_modify_stmt (rhs, lhs);
1627 create_ssa_artificial_load_stmt (new, stmt);
1629 /* Finally enter the statement into the available expression
1630 table. */
1631 lookup_avail_expr (new, true);
1636 /* Replace *OP_P in STMT with any known equivalent value for *OP_P from
1637 CONST_AND_COPIES. */
1639 static bool
1640 cprop_operand (tree stmt, use_operand_p op_p)
1642 bool may_have_exposed_new_symbols = false;
1643 tree val;
1644 tree op = USE_FROM_PTR (op_p);
1646 /* If the operand has a known constant value or it is known to be a
1647 copy of some other variable, use the value or copy stored in
1648 CONST_AND_COPIES. */
1649 val = SSA_NAME_VALUE (op);
1650 if (val && val != op && TREE_CODE (val) != VALUE_HANDLE)
1652 tree op_type, val_type;
1654 /* Do not change the base variable in the virtual operand
1655 tables. That would make it impossible to reconstruct
1656 the renamed virtual operand if we later modify this
1657 statement. Also only allow the new value to be an SSA_NAME
1658 for propagation into virtual operands. */
1659 if (!is_gimple_reg (op)
1660 && (TREE_CODE (val) != SSA_NAME
1661 || is_gimple_reg (val)
1662 || get_virtual_var (val) != get_virtual_var (op)))
1663 return false;
1665 /* Do not replace hard register operands in asm statements. */
1666 if (TREE_CODE (stmt) == ASM_EXPR
1667 && !may_propagate_copy_into_asm (op))
1668 return false;
1670 /* Get the toplevel type of each operand. */
1671 op_type = TREE_TYPE (op);
1672 val_type = TREE_TYPE (val);
1674 /* While both types are pointers, get the type of the object
1675 pointed to. */
1676 while (POINTER_TYPE_P (op_type) && POINTER_TYPE_P (val_type))
1678 op_type = TREE_TYPE (op_type);
1679 val_type = TREE_TYPE (val_type);
1682 /* Make sure underlying types match before propagating a constant by
1683 converting the constant to the proper type. Note that convert may
1684 return a non-gimple expression, in which case we ignore this
1685 propagation opportunity. */
1686 if (TREE_CODE (val) != SSA_NAME)
1688 if (!lang_hooks.types_compatible_p (op_type, val_type))
1690 val = fold_convert (TREE_TYPE (op), val);
1691 if (!is_gimple_min_invariant (val))
1692 return false;
1696 /* Certain operands are not allowed to be copy propagated due
1697 to their interaction with exception handling and some GCC
1698 extensions. */
1699 else if (!may_propagate_copy (op, val))
1700 return false;
1702 /* Do not propagate copies if the propagated value is at a deeper loop
1703 depth than the propagatee. Otherwise, this may move loop variant
1704 variables outside of their loops and prevent coalescing
1705 opportunities. If the value was loop invariant, it will be hoisted
1706 by LICM and exposed for copy propagation. */
1707 if (loop_depth_of_name (val) > loop_depth_of_name (op))
1708 return false;
1710 /* Dump details. */
1711 if (dump_file && (dump_flags & TDF_DETAILS))
1713 fprintf (dump_file, " Replaced '");
1714 print_generic_expr (dump_file, op, dump_flags);
1715 fprintf (dump_file, "' with %s '",
1716 (TREE_CODE (val) != SSA_NAME ? "constant" : "variable"));
1717 print_generic_expr (dump_file, val, dump_flags);
1718 fprintf (dump_file, "'\n");
1721 /* If VAL is an ADDR_EXPR or a constant of pointer type, note
1722 that we may have exposed a new symbol for SSA renaming. */
1723 if (TREE_CODE (val) == ADDR_EXPR
1724 || (POINTER_TYPE_P (TREE_TYPE (op))
1725 && is_gimple_min_invariant (val)))
1726 may_have_exposed_new_symbols = true;
1728 if (TREE_CODE (val) != SSA_NAME)
1729 opt_stats.num_const_prop++;
1730 else
1731 opt_stats.num_copy_prop++;
1733 propagate_value (op_p, val);
1735 /* And note that we modified this statement. This is now
1736 safe, even if we changed virtual operands since we will
1737 rescan the statement and rewrite its operands again. */
1738 mark_stmt_modified (stmt);
1740 return may_have_exposed_new_symbols;
1743 /* CONST_AND_COPIES is a table which maps an SSA_NAME to the current
1744 known value for that SSA_NAME (or NULL if no value is known).
1746 Propagate values from CONST_AND_COPIES into the uses, vuses and
1747 vdef_ops of STMT. */
1749 static bool
1750 cprop_into_stmt (tree stmt)
1752 bool may_have_exposed_new_symbols = false;
1753 use_operand_p op_p;
1754 ssa_op_iter iter;
1756 FOR_EACH_SSA_USE_OPERAND (op_p, stmt, iter, SSA_OP_ALL_USES)
1758 if (TREE_CODE (USE_FROM_PTR (op_p)) == SSA_NAME)
1759 may_have_exposed_new_symbols |= cprop_operand (stmt, op_p);
1762 return may_have_exposed_new_symbols;
1766 /* Optimize the statement pointed to by iterator SI.
1768 We try to perform some simplistic global redundancy elimination and
1769 constant propagation:
1771 1- To detect global redundancy, we keep track of expressions that have
1772 been computed in this block and its dominators. If we find that the
1773 same expression is computed more than once, we eliminate repeated
1774 computations by using the target of the first one.
1776 2- Constant values and copy assignments. This is used to do very
1777 simplistic constant and copy propagation. When a constant or copy
1778 assignment is found, we map the value on the RHS of the assignment to
1779 the variable in the LHS in the CONST_AND_COPIES table. */
1781 static void
1782 optimize_stmt (struct dom_walk_data *walk_data ATTRIBUTE_UNUSED,
1783 basic_block bb, block_stmt_iterator si)
1785 stmt_ann_t ann;
1786 tree stmt, old_stmt;
1787 bool may_optimize_p;
1788 bool may_have_exposed_new_symbols = false;
1790 old_stmt = stmt = bsi_stmt (si);
1792 if (TREE_CODE (stmt) == COND_EXPR)
1793 canonicalize_comparison (stmt);
1795 update_stmt_if_modified (stmt);
1796 ann = stmt_ann (stmt);
1797 opt_stats.num_stmts++;
1798 may_have_exposed_new_symbols = false;
1799 push_stmt_changes (bsi_stmt_ptr (si));
1801 if (dump_file && (dump_flags & TDF_DETAILS))
1803 fprintf (dump_file, "Optimizing statement ");
1804 print_generic_stmt (dump_file, stmt, TDF_SLIM);
1807 /* Const/copy propagate into USES, VUSES and the RHS of VDEFs. */
1808 may_have_exposed_new_symbols = cprop_into_stmt (stmt);
1810 /* If the statement has been modified with constant replacements,
1811 fold its RHS before checking for redundant computations. */
1812 if (ann->modified)
1814 tree rhs;
1816 /* Try to fold the statement making sure that STMT is kept
1817 up to date. */
1818 if (fold_stmt (bsi_stmt_ptr (si)))
1820 stmt = bsi_stmt (si);
1821 ann = stmt_ann (stmt);
1823 if (dump_file && (dump_flags & TDF_DETAILS))
1825 fprintf (dump_file, " Folded to: ");
1826 print_generic_stmt (dump_file, stmt, TDF_SLIM);
1830 rhs = get_rhs (stmt);
1831 if (rhs && TREE_CODE (rhs) == ADDR_EXPR)
1832 recompute_tree_invariant_for_addr_expr (rhs);
1834 /* Constant/copy propagation above may change the set of
1835 virtual operands associated with this statement. Folding
1836 may remove the need for some virtual operands.
1838 Indicate we will need to rescan and rewrite the statement. */
1839 may_have_exposed_new_symbols = true;
1842 /* Check for redundant computations. Do this optimization only
1843 for assignments that have no volatile ops and conditionals. */
1844 may_optimize_p = (!ann->has_volatile_ops
1845 && ((TREE_CODE (stmt) == RETURN_EXPR
1846 && TREE_OPERAND (stmt, 0)
1847 && TREE_CODE (TREE_OPERAND (stmt, 0))
1848 == GIMPLE_MODIFY_STMT
1849 && ! (TREE_SIDE_EFFECTS
1850 (GIMPLE_STMT_OPERAND
1851 (TREE_OPERAND (stmt, 0), 1))))
1852 || (TREE_CODE (stmt) == GIMPLE_MODIFY_STMT
1853 && ! TREE_SIDE_EFFECTS (GIMPLE_STMT_OPERAND (stmt,
1854 1)))
1855 || TREE_CODE (stmt) == COND_EXPR
1856 || TREE_CODE (stmt) == SWITCH_EXPR));
1858 if (may_optimize_p)
1859 may_have_exposed_new_symbols |= eliminate_redundant_computations (stmt);
1861 /* Record any additional equivalences created by this statement. */
1862 if (TREE_CODE (stmt) == GIMPLE_MODIFY_STMT)
1863 record_equivalences_from_stmt (stmt, may_optimize_p, ann);
1865 /* If STMT is a COND_EXPR and it was modified, then we may know
1866 where it goes. If that is the case, then mark the CFG as altered.
1868 This will cause us to later call remove_unreachable_blocks and
1869 cleanup_tree_cfg when it is safe to do so. It is not safe to
1870 clean things up here since removal of edges and such can trigger
1871 the removal of PHI nodes, which in turn can release SSA_NAMEs to
1872 the manager.
1874 That's all fine and good, except that once SSA_NAMEs are released
1875 to the manager, we must not call create_ssa_name until all references
1876 to released SSA_NAMEs have been eliminated.
1878 All references to the deleted SSA_NAMEs can not be eliminated until
1879 we remove unreachable blocks.
1881 We can not remove unreachable blocks until after we have completed
1882 any queued jump threading.
1884 We can not complete any queued jump threads until we have taken
1885 appropriate variables out of SSA form. Taking variables out of
1886 SSA form can call create_ssa_name and thus we lose.
1888 Ultimately I suspect we're going to need to change the interface
1889 into the SSA_NAME manager. */
1890 if (ann->modified)
1892 tree val = NULL;
1894 if (TREE_CODE (stmt) == COND_EXPR)
1895 val = COND_EXPR_COND (stmt);
1896 else if (TREE_CODE (stmt) == SWITCH_EXPR)
1897 val = SWITCH_COND (stmt);
1899 if (val && TREE_CODE (val) == INTEGER_CST && find_taken_edge (bb, val))
1900 cfg_altered = true;
1902 /* If we simplified a statement in such a way as to be shown that it
1903 cannot trap, update the eh information and the cfg to match. */
1904 if (maybe_clean_or_replace_eh_stmt (old_stmt, stmt))
1906 bitmap_set_bit (need_eh_cleanup, bb->index);
1907 if (dump_file && (dump_flags & TDF_DETAILS))
1908 fprintf (dump_file, " Flagged to clear EH edges.\n");
1912 if (may_have_exposed_new_symbols)
1914 /* Queue the statement to be re-scanned after all the
1915 AVAIL_EXPRS have been processed. The change buffer stack for
1916 all the pushed statements will be processed when this queue
1917 is emptied. */
1918 VEC_safe_push (tree_p, heap, stmts_to_rescan, bsi_stmt_ptr (si));
1920 else
1922 /* Otherwise, just discard the recently pushed change buffer. If
1923 not, the STMTS_TO_RESCAN queue will get out of synch with the
1924 change buffer stack. */
1925 discard_stmt_changes (bsi_stmt_ptr (si));
1929 /* Search for an existing instance of STMT in the AVAIL_EXPRS table. If
1930 found, return its LHS. Otherwise insert STMT in the table and return
1931 NULL_TREE.
1933 Also, when an expression is first inserted in the AVAIL_EXPRS table, it
1934 is also added to the stack pointed to by BLOCK_AVAIL_EXPRS_P, so that they
1935 can be removed when we finish processing this block and its children.
1937 NOTE: This function assumes that STMT is a GIMPLE_MODIFY_STMT node that
1938 contains no CALL_EXPR on its RHS and makes no volatile nor
1939 aliased references. */
1941 static tree
1942 lookup_avail_expr (tree stmt, bool insert)
1944 void **slot;
1945 tree lhs;
1946 tree temp;
1947 struct expr_hash_elt *element = XNEW (struct expr_hash_elt);
1949 lhs = TREE_CODE (stmt) == GIMPLE_MODIFY_STMT
1950 ? GIMPLE_STMT_OPERAND (stmt, 0) : NULL;
1952 initialize_hash_element (stmt, lhs, element);
1954 /* Don't bother remembering constant assignments and copy operations.
1955 Constants and copy operations are handled by the constant/copy propagator
1956 in optimize_stmt. */
1957 if (TREE_CODE (element->rhs) == SSA_NAME
1958 || is_gimple_min_invariant (element->rhs))
1960 free (element);
1961 return NULL_TREE;
1964 /* Finally try to find the expression in the main expression hash table. */
1965 slot = htab_find_slot_with_hash (avail_exprs, element, element->hash,
1966 (insert ? INSERT : NO_INSERT));
1967 if (slot == NULL)
1969 free (element);
1970 return NULL_TREE;
1973 if (*slot == NULL)
1975 *slot = (void *) element;
1976 VEC_safe_push (tree, heap, avail_exprs_stack,
1977 stmt ? stmt : element->rhs);
1978 return NULL_TREE;
1981 /* Extract the LHS of the assignment so that it can be used as the current
1982 definition of another variable. */
1983 lhs = ((struct expr_hash_elt *)*slot)->lhs;
1985 /* See if the LHS appears in the CONST_AND_COPIES table. If it does, then
1986 use the value from the const_and_copies table. */
1987 if (TREE_CODE (lhs) == SSA_NAME)
1989 temp = SSA_NAME_VALUE (lhs);
1990 if (temp && TREE_CODE (temp) != VALUE_HANDLE)
1991 lhs = temp;
1994 free (element);
1995 return lhs;
1998 /* Hashing and equality functions for AVAIL_EXPRS. The table stores
1999 GIMPLE_MODIFY_STMT statements. We compute a value number for expressions
2000 using the code of the expression and the SSA numbers of its operands. */
2002 static hashval_t
2003 avail_expr_hash (const void *p)
2005 tree stmt = ((struct expr_hash_elt *)p)->stmt;
2006 tree rhs = ((struct expr_hash_elt *)p)->rhs;
2007 tree vuse;
2008 ssa_op_iter iter;
2009 hashval_t val = 0;
2011 /* iterative_hash_expr knows how to deal with any expression and
2012 deals with commutative operators as well, so just use it instead
2013 of duplicating such complexities here. */
2014 val = iterative_hash_expr (rhs, val);
2016 /* If the hash table entry is not associated with a statement, then we
2017 can just hash the expression and not worry about virtual operands
2018 and such. */
2019 if (!stmt || !stmt_ann (stmt))
2020 return val;
2022 /* Add the SSA version numbers of every vuse operand. This is important
2023 because compound variables like arrays are not renamed in the
2024 operands. Rather, the rename is done on the virtual variable
2025 representing all the elements of the array. */
2026 FOR_EACH_SSA_TREE_OPERAND (vuse, stmt, iter, SSA_OP_VUSE)
2027 val = iterative_hash_expr (vuse, val);
2029 return val;
2032 static hashval_t
2033 real_avail_expr_hash (const void *p)
2035 return ((const struct expr_hash_elt *)p)->hash;
2038 static int
2039 avail_expr_eq (const void *p1, const void *p2)
2041 tree stmt1 = ((struct expr_hash_elt *)p1)->stmt;
2042 tree rhs1 = ((struct expr_hash_elt *)p1)->rhs;
2043 tree stmt2 = ((struct expr_hash_elt *)p2)->stmt;
2044 tree rhs2 = ((struct expr_hash_elt *)p2)->rhs;
2046 /* If they are the same physical expression, return true. */
2047 if (rhs1 == rhs2 && stmt1 == stmt2)
2048 return true;
2050 /* If their codes are not equal, then quit now. */
2051 if (TREE_CODE (rhs1) != TREE_CODE (rhs2))
2052 return false;
2054 /* In case of a collision, both RHS have to be identical and have the
2055 same VUSE operands. */
2056 if ((TREE_TYPE (rhs1) == TREE_TYPE (rhs2)
2057 || lang_hooks.types_compatible_p (TREE_TYPE (rhs1), TREE_TYPE (rhs2)))
2058 && operand_equal_p (rhs1, rhs2, OEP_PURE_SAME))
2060 bool ret = compare_ssa_operands_equal (stmt1, stmt2, SSA_OP_VUSE);
2061 gcc_assert (!ret || ((struct expr_hash_elt *)p1)->hash
2062 == ((struct expr_hash_elt *)p2)->hash);
2063 return ret;
2066 return false;
2069 /* PHI-ONLY copy and constant propagation. This pass is meant to clean
2070 up degenerate PHIs created by or exposed by jump threading. */
2072 /* Given PHI, return its RHS if the PHI is a degenerate, otherwise return
2073 NULL. */
2075 static tree
2076 degenerate_phi_result (tree phi)
2078 tree lhs = PHI_RESULT (phi);
2079 tree val = NULL;
2080 int i;
2082 /* Ignoring arguments which are the same as LHS, if all the remaining
2083 arguments are the same, then the PHI is a degenerate and has the
2084 value of that common argument. */
2085 for (i = 0; i < PHI_NUM_ARGS (phi); i++)
2087 tree arg = PHI_ARG_DEF (phi, i);
2089 if (arg == lhs)
2090 continue;
2091 else if (!val)
2092 val = arg;
2093 else if (!operand_equal_p (arg, val, 0))
2094 break;
2096 return (i == PHI_NUM_ARGS (phi) ? val : NULL);
2099 /* Given a tree node T, which is either a PHI_NODE or GIMPLE_MODIFY_STMT,
2100 remove it from the IL. */
2102 static void
2103 remove_stmt_or_phi (tree t)
2105 if (TREE_CODE (t) == PHI_NODE)
2106 remove_phi_node (t, NULL, true);
2107 else
2109 block_stmt_iterator bsi = bsi_for_stmt (t);
2110 bsi_remove (&bsi, true);
2111 release_defs (t);
2115 /* Given a tree node T, which is either a PHI_NODE or GIMPLE_MODIFY_STMT,
2116 return the "rhs" of the node, in the case of a non-degenerate
2117 PHI, NULL is returned. */
2119 static tree
2120 get_rhs_or_phi_arg (tree t)
2122 if (TREE_CODE (t) == PHI_NODE)
2123 return degenerate_phi_result (t);
2124 else if (TREE_CODE (t) == GIMPLE_MODIFY_STMT)
2125 return GIMPLE_STMT_OPERAND (t, 1);
2126 gcc_unreachable ();
2130 /* Given a tree node T, which is either a PHI_NODE or a GIMPLE_MODIFY_STMT,
2131 return the "lhs" of the node. */
2133 static tree
2134 get_lhs_or_phi_result (tree t)
2136 if (TREE_CODE (t) == PHI_NODE)
2137 return PHI_RESULT (t);
2138 else if (TREE_CODE (t) == GIMPLE_MODIFY_STMT)
2139 return GIMPLE_STMT_OPERAND (t, 0);
2140 gcc_unreachable ();
2143 /* Propagate RHS into all uses of LHS (when possible).
2145 RHS and LHS are derived from STMT, which is passed in solely so
2146 that we can remove it if propagation is successful.
2148 When propagating into a PHI node or into a statement which turns
2149 into a trivial copy or constant initialization, set the
2150 appropriate bit in INTERESTING_NAMEs so that we will visit those
2151 nodes as well in an effort to pick up secondary optimization
2152 opportunities. */
2154 static void
2155 propagate_rhs_into_lhs (tree stmt, tree lhs, tree rhs, bitmap interesting_names)
2157 /* First verify that propagation is valid and isn't going to move a
2158 loop variant variable outside its loop. */
2159 if (! SSA_NAME_OCCURS_IN_ABNORMAL_PHI (lhs)
2160 && (TREE_CODE (rhs) != SSA_NAME
2161 || ! SSA_NAME_OCCURS_IN_ABNORMAL_PHI (rhs))
2162 && may_propagate_copy (lhs, rhs)
2163 && loop_depth_of_name (lhs) >= loop_depth_of_name (rhs))
2165 use_operand_p use_p;
2166 imm_use_iterator iter;
2167 tree use_stmt;
2168 bool all = true;
2170 /* Dump details. */
2171 if (dump_file && (dump_flags & TDF_DETAILS))
2173 fprintf (dump_file, " Replacing '");
2174 print_generic_expr (dump_file, lhs, dump_flags);
2175 fprintf (dump_file, "' with %s '",
2176 (TREE_CODE (rhs) != SSA_NAME ? "constant" : "variable"));
2177 print_generic_expr (dump_file, rhs, dump_flags);
2178 fprintf (dump_file, "'\n");
2181 /* Walk over every use of LHS and try to replace the use with RHS.
2182 At this point the only reason why such a propagation would not
2183 be successful would be if the use occurs in an ASM_EXPR. */
2184 FOR_EACH_IMM_USE_STMT (use_stmt, iter, lhs)
2187 /* It's not always safe to propagate into an ASM_EXPR. */
2188 if (TREE_CODE (use_stmt) == ASM_EXPR
2189 && ! may_propagate_copy_into_asm (lhs))
2191 all = false;
2192 continue;
2195 /* Dump details. */
2196 if (dump_file && (dump_flags & TDF_DETAILS))
2198 fprintf (dump_file, " Original statement:");
2199 print_generic_expr (dump_file, use_stmt, dump_flags);
2200 fprintf (dump_file, "\n");
2203 push_stmt_changes (&use_stmt);
2205 /* Propagate the RHS into this use of the LHS. */
2206 FOR_EACH_IMM_USE_ON_STMT (use_p, iter)
2207 propagate_value (use_p, rhs);
2209 /* Special cases to avoid useless calls into the folding
2210 routines, operand scanning, etc.
2212 First, propagation into a PHI may cause the PHI to become
2213 a degenerate, so mark the PHI as interesting. No other
2214 actions are necessary.
2216 Second, if we're propagating a virtual operand and the
2217 propagation does not change the underlying _DECL node for
2218 the virtual operand, then no further actions are necessary. */
2219 if (TREE_CODE (use_stmt) == PHI_NODE
2220 || (! is_gimple_reg (lhs)
2221 && TREE_CODE (rhs) == SSA_NAME
2222 && SSA_NAME_VAR (lhs) == SSA_NAME_VAR (rhs)))
2224 /* Dump details. */
2225 if (dump_file && (dump_flags & TDF_DETAILS))
2227 fprintf (dump_file, " Updated statement:");
2228 print_generic_expr (dump_file, use_stmt, dump_flags);
2229 fprintf (dump_file, "\n");
2232 /* Propagation into a PHI may expose new degenerate PHIs,
2233 so mark the result of the PHI as interesting. */
2234 if (TREE_CODE (use_stmt) == PHI_NODE)
2236 tree result = get_lhs_or_phi_result (use_stmt);
2237 bitmap_set_bit (interesting_names, SSA_NAME_VERSION (result));
2240 discard_stmt_changes (&use_stmt);
2241 continue;
2244 /* From this point onward we are propagating into a
2245 real statement. Folding may (or may not) be possible,
2246 we may expose new operands, expose dead EH edges,
2247 etc. */
2248 fold_stmt_inplace (use_stmt);
2250 /* Sometimes propagation can expose new operands to the
2251 renamer. Note this will call update_stmt at the
2252 appropriate time. */
2253 pop_stmt_changes (&use_stmt);
2255 /* Dump details. */
2256 if (dump_file && (dump_flags & TDF_DETAILS))
2258 fprintf (dump_file, " Updated statement:");
2259 print_generic_expr (dump_file, use_stmt, dump_flags);
2260 fprintf (dump_file, "\n");
2263 /* If we replaced a variable index with a constant, then
2264 we would need to update the invariant flag for ADDR_EXPRs. */
2265 if (TREE_CODE (use_stmt) == GIMPLE_MODIFY_STMT
2266 && TREE_CODE (GIMPLE_STMT_OPERAND (use_stmt, 1)) == ADDR_EXPR)
2267 recompute_tree_invariant_for_addr_expr
2268 (GIMPLE_STMT_OPERAND (use_stmt, 1));
2270 /* If we cleaned up EH information from the statement,
2271 mark its containing block as needing EH cleanups. */
2272 if (maybe_clean_or_replace_eh_stmt (use_stmt, use_stmt))
2274 bitmap_set_bit (need_eh_cleanup, bb_for_stmt (use_stmt)->index);
2275 if (dump_file && (dump_flags & TDF_DETAILS))
2276 fprintf (dump_file, " Flagged to clear EH edges.\n");
2279 /* Propagation may expose new trivial copy/constant propagation
2280 opportunities. */
2281 if (TREE_CODE (use_stmt) == GIMPLE_MODIFY_STMT
2282 && TREE_CODE (GIMPLE_STMT_OPERAND (use_stmt, 0)) == SSA_NAME
2283 && (TREE_CODE (GIMPLE_STMT_OPERAND (use_stmt, 1)) == SSA_NAME
2284 || is_gimple_min_invariant (GIMPLE_STMT_OPERAND (use_stmt,
2285 1))))
2287 tree result = get_lhs_or_phi_result (use_stmt);
2288 bitmap_set_bit (interesting_names, SSA_NAME_VERSION (result));
2291 /* Propagation into these nodes may make certain edges in
2292 the CFG unexecutable. We want to identify them as PHI nodes
2293 at the destination of those unexecutable edges may become
2294 degenerates. */
2295 else if (TREE_CODE (use_stmt) == COND_EXPR
2296 || TREE_CODE (use_stmt) == SWITCH_EXPR
2297 || TREE_CODE (use_stmt) == GOTO_EXPR)
2299 tree val;
2301 if (TREE_CODE (use_stmt) == COND_EXPR)
2302 val = COND_EXPR_COND (use_stmt);
2303 else if (TREE_CODE (use_stmt) == SWITCH_EXPR)
2304 val = SWITCH_COND (use_stmt);
2305 else
2306 val = GOTO_DESTINATION (use_stmt);
2308 if (is_gimple_min_invariant (val))
2310 basic_block bb = bb_for_stmt (use_stmt);
2311 edge te = find_taken_edge (bb, val);
2312 edge_iterator ei;
2313 edge e;
2314 block_stmt_iterator bsi;
2316 /* Remove all outgoing edges except TE. */
2317 for (ei = ei_start (bb->succs); (e = ei_safe_edge (ei));)
2319 if (e != te)
2321 tree phi;
2323 /* Mark all the PHI nodes at the destination of
2324 the unexecutable edge as interesting. */
2325 for (phi = phi_nodes (e->dest);
2326 phi;
2327 phi = PHI_CHAIN (phi))
2329 tree result = PHI_RESULT (phi);
2330 int version = SSA_NAME_VERSION (result);
2332 bitmap_set_bit (interesting_names, version);
2335 te->probability += e->probability;
2337 te->count += e->count;
2338 remove_edge (e);
2339 cfg_altered = 1;
2341 else
2342 ei_next (&ei);
2345 bsi = bsi_last (bb_for_stmt (use_stmt));
2346 bsi_remove (&bsi, true);
2348 /* And fixup the flags on the single remaining edge. */
2349 te->flags &= ~(EDGE_TRUE_VALUE | EDGE_FALSE_VALUE);
2350 te->flags &= ~EDGE_ABNORMAL;
2351 te->flags |= EDGE_FALLTHRU;
2352 if (te->probability > REG_BR_PROB_BASE)
2353 te->probability = REG_BR_PROB_BASE;
2358 /* Ensure there is nothing else to do. */
2359 gcc_assert (!all || has_zero_uses (lhs));
2361 /* If we were able to propagate away all uses of LHS, then
2362 we can remove STMT. */
2363 if (all)
2364 remove_stmt_or_phi (stmt);
2368 /* T is either a PHI node (potentially a degenerate PHI node) or
2369 a statement that is a trivial copy or constant initialization.
2371 Attempt to eliminate T by propagating its RHS into all uses of
2372 its LHS. This may in turn set new bits in INTERESTING_NAMES
2373 for nodes we want to revisit later.
2375 All exit paths should clear INTERESTING_NAMES for the result
2376 of T. */
2378 static void
2379 eliminate_const_or_copy (tree t, bitmap interesting_names)
2381 tree lhs = get_lhs_or_phi_result (t);
2382 tree rhs;
2383 int version = SSA_NAME_VERSION (lhs);
2385 /* If the LHS of this statement or PHI has no uses, then we can
2386 just eliminate it. This can occur if, for example, the PHI
2387 was created by block duplication due to threading and its only
2388 use was in the conditional at the end of the block which was
2389 deleted. */
2390 if (has_zero_uses (lhs))
2392 bitmap_clear_bit (interesting_names, version);
2393 remove_stmt_or_phi (t);
2394 return;
2397 /* Get the RHS of the assignment or PHI node if the PHI is a
2398 degenerate. */
2399 rhs = get_rhs_or_phi_arg (t);
2400 if (!rhs)
2402 bitmap_clear_bit (interesting_names, version);
2403 return;
2406 propagate_rhs_into_lhs (t, lhs, rhs, interesting_names);
2408 /* Note that T may well have been deleted by now, so do
2409 not access it, instead use the saved version # to clear
2410 T's entry in the worklist. */
2411 bitmap_clear_bit (interesting_names, version);
2414 /* The first phase in degenerate PHI elimination.
2416 Eliminate the degenerate PHIs in BB, then recurse on the
2417 dominator children of BB. */
2419 static void
2420 eliminate_degenerate_phis_1 (basic_block bb, bitmap interesting_names)
2422 tree phi, next;
2423 basic_block son;
2425 for (phi = phi_nodes (bb); phi; phi = next)
2427 next = PHI_CHAIN (phi);
2428 eliminate_const_or_copy (phi, interesting_names);
2431 /* Recurse into the dominator children of BB. */
2432 for (son = first_dom_son (CDI_DOMINATORS, bb);
2433 son;
2434 son = next_dom_son (CDI_DOMINATORS, son))
2435 eliminate_degenerate_phis_1 (son, interesting_names);
2439 /* A very simple pass to eliminate degenerate PHI nodes from the
2440 IL. This is meant to be fast enough to be able to be run several
2441 times in the optimization pipeline.
2443 Certain optimizations, particularly those which duplicate blocks
2444 or remove edges from the CFG can create or expose PHIs which are
2445 trivial copies or constant initializations.
2447 While we could pick up these optimizations in DOM or with the
2448 combination of copy-prop and CCP, those solutions are far too
2449 heavy-weight for our needs.
2451 This implementation has two phases so that we can efficiently
2452 eliminate the first order degenerate PHIs and second order
2453 degenerate PHIs.
2455 The first phase performs a dominator walk to identify and eliminate
2456 the vast majority of the degenerate PHIs. When a degenerate PHI
2457 is identified and eliminated any affected statements or PHIs
2458 are put on a worklist.
2460 The second phase eliminates degenerate PHIs and trivial copies
2461 or constant initializations using the worklist. This is how we
2462 pick up the secondary optimization opportunities with minimal
2463 cost. */
2465 static unsigned int
2466 eliminate_degenerate_phis (void)
2468 bitmap interesting_names;
2469 bitmap interesting_names1;
2471 /* Bitmap of blocks which need EH information updated. We can not
2472 update it on-the-fly as doing so invalidates the dominator tree. */
2473 need_eh_cleanup = BITMAP_ALLOC (NULL);
2475 /* INTERESTING_NAMES is effectively our worklist, indexed by
2476 SSA_NAME_VERSION.
2478 A set bit indicates that the statement or PHI node which
2479 defines the SSA_NAME should be (re)examined to determine if
2480 it has become a degenerate PHI or trivial const/copy propagation
2481 opportunity.
2483 Experiments have show we generally get better compilation
2484 time behavior with bitmaps rather than sbitmaps. */
2485 interesting_names = BITMAP_ALLOC (NULL);
2486 interesting_names1 = BITMAP_ALLOC (NULL);
2488 /* First phase. Eliminate degenerate PHIs via a dominator
2489 walk of the CFG.
2491 Experiments have indicated that we generally get better
2492 compile-time behavior by visiting blocks in the first
2493 phase in dominator order. Presumably this is because walking
2494 in dominator order leaves fewer PHIs for later examination
2495 by the worklist phase. */
2496 calculate_dominance_info (CDI_DOMINATORS);
2497 eliminate_degenerate_phis_1 (ENTRY_BLOCK_PTR, interesting_names);
2499 /* Second phase. Eliminate second order degenerate PHIs as well
2500 as trivial copies or constant initializations identified by
2501 the first phase or this phase. Basically we keep iterating
2502 until our set of INTERESTING_NAMEs is empty. */
2503 while (!bitmap_empty_p (interesting_names))
2505 unsigned int i;
2506 bitmap_iterator bi;
2508 /* EXECUTE_IF_SET_IN_BITMAP does not like its bitmap
2509 changed during the loop. Copy it to another bitmap and
2510 use that. */
2511 bitmap_copy (interesting_names1, interesting_names);
2513 EXECUTE_IF_SET_IN_BITMAP (interesting_names1, 0, i, bi)
2515 tree name = ssa_name (i);
2517 /* Ignore SSA_NAMEs that have been released because
2518 their defining statement was deleted (unreachable). */
2519 if (name)
2520 eliminate_const_or_copy (SSA_NAME_DEF_STMT (ssa_name (i)),
2521 interesting_names);
2525 /* Propagation of const and copies may make some EH edges dead. Purge
2526 such edges from the CFG as needed. */
2527 if (!bitmap_empty_p (need_eh_cleanup))
2529 cfg_altered |= tree_purge_all_dead_eh_edges (need_eh_cleanup);
2530 BITMAP_FREE (need_eh_cleanup);
2533 BITMAP_FREE (interesting_names);
2534 BITMAP_FREE (interesting_names1);
2535 if (cfg_altered)
2536 free_dominance_info (CDI_DOMINATORS);
2537 return 0;
2540 struct tree_opt_pass pass_phi_only_cprop =
2542 "phicprop", /* name */
2543 gate_dominator, /* gate */
2544 eliminate_degenerate_phis, /* execute */
2545 NULL, /* sub */
2546 NULL, /* next */
2547 0, /* static_pass_number */
2548 TV_TREE_PHI_CPROP, /* tv_id */
2549 PROP_cfg | PROP_ssa | PROP_alias, /* properties_required */
2550 0, /* properties_provided */
2551 0, /* properties_destroyed */
2552 0, /* todo_flags_start */
2553 TODO_cleanup_cfg
2554 | TODO_dump_func
2555 | TODO_ggc_collect
2556 | TODO_verify_ssa
2557 | TODO_verify_stmts
2558 | TODO_update_ssa, /* todo_flags_finish */
2559 0 /* letter */