* gcc.dg/atomic/c11-atomic-exec-5.c (dg-additional-options): Use
[official-gcc.git] / gcc / tree-ssa-dom.c
blobc4ec4e5415c8dc749fd85b0c330361eebb32a9e4
1 /* SSA Dominator optimizations for trees
2 Copyright (C) 2001-2014 Free Software Foundation, Inc.
3 Contributed by Diego Novillo <dnovillo@redhat.com>
5 This file is part of GCC.
7 GCC is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3, or (at your option)
10 any later version.
12 GCC is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING3. If not see
19 <http://www.gnu.org/licenses/>. */
21 #include "config.h"
22 #include "system.h"
23 #include "coretypes.h"
24 #include "hash-table.h"
25 #include "tm.h"
26 #include "tree.h"
27 #include "stor-layout.h"
28 #include "flags.h"
29 #include "tm_p.h"
30 #include "basic-block.h"
31 #include "cfgloop.h"
32 #include "function.h"
33 #include "gimple-pretty-print.h"
34 #include "tree-ssa-alias.h"
35 #include "internal-fn.h"
36 #include "gimple-fold.h"
37 #include "tree-eh.h"
38 #include "gimple-expr.h"
39 #include "is-a.h"
40 #include "gimple.h"
41 #include "gimple-iterator.h"
42 #include "gimple-ssa.h"
43 #include "tree-cfg.h"
44 #include "tree-phinodes.h"
45 #include "ssa-iterators.h"
46 #include "stringpool.h"
47 #include "tree-ssanames.h"
48 #include "tree-into-ssa.h"
49 #include "domwalk.h"
50 #include "tree-pass.h"
51 #include "tree-ssa-propagate.h"
52 #include "tree-ssa-threadupdate.h"
53 #include "langhooks.h"
54 #include "params.h"
55 #include "tree-ssa-threadedge.h"
56 #include "tree-ssa-dom.h"
58 /* This file implements optimizations on the dominator tree. */
60 /* Representation of a "naked" right-hand-side expression, to be used
61 in recording available expressions in the expression hash table. */
63 enum expr_kind
65 EXPR_SINGLE,
66 EXPR_UNARY,
67 EXPR_BINARY,
68 EXPR_TERNARY,
69 EXPR_CALL,
70 EXPR_PHI
73 struct hashable_expr
75 tree type;
76 enum expr_kind kind;
77 union {
78 struct { tree rhs; } single;
79 struct { enum tree_code op; tree opnd; } unary;
80 struct { enum tree_code op; tree opnd0, opnd1; } binary;
81 struct { enum tree_code op; tree opnd0, opnd1, opnd2; } ternary;
82 struct { gimple fn_from; bool pure; size_t nargs; tree *args; } call;
83 struct { size_t nargs; tree *args; } phi;
84 } ops;
87 /* Structure for recording known values of a conditional expression
88 at the exits from its block. */
90 typedef struct cond_equivalence_s
92 struct hashable_expr cond;
93 tree value;
94 } cond_equivalence;
97 /* Structure for recording edge equivalences as well as any pending
98 edge redirections during the dominator optimizer.
100 Computing and storing the edge equivalences instead of creating
101 them on-demand can save significant amounts of time, particularly
102 for pathological cases involving switch statements.
104 These structures live for a single iteration of the dominator
105 optimizer in the edge's AUX field. At the end of an iteration we
106 free each of these structures and update the AUX field to point
107 to any requested redirection target (the code for updating the
108 CFG and SSA graph for edge redirection expects redirection edge
109 targets to be in the AUX field for each edge. */
111 struct edge_info
113 /* If this edge creates a simple equivalence, the LHS and RHS of
114 the equivalence will be stored here. */
115 tree lhs;
116 tree rhs;
118 /* Traversing an edge may also indicate one or more particular conditions
119 are true or false. */
120 vec<cond_equivalence> cond_equivalences;
123 /* Stack of available expressions in AVAIL_EXPRs. Each block pushes any
124 expressions it enters into the hash table along with a marker entry
125 (null). When we finish processing the block, we pop off entries and
126 remove the expressions from the global hash table until we hit the
127 marker. */
128 typedef struct expr_hash_elt * expr_hash_elt_t;
130 static vec<expr_hash_elt_t> avail_exprs_stack;
132 /* Structure for entries in the expression hash table. */
134 struct expr_hash_elt
136 /* The value (lhs) of this expression. */
137 tree lhs;
139 /* The expression (rhs) we want to record. */
140 struct hashable_expr expr;
142 /* The stmt pointer if this element corresponds to a statement. */
143 gimple stmt;
145 /* The hash value for RHS. */
146 hashval_t hash;
148 /* A unique stamp, typically the address of the hash
149 element itself, used in removing entries from the table. */
150 struct expr_hash_elt *stamp;
153 /* Hashtable helpers. */
155 static bool hashable_expr_equal_p (const struct hashable_expr *,
156 const struct hashable_expr *);
157 static void free_expr_hash_elt (void *);
159 struct expr_elt_hasher
161 typedef expr_hash_elt *value_type;
162 typedef expr_hash_elt *compare_type;
163 typedef int store_values_directly;
164 static inline hashval_t hash (const value_type &);
165 static inline bool equal (const value_type &, const compare_type &);
166 static inline void remove (value_type &);
169 inline hashval_t
170 expr_elt_hasher::hash (const value_type &p)
172 return p->hash;
175 inline bool
176 expr_elt_hasher::equal (const value_type &p1, const compare_type &p2)
178 gimple stmt1 = p1->stmt;
179 const struct hashable_expr *expr1 = &p1->expr;
180 const struct expr_hash_elt *stamp1 = p1->stamp;
181 gimple stmt2 = p2->stmt;
182 const struct hashable_expr *expr2 = &p2->expr;
183 const struct expr_hash_elt *stamp2 = p2->stamp;
185 /* This case should apply only when removing entries from the table. */
186 if (stamp1 == stamp2)
187 return true;
189 /* FIXME tuples:
190 We add stmts to a hash table and them modify them. To detect the case
191 that we modify a stmt and then search for it, we assume that the hash
192 is always modified by that change.
193 We have to fully check why this doesn't happen on trunk or rewrite
194 this in a more reliable (and easier to understand) way. */
195 if (((const struct expr_hash_elt *)p1)->hash
196 != ((const struct expr_hash_elt *)p2)->hash)
197 return false;
199 /* In case of a collision, both RHS have to be identical and have the
200 same VUSE operands. */
201 if (hashable_expr_equal_p (expr1, expr2)
202 && types_compatible_p (expr1->type, expr2->type))
204 /* Note that STMT1 and/or STMT2 may be NULL. */
205 return ((stmt1 ? gimple_vuse (stmt1) : NULL_TREE)
206 == (stmt2 ? gimple_vuse (stmt2) : NULL_TREE));
209 return false;
212 /* Delete an expr_hash_elt and reclaim its storage. */
214 inline void
215 expr_elt_hasher::remove (value_type &element)
217 free_expr_hash_elt (element);
220 /* Hash table with expressions made available during the renaming process.
221 When an assignment of the form X_i = EXPR is found, the statement is
222 stored in this table. If the same expression EXPR is later found on the
223 RHS of another statement, it is replaced with X_i (thus performing
224 global redundancy elimination). Similarly as we pass through conditionals
225 we record the conditional itself as having either a true or false value
226 in this table. */
227 static hash_table<expr_elt_hasher> *avail_exprs;
229 /* Stack of dest,src pairs that need to be restored during finalization.
231 A NULL entry is used to mark the end of pairs which need to be
232 restored during finalization of this block. */
233 static vec<tree> const_and_copies_stack;
235 /* Track whether or not we have changed the control flow graph. */
236 static bool cfg_altered;
238 /* Bitmap of blocks that have had EH statements cleaned. We should
239 remove their dead edges eventually. */
240 static bitmap need_eh_cleanup;
242 /* Statistics for dominator optimizations. */
243 struct opt_stats_d
245 long num_stmts;
246 long num_exprs_considered;
247 long num_re;
248 long num_const_prop;
249 long num_copy_prop;
252 static struct opt_stats_d opt_stats;
254 /* Local functions. */
255 static void optimize_stmt (basic_block, gimple_stmt_iterator);
256 static tree lookup_avail_expr (gimple, bool);
257 static hashval_t avail_expr_hash (const void *);
258 static void htab_statistics (FILE *,
259 const hash_table<expr_elt_hasher> &);
260 static void record_cond (cond_equivalence *);
261 static void record_const_or_copy (tree, tree);
262 static void record_equality (tree, tree);
263 static void record_equivalences_from_phis (basic_block);
264 static void record_equivalences_from_incoming_edge (basic_block);
265 static void eliminate_redundant_computations (gimple_stmt_iterator *);
266 static void record_equivalences_from_stmt (gimple, int);
267 static void remove_local_expressions_from_table (void);
268 static void restore_vars_to_original_value (void);
269 static edge single_incoming_edge_ignoring_loop_edges (basic_block);
272 /* Given a statement STMT, initialize the hash table element pointed to
273 by ELEMENT. */
275 static void
276 initialize_hash_element (gimple stmt, tree lhs,
277 struct expr_hash_elt *element)
279 enum gimple_code code = gimple_code (stmt);
280 struct hashable_expr *expr = &element->expr;
282 if (code == GIMPLE_ASSIGN)
284 enum tree_code subcode = gimple_assign_rhs_code (stmt);
286 switch (get_gimple_rhs_class (subcode))
288 case GIMPLE_SINGLE_RHS:
289 expr->kind = EXPR_SINGLE;
290 expr->type = TREE_TYPE (gimple_assign_rhs1 (stmt));
291 expr->ops.single.rhs = gimple_assign_rhs1 (stmt);
292 break;
293 case GIMPLE_UNARY_RHS:
294 expr->kind = EXPR_UNARY;
295 expr->type = TREE_TYPE (gimple_assign_lhs (stmt));
296 expr->ops.unary.op = subcode;
297 expr->ops.unary.opnd = gimple_assign_rhs1 (stmt);
298 break;
299 case GIMPLE_BINARY_RHS:
300 expr->kind = EXPR_BINARY;
301 expr->type = TREE_TYPE (gimple_assign_lhs (stmt));
302 expr->ops.binary.op = subcode;
303 expr->ops.binary.opnd0 = gimple_assign_rhs1 (stmt);
304 expr->ops.binary.opnd1 = gimple_assign_rhs2 (stmt);
305 break;
306 case GIMPLE_TERNARY_RHS:
307 expr->kind = EXPR_TERNARY;
308 expr->type = TREE_TYPE (gimple_assign_lhs (stmt));
309 expr->ops.ternary.op = subcode;
310 expr->ops.ternary.opnd0 = gimple_assign_rhs1 (stmt);
311 expr->ops.ternary.opnd1 = gimple_assign_rhs2 (stmt);
312 expr->ops.ternary.opnd2 = gimple_assign_rhs3 (stmt);
313 break;
314 default:
315 gcc_unreachable ();
318 else if (code == GIMPLE_COND)
320 expr->type = boolean_type_node;
321 expr->kind = EXPR_BINARY;
322 expr->ops.binary.op = gimple_cond_code (stmt);
323 expr->ops.binary.opnd0 = gimple_cond_lhs (stmt);
324 expr->ops.binary.opnd1 = gimple_cond_rhs (stmt);
326 else if (code == GIMPLE_CALL)
328 size_t nargs = gimple_call_num_args (stmt);
329 size_t i;
331 gcc_assert (gimple_call_lhs (stmt));
333 expr->type = TREE_TYPE (gimple_call_lhs (stmt));
334 expr->kind = EXPR_CALL;
335 expr->ops.call.fn_from = stmt;
337 if (gimple_call_flags (stmt) & (ECF_CONST | ECF_PURE))
338 expr->ops.call.pure = true;
339 else
340 expr->ops.call.pure = false;
342 expr->ops.call.nargs = nargs;
343 expr->ops.call.args = XCNEWVEC (tree, nargs);
344 for (i = 0; i < nargs; i++)
345 expr->ops.call.args[i] = gimple_call_arg (stmt, i);
347 else if (code == GIMPLE_SWITCH)
349 expr->type = TREE_TYPE (gimple_switch_index (stmt));
350 expr->kind = EXPR_SINGLE;
351 expr->ops.single.rhs = gimple_switch_index (stmt);
353 else if (code == GIMPLE_GOTO)
355 expr->type = TREE_TYPE (gimple_goto_dest (stmt));
356 expr->kind = EXPR_SINGLE;
357 expr->ops.single.rhs = gimple_goto_dest (stmt);
359 else if (code == GIMPLE_PHI)
361 size_t nargs = gimple_phi_num_args (stmt);
362 size_t i;
364 expr->type = TREE_TYPE (gimple_phi_result (stmt));
365 expr->kind = EXPR_PHI;
366 expr->ops.phi.nargs = nargs;
367 expr->ops.phi.args = XCNEWVEC (tree, nargs);
369 for (i = 0; i < nargs; i++)
370 expr->ops.phi.args[i] = gimple_phi_arg_def (stmt, i);
372 else
373 gcc_unreachable ();
375 element->lhs = lhs;
376 element->stmt = stmt;
377 element->hash = avail_expr_hash (element);
378 element->stamp = element;
381 /* Given a conditional expression COND as a tree, initialize
382 a hashable_expr expression EXPR. The conditional must be a
383 comparison or logical negation. A constant or a variable is
384 not permitted. */
386 static void
387 initialize_expr_from_cond (tree cond, struct hashable_expr *expr)
389 expr->type = boolean_type_node;
391 if (COMPARISON_CLASS_P (cond))
393 expr->kind = EXPR_BINARY;
394 expr->ops.binary.op = TREE_CODE (cond);
395 expr->ops.binary.opnd0 = TREE_OPERAND (cond, 0);
396 expr->ops.binary.opnd1 = TREE_OPERAND (cond, 1);
398 else if (TREE_CODE (cond) == TRUTH_NOT_EXPR)
400 expr->kind = EXPR_UNARY;
401 expr->ops.unary.op = TRUTH_NOT_EXPR;
402 expr->ops.unary.opnd = TREE_OPERAND (cond, 0);
404 else
405 gcc_unreachable ();
408 /* Given a hashable_expr expression EXPR and an LHS,
409 initialize the hash table element pointed to by ELEMENT. */
411 static void
412 initialize_hash_element_from_expr (struct hashable_expr *expr,
413 tree lhs,
414 struct expr_hash_elt *element)
416 element->expr = *expr;
417 element->lhs = lhs;
418 element->stmt = NULL;
419 element->hash = avail_expr_hash (element);
420 element->stamp = element;
423 /* Compare two hashable_expr structures for equivalence.
424 They are considered equivalent when the the expressions
425 they denote must necessarily be equal. The logic is intended
426 to follow that of operand_equal_p in fold-const.c */
428 static bool
429 hashable_expr_equal_p (const struct hashable_expr *expr0,
430 const struct hashable_expr *expr1)
432 tree type0 = expr0->type;
433 tree type1 = expr1->type;
435 /* If either type is NULL, there is nothing to check. */
436 if ((type0 == NULL_TREE) ^ (type1 == NULL_TREE))
437 return false;
439 /* If both types don't have the same signedness, precision, and mode,
440 then we can't consider them equal. */
441 if (type0 != type1
442 && (TREE_CODE (type0) == ERROR_MARK
443 || TREE_CODE (type1) == ERROR_MARK
444 || TYPE_UNSIGNED (type0) != TYPE_UNSIGNED (type1)
445 || TYPE_PRECISION (type0) != TYPE_PRECISION (type1)
446 || TYPE_MODE (type0) != TYPE_MODE (type1)))
447 return false;
449 if (expr0->kind != expr1->kind)
450 return false;
452 switch (expr0->kind)
454 case EXPR_SINGLE:
455 return operand_equal_p (expr0->ops.single.rhs,
456 expr1->ops.single.rhs, 0);
458 case EXPR_UNARY:
459 if (expr0->ops.unary.op != expr1->ops.unary.op)
460 return false;
462 if ((CONVERT_EXPR_CODE_P (expr0->ops.unary.op)
463 || expr0->ops.unary.op == NON_LVALUE_EXPR)
464 && TYPE_UNSIGNED (expr0->type) != TYPE_UNSIGNED (expr1->type))
465 return false;
467 return operand_equal_p (expr0->ops.unary.opnd,
468 expr1->ops.unary.opnd, 0);
470 case EXPR_BINARY:
471 if (expr0->ops.binary.op != expr1->ops.binary.op)
472 return false;
474 if (operand_equal_p (expr0->ops.binary.opnd0,
475 expr1->ops.binary.opnd0, 0)
476 && operand_equal_p (expr0->ops.binary.opnd1,
477 expr1->ops.binary.opnd1, 0))
478 return true;
480 /* For commutative ops, allow the other order. */
481 return (commutative_tree_code (expr0->ops.binary.op)
482 && operand_equal_p (expr0->ops.binary.opnd0,
483 expr1->ops.binary.opnd1, 0)
484 && operand_equal_p (expr0->ops.binary.opnd1,
485 expr1->ops.binary.opnd0, 0));
487 case EXPR_TERNARY:
488 if (expr0->ops.ternary.op != expr1->ops.ternary.op
489 || !operand_equal_p (expr0->ops.ternary.opnd2,
490 expr1->ops.ternary.opnd2, 0))
491 return false;
493 if (operand_equal_p (expr0->ops.ternary.opnd0,
494 expr1->ops.ternary.opnd0, 0)
495 && operand_equal_p (expr0->ops.ternary.opnd1,
496 expr1->ops.ternary.opnd1, 0))
497 return true;
499 /* For commutative ops, allow the other order. */
500 return (commutative_ternary_tree_code (expr0->ops.ternary.op)
501 && operand_equal_p (expr0->ops.ternary.opnd0,
502 expr1->ops.ternary.opnd1, 0)
503 && operand_equal_p (expr0->ops.ternary.opnd1,
504 expr1->ops.ternary.opnd0, 0));
506 case EXPR_CALL:
508 size_t i;
510 /* If the calls are to different functions, then they
511 clearly cannot be equal. */
512 if (!gimple_call_same_target_p (expr0->ops.call.fn_from,
513 expr1->ops.call.fn_from))
514 return false;
516 if (! expr0->ops.call.pure)
517 return false;
519 if (expr0->ops.call.nargs != expr1->ops.call.nargs)
520 return false;
522 for (i = 0; i < expr0->ops.call.nargs; i++)
523 if (! operand_equal_p (expr0->ops.call.args[i],
524 expr1->ops.call.args[i], 0))
525 return false;
527 if (stmt_could_throw_p (expr0->ops.call.fn_from))
529 int lp0 = lookup_stmt_eh_lp (expr0->ops.call.fn_from);
530 int lp1 = lookup_stmt_eh_lp (expr1->ops.call.fn_from);
531 if ((lp0 > 0 || lp1 > 0) && lp0 != lp1)
532 return false;
535 return true;
538 case EXPR_PHI:
540 size_t i;
542 if (expr0->ops.phi.nargs != expr1->ops.phi.nargs)
543 return false;
545 for (i = 0; i < expr0->ops.phi.nargs; i++)
546 if (! operand_equal_p (expr0->ops.phi.args[i],
547 expr1->ops.phi.args[i], 0))
548 return false;
550 return true;
553 default:
554 gcc_unreachable ();
558 /* Generate a hash value for a pair of expressions. This can be used
559 iteratively by passing a previous result as the VAL argument.
561 The same hash value is always returned for a given pair of expressions,
562 regardless of the order in which they are presented. This is useful in
563 hashing the operands of commutative functions. */
565 static hashval_t
566 iterative_hash_exprs_commutative (const_tree t1,
567 const_tree t2, hashval_t val)
569 hashval_t one = iterative_hash_expr (t1, 0);
570 hashval_t two = iterative_hash_expr (t2, 0);
571 hashval_t t;
573 if (one > two)
574 t = one, one = two, two = t;
575 val = iterative_hash_hashval_t (one, val);
576 val = iterative_hash_hashval_t (two, val);
578 return val;
581 /* Compute a hash value for a hashable_expr value EXPR and a
582 previously accumulated hash value VAL. If two hashable_expr
583 values compare equal with hashable_expr_equal_p, they must
584 hash to the same value, given an identical value of VAL.
585 The logic is intended to follow iterative_hash_expr in tree.c. */
587 static hashval_t
588 iterative_hash_hashable_expr (const struct hashable_expr *expr, hashval_t val)
590 switch (expr->kind)
592 case EXPR_SINGLE:
593 val = iterative_hash_expr (expr->ops.single.rhs, val);
594 break;
596 case EXPR_UNARY:
597 val = iterative_hash_object (expr->ops.unary.op, val);
599 /* Make sure to include signedness in the hash computation.
600 Don't hash the type, that can lead to having nodes which
601 compare equal according to operand_equal_p, but which
602 have different hash codes. */
603 if (CONVERT_EXPR_CODE_P (expr->ops.unary.op)
604 || expr->ops.unary.op == NON_LVALUE_EXPR)
605 val += TYPE_UNSIGNED (expr->type);
607 val = iterative_hash_expr (expr->ops.unary.opnd, val);
608 break;
610 case EXPR_BINARY:
611 val = iterative_hash_object (expr->ops.binary.op, val);
612 if (commutative_tree_code (expr->ops.binary.op))
613 val = iterative_hash_exprs_commutative (expr->ops.binary.opnd0,
614 expr->ops.binary.opnd1, val);
615 else
617 val = iterative_hash_expr (expr->ops.binary.opnd0, val);
618 val = iterative_hash_expr (expr->ops.binary.opnd1, val);
620 break;
622 case EXPR_TERNARY:
623 val = iterative_hash_object (expr->ops.ternary.op, val);
624 if (commutative_ternary_tree_code (expr->ops.ternary.op))
625 val = iterative_hash_exprs_commutative (expr->ops.ternary.opnd0,
626 expr->ops.ternary.opnd1, val);
627 else
629 val = iterative_hash_expr (expr->ops.ternary.opnd0, val);
630 val = iterative_hash_expr (expr->ops.ternary.opnd1, val);
632 val = iterative_hash_expr (expr->ops.ternary.opnd2, val);
633 break;
635 case EXPR_CALL:
637 size_t i;
638 enum tree_code code = CALL_EXPR;
639 gimple fn_from;
641 val = iterative_hash_object (code, val);
642 fn_from = expr->ops.call.fn_from;
643 if (gimple_call_internal_p (fn_from))
644 val = iterative_hash_hashval_t
645 ((hashval_t) gimple_call_internal_fn (fn_from), val);
646 else
647 val = iterative_hash_expr (gimple_call_fn (fn_from), val);
648 for (i = 0; i < expr->ops.call.nargs; i++)
649 val = iterative_hash_expr (expr->ops.call.args[i], val);
651 break;
653 case EXPR_PHI:
655 size_t i;
657 for (i = 0; i < expr->ops.phi.nargs; i++)
658 val = iterative_hash_expr (expr->ops.phi.args[i], val);
660 break;
662 default:
663 gcc_unreachable ();
666 return val;
669 /* Print a diagnostic dump of an expression hash table entry. */
671 static void
672 print_expr_hash_elt (FILE * stream, const struct expr_hash_elt *element)
674 if (element->stmt)
675 fprintf (stream, "STMT ");
676 else
677 fprintf (stream, "COND ");
679 if (element->lhs)
681 print_generic_expr (stream, element->lhs, 0);
682 fprintf (stream, " = ");
685 switch (element->expr.kind)
687 case EXPR_SINGLE:
688 print_generic_expr (stream, element->expr.ops.single.rhs, 0);
689 break;
691 case EXPR_UNARY:
692 fprintf (stream, "%s ", get_tree_code_name (element->expr.ops.unary.op));
693 print_generic_expr (stream, element->expr.ops.unary.opnd, 0);
694 break;
696 case EXPR_BINARY:
697 print_generic_expr (stream, element->expr.ops.binary.opnd0, 0);
698 fprintf (stream, " %s ", get_tree_code_name (element->expr.ops.binary.op));
699 print_generic_expr (stream, element->expr.ops.binary.opnd1, 0);
700 break;
702 case EXPR_TERNARY:
703 fprintf (stream, " %s <", get_tree_code_name (element->expr.ops.ternary.op));
704 print_generic_expr (stream, element->expr.ops.ternary.opnd0, 0);
705 fputs (", ", stream);
706 print_generic_expr (stream, element->expr.ops.ternary.opnd1, 0);
707 fputs (", ", stream);
708 print_generic_expr (stream, element->expr.ops.ternary.opnd2, 0);
709 fputs (">", stream);
710 break;
712 case EXPR_CALL:
714 size_t i;
715 size_t nargs = element->expr.ops.call.nargs;
716 gimple fn_from;
718 fn_from = element->expr.ops.call.fn_from;
719 if (gimple_call_internal_p (fn_from))
720 fputs (internal_fn_name (gimple_call_internal_fn (fn_from)),
721 stream);
722 else
723 print_generic_expr (stream, gimple_call_fn (fn_from), 0);
724 fprintf (stream, " (");
725 for (i = 0; i < nargs; i++)
727 print_generic_expr (stream, element->expr.ops.call.args[i], 0);
728 if (i + 1 < nargs)
729 fprintf (stream, ", ");
731 fprintf (stream, ")");
733 break;
735 case EXPR_PHI:
737 size_t i;
738 size_t nargs = element->expr.ops.phi.nargs;
740 fprintf (stream, "PHI <");
741 for (i = 0; i < nargs; i++)
743 print_generic_expr (stream, element->expr.ops.phi.args[i], 0);
744 if (i + 1 < nargs)
745 fprintf (stream, ", ");
747 fprintf (stream, ">");
749 break;
751 fprintf (stream, "\n");
753 if (element->stmt)
755 fprintf (stream, " ");
756 print_gimple_stmt (stream, element->stmt, 0, 0);
760 /* Delete variable sized pieces of the expr_hash_elt ELEMENT. */
762 static void
763 free_expr_hash_elt_contents (struct expr_hash_elt *element)
765 if (element->expr.kind == EXPR_CALL)
766 free (element->expr.ops.call.args);
767 else if (element->expr.kind == EXPR_PHI)
768 free (element->expr.ops.phi.args);
771 /* Delete an expr_hash_elt and reclaim its storage. */
773 static void
774 free_expr_hash_elt (void *elt)
776 struct expr_hash_elt *element = ((struct expr_hash_elt *)elt);
777 free_expr_hash_elt_contents (element);
778 free (element);
781 /* Allocate an EDGE_INFO for edge E and attach it to E.
782 Return the new EDGE_INFO structure. */
784 static struct edge_info *
785 allocate_edge_info (edge e)
787 struct edge_info *edge_info;
789 edge_info = XCNEW (struct edge_info);
791 e->aux = edge_info;
792 return edge_info;
795 /* Free all EDGE_INFO structures associated with edges in the CFG.
796 If a particular edge can be threaded, copy the redirection
797 target from the EDGE_INFO structure into the edge's AUX field
798 as required by code to update the CFG and SSA graph for
799 jump threading. */
801 static void
802 free_all_edge_infos (void)
804 basic_block bb;
805 edge_iterator ei;
806 edge e;
808 FOR_EACH_BB_FN (bb, cfun)
810 FOR_EACH_EDGE (e, ei, bb->preds)
812 struct edge_info *edge_info = (struct edge_info *) e->aux;
814 if (edge_info)
816 edge_info->cond_equivalences.release ();
817 free (edge_info);
818 e->aux = NULL;
824 class dom_opt_dom_walker : public dom_walker
826 public:
827 dom_opt_dom_walker (cdi_direction direction)
828 : dom_walker (direction), m_dummy_cond (NULL) {}
830 virtual void before_dom_children (basic_block);
831 virtual void after_dom_children (basic_block);
833 private:
834 void thread_across_edge (edge);
836 gimple m_dummy_cond;
839 /* Jump threading, redundancy elimination and const/copy propagation.
841 This pass may expose new symbols that need to be renamed into SSA. For
842 every new symbol exposed, its corresponding bit will be set in
843 VARS_TO_RENAME. */
845 namespace {
847 const pass_data pass_data_dominator =
849 GIMPLE_PASS, /* type */
850 "dom", /* name */
851 OPTGROUP_NONE, /* optinfo_flags */
852 TV_TREE_SSA_DOMINATOR_OPTS, /* tv_id */
853 ( PROP_cfg | PROP_ssa ), /* properties_required */
854 0, /* properties_provided */
855 0, /* properties_destroyed */
856 0, /* todo_flags_start */
857 ( TODO_cleanup_cfg | TODO_update_ssa ), /* todo_flags_finish */
860 class pass_dominator : public gimple_opt_pass
862 public:
863 pass_dominator (gcc::context *ctxt)
864 : gimple_opt_pass (pass_data_dominator, ctxt)
867 /* opt_pass methods: */
868 opt_pass * clone () { return new pass_dominator (m_ctxt); }
869 virtual bool gate (function *) { return flag_tree_dom != 0; }
870 virtual unsigned int execute (function *);
872 }; // class pass_dominator
874 unsigned int
875 pass_dominator::execute (function *fun)
877 memset (&opt_stats, 0, sizeof (opt_stats));
879 /* Create our hash tables. */
880 avail_exprs = new hash_table<expr_elt_hasher> (1024);
881 avail_exprs_stack.create (20);
882 const_and_copies_stack.create (20);
883 need_eh_cleanup = BITMAP_ALLOC (NULL);
885 calculate_dominance_info (CDI_DOMINATORS);
886 cfg_altered = false;
888 /* We need to know loop structures in order to avoid destroying them
889 in jump threading. Note that we still can e.g. thread through loop
890 headers to an exit edge, or through loop header to the loop body, assuming
891 that we update the loop info.
893 TODO: We don't need to set LOOPS_HAVE_PREHEADERS generally, but due
894 to several overly conservative bail-outs in jump threading, case
895 gcc.dg/tree-ssa/pr21417.c can't be threaded if loop preheader is
896 missing. We should improve jump threading in future then
897 LOOPS_HAVE_PREHEADERS won't be needed here. */
898 loop_optimizer_init (LOOPS_HAVE_PREHEADERS | LOOPS_HAVE_SIMPLE_LATCHES);
900 /* Initialize the value-handle array. */
901 threadedge_initialize_values ();
903 /* We need accurate information regarding back edges in the CFG
904 for jump threading; this may include back edges that are not part of
905 a single loop. */
906 mark_dfs_back_edges ();
908 /* Recursively walk the dominator tree optimizing statements. */
909 dom_opt_dom_walker (CDI_DOMINATORS).walk (fun->cfg->x_entry_block_ptr);
912 gimple_stmt_iterator gsi;
913 basic_block bb;
914 FOR_EACH_BB_FN (bb, fun)
916 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
917 update_stmt_if_modified (gsi_stmt (gsi));
921 /* If we exposed any new variables, go ahead and put them into
922 SSA form now, before we handle jump threading. This simplifies
923 interactions between rewriting of _DECL nodes into SSA form
924 and rewriting SSA_NAME nodes into SSA form after block
925 duplication and CFG manipulation. */
926 update_ssa (TODO_update_ssa);
928 free_all_edge_infos ();
930 /* Thread jumps, creating duplicate blocks as needed. */
931 cfg_altered |= thread_through_all_blocks (first_pass_instance);
933 if (cfg_altered)
934 free_dominance_info (CDI_DOMINATORS);
936 /* Removal of statements may make some EH edges dead. Purge
937 such edges from the CFG as needed. */
938 if (!bitmap_empty_p (need_eh_cleanup))
940 unsigned i;
941 bitmap_iterator bi;
943 /* Jump threading may have created forwarder blocks from blocks
944 needing EH cleanup; the new successor of these blocks, which
945 has inherited from the original block, needs the cleanup.
946 Don't clear bits in the bitmap, as that can break the bitmap
947 iterator. */
948 EXECUTE_IF_SET_IN_BITMAP (need_eh_cleanup, 0, i, bi)
950 basic_block bb = BASIC_BLOCK_FOR_FN (fun, i);
951 if (bb == NULL)
952 continue;
953 while (single_succ_p (bb)
954 && (single_succ_edge (bb)->flags & EDGE_EH) == 0)
955 bb = single_succ (bb);
956 if (bb == EXIT_BLOCK_PTR_FOR_FN (fun))
957 continue;
958 if ((unsigned) bb->index != i)
959 bitmap_set_bit (need_eh_cleanup, bb->index);
962 gimple_purge_all_dead_eh_edges (need_eh_cleanup);
963 bitmap_clear (need_eh_cleanup);
966 statistics_counter_event (fun, "Redundant expressions eliminated",
967 opt_stats.num_re);
968 statistics_counter_event (fun, "Constants propagated",
969 opt_stats.num_const_prop);
970 statistics_counter_event (fun, "Copies propagated",
971 opt_stats.num_copy_prop);
973 /* Debugging dumps. */
974 if (dump_file && (dump_flags & TDF_STATS))
975 dump_dominator_optimization_stats (dump_file);
977 loop_optimizer_finalize ();
979 /* Delete our main hashtable. */
980 delete avail_exprs;
981 avail_exprs = NULL;
983 /* Free asserted bitmaps and stacks. */
984 BITMAP_FREE (need_eh_cleanup);
986 avail_exprs_stack.release ();
987 const_and_copies_stack.release ();
989 /* Free the value-handle array. */
990 threadedge_finalize_values ();
992 return 0;
995 } // anon namespace
997 gimple_opt_pass *
998 make_pass_dominator (gcc::context *ctxt)
1000 return new pass_dominator (ctxt);
1004 /* Given a conditional statement CONDSTMT, convert the
1005 condition to a canonical form. */
1007 static void
1008 canonicalize_comparison (gimple condstmt)
1010 tree op0;
1011 tree op1;
1012 enum tree_code code;
1014 gcc_assert (gimple_code (condstmt) == GIMPLE_COND);
1016 op0 = gimple_cond_lhs (condstmt);
1017 op1 = gimple_cond_rhs (condstmt);
1019 code = gimple_cond_code (condstmt);
1021 /* If it would be profitable to swap the operands, then do so to
1022 canonicalize the statement, enabling better optimization.
1024 By placing canonicalization of such expressions here we
1025 transparently keep statements in canonical form, even
1026 when the statement is modified. */
1027 if (tree_swap_operands_p (op0, op1, false))
1029 /* For relationals we need to swap the operands
1030 and change the code. */
1031 if (code == LT_EXPR
1032 || code == GT_EXPR
1033 || code == LE_EXPR
1034 || code == GE_EXPR)
1036 code = swap_tree_comparison (code);
1038 gimple_cond_set_code (condstmt, code);
1039 gimple_cond_set_lhs (condstmt, op1);
1040 gimple_cond_set_rhs (condstmt, op0);
1042 update_stmt (condstmt);
1047 /* Initialize local stacks for this optimizer and record equivalences
1048 upon entry to BB. Equivalences can come from the edge traversed to
1049 reach BB or they may come from PHI nodes at the start of BB. */
1051 /* Remove all the expressions in LOCALS from TABLE, stopping when there are
1052 LIMIT entries left in LOCALs. */
1054 static void
1055 remove_local_expressions_from_table (void)
1057 /* Remove all the expressions made available in this block. */
1058 while (avail_exprs_stack.length () > 0)
1060 expr_hash_elt_t victim = avail_exprs_stack.pop ();
1061 expr_hash_elt **slot;
1063 if (victim == NULL)
1064 break;
1066 /* This must precede the actual removal from the hash table,
1067 as ELEMENT and the table entry may share a call argument
1068 vector which will be freed during removal. */
1069 if (dump_file && (dump_flags & TDF_DETAILS))
1071 fprintf (dump_file, "<<<< ");
1072 print_expr_hash_elt (dump_file, victim);
1075 slot = avail_exprs->find_slot (victim, NO_INSERT);
1076 gcc_assert (slot && *slot == victim);
1077 avail_exprs->clear_slot (slot);
1081 /* Use the source/dest pairs in CONST_AND_COPIES_STACK to restore
1082 CONST_AND_COPIES to its original state, stopping when we hit a
1083 NULL marker. */
1085 static void
1086 restore_vars_to_original_value (void)
1088 while (const_and_copies_stack.length () > 0)
1090 tree prev_value, dest;
1092 dest = const_and_copies_stack.pop ();
1094 if (dest == NULL)
1095 break;
1097 if (dump_file && (dump_flags & TDF_DETAILS))
1099 fprintf (dump_file, "<<<< COPY ");
1100 print_generic_expr (dump_file, dest, 0);
1101 fprintf (dump_file, " = ");
1102 print_generic_expr (dump_file, SSA_NAME_VALUE (dest), 0);
1103 fprintf (dump_file, "\n");
1106 prev_value = const_and_copies_stack.pop ();
1107 set_ssa_name_value (dest, prev_value);
1111 /* A trivial wrapper so that we can present the generic jump
1112 threading code with a simple API for simplifying statements. */
1113 static tree
1114 simplify_stmt_for_jump_threading (gimple stmt,
1115 gimple within_stmt ATTRIBUTE_UNUSED)
1117 return lookup_avail_expr (stmt, false);
1120 /* Record into the equivalence tables any equivalences implied by
1121 traversing edge E (which are cached in E->aux).
1123 Callers are responsible for managing the unwinding markers. */
1124 static void
1125 record_temporary_equivalences (edge e)
1127 int i;
1128 struct edge_info *edge_info = (struct edge_info *) e->aux;
1130 /* If we have info associated with this edge, record it into
1131 our equivalence tables. */
1132 if (edge_info)
1134 cond_equivalence *eq;
1135 tree lhs = edge_info->lhs;
1136 tree rhs = edge_info->rhs;
1138 /* If we have a simple NAME = VALUE equivalence, record it. */
1139 if (lhs && TREE_CODE (lhs) == SSA_NAME)
1140 record_const_or_copy (lhs, rhs);
1142 /* If we have 0 = COND or 1 = COND equivalences, record them
1143 into our expression hash tables. */
1144 for (i = 0; edge_info->cond_equivalences.iterate (i, &eq); ++i)
1145 record_cond (eq);
1149 /* Wrapper for common code to attempt to thread an edge. For example,
1150 it handles lazily building the dummy condition and the bookkeeping
1151 when jump threading is successful. */
1153 void
1154 dom_opt_dom_walker::thread_across_edge (edge e)
1156 if (! m_dummy_cond)
1157 m_dummy_cond =
1158 gimple_build_cond (NE_EXPR,
1159 integer_zero_node, integer_zero_node,
1160 NULL, NULL);
1162 /* Push a marker on both stacks so we can unwind the tables back to their
1163 current state. */
1164 avail_exprs_stack.safe_push (NULL);
1165 const_and_copies_stack.safe_push (NULL_TREE);
1167 /* Traversing E may result in equivalences we can utilize. */
1168 record_temporary_equivalences (e);
1170 /* With all the edge equivalences in the tables, go ahead and attempt
1171 to thread through E->dest. */
1172 ::thread_across_edge (m_dummy_cond, e, false,
1173 &const_and_copies_stack,
1174 simplify_stmt_for_jump_threading);
1176 /* And restore the various tables to their state before
1177 we threaded this edge.
1179 XXX The code in tree-ssa-threadedge.c will restore the state of
1180 the const_and_copies table. We we just have to restore the expression
1181 table. */
1182 remove_local_expressions_from_table ();
1185 /* PHI nodes can create equivalences too.
1187 Ignoring any alternatives which are the same as the result, if
1188 all the alternatives are equal, then the PHI node creates an
1189 equivalence. */
1191 static void
1192 record_equivalences_from_phis (basic_block bb)
1194 gimple_stmt_iterator gsi;
1196 for (gsi = gsi_start_phis (bb); !gsi_end_p (gsi); gsi_next (&gsi))
1198 gimple phi = gsi_stmt (gsi);
1200 tree lhs = gimple_phi_result (phi);
1201 tree rhs = NULL;
1202 size_t i;
1204 for (i = 0; i < gimple_phi_num_args (phi); i++)
1206 tree t = gimple_phi_arg_def (phi, i);
1208 /* Ignore alternatives which are the same as our LHS. Since
1209 LHS is a PHI_RESULT, it is known to be a SSA_NAME, so we
1210 can simply compare pointers. */
1211 if (lhs == t)
1212 continue;
1214 /* If we have not processed an alternative yet, then set
1215 RHS to this alternative. */
1216 if (rhs == NULL)
1217 rhs = t;
1218 /* If we have processed an alternative (stored in RHS), then
1219 see if it is equal to this one. If it isn't, then stop
1220 the search. */
1221 else if (! operand_equal_for_phi_arg_p (rhs, t))
1222 break;
1225 /* If we had no interesting alternatives, then all the RHS alternatives
1226 must have been the same as LHS. */
1227 if (!rhs)
1228 rhs = lhs;
1230 /* If we managed to iterate through each PHI alternative without
1231 breaking out of the loop, then we have a PHI which may create
1232 a useful equivalence. We do not need to record unwind data for
1233 this, since this is a true assignment and not an equivalence
1234 inferred from a comparison. All uses of this ssa name are dominated
1235 by this assignment, so unwinding just costs time and space. */
1236 if (i == gimple_phi_num_args (phi)
1237 && may_propagate_copy (lhs, rhs))
1238 set_ssa_name_value (lhs, rhs);
1242 /* Ignoring loop backedges, if BB has precisely one incoming edge then
1243 return that edge. Otherwise return NULL. */
1244 static edge
1245 single_incoming_edge_ignoring_loop_edges (basic_block bb)
1247 edge retval = NULL;
1248 edge e;
1249 edge_iterator ei;
1251 FOR_EACH_EDGE (e, ei, bb->preds)
1253 /* A loop back edge can be identified by the destination of
1254 the edge dominating the source of the edge. */
1255 if (dominated_by_p (CDI_DOMINATORS, e->src, e->dest))
1256 continue;
1258 /* If we have already seen a non-loop edge, then we must have
1259 multiple incoming non-loop edges and thus we return NULL. */
1260 if (retval)
1261 return NULL;
1263 /* This is the first non-loop incoming edge we have found. Record
1264 it. */
1265 retval = e;
1268 return retval;
1271 /* Record any equivalences created by the incoming edge to BB. If BB
1272 has more than one incoming edge, then no equivalence is created. */
1274 static void
1275 record_equivalences_from_incoming_edge (basic_block bb)
1277 edge e;
1278 basic_block parent;
1279 struct edge_info *edge_info;
1281 /* If our parent block ended with a control statement, then we may be
1282 able to record some equivalences based on which outgoing edge from
1283 the parent was followed. */
1284 parent = get_immediate_dominator (CDI_DOMINATORS, bb);
1286 e = single_incoming_edge_ignoring_loop_edges (bb);
1288 /* If we had a single incoming edge from our parent block, then enter
1289 any data associated with the edge into our tables. */
1290 if (e && e->src == parent)
1292 unsigned int i;
1294 edge_info = (struct edge_info *) e->aux;
1296 if (edge_info)
1298 tree lhs = edge_info->lhs;
1299 tree rhs = edge_info->rhs;
1300 cond_equivalence *eq;
1302 if (lhs)
1303 record_equality (lhs, rhs);
1305 /* If LHS is an SSA_NAME and RHS is a constant integer and LHS was
1306 set via a widening type conversion, then we may be able to record
1307 additional equivalences. */
1308 if (lhs
1309 && TREE_CODE (lhs) == SSA_NAME
1310 && is_gimple_constant (rhs)
1311 && TREE_CODE (rhs) == INTEGER_CST)
1313 gimple defstmt = SSA_NAME_DEF_STMT (lhs);
1315 if (defstmt
1316 && is_gimple_assign (defstmt)
1317 && CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (defstmt)))
1319 tree old_rhs = gimple_assign_rhs1 (defstmt);
1321 /* If the conversion widens the original value and
1322 the constant is in the range of the type of OLD_RHS,
1323 then convert the constant and record the equivalence.
1325 Note that int_fits_type_p does not check the precision
1326 if the upper and lower bounds are OK. */
1327 if (INTEGRAL_TYPE_P (TREE_TYPE (old_rhs))
1328 && (TYPE_PRECISION (TREE_TYPE (lhs))
1329 > TYPE_PRECISION (TREE_TYPE (old_rhs)))
1330 && int_fits_type_p (rhs, TREE_TYPE (old_rhs)))
1332 tree newval = fold_convert (TREE_TYPE (old_rhs), rhs);
1333 record_equality (old_rhs, newval);
1338 for (i = 0; edge_info->cond_equivalences.iterate (i, &eq); ++i)
1339 record_cond (eq);
1344 /* Dump SSA statistics on FILE. */
1346 void
1347 dump_dominator_optimization_stats (FILE *file)
1349 fprintf (file, "Total number of statements: %6ld\n\n",
1350 opt_stats.num_stmts);
1351 fprintf (file, "Exprs considered for dominator optimizations: %6ld\n",
1352 opt_stats.num_exprs_considered);
1354 fprintf (file, "\nHash table statistics:\n");
1356 fprintf (file, " avail_exprs: ");
1357 htab_statistics (file, *avail_exprs);
1361 /* Dump SSA statistics on stderr. */
1363 DEBUG_FUNCTION void
1364 debug_dominator_optimization_stats (void)
1366 dump_dominator_optimization_stats (stderr);
1370 /* Dump statistics for the hash table HTAB. */
1372 static void
1373 htab_statistics (FILE *file, const hash_table<expr_elt_hasher> &htab)
1375 fprintf (file, "size %ld, %ld elements, %f collision/search ratio\n",
1376 (long) htab.size (),
1377 (long) htab.elements (),
1378 htab.collisions ());
1382 /* Enter condition equivalence into the expression hash table.
1383 This indicates that a conditional expression has a known
1384 boolean value. */
1386 static void
1387 record_cond (cond_equivalence *p)
1389 struct expr_hash_elt *element = XCNEW (struct expr_hash_elt);
1390 expr_hash_elt **slot;
1392 initialize_hash_element_from_expr (&p->cond, p->value, element);
1394 slot = avail_exprs->find_slot_with_hash (element, element->hash, INSERT);
1395 if (*slot == NULL)
1397 *slot = element;
1399 if (dump_file && (dump_flags & TDF_DETAILS))
1401 fprintf (dump_file, "1>>> ");
1402 print_expr_hash_elt (dump_file, element);
1405 avail_exprs_stack.safe_push (element);
1407 else
1408 free_expr_hash_elt (element);
1411 /* Build a cond_equivalence record indicating that the comparison
1412 CODE holds between operands OP0 and OP1 and push it to **P. */
1414 static void
1415 build_and_record_new_cond (enum tree_code code,
1416 tree op0, tree op1,
1417 vec<cond_equivalence> *p)
1419 cond_equivalence c;
1420 struct hashable_expr *cond = &c.cond;
1422 gcc_assert (TREE_CODE_CLASS (code) == tcc_comparison);
1424 cond->type = boolean_type_node;
1425 cond->kind = EXPR_BINARY;
1426 cond->ops.binary.op = code;
1427 cond->ops.binary.opnd0 = op0;
1428 cond->ops.binary.opnd1 = op1;
1430 c.value = boolean_true_node;
1431 p->safe_push (c);
1434 /* Record that COND is true and INVERTED is false into the edge information
1435 structure. Also record that any conditions dominated by COND are true
1436 as well.
1438 For example, if a < b is true, then a <= b must also be true. */
1440 static void
1441 record_conditions (struct edge_info *edge_info, tree cond, tree inverted)
1443 tree op0, op1;
1444 cond_equivalence c;
1446 if (!COMPARISON_CLASS_P (cond))
1447 return;
1449 op0 = TREE_OPERAND (cond, 0);
1450 op1 = TREE_OPERAND (cond, 1);
1452 switch (TREE_CODE (cond))
1454 case LT_EXPR:
1455 case GT_EXPR:
1456 if (FLOAT_TYPE_P (TREE_TYPE (op0)))
1458 build_and_record_new_cond (ORDERED_EXPR, op0, op1,
1459 &edge_info->cond_equivalences);
1460 build_and_record_new_cond (LTGT_EXPR, op0, op1,
1461 &edge_info->cond_equivalences);
1464 build_and_record_new_cond ((TREE_CODE (cond) == LT_EXPR
1465 ? LE_EXPR : GE_EXPR),
1466 op0, op1, &edge_info->cond_equivalences);
1467 build_and_record_new_cond (NE_EXPR, op0, op1,
1468 &edge_info->cond_equivalences);
1469 break;
1471 case GE_EXPR:
1472 case LE_EXPR:
1473 if (FLOAT_TYPE_P (TREE_TYPE (op0)))
1475 build_and_record_new_cond (ORDERED_EXPR, op0, op1,
1476 &edge_info->cond_equivalences);
1478 break;
1480 case EQ_EXPR:
1481 if (FLOAT_TYPE_P (TREE_TYPE (op0)))
1483 build_and_record_new_cond (ORDERED_EXPR, op0, op1,
1484 &edge_info->cond_equivalences);
1486 build_and_record_new_cond (LE_EXPR, op0, op1,
1487 &edge_info->cond_equivalences);
1488 build_and_record_new_cond (GE_EXPR, op0, op1,
1489 &edge_info->cond_equivalences);
1490 break;
1492 case UNORDERED_EXPR:
1493 build_and_record_new_cond (NE_EXPR, op0, op1,
1494 &edge_info->cond_equivalences);
1495 build_and_record_new_cond (UNLE_EXPR, op0, op1,
1496 &edge_info->cond_equivalences);
1497 build_and_record_new_cond (UNGE_EXPR, op0, op1,
1498 &edge_info->cond_equivalences);
1499 build_and_record_new_cond (UNEQ_EXPR, op0, op1,
1500 &edge_info->cond_equivalences);
1501 build_and_record_new_cond (UNLT_EXPR, op0, op1,
1502 &edge_info->cond_equivalences);
1503 build_and_record_new_cond (UNGT_EXPR, op0, op1,
1504 &edge_info->cond_equivalences);
1505 break;
1507 case UNLT_EXPR:
1508 case UNGT_EXPR:
1509 build_and_record_new_cond ((TREE_CODE (cond) == UNLT_EXPR
1510 ? UNLE_EXPR : UNGE_EXPR),
1511 op0, op1, &edge_info->cond_equivalences);
1512 build_and_record_new_cond (NE_EXPR, op0, op1,
1513 &edge_info->cond_equivalences);
1514 break;
1516 case UNEQ_EXPR:
1517 build_and_record_new_cond (UNLE_EXPR, op0, op1,
1518 &edge_info->cond_equivalences);
1519 build_and_record_new_cond (UNGE_EXPR, op0, op1,
1520 &edge_info->cond_equivalences);
1521 break;
1523 case LTGT_EXPR:
1524 build_and_record_new_cond (NE_EXPR, op0, op1,
1525 &edge_info->cond_equivalences);
1526 build_and_record_new_cond (ORDERED_EXPR, op0, op1,
1527 &edge_info->cond_equivalences);
1528 break;
1530 default:
1531 break;
1534 /* Now store the original true and false conditions into the first
1535 two slots. */
1536 initialize_expr_from_cond (cond, &c.cond);
1537 c.value = boolean_true_node;
1538 edge_info->cond_equivalences.safe_push (c);
1540 /* It is possible for INVERTED to be the negation of a comparison,
1541 and not a valid RHS or GIMPLE_COND condition. This happens because
1542 invert_truthvalue may return such an expression when asked to invert
1543 a floating-point comparison. These comparisons are not assumed to
1544 obey the trichotomy law. */
1545 initialize_expr_from_cond (inverted, &c.cond);
1546 c.value = boolean_false_node;
1547 edge_info->cond_equivalences.safe_push (c);
1550 /* A helper function for record_const_or_copy and record_equality.
1551 Do the work of recording the value and undo info. */
1553 static void
1554 record_const_or_copy_1 (tree x, tree y, tree prev_x)
1556 set_ssa_name_value (x, y);
1558 if (dump_file && (dump_flags & TDF_DETAILS))
1560 fprintf (dump_file, "0>>> COPY ");
1561 print_generic_expr (dump_file, x, 0);
1562 fprintf (dump_file, " = ");
1563 print_generic_expr (dump_file, y, 0);
1564 fprintf (dump_file, "\n");
1567 const_and_copies_stack.reserve (2);
1568 const_and_copies_stack.quick_push (prev_x);
1569 const_and_copies_stack.quick_push (x);
1572 /* Record that X is equal to Y in const_and_copies. Record undo
1573 information in the block-local vector. */
1575 static void
1576 record_const_or_copy (tree x, tree y)
1578 tree prev_x = SSA_NAME_VALUE (x);
1580 gcc_assert (TREE_CODE (x) == SSA_NAME);
1582 if (TREE_CODE (y) == SSA_NAME)
1584 tree tmp = SSA_NAME_VALUE (y);
1585 if (tmp)
1586 y = tmp;
1589 record_const_or_copy_1 (x, y, prev_x);
1592 /* Return the loop depth of the basic block of the defining statement of X.
1593 This number should not be treated as absolutely correct because the loop
1594 information may not be completely up-to-date when dom runs. However, it
1595 will be relatively correct, and as more passes are taught to keep loop info
1596 up to date, the result will become more and more accurate. */
1598 static int
1599 loop_depth_of_name (tree x)
1601 gimple defstmt;
1602 basic_block defbb;
1604 /* If it's not an SSA_NAME, we have no clue where the definition is. */
1605 if (TREE_CODE (x) != SSA_NAME)
1606 return 0;
1608 /* Otherwise return the loop depth of the defining statement's bb.
1609 Note that there may not actually be a bb for this statement, if the
1610 ssa_name is live on entry. */
1611 defstmt = SSA_NAME_DEF_STMT (x);
1612 defbb = gimple_bb (defstmt);
1613 if (!defbb)
1614 return 0;
1616 return bb_loop_depth (defbb);
1619 /* Similarly, but assume that X and Y are the two operands of an EQ_EXPR.
1620 This constrains the cases in which we may treat this as assignment. */
1622 static void
1623 record_equality (tree x, tree y)
1625 tree prev_x = NULL, prev_y = NULL;
1627 if (TREE_CODE (x) == SSA_NAME)
1628 prev_x = SSA_NAME_VALUE (x);
1629 if (TREE_CODE (y) == SSA_NAME)
1630 prev_y = SSA_NAME_VALUE (y);
1632 /* If one of the previous values is invariant, or invariant in more loops
1633 (by depth), then use that.
1634 Otherwise it doesn't matter which value we choose, just so
1635 long as we canonicalize on one value. */
1636 if (is_gimple_min_invariant (y))
1638 else if (is_gimple_min_invariant (x)
1639 /* ??? When threading over backedges the following is important
1640 for correctness. See PR61757. */
1641 || (loop_depth_of_name (x) <= loop_depth_of_name (y)))
1642 prev_x = x, x = y, y = prev_x, prev_x = prev_y;
1643 else if (prev_x && is_gimple_min_invariant (prev_x))
1644 x = y, y = prev_x, prev_x = prev_y;
1645 else if (prev_y)
1646 y = prev_y;
1648 /* After the swapping, we must have one SSA_NAME. */
1649 if (TREE_CODE (x) != SSA_NAME)
1650 return;
1652 /* For IEEE, -0.0 == 0.0, so we don't necessarily know the sign of a
1653 variable compared against zero. If we're honoring signed zeros,
1654 then we cannot record this value unless we know that the value is
1655 nonzero. */
1656 if (HONOR_SIGNED_ZEROS (TYPE_MODE (TREE_TYPE (x)))
1657 && (TREE_CODE (y) != REAL_CST
1658 || REAL_VALUES_EQUAL (dconst0, TREE_REAL_CST (y))))
1659 return;
1661 record_const_or_copy_1 (x, y, prev_x);
1664 /* Returns true when STMT is a simple iv increment. It detects the
1665 following situation:
1667 i_1 = phi (..., i_2)
1668 i_2 = i_1 +/- ... */
1670 bool
1671 simple_iv_increment_p (gimple stmt)
1673 enum tree_code code;
1674 tree lhs, preinc;
1675 gimple phi;
1676 size_t i;
1678 if (gimple_code (stmt) != GIMPLE_ASSIGN)
1679 return false;
1681 lhs = gimple_assign_lhs (stmt);
1682 if (TREE_CODE (lhs) != SSA_NAME)
1683 return false;
1685 code = gimple_assign_rhs_code (stmt);
1686 if (code != PLUS_EXPR
1687 && code != MINUS_EXPR
1688 && code != POINTER_PLUS_EXPR)
1689 return false;
1691 preinc = gimple_assign_rhs1 (stmt);
1692 if (TREE_CODE (preinc) != SSA_NAME)
1693 return false;
1695 phi = SSA_NAME_DEF_STMT (preinc);
1696 if (gimple_code (phi) != GIMPLE_PHI)
1697 return false;
1699 for (i = 0; i < gimple_phi_num_args (phi); i++)
1700 if (gimple_phi_arg_def (phi, i) == lhs)
1701 return true;
1703 return false;
1706 /* CONST_AND_COPIES is a table which maps an SSA_NAME to the current
1707 known value for that SSA_NAME (or NULL if no value is known).
1709 Propagate values from CONST_AND_COPIES into the PHI nodes of the
1710 successors of BB. */
1712 static void
1713 cprop_into_successor_phis (basic_block bb)
1715 edge e;
1716 edge_iterator ei;
1718 FOR_EACH_EDGE (e, ei, bb->succs)
1720 int indx;
1721 gimple_stmt_iterator gsi;
1723 /* If this is an abnormal edge, then we do not want to copy propagate
1724 into the PHI alternative associated with this edge. */
1725 if (e->flags & EDGE_ABNORMAL)
1726 continue;
1728 gsi = gsi_start_phis (e->dest);
1729 if (gsi_end_p (gsi))
1730 continue;
1732 /* We may have an equivalence associated with this edge. While
1733 we can not propagate it into non-dominated blocks, we can
1734 propagate them into PHIs in non-dominated blocks. */
1736 /* Push the unwind marker so we can reset the const and copies
1737 table back to its original state after processing this edge. */
1738 const_and_copies_stack.safe_push (NULL_TREE);
1740 /* Extract and record any simple NAME = VALUE equivalences.
1742 Don't bother with [01] = COND equivalences, they're not useful
1743 here. */
1744 struct edge_info *edge_info = (struct edge_info *) e->aux;
1745 if (edge_info)
1747 tree lhs = edge_info->lhs;
1748 tree rhs = edge_info->rhs;
1750 if (lhs && TREE_CODE (lhs) == SSA_NAME)
1751 record_const_or_copy (lhs, rhs);
1754 indx = e->dest_idx;
1755 for ( ; !gsi_end_p (gsi); gsi_next (&gsi))
1757 tree new_val;
1758 use_operand_p orig_p;
1759 tree orig_val;
1760 gimple phi = gsi_stmt (gsi);
1762 /* The alternative may be associated with a constant, so verify
1763 it is an SSA_NAME before doing anything with it. */
1764 orig_p = gimple_phi_arg_imm_use_ptr (phi, indx);
1765 orig_val = get_use_from_ptr (orig_p);
1766 if (TREE_CODE (orig_val) != SSA_NAME)
1767 continue;
1769 /* If we have *ORIG_P in our constant/copy table, then replace
1770 ORIG_P with its value in our constant/copy table. */
1771 new_val = SSA_NAME_VALUE (orig_val);
1772 if (new_val
1773 && new_val != orig_val
1774 && (TREE_CODE (new_val) == SSA_NAME
1775 || is_gimple_min_invariant (new_val))
1776 && may_propagate_copy (orig_val, new_val))
1777 propagate_value (orig_p, new_val);
1780 restore_vars_to_original_value ();
1784 /* We have finished optimizing BB, record any information implied by
1785 taking a specific outgoing edge from BB. */
1787 static void
1788 record_edge_info (basic_block bb)
1790 gimple_stmt_iterator gsi = gsi_last_bb (bb);
1791 struct edge_info *edge_info;
1793 if (! gsi_end_p (gsi))
1795 gimple stmt = gsi_stmt (gsi);
1796 location_t loc = gimple_location (stmt);
1798 if (gimple_code (stmt) == GIMPLE_SWITCH)
1800 tree index = gimple_switch_index (stmt);
1802 if (TREE_CODE (index) == SSA_NAME)
1804 int i;
1805 int n_labels = gimple_switch_num_labels (stmt);
1806 tree *info = XCNEWVEC (tree, last_basic_block_for_fn (cfun));
1807 edge e;
1808 edge_iterator ei;
1810 for (i = 0; i < n_labels; i++)
1812 tree label = gimple_switch_label (stmt, i);
1813 basic_block target_bb = label_to_block (CASE_LABEL (label));
1814 if (CASE_HIGH (label)
1815 || !CASE_LOW (label)
1816 || info[target_bb->index])
1817 info[target_bb->index] = error_mark_node;
1818 else
1819 info[target_bb->index] = label;
1822 FOR_EACH_EDGE (e, ei, bb->succs)
1824 basic_block target_bb = e->dest;
1825 tree label = info[target_bb->index];
1827 if (label != NULL && label != error_mark_node)
1829 tree x = fold_convert_loc (loc, TREE_TYPE (index),
1830 CASE_LOW (label));
1831 edge_info = allocate_edge_info (e);
1832 edge_info->lhs = index;
1833 edge_info->rhs = x;
1836 free (info);
1840 /* A COND_EXPR may create equivalences too. */
1841 if (gimple_code (stmt) == GIMPLE_COND)
1843 edge true_edge;
1844 edge false_edge;
1846 tree op0 = gimple_cond_lhs (stmt);
1847 tree op1 = gimple_cond_rhs (stmt);
1848 enum tree_code code = gimple_cond_code (stmt);
1850 extract_true_false_edges_from_block (bb, &true_edge, &false_edge);
1852 /* Special case comparing booleans against a constant as we
1853 know the value of OP0 on both arms of the branch. i.e., we
1854 can record an equivalence for OP0 rather than COND. */
1855 if ((code == EQ_EXPR || code == NE_EXPR)
1856 && TREE_CODE (op0) == SSA_NAME
1857 && TREE_CODE (TREE_TYPE (op0)) == BOOLEAN_TYPE
1858 && is_gimple_min_invariant (op1))
1860 if (code == EQ_EXPR)
1862 edge_info = allocate_edge_info (true_edge);
1863 edge_info->lhs = op0;
1864 edge_info->rhs = (integer_zerop (op1)
1865 ? boolean_false_node
1866 : boolean_true_node);
1868 edge_info = allocate_edge_info (false_edge);
1869 edge_info->lhs = op0;
1870 edge_info->rhs = (integer_zerop (op1)
1871 ? boolean_true_node
1872 : boolean_false_node);
1874 else
1876 edge_info = allocate_edge_info (true_edge);
1877 edge_info->lhs = op0;
1878 edge_info->rhs = (integer_zerop (op1)
1879 ? boolean_true_node
1880 : boolean_false_node);
1882 edge_info = allocate_edge_info (false_edge);
1883 edge_info->lhs = op0;
1884 edge_info->rhs = (integer_zerop (op1)
1885 ? boolean_false_node
1886 : boolean_true_node);
1889 else if (is_gimple_min_invariant (op0)
1890 && (TREE_CODE (op1) == SSA_NAME
1891 || is_gimple_min_invariant (op1)))
1893 tree cond = build2 (code, boolean_type_node, op0, op1);
1894 tree inverted = invert_truthvalue_loc (loc, cond);
1895 bool can_infer_simple_equiv
1896 = !(HONOR_SIGNED_ZEROS (TYPE_MODE (TREE_TYPE (op0)))
1897 && real_zerop (op0));
1898 struct edge_info *edge_info;
1900 edge_info = allocate_edge_info (true_edge);
1901 record_conditions (edge_info, cond, inverted);
1903 if (can_infer_simple_equiv && code == EQ_EXPR)
1905 edge_info->lhs = op1;
1906 edge_info->rhs = op0;
1909 edge_info = allocate_edge_info (false_edge);
1910 record_conditions (edge_info, inverted, cond);
1912 if (can_infer_simple_equiv && TREE_CODE (inverted) == EQ_EXPR)
1914 edge_info->lhs = op1;
1915 edge_info->rhs = op0;
1919 else if (TREE_CODE (op0) == SSA_NAME
1920 && (TREE_CODE (op1) == SSA_NAME
1921 || is_gimple_min_invariant (op1)))
1923 tree cond = build2 (code, boolean_type_node, op0, op1);
1924 tree inverted = invert_truthvalue_loc (loc, cond);
1925 bool can_infer_simple_equiv
1926 = !(HONOR_SIGNED_ZEROS (TYPE_MODE (TREE_TYPE (op1)))
1927 && (TREE_CODE (op1) == SSA_NAME || real_zerop (op1)));
1928 struct edge_info *edge_info;
1930 edge_info = allocate_edge_info (true_edge);
1931 record_conditions (edge_info, cond, inverted);
1933 if (can_infer_simple_equiv && code == EQ_EXPR)
1935 edge_info->lhs = op0;
1936 edge_info->rhs = op1;
1939 edge_info = allocate_edge_info (false_edge);
1940 record_conditions (edge_info, inverted, cond);
1942 if (can_infer_simple_equiv && TREE_CODE (inverted) == EQ_EXPR)
1944 edge_info->lhs = op0;
1945 edge_info->rhs = op1;
1950 /* ??? TRUTH_NOT_EXPR can create an equivalence too. */
1954 void
1955 dom_opt_dom_walker::before_dom_children (basic_block bb)
1957 gimple_stmt_iterator gsi;
1959 if (dump_file && (dump_flags & TDF_DETAILS))
1960 fprintf (dump_file, "\n\nOptimizing block #%d\n\n", bb->index);
1962 /* Push a marker on the stacks of local information so that we know how
1963 far to unwind when we finalize this block. */
1964 avail_exprs_stack.safe_push (NULL);
1965 const_and_copies_stack.safe_push (NULL_TREE);
1967 record_equivalences_from_incoming_edge (bb);
1969 /* PHI nodes can create equivalences too. */
1970 record_equivalences_from_phis (bb);
1972 /* Create equivalences from redundant PHIs. PHIs are only truly
1973 redundant when they exist in the same block, so push another
1974 marker and unwind right afterwards. */
1975 avail_exprs_stack.safe_push (NULL);
1976 for (gsi = gsi_start_phis (bb); !gsi_end_p (gsi); gsi_next (&gsi))
1977 eliminate_redundant_computations (&gsi);
1978 remove_local_expressions_from_table ();
1980 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
1981 optimize_stmt (bb, gsi);
1983 /* Now prepare to process dominated blocks. */
1984 record_edge_info (bb);
1985 cprop_into_successor_phis (bb);
1988 /* We have finished processing the dominator children of BB, perform
1989 any finalization actions in preparation for leaving this node in
1990 the dominator tree. */
1992 void
1993 dom_opt_dom_walker::after_dom_children (basic_block bb)
1995 gimple last;
1997 /* If we have an outgoing edge to a block with multiple incoming and
1998 outgoing edges, then we may be able to thread the edge, i.e., we
1999 may be able to statically determine which of the outgoing edges
2000 will be traversed when the incoming edge from BB is traversed. */
2001 if (single_succ_p (bb)
2002 && (single_succ_edge (bb)->flags & EDGE_ABNORMAL) == 0
2003 && potentially_threadable_block (single_succ (bb)))
2005 thread_across_edge (single_succ_edge (bb));
2007 else if ((last = last_stmt (bb))
2008 && gimple_code (last) == GIMPLE_COND
2009 && EDGE_COUNT (bb->succs) == 2
2010 && (EDGE_SUCC (bb, 0)->flags & EDGE_ABNORMAL) == 0
2011 && (EDGE_SUCC (bb, 1)->flags & EDGE_ABNORMAL) == 0)
2013 edge true_edge, false_edge;
2015 extract_true_false_edges_from_block (bb, &true_edge, &false_edge);
2017 /* Only try to thread the edge if it reaches a target block with
2018 more than one predecessor and more than one successor. */
2019 if (potentially_threadable_block (true_edge->dest))
2020 thread_across_edge (true_edge);
2022 /* Similarly for the ELSE arm. */
2023 if (potentially_threadable_block (false_edge->dest))
2024 thread_across_edge (false_edge);
2028 /* These remove expressions local to BB from the tables. */
2029 remove_local_expressions_from_table ();
2030 restore_vars_to_original_value ();
2033 /* Search for redundant computations in STMT. If any are found, then
2034 replace them with the variable holding the result of the computation.
2036 If safe, record this expression into the available expression hash
2037 table. */
2039 static void
2040 eliminate_redundant_computations (gimple_stmt_iterator* gsi)
2042 tree expr_type;
2043 tree cached_lhs;
2044 tree def;
2045 bool insert = true;
2046 bool assigns_var_p = false;
2048 gimple stmt = gsi_stmt (*gsi);
2050 if (gimple_code (stmt) == GIMPLE_PHI)
2051 def = gimple_phi_result (stmt);
2052 else
2053 def = gimple_get_lhs (stmt);
2055 /* Certain expressions on the RHS can be optimized away, but can not
2056 themselves be entered into the hash tables. */
2057 if (! def
2058 || TREE_CODE (def) != SSA_NAME
2059 || SSA_NAME_OCCURS_IN_ABNORMAL_PHI (def)
2060 || gimple_vdef (stmt)
2061 /* Do not record equivalences for increments of ivs. This would create
2062 overlapping live ranges for a very questionable gain. */
2063 || simple_iv_increment_p (stmt))
2064 insert = false;
2066 /* Check if the expression has been computed before. */
2067 cached_lhs = lookup_avail_expr (stmt, insert);
2069 opt_stats.num_exprs_considered++;
2071 /* Get the type of the expression we are trying to optimize. */
2072 if (is_gimple_assign (stmt))
2074 expr_type = TREE_TYPE (gimple_assign_lhs (stmt));
2075 assigns_var_p = true;
2077 else if (gimple_code (stmt) == GIMPLE_COND)
2078 expr_type = boolean_type_node;
2079 else if (is_gimple_call (stmt))
2081 gcc_assert (gimple_call_lhs (stmt));
2082 expr_type = TREE_TYPE (gimple_call_lhs (stmt));
2083 assigns_var_p = true;
2085 else if (gimple_code (stmt) == GIMPLE_SWITCH)
2086 expr_type = TREE_TYPE (gimple_switch_index (stmt));
2087 else if (gimple_code (stmt) == GIMPLE_PHI)
2088 /* We can't propagate into a phi, so the logic below doesn't apply.
2089 Instead record an equivalence between the cached LHS and the
2090 PHI result of this statement, provided they are in the same block.
2091 This should be sufficient to kill the redundant phi. */
2093 if (def && cached_lhs)
2094 record_const_or_copy (def, cached_lhs);
2095 return;
2097 else
2098 gcc_unreachable ();
2100 if (!cached_lhs)
2101 return;
2103 /* It is safe to ignore types here since we have already done
2104 type checking in the hashing and equality routines. In fact
2105 type checking here merely gets in the way of constant
2106 propagation. Also, make sure that it is safe to propagate
2107 CACHED_LHS into the expression in STMT. */
2108 if ((TREE_CODE (cached_lhs) != SSA_NAME
2109 && (assigns_var_p
2110 || useless_type_conversion_p (expr_type, TREE_TYPE (cached_lhs))))
2111 || may_propagate_copy_into_stmt (stmt, cached_lhs))
2113 gcc_checking_assert (TREE_CODE (cached_lhs) == SSA_NAME
2114 || is_gimple_min_invariant (cached_lhs));
2116 if (dump_file && (dump_flags & TDF_DETAILS))
2118 fprintf (dump_file, " Replaced redundant expr '");
2119 print_gimple_expr (dump_file, stmt, 0, dump_flags);
2120 fprintf (dump_file, "' with '");
2121 print_generic_expr (dump_file, cached_lhs, dump_flags);
2122 fprintf (dump_file, "'\n");
2125 opt_stats.num_re++;
2127 if (assigns_var_p
2128 && !useless_type_conversion_p (expr_type, TREE_TYPE (cached_lhs)))
2129 cached_lhs = fold_convert (expr_type, cached_lhs);
2131 propagate_tree_value_into_stmt (gsi, cached_lhs);
2133 /* Since it is always necessary to mark the result as modified,
2134 perhaps we should move this into propagate_tree_value_into_stmt
2135 itself. */
2136 gimple_set_modified (gsi_stmt (*gsi), true);
2140 /* STMT, a GIMPLE_ASSIGN, may create certain equivalences, in either
2141 the available expressions table or the const_and_copies table.
2142 Detect and record those equivalences. */
2143 /* We handle only very simple copy equivalences here. The heavy
2144 lifing is done by eliminate_redundant_computations. */
2146 static void
2147 record_equivalences_from_stmt (gimple stmt, int may_optimize_p)
2149 tree lhs;
2150 enum tree_code lhs_code;
2152 gcc_assert (is_gimple_assign (stmt));
2154 lhs = gimple_assign_lhs (stmt);
2155 lhs_code = TREE_CODE (lhs);
2157 if (lhs_code == SSA_NAME
2158 && gimple_assign_single_p (stmt))
2160 tree rhs = gimple_assign_rhs1 (stmt);
2162 /* If the RHS of the assignment is a constant or another variable that
2163 may be propagated, register it in the CONST_AND_COPIES table. We
2164 do not need to record unwind data for this, since this is a true
2165 assignment and not an equivalence inferred from a comparison. All
2166 uses of this ssa name are dominated by this assignment, so unwinding
2167 just costs time and space. */
2168 if (may_optimize_p
2169 && (TREE_CODE (rhs) == SSA_NAME
2170 || is_gimple_min_invariant (rhs)))
2172 if (dump_file && (dump_flags & TDF_DETAILS))
2174 fprintf (dump_file, "==== ASGN ");
2175 print_generic_expr (dump_file, lhs, 0);
2176 fprintf (dump_file, " = ");
2177 print_generic_expr (dump_file, rhs, 0);
2178 fprintf (dump_file, "\n");
2181 set_ssa_name_value (lhs, rhs);
2185 /* A memory store, even an aliased store, creates a useful
2186 equivalence. By exchanging the LHS and RHS, creating suitable
2187 vops and recording the result in the available expression table,
2188 we may be able to expose more redundant loads. */
2189 if (!gimple_has_volatile_ops (stmt)
2190 && gimple_references_memory_p (stmt)
2191 && gimple_assign_single_p (stmt)
2192 && (TREE_CODE (gimple_assign_rhs1 (stmt)) == SSA_NAME
2193 || is_gimple_min_invariant (gimple_assign_rhs1 (stmt)))
2194 && !is_gimple_reg (lhs))
2196 tree rhs = gimple_assign_rhs1 (stmt);
2197 gimple new_stmt;
2199 /* Build a new statement with the RHS and LHS exchanged. */
2200 if (TREE_CODE (rhs) == SSA_NAME)
2202 /* NOTE tuples. The call to gimple_build_assign below replaced
2203 a call to build_gimple_modify_stmt, which did not set the
2204 SSA_NAME_DEF_STMT on the LHS of the assignment. Doing so
2205 may cause an SSA validation failure, as the LHS may be a
2206 default-initialized name and should have no definition. I'm
2207 a bit dubious of this, as the artificial statement that we
2208 generate here may in fact be ill-formed, but it is simply
2209 used as an internal device in this pass, and never becomes
2210 part of the CFG. */
2211 gimple defstmt = SSA_NAME_DEF_STMT (rhs);
2212 new_stmt = gimple_build_assign (rhs, lhs);
2213 SSA_NAME_DEF_STMT (rhs) = defstmt;
2215 else
2216 new_stmt = gimple_build_assign (rhs, lhs);
2218 gimple_set_vuse (new_stmt, gimple_vdef (stmt));
2220 /* Finally enter the statement into the available expression
2221 table. */
2222 lookup_avail_expr (new_stmt, true);
2226 /* Replace *OP_P in STMT with any known equivalent value for *OP_P from
2227 CONST_AND_COPIES. */
2229 static void
2230 cprop_operand (gimple stmt, use_operand_p op_p)
2232 tree val;
2233 tree op = USE_FROM_PTR (op_p);
2235 /* If the operand has a known constant value or it is known to be a
2236 copy of some other variable, use the value or copy stored in
2237 CONST_AND_COPIES. */
2238 val = SSA_NAME_VALUE (op);
2239 if (val && val != op)
2241 /* Do not replace hard register operands in asm statements. */
2242 if (gimple_code (stmt) == GIMPLE_ASM
2243 && !may_propagate_copy_into_asm (op))
2244 return;
2246 /* Certain operands are not allowed to be copy propagated due
2247 to their interaction with exception handling and some GCC
2248 extensions. */
2249 if (!may_propagate_copy (op, val))
2250 return;
2252 /* Do not propagate copies into simple IV increment statements.
2253 See PR23821 for how this can disturb IV analysis. */
2254 if (TREE_CODE (val) != INTEGER_CST
2255 && simple_iv_increment_p (stmt))
2256 return;
2258 /* Dump details. */
2259 if (dump_file && (dump_flags & TDF_DETAILS))
2261 fprintf (dump_file, " Replaced '");
2262 print_generic_expr (dump_file, op, dump_flags);
2263 fprintf (dump_file, "' with %s '",
2264 (TREE_CODE (val) != SSA_NAME ? "constant" : "variable"));
2265 print_generic_expr (dump_file, val, dump_flags);
2266 fprintf (dump_file, "'\n");
2269 if (TREE_CODE (val) != SSA_NAME)
2270 opt_stats.num_const_prop++;
2271 else
2272 opt_stats.num_copy_prop++;
2274 propagate_value (op_p, val);
2276 /* And note that we modified this statement. This is now
2277 safe, even if we changed virtual operands since we will
2278 rescan the statement and rewrite its operands again. */
2279 gimple_set_modified (stmt, true);
2283 /* CONST_AND_COPIES is a table which maps an SSA_NAME to the current
2284 known value for that SSA_NAME (or NULL if no value is known).
2286 Propagate values from CONST_AND_COPIES into the uses, vuses and
2287 vdef_ops of STMT. */
2289 static void
2290 cprop_into_stmt (gimple stmt)
2292 use_operand_p op_p;
2293 ssa_op_iter iter;
2295 FOR_EACH_SSA_USE_OPERAND (op_p, stmt, iter, SSA_OP_USE)
2296 cprop_operand (stmt, op_p);
2299 /* Optimize the statement pointed to by iterator SI.
2301 We try to perform some simplistic global redundancy elimination and
2302 constant propagation:
2304 1- To detect global redundancy, we keep track of expressions that have
2305 been computed in this block and its dominators. If we find that the
2306 same expression is computed more than once, we eliminate repeated
2307 computations by using the target of the first one.
2309 2- Constant values and copy assignments. This is used to do very
2310 simplistic constant and copy propagation. When a constant or copy
2311 assignment is found, we map the value on the RHS of the assignment to
2312 the variable in the LHS in the CONST_AND_COPIES table. */
2314 static void
2315 optimize_stmt (basic_block bb, gimple_stmt_iterator si)
2317 gimple stmt, old_stmt;
2318 bool may_optimize_p;
2319 bool modified_p = false;
2321 old_stmt = stmt = gsi_stmt (si);
2323 if (dump_file && (dump_flags & TDF_DETAILS))
2325 fprintf (dump_file, "Optimizing statement ");
2326 print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
2329 if (gimple_code (stmt) == GIMPLE_COND)
2330 canonicalize_comparison (stmt);
2332 update_stmt_if_modified (stmt);
2333 opt_stats.num_stmts++;
2335 /* Const/copy propagate into USES, VUSES and the RHS of VDEFs. */
2336 cprop_into_stmt (stmt);
2338 /* If the statement has been modified with constant replacements,
2339 fold its RHS before checking for redundant computations. */
2340 if (gimple_modified_p (stmt))
2342 tree rhs = NULL;
2344 /* Try to fold the statement making sure that STMT is kept
2345 up to date. */
2346 if (fold_stmt (&si))
2348 stmt = gsi_stmt (si);
2349 gimple_set_modified (stmt, true);
2351 if (dump_file && (dump_flags & TDF_DETAILS))
2353 fprintf (dump_file, " Folded to: ");
2354 print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
2358 /* We only need to consider cases that can yield a gimple operand. */
2359 if (gimple_assign_single_p (stmt))
2360 rhs = gimple_assign_rhs1 (stmt);
2361 else if (gimple_code (stmt) == GIMPLE_GOTO)
2362 rhs = gimple_goto_dest (stmt);
2363 else if (gimple_code (stmt) == GIMPLE_SWITCH)
2364 /* This should never be an ADDR_EXPR. */
2365 rhs = gimple_switch_index (stmt);
2367 if (rhs && TREE_CODE (rhs) == ADDR_EXPR)
2368 recompute_tree_invariant_for_addr_expr (rhs);
2370 /* Indicate that maybe_clean_or_replace_eh_stmt needs to be called,
2371 even if fold_stmt updated the stmt already and thus cleared
2372 gimple_modified_p flag on it. */
2373 modified_p = true;
2376 /* Check for redundant computations. Do this optimization only
2377 for assignments that have no volatile ops and conditionals. */
2378 may_optimize_p = (!gimple_has_side_effects (stmt)
2379 && (is_gimple_assign (stmt)
2380 || (is_gimple_call (stmt)
2381 && gimple_call_lhs (stmt) != NULL_TREE)
2382 || gimple_code (stmt) == GIMPLE_COND
2383 || gimple_code (stmt) == GIMPLE_SWITCH));
2385 if (may_optimize_p)
2387 if (gimple_code (stmt) == GIMPLE_CALL)
2389 /* Resolve __builtin_constant_p. If it hasn't been
2390 folded to integer_one_node by now, it's fairly
2391 certain that the value simply isn't constant. */
2392 tree callee = gimple_call_fndecl (stmt);
2393 if (callee
2394 && DECL_BUILT_IN_CLASS (callee) == BUILT_IN_NORMAL
2395 && DECL_FUNCTION_CODE (callee) == BUILT_IN_CONSTANT_P)
2397 propagate_tree_value_into_stmt (&si, integer_zero_node);
2398 stmt = gsi_stmt (si);
2402 update_stmt_if_modified (stmt);
2403 eliminate_redundant_computations (&si);
2404 stmt = gsi_stmt (si);
2406 /* Perform simple redundant store elimination. */
2407 if (gimple_assign_single_p (stmt)
2408 && TREE_CODE (gimple_assign_lhs (stmt)) != SSA_NAME)
2410 tree lhs = gimple_assign_lhs (stmt);
2411 tree rhs = gimple_assign_rhs1 (stmt);
2412 tree cached_lhs;
2413 gimple new_stmt;
2414 if (TREE_CODE (rhs) == SSA_NAME)
2416 tree tem = SSA_NAME_VALUE (rhs);
2417 if (tem)
2418 rhs = tem;
2420 /* Build a new statement with the RHS and LHS exchanged. */
2421 if (TREE_CODE (rhs) == SSA_NAME)
2423 gimple defstmt = SSA_NAME_DEF_STMT (rhs);
2424 new_stmt = gimple_build_assign (rhs, lhs);
2425 SSA_NAME_DEF_STMT (rhs) = defstmt;
2427 else
2428 new_stmt = gimple_build_assign (rhs, lhs);
2429 gimple_set_vuse (new_stmt, gimple_vuse (stmt));
2430 cached_lhs = lookup_avail_expr (new_stmt, false);
2431 if (cached_lhs
2432 && rhs == cached_lhs)
2434 basic_block bb = gimple_bb (stmt);
2435 unlink_stmt_vdef (stmt);
2436 if (gsi_remove (&si, true))
2438 bitmap_set_bit (need_eh_cleanup, bb->index);
2439 if (dump_file && (dump_flags & TDF_DETAILS))
2440 fprintf (dump_file, " Flagged to clear EH edges.\n");
2442 release_defs (stmt);
2443 return;
2448 /* Record any additional equivalences created by this statement. */
2449 if (is_gimple_assign (stmt))
2450 record_equivalences_from_stmt (stmt, may_optimize_p);
2452 /* If STMT is a COND_EXPR and it was modified, then we may know
2453 where it goes. If that is the case, then mark the CFG as altered.
2455 This will cause us to later call remove_unreachable_blocks and
2456 cleanup_tree_cfg when it is safe to do so. It is not safe to
2457 clean things up here since removal of edges and such can trigger
2458 the removal of PHI nodes, which in turn can release SSA_NAMEs to
2459 the manager.
2461 That's all fine and good, except that once SSA_NAMEs are released
2462 to the manager, we must not call create_ssa_name until all references
2463 to released SSA_NAMEs have been eliminated.
2465 All references to the deleted SSA_NAMEs can not be eliminated until
2466 we remove unreachable blocks.
2468 We can not remove unreachable blocks until after we have completed
2469 any queued jump threading.
2471 We can not complete any queued jump threads until we have taken
2472 appropriate variables out of SSA form. Taking variables out of
2473 SSA form can call create_ssa_name and thus we lose.
2475 Ultimately I suspect we're going to need to change the interface
2476 into the SSA_NAME manager. */
2477 if (gimple_modified_p (stmt) || modified_p)
2479 tree val = NULL;
2481 update_stmt_if_modified (stmt);
2483 if (gimple_code (stmt) == GIMPLE_COND)
2484 val = fold_binary_loc (gimple_location (stmt),
2485 gimple_cond_code (stmt), boolean_type_node,
2486 gimple_cond_lhs (stmt), gimple_cond_rhs (stmt));
2487 else if (gimple_code (stmt) == GIMPLE_SWITCH)
2488 val = gimple_switch_index (stmt);
2490 if (val && TREE_CODE (val) == INTEGER_CST && find_taken_edge (bb, val))
2491 cfg_altered = true;
2493 /* If we simplified a statement in such a way as to be shown that it
2494 cannot trap, update the eh information and the cfg to match. */
2495 if (maybe_clean_or_replace_eh_stmt (old_stmt, stmt))
2497 bitmap_set_bit (need_eh_cleanup, bb->index);
2498 if (dump_file && (dump_flags & TDF_DETAILS))
2499 fprintf (dump_file, " Flagged to clear EH edges.\n");
2504 /* Search for an existing instance of STMT in the AVAIL_EXPRS table.
2505 If found, return its LHS. Otherwise insert STMT in the table and
2506 return NULL_TREE.
2508 Also, when an expression is first inserted in the table, it is also
2509 is also added to AVAIL_EXPRS_STACK, so that it can be removed when
2510 we finish processing this block and its children. */
2512 static tree
2513 lookup_avail_expr (gimple stmt, bool insert)
2515 expr_hash_elt **slot;
2516 tree lhs;
2517 tree temp;
2518 struct expr_hash_elt element;
2520 /* Get LHS of phi, assignment, or call; else NULL_TREE. */
2521 if (gimple_code (stmt) == GIMPLE_PHI)
2522 lhs = gimple_phi_result (stmt);
2523 else
2524 lhs = gimple_get_lhs (stmt);
2526 initialize_hash_element (stmt, lhs, &element);
2528 if (dump_file && (dump_flags & TDF_DETAILS))
2530 fprintf (dump_file, "LKUP ");
2531 print_expr_hash_elt (dump_file, &element);
2534 /* Don't bother remembering constant assignments and copy operations.
2535 Constants and copy operations are handled by the constant/copy propagator
2536 in optimize_stmt. */
2537 if (element.expr.kind == EXPR_SINGLE
2538 && (TREE_CODE (element.expr.ops.single.rhs) == SSA_NAME
2539 || is_gimple_min_invariant (element.expr.ops.single.rhs)))
2540 return NULL_TREE;
2542 /* Finally try to find the expression in the main expression hash table. */
2543 slot = avail_exprs->find_slot (&element, (insert ? INSERT : NO_INSERT));
2544 if (slot == NULL)
2546 free_expr_hash_elt_contents (&element);
2547 return NULL_TREE;
2549 else if (*slot == NULL)
2551 struct expr_hash_elt *element2 = XNEW (struct expr_hash_elt);
2552 *element2 = element;
2553 element2->stamp = element2;
2554 *slot = element2;
2556 if (dump_file && (dump_flags & TDF_DETAILS))
2558 fprintf (dump_file, "2>>> ");
2559 print_expr_hash_elt (dump_file, element2);
2562 avail_exprs_stack.safe_push (element2);
2563 return NULL_TREE;
2565 else
2566 free_expr_hash_elt_contents (&element);
2568 /* Extract the LHS of the assignment so that it can be used as the current
2569 definition of another variable. */
2570 lhs = ((struct expr_hash_elt *)*slot)->lhs;
2572 /* See if the LHS appears in the CONST_AND_COPIES table. If it does, then
2573 use the value from the const_and_copies table. */
2574 if (TREE_CODE (lhs) == SSA_NAME)
2576 temp = SSA_NAME_VALUE (lhs);
2577 if (temp)
2578 lhs = temp;
2581 if (dump_file && (dump_flags & TDF_DETAILS))
2583 fprintf (dump_file, "FIND: ");
2584 print_generic_expr (dump_file, lhs, 0);
2585 fprintf (dump_file, "\n");
2588 return lhs;
2591 /* Hashing and equality functions for AVAIL_EXPRS. We compute a value number
2592 for expressions using the code of the expression and the SSA numbers of
2593 its operands. */
2595 static hashval_t
2596 avail_expr_hash (const void *p)
2598 gimple stmt = ((const struct expr_hash_elt *)p)->stmt;
2599 const struct hashable_expr *expr = &((const struct expr_hash_elt *)p)->expr;
2600 tree vuse;
2601 hashval_t val = 0;
2603 val = iterative_hash_hashable_expr (expr, val);
2605 /* If the hash table entry is not associated with a statement, then we
2606 can just hash the expression and not worry about virtual operands
2607 and such. */
2608 if (!stmt)
2609 return val;
2611 /* Add the SSA version numbers of the vuse operand. This is important
2612 because compound variables like arrays are not renamed in the
2613 operands. Rather, the rename is done on the virtual variable
2614 representing all the elements of the array. */
2615 if ((vuse = gimple_vuse (stmt)))
2616 val = iterative_hash_expr (vuse, val);
2618 return val;
2621 /* PHI-ONLY copy and constant propagation. This pass is meant to clean
2622 up degenerate PHIs created by or exposed by jump threading. */
2624 /* Given a statement STMT, which is either a PHI node or an assignment,
2625 remove it from the IL. */
2627 static void
2628 remove_stmt_or_phi (gimple stmt)
2630 gimple_stmt_iterator gsi = gsi_for_stmt (stmt);
2632 if (gimple_code (stmt) == GIMPLE_PHI)
2633 remove_phi_node (&gsi, true);
2634 else
2636 gsi_remove (&gsi, true);
2637 release_defs (stmt);
2641 /* Given a statement STMT, which is either a PHI node or an assignment,
2642 return the "rhs" of the node, in the case of a non-degenerate
2643 phi, NULL is returned. */
2645 static tree
2646 get_rhs_or_phi_arg (gimple stmt)
2648 if (gimple_code (stmt) == GIMPLE_PHI)
2649 return degenerate_phi_result (stmt);
2650 else if (gimple_assign_single_p (stmt))
2651 return gimple_assign_rhs1 (stmt);
2652 else
2653 gcc_unreachable ();
2657 /* Given a statement STMT, which is either a PHI node or an assignment,
2658 return the "lhs" of the node. */
2660 static tree
2661 get_lhs_or_phi_result (gimple stmt)
2663 if (gimple_code (stmt) == GIMPLE_PHI)
2664 return gimple_phi_result (stmt);
2665 else if (is_gimple_assign (stmt))
2666 return gimple_assign_lhs (stmt);
2667 else
2668 gcc_unreachable ();
2671 /* Propagate RHS into all uses of LHS (when possible).
2673 RHS and LHS are derived from STMT, which is passed in solely so
2674 that we can remove it if propagation is successful.
2676 When propagating into a PHI node or into a statement which turns
2677 into a trivial copy or constant initialization, set the
2678 appropriate bit in INTERESTING_NAMEs so that we will visit those
2679 nodes as well in an effort to pick up secondary optimization
2680 opportunities. */
2682 static void
2683 propagate_rhs_into_lhs (gimple stmt, tree lhs, tree rhs, bitmap interesting_names)
2685 /* First verify that propagation is valid. */
2686 if (may_propagate_copy (lhs, rhs))
2688 use_operand_p use_p;
2689 imm_use_iterator iter;
2690 gimple use_stmt;
2691 bool all = true;
2693 /* Dump details. */
2694 if (dump_file && (dump_flags & TDF_DETAILS))
2696 fprintf (dump_file, " Replacing '");
2697 print_generic_expr (dump_file, lhs, dump_flags);
2698 fprintf (dump_file, "' with %s '",
2699 (TREE_CODE (rhs) != SSA_NAME ? "constant" : "variable"));
2700 print_generic_expr (dump_file, rhs, dump_flags);
2701 fprintf (dump_file, "'\n");
2704 /* Walk over every use of LHS and try to replace the use with RHS.
2705 At this point the only reason why such a propagation would not
2706 be successful would be if the use occurs in an ASM_EXPR. */
2707 FOR_EACH_IMM_USE_STMT (use_stmt, iter, lhs)
2709 /* Leave debug stmts alone. If we succeed in propagating
2710 all non-debug uses, we'll drop the DEF, and propagation
2711 into debug stmts will occur then. */
2712 if (gimple_debug_bind_p (use_stmt))
2713 continue;
2715 /* It's not always safe to propagate into an ASM_EXPR. */
2716 if (gimple_code (use_stmt) == GIMPLE_ASM
2717 && ! may_propagate_copy_into_asm (lhs))
2719 all = false;
2720 continue;
2723 /* It's not ok to propagate into the definition stmt of RHS.
2724 <bb 9>:
2725 # prephitmp.12_36 = PHI <g_67.1_6(9)>
2726 g_67.1_6 = prephitmp.12_36;
2727 goto <bb 9>;
2728 While this is strictly all dead code we do not want to
2729 deal with this here. */
2730 if (TREE_CODE (rhs) == SSA_NAME
2731 && SSA_NAME_DEF_STMT (rhs) == use_stmt)
2733 all = false;
2734 continue;
2737 /* Dump details. */
2738 if (dump_file && (dump_flags & TDF_DETAILS))
2740 fprintf (dump_file, " Original statement:");
2741 print_gimple_stmt (dump_file, use_stmt, 0, dump_flags);
2744 /* Propagate the RHS into this use of the LHS. */
2745 FOR_EACH_IMM_USE_ON_STMT (use_p, iter)
2746 propagate_value (use_p, rhs);
2748 /* Special cases to avoid useless calls into the folding
2749 routines, operand scanning, etc.
2751 Propagation into a PHI may cause the PHI to become
2752 a degenerate, so mark the PHI as interesting. No other
2753 actions are necessary. */
2754 if (gimple_code (use_stmt) == GIMPLE_PHI)
2756 tree result;
2758 /* Dump details. */
2759 if (dump_file && (dump_flags & TDF_DETAILS))
2761 fprintf (dump_file, " Updated statement:");
2762 print_gimple_stmt (dump_file, use_stmt, 0, dump_flags);
2765 result = get_lhs_or_phi_result (use_stmt);
2766 bitmap_set_bit (interesting_names, SSA_NAME_VERSION (result));
2767 continue;
2770 /* From this point onward we are propagating into a
2771 real statement. Folding may (or may not) be possible,
2772 we may expose new operands, expose dead EH edges,
2773 etc. */
2774 /* NOTE tuples. In the tuples world, fold_stmt_inplace
2775 cannot fold a call that simplifies to a constant,
2776 because the GIMPLE_CALL must be replaced by a
2777 GIMPLE_ASSIGN, and there is no way to effect such a
2778 transformation in-place. We might want to consider
2779 using the more general fold_stmt here. */
2781 gimple_stmt_iterator gsi = gsi_for_stmt (use_stmt);
2782 fold_stmt_inplace (&gsi);
2785 /* Sometimes propagation can expose new operands to the
2786 renamer. */
2787 update_stmt (use_stmt);
2789 /* Dump details. */
2790 if (dump_file && (dump_flags & TDF_DETAILS))
2792 fprintf (dump_file, " Updated statement:");
2793 print_gimple_stmt (dump_file, use_stmt, 0, dump_flags);
2796 /* If we replaced a variable index with a constant, then
2797 we would need to update the invariant flag for ADDR_EXPRs. */
2798 if (gimple_assign_single_p (use_stmt)
2799 && TREE_CODE (gimple_assign_rhs1 (use_stmt)) == ADDR_EXPR)
2800 recompute_tree_invariant_for_addr_expr
2801 (gimple_assign_rhs1 (use_stmt));
2803 /* If we cleaned up EH information from the statement,
2804 mark its containing block as needing EH cleanups. */
2805 if (maybe_clean_or_replace_eh_stmt (use_stmt, use_stmt))
2807 bitmap_set_bit (need_eh_cleanup, gimple_bb (use_stmt)->index);
2808 if (dump_file && (dump_flags & TDF_DETAILS))
2809 fprintf (dump_file, " Flagged to clear EH edges.\n");
2812 /* Propagation may expose new trivial copy/constant propagation
2813 opportunities. */
2814 if (gimple_assign_single_p (use_stmt)
2815 && TREE_CODE (gimple_assign_lhs (use_stmt)) == SSA_NAME
2816 && (TREE_CODE (gimple_assign_rhs1 (use_stmt)) == SSA_NAME
2817 || is_gimple_min_invariant (gimple_assign_rhs1 (use_stmt))))
2819 tree result = get_lhs_or_phi_result (use_stmt);
2820 bitmap_set_bit (interesting_names, SSA_NAME_VERSION (result));
2823 /* Propagation into these nodes may make certain edges in
2824 the CFG unexecutable. We want to identify them as PHI nodes
2825 at the destination of those unexecutable edges may become
2826 degenerates. */
2827 else if (gimple_code (use_stmt) == GIMPLE_COND
2828 || gimple_code (use_stmt) == GIMPLE_SWITCH
2829 || gimple_code (use_stmt) == GIMPLE_GOTO)
2831 tree val;
2833 if (gimple_code (use_stmt) == GIMPLE_COND)
2834 val = fold_binary_loc (gimple_location (use_stmt),
2835 gimple_cond_code (use_stmt),
2836 boolean_type_node,
2837 gimple_cond_lhs (use_stmt),
2838 gimple_cond_rhs (use_stmt));
2839 else if (gimple_code (use_stmt) == GIMPLE_SWITCH)
2840 val = gimple_switch_index (use_stmt);
2841 else
2842 val = gimple_goto_dest (use_stmt);
2844 if (val && is_gimple_min_invariant (val))
2846 basic_block bb = gimple_bb (use_stmt);
2847 edge te = find_taken_edge (bb, val);
2848 edge_iterator ei;
2849 edge e;
2850 gimple_stmt_iterator gsi, psi;
2852 /* Remove all outgoing edges except TE. */
2853 for (ei = ei_start (bb->succs); (e = ei_safe_edge (ei));)
2855 if (e != te)
2857 /* Mark all the PHI nodes at the destination of
2858 the unexecutable edge as interesting. */
2859 for (psi = gsi_start_phis (e->dest);
2860 !gsi_end_p (psi);
2861 gsi_next (&psi))
2863 gimple phi = gsi_stmt (psi);
2865 tree result = gimple_phi_result (phi);
2866 int version = SSA_NAME_VERSION (result);
2868 bitmap_set_bit (interesting_names, version);
2871 te->probability += e->probability;
2873 te->count += e->count;
2874 remove_edge (e);
2875 cfg_altered = true;
2877 else
2878 ei_next (&ei);
2881 gsi = gsi_last_bb (gimple_bb (use_stmt));
2882 gsi_remove (&gsi, true);
2884 /* And fixup the flags on the single remaining edge. */
2885 te->flags &= ~(EDGE_TRUE_VALUE | EDGE_FALSE_VALUE);
2886 te->flags &= ~EDGE_ABNORMAL;
2887 te->flags |= EDGE_FALLTHRU;
2888 if (te->probability > REG_BR_PROB_BASE)
2889 te->probability = REG_BR_PROB_BASE;
2894 /* Ensure there is nothing else to do. */
2895 gcc_assert (!all || has_zero_uses (lhs));
2897 /* If we were able to propagate away all uses of LHS, then
2898 we can remove STMT. */
2899 if (all)
2900 remove_stmt_or_phi (stmt);
2904 /* STMT is either a PHI node (potentially a degenerate PHI node) or
2905 a statement that is a trivial copy or constant initialization.
2907 Attempt to eliminate T by propagating its RHS into all uses of
2908 its LHS. This may in turn set new bits in INTERESTING_NAMES
2909 for nodes we want to revisit later.
2911 All exit paths should clear INTERESTING_NAMES for the result
2912 of STMT. */
2914 static void
2915 eliminate_const_or_copy (gimple stmt, bitmap interesting_names)
2917 tree lhs = get_lhs_or_phi_result (stmt);
2918 tree rhs;
2919 int version = SSA_NAME_VERSION (lhs);
2921 /* If the LHS of this statement or PHI has no uses, then we can
2922 just eliminate it. This can occur if, for example, the PHI
2923 was created by block duplication due to threading and its only
2924 use was in the conditional at the end of the block which was
2925 deleted. */
2926 if (has_zero_uses (lhs))
2928 bitmap_clear_bit (interesting_names, version);
2929 remove_stmt_or_phi (stmt);
2930 return;
2933 /* Get the RHS of the assignment or PHI node if the PHI is a
2934 degenerate. */
2935 rhs = get_rhs_or_phi_arg (stmt);
2936 if (!rhs)
2938 bitmap_clear_bit (interesting_names, version);
2939 return;
2942 if (!virtual_operand_p (lhs))
2943 propagate_rhs_into_lhs (stmt, lhs, rhs, interesting_names);
2944 else
2946 gimple use_stmt;
2947 imm_use_iterator iter;
2948 use_operand_p use_p;
2949 /* For virtual operands we have to propagate into all uses as
2950 otherwise we will create overlapping life-ranges. */
2951 FOR_EACH_IMM_USE_STMT (use_stmt, iter, lhs)
2952 FOR_EACH_IMM_USE_ON_STMT (use_p, iter)
2953 SET_USE (use_p, rhs);
2954 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (lhs))
2955 SSA_NAME_OCCURS_IN_ABNORMAL_PHI (rhs) = 1;
2956 remove_stmt_or_phi (stmt);
2959 /* Note that STMT may well have been deleted by now, so do
2960 not access it, instead use the saved version # to clear
2961 T's entry in the worklist. */
2962 bitmap_clear_bit (interesting_names, version);
2965 /* The first phase in degenerate PHI elimination.
2967 Eliminate the degenerate PHIs in BB, then recurse on the
2968 dominator children of BB. */
2970 static void
2971 eliminate_degenerate_phis_1 (basic_block bb, bitmap interesting_names)
2973 gimple_stmt_iterator gsi;
2974 basic_block son;
2976 for (gsi = gsi_start_phis (bb); !gsi_end_p (gsi); gsi_next (&gsi))
2978 gimple phi = gsi_stmt (gsi);
2980 eliminate_const_or_copy (phi, interesting_names);
2983 /* Recurse into the dominator children of BB. */
2984 for (son = first_dom_son (CDI_DOMINATORS, bb);
2985 son;
2986 son = next_dom_son (CDI_DOMINATORS, son))
2987 eliminate_degenerate_phis_1 (son, interesting_names);
2991 /* A very simple pass to eliminate degenerate PHI nodes from the
2992 IL. This is meant to be fast enough to be able to be run several
2993 times in the optimization pipeline.
2995 Certain optimizations, particularly those which duplicate blocks
2996 or remove edges from the CFG can create or expose PHIs which are
2997 trivial copies or constant initializations.
2999 While we could pick up these optimizations in DOM or with the
3000 combination of copy-prop and CCP, those solutions are far too
3001 heavy-weight for our needs.
3003 This implementation has two phases so that we can efficiently
3004 eliminate the first order degenerate PHIs and second order
3005 degenerate PHIs.
3007 The first phase performs a dominator walk to identify and eliminate
3008 the vast majority of the degenerate PHIs. When a degenerate PHI
3009 is identified and eliminated any affected statements or PHIs
3010 are put on a worklist.
3012 The second phase eliminates degenerate PHIs and trivial copies
3013 or constant initializations using the worklist. This is how we
3014 pick up the secondary optimization opportunities with minimal
3015 cost. */
3017 namespace {
3019 const pass_data pass_data_phi_only_cprop =
3021 GIMPLE_PASS, /* type */
3022 "phicprop", /* name */
3023 OPTGROUP_NONE, /* optinfo_flags */
3024 TV_TREE_PHI_CPROP, /* tv_id */
3025 ( PROP_cfg | PROP_ssa ), /* properties_required */
3026 0, /* properties_provided */
3027 0, /* properties_destroyed */
3028 0, /* todo_flags_start */
3029 ( TODO_cleanup_cfg | TODO_update_ssa ), /* todo_flags_finish */
3032 class pass_phi_only_cprop : public gimple_opt_pass
3034 public:
3035 pass_phi_only_cprop (gcc::context *ctxt)
3036 : gimple_opt_pass (pass_data_phi_only_cprop, ctxt)
3039 /* opt_pass methods: */
3040 opt_pass * clone () { return new pass_phi_only_cprop (m_ctxt); }
3041 virtual bool gate (function *) { return flag_tree_dom != 0; }
3042 virtual unsigned int execute (function *);
3044 }; // class pass_phi_only_cprop
3046 unsigned int
3047 pass_phi_only_cprop::execute (function *fun)
3049 bitmap interesting_names;
3050 bitmap interesting_names1;
3052 /* Bitmap of blocks which need EH information updated. We can not
3053 update it on-the-fly as doing so invalidates the dominator tree. */
3054 need_eh_cleanup = BITMAP_ALLOC (NULL);
3056 /* INTERESTING_NAMES is effectively our worklist, indexed by
3057 SSA_NAME_VERSION.
3059 A set bit indicates that the statement or PHI node which
3060 defines the SSA_NAME should be (re)examined to determine if
3061 it has become a degenerate PHI or trivial const/copy propagation
3062 opportunity.
3064 Experiments have show we generally get better compilation
3065 time behavior with bitmaps rather than sbitmaps. */
3066 interesting_names = BITMAP_ALLOC (NULL);
3067 interesting_names1 = BITMAP_ALLOC (NULL);
3069 calculate_dominance_info (CDI_DOMINATORS);
3070 cfg_altered = false;
3072 /* First phase. Eliminate degenerate PHIs via a dominator
3073 walk of the CFG.
3075 Experiments have indicated that we generally get better
3076 compile-time behavior by visiting blocks in the first
3077 phase in dominator order. Presumably this is because walking
3078 in dominator order leaves fewer PHIs for later examination
3079 by the worklist phase. */
3080 eliminate_degenerate_phis_1 (ENTRY_BLOCK_PTR_FOR_FN (fun),
3081 interesting_names);
3083 /* Second phase. Eliminate second order degenerate PHIs as well
3084 as trivial copies or constant initializations identified by
3085 the first phase or this phase. Basically we keep iterating
3086 until our set of INTERESTING_NAMEs is empty. */
3087 while (!bitmap_empty_p (interesting_names))
3089 unsigned int i;
3090 bitmap_iterator bi;
3092 /* EXECUTE_IF_SET_IN_BITMAP does not like its bitmap
3093 changed during the loop. Copy it to another bitmap and
3094 use that. */
3095 bitmap_copy (interesting_names1, interesting_names);
3097 EXECUTE_IF_SET_IN_BITMAP (interesting_names1, 0, i, bi)
3099 tree name = ssa_name (i);
3101 /* Ignore SSA_NAMEs that have been released because
3102 their defining statement was deleted (unreachable). */
3103 if (name)
3104 eliminate_const_or_copy (SSA_NAME_DEF_STMT (ssa_name (i)),
3105 interesting_names);
3109 if (cfg_altered)
3111 free_dominance_info (CDI_DOMINATORS);
3112 /* If we changed the CFG schedule loops for fixup by cfgcleanup. */
3113 loops_state_set (LOOPS_NEED_FIXUP);
3116 /* Propagation of const and copies may make some EH edges dead. Purge
3117 such edges from the CFG as needed. */
3118 if (!bitmap_empty_p (need_eh_cleanup))
3120 gimple_purge_all_dead_eh_edges (need_eh_cleanup);
3121 BITMAP_FREE (need_eh_cleanup);
3124 BITMAP_FREE (interesting_names);
3125 BITMAP_FREE (interesting_names1);
3126 return 0;
3129 } // anon namespace
3131 gimple_opt_pass *
3132 make_pass_phi_only_cprop (gcc::context *ctxt)
3134 return new pass_phi_only_cprop (ctxt);