2015-05-22 Ed Schonberg <schonberg@adacore.com>
[official-gcc.git] / gcc / tree-into-ssa.c
blobe8b55c134de7f7b73aed4ca8d981275fae3c6886
1 /* Rewrite a program in Normal form into SSA.
2 Copyright (C) 2001-2015 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 "tm.h"
25 #include "hash-set.h"
26 #include "machmode.h"
27 #include "vec.h"
28 #include "double-int.h"
29 #include "input.h"
30 #include "alias.h"
31 #include "symtab.h"
32 #include "wide-int.h"
33 #include "inchash.h"
34 #include "tree.h"
35 #include "fold-const.h"
36 #include "flags.h"
37 #include "tm_p.h"
38 #include "langhooks.h"
39 #include "predict.h"
40 #include "hard-reg-set.h"
41 #include "function.h"
42 #include "dominance.h"
43 #include "cfg.h"
44 #include "cfganal.h"
45 #include "basic-block.h"
46 #include "gimple-pretty-print.h"
47 #include "hash-table.h"
48 #include "tree-ssa-alias.h"
49 #include "internal-fn.h"
50 #include "gimple-expr.h"
51 #include "is-a.h"
52 #include "gimple.h"
53 #include "gimple-iterator.h"
54 #include "gimple-ssa.h"
55 #include "tree-cfg.h"
56 #include "tree-phinodes.h"
57 #include "ssa-iterators.h"
58 #include "stringpool.h"
59 #include "tree-ssanames.h"
60 #include "tree-into-ssa.h"
61 #include "hashtab.h"
62 #include "rtl.h"
63 #include "statistics.h"
64 #include "real.h"
65 #include "fixed-value.h"
66 #include "insn-config.h"
67 #include "expmed.h"
68 #include "dojump.h"
69 #include "explow.h"
70 #include "calls.h"
71 #include "emit-rtl.h"
72 #include "varasm.h"
73 #include "stmt.h"
74 #include "expr.h"
75 #include "tree-dfa.h"
76 #include "tree-ssa.h"
77 #include "tree-inline.h"
78 #include "tree-pass.h"
79 #include "cfgloop.h"
80 #include "domwalk.h"
81 #include "params.h"
82 #include "diagnostic-core.h"
84 #define PERCENT(x,y) ((float)(x) * 100.0 / (float)(y))
86 /* This file builds the SSA form for a function as described in:
87 R. Cytron, J. Ferrante, B. Rosen, M. Wegman, and K. Zadeck. Efficiently
88 Computing Static Single Assignment Form and the Control Dependence
89 Graph. ACM Transactions on Programming Languages and Systems,
90 13(4):451-490, October 1991. */
92 /* Structure to map a variable VAR to the set of blocks that contain
93 definitions for VAR. */
94 struct def_blocks_d
96 /* Blocks that contain definitions of VAR. Bit I will be set if the
97 Ith block contains a definition of VAR. */
98 bitmap def_blocks;
100 /* Blocks that contain a PHI node for VAR. */
101 bitmap phi_blocks;
103 /* Blocks where VAR is live-on-entry. Similar semantics as
104 DEF_BLOCKS. */
105 bitmap livein_blocks;
108 typedef struct def_blocks_d *def_blocks_p;
111 /* Stack of trees used to restore the global currdefs to its original
112 state after completing rewriting of a block and its dominator
113 children. Its elements have the following properties:
115 - An SSA_NAME (N) indicates that the current definition of the
116 underlying variable should be set to the given SSA_NAME. If the
117 symbol associated with the SSA_NAME is not a GIMPLE register, the
118 next slot in the stack must be a _DECL node (SYM). In this case,
119 the name N in the previous slot is the current reaching
120 definition for SYM.
122 - A _DECL node indicates that the underlying variable has no
123 current definition.
125 - A NULL node at the top entry is used to mark the last slot
126 associated with the current block. */
127 static vec<tree> block_defs_stack;
130 /* Set of existing SSA names being replaced by update_ssa. */
131 static sbitmap old_ssa_names;
133 /* Set of new SSA names being added by update_ssa. Note that both
134 NEW_SSA_NAMES and OLD_SSA_NAMES are dense bitmaps because most of
135 the operations done on them are presence tests. */
136 static sbitmap new_ssa_names;
138 static sbitmap interesting_blocks;
140 /* Set of SSA names that have been marked to be released after they
141 were registered in the replacement table. They will be finally
142 released after we finish updating the SSA web. */
143 static bitmap names_to_release;
145 /* vec of vec of PHIs to rewrite in a basic block. Element I corresponds
146 the to basic block with index I. Allocated once per compilation, *not*
147 released between different functions. */
148 static vec< vec<gphi *> > phis_to_rewrite;
150 /* The bitmap of non-NULL elements of PHIS_TO_REWRITE. */
151 static bitmap blocks_with_phis_to_rewrite;
153 /* Growth factor for NEW_SSA_NAMES and OLD_SSA_NAMES. These sets need
154 to grow as the callers to create_new_def_for will create new names on
155 the fly.
156 FIXME. Currently set to 1/3 to avoid frequent reallocations but still
157 need to find a reasonable growth strategy. */
158 #define NAME_SETS_GROWTH_FACTOR (MAX (3, num_ssa_names / 3))
161 /* The function the SSA updating data structures have been initialized for.
162 NULL if they need to be initialized by create_new_def_for. */
163 static struct function *update_ssa_initialized_fn = NULL;
165 /* Global data to attach to the main dominator walk structure. */
166 struct mark_def_sites_global_data
168 /* This bitmap contains the variables which are set before they
169 are used in a basic block. */
170 bitmap kills;
173 /* It is advantageous to avoid things like life analysis for variables which
174 do not need PHI nodes. This enum describes whether or not a particular
175 variable may need a PHI node. */
177 enum need_phi_state {
178 /* This is the default. If we are still in this state after finding
179 all the definition and use sites, then we will assume the variable
180 needs PHI nodes. This is probably an overly conservative assumption. */
181 NEED_PHI_STATE_UNKNOWN,
183 /* This state indicates that we have seen one or more sets of the
184 variable in a single basic block and that the sets dominate all
185 uses seen so far. If after finding all definition and use sites
186 we are still in this state, then the variable does not need any
187 PHI nodes. */
188 NEED_PHI_STATE_NO,
190 /* This state indicates that we have either seen multiple definitions of
191 the variable in multiple blocks, or that we encountered a use in a
192 block that was not dominated by the block containing the set(s) of
193 this variable. This variable is assumed to need PHI nodes. */
194 NEED_PHI_STATE_MAYBE
197 /* Information stored for both SSA names and decls. */
198 struct common_info_d
200 /* This field indicates whether or not the variable may need PHI nodes.
201 See the enum's definition for more detailed information about the
202 states. */
203 ENUM_BITFIELD (need_phi_state) need_phi_state : 2;
205 /* The current reaching definition replacing this var. */
206 tree current_def;
208 /* Definitions for this var. */
209 struct def_blocks_d def_blocks;
212 /* The information associated with decls and SSA names. */
213 typedef struct common_info_d *common_info_p;
215 /* Information stored for decls. */
216 struct var_info_d
218 /* The variable. */
219 tree var;
221 /* Information stored for both SSA names and decls. */
222 struct common_info_d info;
225 /* The information associated with decls. */
226 typedef struct var_info_d *var_info_p;
229 /* VAR_INFOS hashtable helpers. */
231 struct var_info_hasher : typed_free_remove <var_info_d>
233 typedef var_info_d *value_type;
234 typedef var_info_d *compare_type;
235 static inline hashval_t hash (const value_type &);
236 static inline bool equal (const value_type &, const compare_type &);
239 inline hashval_t
240 var_info_hasher::hash (const value_type &p)
242 return DECL_UID (p->var);
245 inline bool
246 var_info_hasher::equal (const value_type &p1, const compare_type &p2)
248 return p1->var == p2->var;
252 /* Each entry in VAR_INFOS contains an element of type STRUCT
253 VAR_INFO_D. */
254 static hash_table<var_info_hasher> *var_infos;
257 /* Information stored for SSA names. */
258 struct ssa_name_info
260 /* Age of this record (so that info_for_ssa_name table can be cleared
261 quickly); if AGE < CURRENT_INFO_FOR_SSA_NAME_AGE, then the fields
262 are assumed to be null. */
263 unsigned age;
265 /* Replacement mappings, allocated from update_ssa_obstack. */
266 bitmap repl_set;
268 /* Information stored for both SSA names and decls. */
269 struct common_info_d info;
272 /* The information associated with names. */
273 typedef struct ssa_name_info *ssa_name_info_p;
275 static vec<ssa_name_info_p> info_for_ssa_name;
276 static unsigned current_info_for_ssa_name_age;
278 static bitmap_obstack update_ssa_obstack;
280 /* The set of blocks affected by update_ssa. */
281 static bitmap blocks_to_update;
283 /* The main entry point to the SSA renamer (rewrite_blocks) may be
284 called several times to do different, but related, tasks.
285 Initially, we need it to rename the whole program into SSA form.
286 At other times, we may need it to only rename into SSA newly
287 exposed symbols. Finally, we can also call it to incrementally fix
288 an already built SSA web. */
289 enum rewrite_mode {
290 /* Convert the whole function into SSA form. */
291 REWRITE_ALL,
293 /* Incrementally update the SSA web by replacing existing SSA
294 names with new ones. See update_ssa for details. */
295 REWRITE_UPDATE
298 /* The set of symbols we ought to re-write into SSA form in update_ssa. */
299 static bitmap symbols_to_rename_set;
300 static vec<tree> symbols_to_rename;
302 /* Mark SYM for renaming. */
304 static void
305 mark_for_renaming (tree sym)
307 if (!symbols_to_rename_set)
308 symbols_to_rename_set = BITMAP_ALLOC (NULL);
309 if (bitmap_set_bit (symbols_to_rename_set, DECL_UID (sym)))
310 symbols_to_rename.safe_push (sym);
313 /* Return true if SYM is marked for renaming. */
315 static bool
316 marked_for_renaming (tree sym)
318 if (!symbols_to_rename_set || sym == NULL_TREE)
319 return false;
320 return bitmap_bit_p (symbols_to_rename_set, DECL_UID (sym));
324 /* Return true if STMT needs to be rewritten. When renaming a subset
325 of the variables, not all statements will be processed. This is
326 decided in mark_def_sites. */
328 static inline bool
329 rewrite_uses_p (gimple stmt)
331 return gimple_visited_p (stmt);
335 /* Set the rewrite marker on STMT to the value given by REWRITE_P. */
337 static inline void
338 set_rewrite_uses (gimple stmt, bool rewrite_p)
340 gimple_set_visited (stmt, rewrite_p);
344 /* Return true if the DEFs created by statement STMT should be
345 registered when marking new definition sites. This is slightly
346 different than rewrite_uses_p: it's used by update_ssa to
347 distinguish statements that need to have both uses and defs
348 processed from those that only need to have their defs processed.
349 Statements that define new SSA names only need to have their defs
350 registered, but they don't need to have their uses renamed. */
352 static inline bool
353 register_defs_p (gimple stmt)
355 return gimple_plf (stmt, GF_PLF_1) != 0;
359 /* If REGISTER_DEFS_P is true, mark STMT to have its DEFs registered. */
361 static inline void
362 set_register_defs (gimple stmt, bool register_defs_p)
364 gimple_set_plf (stmt, GF_PLF_1, register_defs_p);
368 /* Get the information associated with NAME. */
370 static inline ssa_name_info_p
371 get_ssa_name_ann (tree name)
373 unsigned ver = SSA_NAME_VERSION (name);
374 unsigned len = info_for_ssa_name.length ();
375 struct ssa_name_info *info;
377 /* Re-allocate the vector at most once per update/into-SSA. */
378 if (ver >= len)
379 info_for_ssa_name.safe_grow_cleared (num_ssa_names);
381 /* But allocate infos lazily. */
382 info = info_for_ssa_name[ver];
383 if (!info)
385 info = XCNEW (struct ssa_name_info);
386 info->age = current_info_for_ssa_name_age;
387 info->info.need_phi_state = NEED_PHI_STATE_UNKNOWN;
388 info_for_ssa_name[ver] = info;
391 if (info->age < current_info_for_ssa_name_age)
393 info->age = current_info_for_ssa_name_age;
394 info->repl_set = NULL;
395 info->info.need_phi_state = NEED_PHI_STATE_UNKNOWN;
396 info->info.current_def = NULL_TREE;
397 info->info.def_blocks.def_blocks = NULL;
398 info->info.def_blocks.phi_blocks = NULL;
399 info->info.def_blocks.livein_blocks = NULL;
402 return info;
405 /* Return and allocate the auxiliar information for DECL. */
407 static inline var_info_p
408 get_var_info (tree decl)
410 struct var_info_d vi;
411 var_info_d **slot;
412 vi.var = decl;
413 slot = var_infos->find_slot_with_hash (&vi, DECL_UID (decl), INSERT);
414 if (*slot == NULL)
416 var_info_p v = XCNEW (struct var_info_d);
417 v->var = decl;
418 *slot = v;
419 return v;
421 return *slot;
425 /* Clears info for SSA names. */
427 static void
428 clear_ssa_name_info (void)
430 current_info_for_ssa_name_age++;
432 /* If current_info_for_ssa_name_age wraps we use stale information.
433 Asser that this does not happen. */
434 gcc_assert (current_info_for_ssa_name_age != 0);
438 /* Get access to the auxiliar information stored per SSA name or decl. */
440 static inline common_info_p
441 get_common_info (tree var)
443 if (TREE_CODE (var) == SSA_NAME)
444 return &get_ssa_name_ann (var)->info;
445 else
446 return &get_var_info (var)->info;
450 /* Return the current definition for VAR. */
452 tree
453 get_current_def (tree var)
455 return get_common_info (var)->current_def;
459 /* Sets current definition of VAR to DEF. */
461 void
462 set_current_def (tree var, tree def)
464 get_common_info (var)->current_def = def;
467 /* Cleans up the REWRITE_THIS_STMT and REGISTER_DEFS_IN_THIS_STMT flags for
468 all statements in basic block BB. */
470 static void
471 initialize_flags_in_bb (basic_block bb)
473 gimple stmt;
474 gimple_stmt_iterator gsi;
476 for (gsi = gsi_start_phis (bb); !gsi_end_p (gsi); gsi_next (&gsi))
478 gimple phi = gsi_stmt (gsi);
479 set_rewrite_uses (phi, false);
480 set_register_defs (phi, false);
483 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
485 stmt = gsi_stmt (gsi);
487 /* We are going to use the operand cache API, such as
488 SET_USE, SET_DEF, and FOR_EACH_IMM_USE_FAST. The operand
489 cache for each statement should be up-to-date. */
490 gcc_checking_assert (!gimple_modified_p (stmt));
491 set_rewrite_uses (stmt, false);
492 set_register_defs (stmt, false);
496 /* Mark block BB as interesting for update_ssa. */
498 static void
499 mark_block_for_update (basic_block bb)
501 gcc_checking_assert (blocks_to_update != NULL);
502 if (!bitmap_set_bit (blocks_to_update, bb->index))
503 return;
504 initialize_flags_in_bb (bb);
507 /* Return the set of blocks where variable VAR is defined and the blocks
508 where VAR is live on entry (livein). If no entry is found in
509 DEF_BLOCKS, a new one is created and returned. */
511 static inline struct def_blocks_d *
512 get_def_blocks_for (common_info_p info)
514 struct def_blocks_d *db_p = &info->def_blocks;
515 if (!db_p->def_blocks)
517 db_p->def_blocks = BITMAP_ALLOC (&update_ssa_obstack);
518 db_p->phi_blocks = BITMAP_ALLOC (&update_ssa_obstack);
519 db_p->livein_blocks = BITMAP_ALLOC (&update_ssa_obstack);
522 return db_p;
526 /* Mark block BB as the definition site for variable VAR. PHI_P is true if
527 VAR is defined by a PHI node. */
529 static void
530 set_def_block (tree var, basic_block bb, bool phi_p)
532 struct def_blocks_d *db_p;
533 common_info_p info;
535 info = get_common_info (var);
536 db_p = get_def_blocks_for (info);
538 /* Set the bit corresponding to the block where VAR is defined. */
539 bitmap_set_bit (db_p->def_blocks, bb->index);
540 if (phi_p)
541 bitmap_set_bit (db_p->phi_blocks, bb->index);
543 /* Keep track of whether or not we may need to insert PHI nodes.
545 If we are in the UNKNOWN state, then this is the first definition
546 of VAR. Additionally, we have not seen any uses of VAR yet, so
547 we do not need a PHI node for this variable at this time (i.e.,
548 transition to NEED_PHI_STATE_NO).
550 If we are in any other state, then we either have multiple definitions
551 of this variable occurring in different blocks or we saw a use of the
552 variable which was not dominated by the block containing the
553 definition(s). In this case we may need a PHI node, so enter
554 state NEED_PHI_STATE_MAYBE. */
555 if (info->need_phi_state == NEED_PHI_STATE_UNKNOWN)
556 info->need_phi_state = NEED_PHI_STATE_NO;
557 else
558 info->need_phi_state = NEED_PHI_STATE_MAYBE;
562 /* Mark block BB as having VAR live at the entry to BB. */
564 static void
565 set_livein_block (tree var, basic_block bb)
567 common_info_p info;
568 struct def_blocks_d *db_p;
570 info = get_common_info (var);
571 db_p = get_def_blocks_for (info);
573 /* Set the bit corresponding to the block where VAR is live in. */
574 bitmap_set_bit (db_p->livein_blocks, bb->index);
576 /* Keep track of whether or not we may need to insert PHI nodes.
578 If we reach here in NEED_PHI_STATE_NO, see if this use is dominated
579 by the single block containing the definition(s) of this variable. If
580 it is, then we remain in NEED_PHI_STATE_NO, otherwise we transition to
581 NEED_PHI_STATE_MAYBE. */
582 if (info->need_phi_state == NEED_PHI_STATE_NO)
584 int def_block_index = bitmap_first_set_bit (db_p->def_blocks);
586 if (def_block_index == -1
587 || ! dominated_by_p (CDI_DOMINATORS, bb,
588 BASIC_BLOCK_FOR_FN (cfun, def_block_index)))
589 info->need_phi_state = NEED_PHI_STATE_MAYBE;
591 else
592 info->need_phi_state = NEED_PHI_STATE_MAYBE;
596 /* Return true if NAME is in OLD_SSA_NAMES. */
598 static inline bool
599 is_old_name (tree name)
601 unsigned ver = SSA_NAME_VERSION (name);
602 if (!old_ssa_names)
603 return false;
604 return (ver < SBITMAP_SIZE (old_ssa_names)
605 && bitmap_bit_p (old_ssa_names, ver));
609 /* Return true if NAME is in NEW_SSA_NAMES. */
611 static inline bool
612 is_new_name (tree name)
614 unsigned ver = SSA_NAME_VERSION (name);
615 if (!new_ssa_names)
616 return false;
617 return (ver < SBITMAP_SIZE (new_ssa_names)
618 && bitmap_bit_p (new_ssa_names, ver));
622 /* Return the names replaced by NEW_TREE (i.e., REPL_TBL[NEW_TREE].SET). */
624 static inline bitmap
625 names_replaced_by (tree new_tree)
627 return get_ssa_name_ann (new_tree)->repl_set;
631 /* Add OLD to REPL_TBL[NEW_TREE].SET. */
633 static inline void
634 add_to_repl_tbl (tree new_tree, tree old)
636 bitmap *set = &get_ssa_name_ann (new_tree)->repl_set;
637 if (!*set)
638 *set = BITMAP_ALLOC (&update_ssa_obstack);
639 bitmap_set_bit (*set, SSA_NAME_VERSION (old));
643 /* Add a new mapping NEW_TREE -> OLD REPL_TBL. Every entry N_i in REPL_TBL
644 represents the set of names O_1 ... O_j replaced by N_i. This is
645 used by update_ssa and its helpers to introduce new SSA names in an
646 already formed SSA web. */
648 static void
649 add_new_name_mapping (tree new_tree, tree old)
651 /* OLD and NEW_TREE must be different SSA names for the same symbol. */
652 gcc_checking_assert (new_tree != old
653 && SSA_NAME_VAR (new_tree) == SSA_NAME_VAR (old));
655 /* We may need to grow NEW_SSA_NAMES and OLD_SSA_NAMES because our
656 caller may have created new names since the set was created. */
657 if (SBITMAP_SIZE (new_ssa_names) <= num_ssa_names - 1)
659 unsigned int new_sz = num_ssa_names + NAME_SETS_GROWTH_FACTOR;
660 new_ssa_names = sbitmap_resize (new_ssa_names, new_sz, 0);
661 old_ssa_names = sbitmap_resize (old_ssa_names, new_sz, 0);
664 /* Update the REPL_TBL table. */
665 add_to_repl_tbl (new_tree, old);
667 /* If OLD had already been registered as a new name, then all the
668 names that OLD replaces should also be replaced by NEW_TREE. */
669 if (is_new_name (old))
670 bitmap_ior_into (names_replaced_by (new_tree), names_replaced_by (old));
672 /* Register NEW_TREE and OLD in NEW_SSA_NAMES and OLD_SSA_NAMES,
673 respectively. */
674 bitmap_set_bit (new_ssa_names, SSA_NAME_VERSION (new_tree));
675 bitmap_set_bit (old_ssa_names, SSA_NAME_VERSION (old));
679 /* Call back for walk_dominator_tree used to collect definition sites
680 for every variable in the function. For every statement S in block
683 1- Variables defined by S in the DEFS of S are marked in the bitmap
684 KILLS.
686 2- If S uses a variable VAR and there is no preceding kill of VAR,
687 then it is marked in the LIVEIN_BLOCKS bitmap associated with VAR.
689 This information is used to determine which variables are live
690 across block boundaries to reduce the number of PHI nodes
691 we create. */
693 static void
694 mark_def_sites (basic_block bb, gimple stmt, bitmap kills)
696 tree def;
697 use_operand_p use_p;
698 ssa_op_iter iter;
700 /* Since this is the first time that we rewrite the program into SSA
701 form, force an operand scan on every statement. */
702 update_stmt (stmt);
704 gcc_checking_assert (blocks_to_update == NULL);
705 set_register_defs (stmt, false);
706 set_rewrite_uses (stmt, false);
708 if (is_gimple_debug (stmt))
710 FOR_EACH_SSA_USE_OPERAND (use_p, stmt, iter, SSA_OP_USE)
712 tree sym = USE_FROM_PTR (use_p);
713 gcc_checking_assert (DECL_P (sym));
714 set_rewrite_uses (stmt, true);
716 if (rewrite_uses_p (stmt))
717 bitmap_set_bit (interesting_blocks, bb->index);
718 return;
721 /* If a variable is used before being set, then the variable is live
722 across a block boundary, so mark it live-on-entry to BB. */
723 FOR_EACH_SSA_USE_OPERAND (use_p, stmt, iter, SSA_OP_ALL_USES)
725 tree sym = USE_FROM_PTR (use_p);
726 gcc_checking_assert (DECL_P (sym));
727 if (!bitmap_bit_p (kills, DECL_UID (sym)))
728 set_livein_block (sym, bb);
729 set_rewrite_uses (stmt, true);
732 /* Now process the defs. Mark BB as the definition block and add
733 each def to the set of killed symbols. */
734 FOR_EACH_SSA_TREE_OPERAND (def, stmt, iter, SSA_OP_ALL_DEFS)
736 gcc_checking_assert (DECL_P (def));
737 set_def_block (def, bb, false);
738 bitmap_set_bit (kills, DECL_UID (def));
739 set_register_defs (stmt, true);
742 /* If we found the statement interesting then also mark the block BB
743 as interesting. */
744 if (rewrite_uses_p (stmt) || register_defs_p (stmt))
745 bitmap_set_bit (interesting_blocks, bb->index);
748 /* Structure used by prune_unused_phi_nodes to record bounds of the intervals
749 in the dfs numbering of the dominance tree. */
751 struct dom_dfsnum
753 /* Basic block whose index this entry corresponds to. */
754 unsigned bb_index;
756 /* The dfs number of this node. */
757 unsigned dfs_num;
760 /* Compares two entries of type struct dom_dfsnum by dfs_num field. Callback
761 for qsort. */
763 static int
764 cmp_dfsnum (const void *a, const void *b)
766 const struct dom_dfsnum *const da = (const struct dom_dfsnum *) a;
767 const struct dom_dfsnum *const db = (const struct dom_dfsnum *) b;
769 return (int) da->dfs_num - (int) db->dfs_num;
772 /* Among the intervals starting at the N points specified in DEFS, find
773 the one that contains S, and return its bb_index. */
775 static unsigned
776 find_dfsnum_interval (struct dom_dfsnum *defs, unsigned n, unsigned s)
778 unsigned f = 0, t = n, m;
780 while (t > f + 1)
782 m = (f + t) / 2;
783 if (defs[m].dfs_num <= s)
784 f = m;
785 else
786 t = m;
789 return defs[f].bb_index;
792 /* Clean bits from PHIS for phi nodes whose value cannot be used in USES.
793 KILLS is a bitmap of blocks where the value is defined before any use. */
795 static void
796 prune_unused_phi_nodes (bitmap phis, bitmap kills, bitmap uses)
798 bitmap_iterator bi;
799 unsigned i, b, p, u, top;
800 bitmap live_phis;
801 basic_block def_bb, use_bb;
802 edge e;
803 edge_iterator ei;
804 bitmap to_remove;
805 struct dom_dfsnum *defs;
806 unsigned n_defs, adef;
808 if (bitmap_empty_p (uses))
810 bitmap_clear (phis);
811 return;
814 /* The phi must dominate a use, or an argument of a live phi. Also, we
815 do not create any phi nodes in def blocks, unless they are also livein. */
816 to_remove = BITMAP_ALLOC (NULL);
817 bitmap_and_compl (to_remove, kills, uses);
818 bitmap_and_compl_into (phis, to_remove);
819 if (bitmap_empty_p (phis))
821 BITMAP_FREE (to_remove);
822 return;
825 /* We want to remove the unnecessary phi nodes, but we do not want to compute
826 liveness information, as that may be linear in the size of CFG, and if
827 there are lot of different variables to rewrite, this may lead to quadratic
828 behavior.
830 Instead, we basically emulate standard dce. We put all uses to worklist,
831 then for each of them find the nearest def that dominates them. If this
832 def is a phi node, we mark it live, and if it was not live before, we
833 add the predecessors of its basic block to the worklist.
835 To quickly locate the nearest def that dominates use, we use dfs numbering
836 of the dominance tree (that is already available in order to speed up
837 queries). For each def, we have the interval given by the dfs number on
838 entry to and on exit from the corresponding subtree in the dominance tree.
839 The nearest dominator for a given use is the smallest of these intervals
840 that contains entry and exit dfs numbers for the basic block with the use.
841 If we store the bounds for all the uses to an array and sort it, we can
842 locate the nearest dominating def in logarithmic time by binary search.*/
843 bitmap_ior (to_remove, kills, phis);
844 n_defs = bitmap_count_bits (to_remove);
845 defs = XNEWVEC (struct dom_dfsnum, 2 * n_defs + 1);
846 defs[0].bb_index = 1;
847 defs[0].dfs_num = 0;
848 adef = 1;
849 EXECUTE_IF_SET_IN_BITMAP (to_remove, 0, i, bi)
851 def_bb = BASIC_BLOCK_FOR_FN (cfun, i);
852 defs[adef].bb_index = i;
853 defs[adef].dfs_num = bb_dom_dfs_in (CDI_DOMINATORS, def_bb);
854 defs[adef + 1].bb_index = i;
855 defs[adef + 1].dfs_num = bb_dom_dfs_out (CDI_DOMINATORS, def_bb);
856 adef += 2;
858 BITMAP_FREE (to_remove);
859 gcc_assert (adef == 2 * n_defs + 1);
860 qsort (defs, adef, sizeof (struct dom_dfsnum), cmp_dfsnum);
861 gcc_assert (defs[0].bb_index == 1);
863 /* Now each DEFS entry contains the number of the basic block to that the
864 dfs number corresponds. Change them to the number of basic block that
865 corresponds to the interval following the dfs number. Also, for the
866 dfs_out numbers, increase the dfs number by one (so that it corresponds
867 to the start of the following interval, not to the end of the current
868 one). We use WORKLIST as a stack. */
869 auto_vec<int> worklist (n_defs + 1);
870 worklist.quick_push (1);
871 top = 1;
872 n_defs = 1;
873 for (i = 1; i < adef; i++)
875 b = defs[i].bb_index;
876 if (b == top)
878 /* This is a closing element. Interval corresponding to the top
879 of the stack after removing it follows. */
880 worklist.pop ();
881 top = worklist[worklist.length () - 1];
882 defs[n_defs].bb_index = top;
883 defs[n_defs].dfs_num = defs[i].dfs_num + 1;
885 else
887 /* Opening element. Nothing to do, just push it to the stack and move
888 it to the correct position. */
889 defs[n_defs].bb_index = defs[i].bb_index;
890 defs[n_defs].dfs_num = defs[i].dfs_num;
891 worklist.quick_push (b);
892 top = b;
895 /* If this interval starts at the same point as the previous one, cancel
896 the previous one. */
897 if (defs[n_defs].dfs_num == defs[n_defs - 1].dfs_num)
898 defs[n_defs - 1].bb_index = defs[n_defs].bb_index;
899 else
900 n_defs++;
902 worklist.pop ();
903 gcc_assert (worklist.is_empty ());
905 /* Now process the uses. */
906 live_phis = BITMAP_ALLOC (NULL);
907 EXECUTE_IF_SET_IN_BITMAP (uses, 0, i, bi)
909 worklist.safe_push (i);
912 while (!worklist.is_empty ())
914 b = worklist.pop ();
915 if (b == ENTRY_BLOCK)
916 continue;
918 /* If there is a phi node in USE_BB, it is made live. Otherwise,
919 find the def that dominates the immediate dominator of USE_BB
920 (the kill in USE_BB does not dominate the use). */
921 if (bitmap_bit_p (phis, b))
922 p = b;
923 else
925 use_bb = get_immediate_dominator (CDI_DOMINATORS,
926 BASIC_BLOCK_FOR_FN (cfun, b));
927 p = find_dfsnum_interval (defs, n_defs,
928 bb_dom_dfs_in (CDI_DOMINATORS, use_bb));
929 if (!bitmap_bit_p (phis, p))
930 continue;
933 /* If the phi node is already live, there is nothing to do. */
934 if (!bitmap_set_bit (live_phis, p))
935 continue;
937 /* Add the new uses to the worklist. */
938 def_bb = BASIC_BLOCK_FOR_FN (cfun, p);
939 FOR_EACH_EDGE (e, ei, def_bb->preds)
941 u = e->src->index;
942 if (bitmap_bit_p (uses, u))
943 continue;
945 /* In case there is a kill directly in the use block, do not record
946 the use (this is also necessary for correctness, as we assume that
947 uses dominated by a def directly in their block have been filtered
948 out before). */
949 if (bitmap_bit_p (kills, u))
950 continue;
952 bitmap_set_bit (uses, u);
953 worklist.safe_push (u);
957 bitmap_copy (phis, live_phis);
958 BITMAP_FREE (live_phis);
959 free (defs);
962 /* Return the set of blocks where variable VAR is defined and the blocks
963 where VAR is live on entry (livein). Return NULL, if no entry is
964 found in DEF_BLOCKS. */
966 static inline struct def_blocks_d *
967 find_def_blocks_for (tree var)
969 def_blocks_p p = &get_common_info (var)->def_blocks;
970 if (!p->def_blocks)
971 return NULL;
972 return p;
976 /* Marks phi node PHI in basic block BB for rewrite. */
978 static void
979 mark_phi_for_rewrite (basic_block bb, gphi *phi)
981 vec<gphi *> phis;
982 unsigned n, idx = bb->index;
984 if (rewrite_uses_p (phi))
985 return;
987 set_rewrite_uses (phi, true);
989 if (!blocks_with_phis_to_rewrite)
990 return;
992 bitmap_set_bit (blocks_with_phis_to_rewrite, idx);
994 n = (unsigned) last_basic_block_for_fn (cfun) + 1;
995 if (phis_to_rewrite.length () < n)
996 phis_to_rewrite.safe_grow_cleared (n);
998 phis = phis_to_rewrite[idx];
999 phis.reserve (10);
1001 phis.safe_push (phi);
1002 phis_to_rewrite[idx] = phis;
1005 /* Insert PHI nodes for variable VAR using the iterated dominance
1006 frontier given in PHI_INSERTION_POINTS. If UPDATE_P is true, this
1007 function assumes that the caller is incrementally updating the
1008 existing SSA form, in which case VAR may be an SSA name instead of
1009 a symbol.
1011 PHI_INSERTION_POINTS is updated to reflect nodes that already had a
1012 PHI node for VAR. On exit, only the nodes that received a PHI node
1013 for VAR will be present in PHI_INSERTION_POINTS. */
1015 static void
1016 insert_phi_nodes_for (tree var, bitmap phi_insertion_points, bool update_p)
1018 unsigned bb_index;
1019 edge e;
1020 gphi *phi;
1021 basic_block bb;
1022 bitmap_iterator bi;
1023 struct def_blocks_d *def_map = find_def_blocks_for (var);
1025 /* Remove the blocks where we already have PHI nodes for VAR. */
1026 bitmap_and_compl_into (phi_insertion_points, def_map->phi_blocks);
1028 /* Remove obviously useless phi nodes. */
1029 prune_unused_phi_nodes (phi_insertion_points, def_map->def_blocks,
1030 def_map->livein_blocks);
1032 /* And insert the PHI nodes. */
1033 EXECUTE_IF_SET_IN_BITMAP (phi_insertion_points, 0, bb_index, bi)
1035 bb = BASIC_BLOCK_FOR_FN (cfun, bb_index);
1036 if (update_p)
1037 mark_block_for_update (bb);
1039 if (dump_file && (dump_flags & TDF_DETAILS))
1041 fprintf (dump_file, "creating PHI node in block #%d for ", bb_index);
1042 print_generic_expr (dump_file, var, TDF_SLIM);
1043 fprintf (dump_file, "\n");
1045 phi = NULL;
1047 if (TREE_CODE (var) == SSA_NAME)
1049 /* If we are rewriting SSA names, create the LHS of the PHI
1050 node by duplicating VAR. This is useful in the case of
1051 pointers, to also duplicate pointer attributes (alias
1052 information, in particular). */
1053 edge_iterator ei;
1054 tree new_lhs;
1056 gcc_checking_assert (update_p);
1057 new_lhs = duplicate_ssa_name (var, NULL);
1058 phi = create_phi_node (new_lhs, bb);
1059 add_new_name_mapping (new_lhs, var);
1061 /* Add VAR to every argument slot of PHI. We need VAR in
1062 every argument so that rewrite_update_phi_arguments knows
1063 which name is this PHI node replacing. If VAR is a
1064 symbol marked for renaming, this is not necessary, the
1065 renamer will use the symbol on the LHS to get its
1066 reaching definition. */
1067 FOR_EACH_EDGE (e, ei, bb->preds)
1068 add_phi_arg (phi, var, e, UNKNOWN_LOCATION);
1070 else
1072 tree tracked_var;
1074 gcc_checking_assert (DECL_P (var));
1075 phi = create_phi_node (var, bb);
1077 tracked_var = target_for_debug_bind (var);
1078 if (tracked_var)
1080 gimple note = gimple_build_debug_bind (tracked_var,
1081 PHI_RESULT (phi),
1082 phi);
1083 gimple_stmt_iterator si = gsi_after_labels (bb);
1084 gsi_insert_before (&si, note, GSI_SAME_STMT);
1088 /* Mark this PHI node as interesting for update_ssa. */
1089 set_register_defs (phi, true);
1090 mark_phi_for_rewrite (bb, phi);
1094 /* Sort var_infos after DECL_UID of their var. */
1096 static int
1097 insert_phi_nodes_compare_var_infos (const void *a, const void *b)
1099 const struct var_info_d *defa = *(struct var_info_d * const *)a;
1100 const struct var_info_d *defb = *(struct var_info_d * const *)b;
1101 if (DECL_UID (defa->var) < DECL_UID (defb->var))
1102 return -1;
1103 else
1104 return 1;
1107 /* Insert PHI nodes at the dominance frontier of blocks with variable
1108 definitions. DFS contains the dominance frontier information for
1109 the flowgraph. */
1111 static void
1112 insert_phi_nodes (bitmap_head *dfs)
1114 hash_table<var_info_hasher>::iterator hi;
1115 unsigned i;
1116 var_info_p info;
1118 timevar_push (TV_TREE_INSERT_PHI_NODES);
1120 auto_vec<var_info_p> vars (var_infos->elements ());
1121 FOR_EACH_HASH_TABLE_ELEMENT (*var_infos, info, var_info_p, hi)
1122 if (info->info.need_phi_state != NEED_PHI_STATE_NO)
1123 vars.quick_push (info);
1125 /* Do two stages to avoid code generation differences for UID
1126 differences but no UID ordering differences. */
1127 vars.qsort (insert_phi_nodes_compare_var_infos);
1129 FOR_EACH_VEC_ELT (vars, i, info)
1131 bitmap idf = compute_idf (info->info.def_blocks.def_blocks, dfs);
1132 insert_phi_nodes_for (info->var, idf, false);
1133 BITMAP_FREE (idf);
1136 timevar_pop (TV_TREE_INSERT_PHI_NODES);
1140 /* Push SYM's current reaching definition into BLOCK_DEFS_STACK and
1141 register DEF (an SSA_NAME) to be a new definition for SYM. */
1143 static void
1144 register_new_def (tree def, tree sym)
1146 common_info_p info = get_common_info (sym);
1147 tree currdef;
1149 /* If this variable is set in a single basic block and all uses are
1150 dominated by the set(s) in that single basic block, then there is
1151 no reason to record anything for this variable in the block local
1152 definition stacks. Doing so just wastes time and memory.
1154 This is the same test to prune the set of variables which may
1155 need PHI nodes. So we just use that information since it's already
1156 computed and available for us to use. */
1157 if (info->need_phi_state == NEED_PHI_STATE_NO)
1159 info->current_def = def;
1160 return;
1163 currdef = info->current_def;
1165 /* If SYM is not a GIMPLE register, then CURRDEF may be a name whose
1166 SSA_NAME_VAR is not necessarily SYM. In this case, also push SYM
1167 in the stack so that we know which symbol is being defined by
1168 this SSA name when we unwind the stack. */
1169 if (currdef && !is_gimple_reg (sym))
1170 block_defs_stack.safe_push (sym);
1172 /* Push the current reaching definition into BLOCK_DEFS_STACK. This
1173 stack is later used by the dominator tree callbacks to restore
1174 the reaching definitions for all the variables defined in the
1175 block after a recursive visit to all its immediately dominated
1176 blocks. If there is no current reaching definition, then just
1177 record the underlying _DECL node. */
1178 block_defs_stack.safe_push (currdef ? currdef : sym);
1180 /* Set the current reaching definition for SYM to be DEF. */
1181 info->current_def = def;
1185 /* Perform a depth-first traversal of the dominator tree looking for
1186 variables to rename. BB is the block where to start searching.
1187 Renaming is a five step process:
1189 1- Every definition made by PHI nodes at the start of the blocks is
1190 registered as the current definition for the corresponding variable.
1192 2- Every statement in BB is rewritten. USE and VUSE operands are
1193 rewritten with their corresponding reaching definition. DEF and
1194 VDEF targets are registered as new definitions.
1196 3- All the PHI nodes in successor blocks of BB are visited. The
1197 argument corresponding to BB is replaced with its current reaching
1198 definition.
1200 4- Recursively rewrite every dominator child block of BB.
1202 5- Restore (in reverse order) the current reaching definition for every
1203 new definition introduced in this block. This is done so that when
1204 we return from the recursive call, all the current reaching
1205 definitions are restored to the names that were valid in the
1206 dominator parent of BB. */
1208 /* Return the current definition for variable VAR. If none is found,
1209 create a new SSA name to act as the zeroth definition for VAR. */
1211 static tree
1212 get_reaching_def (tree var)
1214 common_info_p info = get_common_info (var);
1215 tree currdef;
1217 /* Lookup the current reaching definition for VAR. */
1218 currdef = info->current_def;
1220 /* If there is no reaching definition for VAR, create and register a
1221 default definition for it (if needed). */
1222 if (currdef == NULL_TREE)
1224 tree sym = DECL_P (var) ? var : SSA_NAME_VAR (var);
1225 currdef = get_or_create_ssa_default_def (cfun, sym);
1228 /* Return the current reaching definition for VAR, or the default
1229 definition, if we had to create one. */
1230 return currdef;
1234 /* Helper function for rewrite_stmt. Rewrite uses in a debug stmt. */
1236 static void
1237 rewrite_debug_stmt_uses (gimple stmt)
1239 use_operand_p use_p;
1240 ssa_op_iter iter;
1241 bool update = false;
1243 FOR_EACH_SSA_USE_OPERAND (use_p, stmt, iter, SSA_OP_USE)
1245 tree var = USE_FROM_PTR (use_p), def;
1246 common_info_p info = get_common_info (var);
1247 gcc_checking_assert (DECL_P (var));
1248 def = info->current_def;
1249 if (!def)
1251 if (TREE_CODE (var) == PARM_DECL
1252 && single_succ_p (ENTRY_BLOCK_PTR_FOR_FN (cfun)))
1254 gimple_stmt_iterator gsi
1256 gsi_after_labels (single_succ (ENTRY_BLOCK_PTR_FOR_FN (cfun)));
1257 int lim;
1258 /* Search a few source bind stmts at the start of first bb to
1259 see if a DEBUG_EXPR_DECL can't be reused. */
1260 for (lim = 32;
1261 !gsi_end_p (gsi) && lim > 0;
1262 gsi_next (&gsi), lim--)
1264 gimple gstmt = gsi_stmt (gsi);
1265 if (!gimple_debug_source_bind_p (gstmt))
1266 break;
1267 if (gimple_debug_source_bind_get_value (gstmt) == var)
1269 def = gimple_debug_source_bind_get_var (gstmt);
1270 if (TREE_CODE (def) == DEBUG_EXPR_DECL)
1271 break;
1272 else
1273 def = NULL_TREE;
1276 /* If not, add a new source bind stmt. */
1277 if (def == NULL_TREE)
1279 gimple def_temp;
1280 def = make_node (DEBUG_EXPR_DECL);
1281 def_temp = gimple_build_debug_source_bind (def, var, NULL);
1282 DECL_ARTIFICIAL (def) = 1;
1283 TREE_TYPE (def) = TREE_TYPE (var);
1284 DECL_MODE (def) = DECL_MODE (var);
1285 gsi =
1286 gsi_after_labels (single_succ (ENTRY_BLOCK_PTR_FOR_FN (cfun)));
1287 gsi_insert_before (&gsi, def_temp, GSI_SAME_STMT);
1289 update = true;
1292 else
1294 /* Check if info->current_def can be trusted. */
1295 basic_block bb = gimple_bb (stmt);
1296 basic_block def_bb
1297 = SSA_NAME_IS_DEFAULT_DEF (def)
1298 ? NULL : gimple_bb (SSA_NAME_DEF_STMT (def));
1300 /* If definition is in current bb, it is fine. */
1301 if (bb == def_bb)
1303 /* If definition bb doesn't dominate the current bb,
1304 it can't be used. */
1305 else if (def_bb && !dominated_by_p (CDI_DOMINATORS, bb, def_bb))
1306 def = NULL;
1307 /* If there is just one definition and dominates the current
1308 bb, it is fine. */
1309 else if (info->need_phi_state == NEED_PHI_STATE_NO)
1311 else
1313 struct def_blocks_d *db_p = get_def_blocks_for (info);
1315 /* If there are some non-debug uses in the current bb,
1316 it is fine. */
1317 if (bitmap_bit_p (db_p->livein_blocks, bb->index))
1319 /* Otherwise give up for now. */
1320 else
1321 def = NULL;
1324 if (def == NULL)
1326 gimple_debug_bind_reset_value (stmt);
1327 update_stmt (stmt);
1328 return;
1330 SET_USE (use_p, def);
1332 if (update)
1333 update_stmt (stmt);
1336 /* SSA Rewriting Step 2. Rewrite every variable used in each statement in
1337 the block with its immediate reaching definitions. Update the current
1338 definition of a variable when a new real or virtual definition is found. */
1340 static void
1341 rewrite_stmt (gimple_stmt_iterator *si)
1343 use_operand_p use_p;
1344 def_operand_p def_p;
1345 ssa_op_iter iter;
1346 gimple stmt = gsi_stmt (*si);
1348 /* If mark_def_sites decided that we don't need to rewrite this
1349 statement, ignore it. */
1350 gcc_assert (blocks_to_update == NULL);
1351 if (!rewrite_uses_p (stmt) && !register_defs_p (stmt))
1352 return;
1354 if (dump_file && (dump_flags & TDF_DETAILS))
1356 fprintf (dump_file, "Renaming statement ");
1357 print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
1358 fprintf (dump_file, "\n");
1361 /* Step 1. Rewrite USES in the statement. */
1362 if (rewrite_uses_p (stmt))
1364 if (is_gimple_debug (stmt))
1365 rewrite_debug_stmt_uses (stmt);
1366 else
1367 FOR_EACH_SSA_USE_OPERAND (use_p, stmt, iter, SSA_OP_ALL_USES)
1369 tree var = USE_FROM_PTR (use_p);
1370 gcc_checking_assert (DECL_P (var));
1371 SET_USE (use_p, get_reaching_def (var));
1375 /* Step 2. Register the statement's DEF operands. */
1376 if (register_defs_p (stmt))
1377 FOR_EACH_SSA_DEF_OPERAND (def_p, stmt, iter, SSA_OP_ALL_DEFS)
1379 tree var = DEF_FROM_PTR (def_p);
1380 tree name;
1381 tree tracked_var;
1383 gcc_checking_assert (DECL_P (var));
1385 if (gimple_clobber_p (stmt)
1386 && is_gimple_reg (var))
1388 /* If we rewrite a DECL into SSA form then drop its
1389 clobber stmts and replace uses with a new default def. */
1390 gcc_checking_assert (TREE_CODE (var) == VAR_DECL
1391 && !gimple_vdef (stmt));
1392 gsi_replace (si, gimple_build_nop (), true);
1393 register_new_def (get_or_create_ssa_default_def (cfun, var), var);
1394 break;
1397 name = make_ssa_name (var, stmt);
1398 SET_DEF (def_p, name);
1399 register_new_def (DEF_FROM_PTR (def_p), var);
1401 tracked_var = target_for_debug_bind (var);
1402 if (tracked_var)
1404 gimple note = gimple_build_debug_bind (tracked_var, name, stmt);
1405 gsi_insert_after (si, note, GSI_SAME_STMT);
1411 /* SSA Rewriting Step 3. Visit all the successor blocks of BB looking for
1412 PHI nodes. For every PHI node found, add a new argument containing the
1413 current reaching definition for the variable and the edge through which
1414 that definition is reaching the PHI node. */
1416 static void
1417 rewrite_add_phi_arguments (basic_block bb)
1419 edge e;
1420 edge_iterator ei;
1422 FOR_EACH_EDGE (e, ei, bb->succs)
1424 gphi *phi;
1425 gphi_iterator gsi;
1427 for (gsi = gsi_start_phis (e->dest); !gsi_end_p (gsi);
1428 gsi_next (&gsi))
1430 tree currdef, res;
1431 location_t loc;
1433 phi = gsi.phi ();
1434 res = gimple_phi_result (phi);
1435 currdef = get_reaching_def (SSA_NAME_VAR (res));
1436 /* Virtual operand PHI args do not need a location. */
1437 if (virtual_operand_p (res))
1438 loc = UNKNOWN_LOCATION;
1439 else
1440 loc = gimple_location (SSA_NAME_DEF_STMT (currdef));
1441 add_phi_arg (phi, currdef, e, loc);
1446 class rewrite_dom_walker : public dom_walker
1448 public:
1449 rewrite_dom_walker (cdi_direction direction) : dom_walker (direction) {}
1451 virtual void before_dom_children (basic_block);
1452 virtual void after_dom_children (basic_block);
1455 /* SSA Rewriting Step 1. Initialization, create a block local stack
1456 of reaching definitions for new SSA names produced in this block
1457 (BLOCK_DEFS). Register new definitions for every PHI node in the
1458 block. */
1460 void
1461 rewrite_dom_walker::before_dom_children (basic_block bb)
1463 if (dump_file && (dump_flags & TDF_DETAILS))
1464 fprintf (dump_file, "\n\nRenaming block #%d\n\n", bb->index);
1466 /* Mark the unwind point for this block. */
1467 block_defs_stack.safe_push (NULL_TREE);
1469 /* Step 1. Register new definitions for every PHI node in the block.
1470 Conceptually, all the PHI nodes are executed in parallel and each PHI
1471 node introduces a new version for the associated variable. */
1472 for (gphi_iterator gsi = gsi_start_phis (bb); !gsi_end_p (gsi);
1473 gsi_next (&gsi))
1475 tree result = gimple_phi_result (gsi_stmt (gsi));
1476 register_new_def (result, SSA_NAME_VAR (result));
1479 /* Step 2. Rewrite every variable used in each statement in the block
1480 with its immediate reaching definitions. Update the current definition
1481 of a variable when a new real or virtual definition is found. */
1482 if (bitmap_bit_p (interesting_blocks, bb->index))
1483 for (gimple_stmt_iterator gsi = gsi_start_bb (bb); !gsi_end_p (gsi);
1484 gsi_next (&gsi))
1485 rewrite_stmt (&gsi);
1487 /* Step 3. Visit all the successor blocks of BB looking for PHI nodes.
1488 For every PHI node found, add a new argument containing the current
1489 reaching definition for the variable and the edge through which that
1490 definition is reaching the PHI node. */
1491 rewrite_add_phi_arguments (bb);
1496 /* Called after visiting all the statements in basic block BB and all
1497 of its dominator children. Restore CURRDEFS to its original value. */
1499 void
1500 rewrite_dom_walker::after_dom_children (basic_block bb ATTRIBUTE_UNUSED)
1502 /* Restore CURRDEFS to its original state. */
1503 while (block_defs_stack.length () > 0)
1505 tree tmp = block_defs_stack.pop ();
1506 tree saved_def, var;
1508 if (tmp == NULL_TREE)
1509 break;
1511 if (TREE_CODE (tmp) == SSA_NAME)
1513 /* If we recorded an SSA_NAME, then make the SSA_NAME the
1514 current definition of its underlying variable. Note that
1515 if the SSA_NAME is not for a GIMPLE register, the symbol
1516 being defined is stored in the next slot in the stack.
1517 This mechanism is needed because an SSA name for a
1518 non-register symbol may be the definition for more than
1519 one symbol (e.g., SFTs, aliased variables, etc). */
1520 saved_def = tmp;
1521 var = SSA_NAME_VAR (saved_def);
1522 if (!is_gimple_reg (var))
1523 var = block_defs_stack.pop ();
1525 else
1527 /* If we recorded anything else, it must have been a _DECL
1528 node and its current reaching definition must have been
1529 NULL. */
1530 saved_def = NULL;
1531 var = tmp;
1534 get_common_info (var)->current_def = saved_def;
1539 /* Dump bitmap SET (assumed to contain VAR_DECLs) to FILE. */
1541 DEBUG_FUNCTION void
1542 debug_decl_set (bitmap set)
1544 dump_decl_set (stderr, set);
1545 fprintf (stderr, "\n");
1549 /* Dump the renaming stack (block_defs_stack) to FILE. Traverse the
1550 stack up to a maximum of N levels. If N is -1, the whole stack is
1551 dumped. New levels are created when the dominator tree traversal
1552 used for renaming enters a new sub-tree. */
1554 void
1555 dump_defs_stack (FILE *file, int n)
1557 int i, j;
1559 fprintf (file, "\n\nRenaming stack");
1560 if (n > 0)
1561 fprintf (file, " (up to %d levels)", n);
1562 fprintf (file, "\n\n");
1564 i = 1;
1565 fprintf (file, "Level %d (current level)\n", i);
1566 for (j = (int) block_defs_stack.length () - 1; j >= 0; j--)
1568 tree name, var;
1570 name = block_defs_stack[j];
1571 if (name == NULL_TREE)
1573 i++;
1574 if (n > 0 && i > n)
1575 break;
1576 fprintf (file, "\nLevel %d\n", i);
1577 continue;
1580 if (DECL_P (name))
1582 var = name;
1583 name = NULL_TREE;
1585 else
1587 var = SSA_NAME_VAR (name);
1588 if (!is_gimple_reg (var))
1590 j--;
1591 var = block_defs_stack[j];
1595 fprintf (file, " Previous CURRDEF (");
1596 print_generic_expr (file, var, 0);
1597 fprintf (file, ") = ");
1598 if (name)
1599 print_generic_expr (file, name, 0);
1600 else
1601 fprintf (file, "<NIL>");
1602 fprintf (file, "\n");
1607 /* Dump the renaming stack (block_defs_stack) to stderr. Traverse the
1608 stack up to a maximum of N levels. If N is -1, the whole stack is
1609 dumped. New levels are created when the dominator tree traversal
1610 used for renaming enters a new sub-tree. */
1612 DEBUG_FUNCTION void
1613 debug_defs_stack (int n)
1615 dump_defs_stack (stderr, n);
1619 /* Dump the current reaching definition of every symbol to FILE. */
1621 void
1622 dump_currdefs (FILE *file)
1624 unsigned i;
1625 tree var;
1627 if (symbols_to_rename.is_empty ())
1628 return;
1630 fprintf (file, "\n\nCurrent reaching definitions\n\n");
1631 FOR_EACH_VEC_ELT (symbols_to_rename, i, var)
1633 common_info_p info = get_common_info (var);
1634 fprintf (file, "CURRDEF (");
1635 print_generic_expr (file, var, 0);
1636 fprintf (file, ") = ");
1637 if (info->current_def)
1638 print_generic_expr (file, info->current_def, 0);
1639 else
1640 fprintf (file, "<NIL>");
1641 fprintf (file, "\n");
1646 /* Dump the current reaching definition of every symbol to stderr. */
1648 DEBUG_FUNCTION void
1649 debug_currdefs (void)
1651 dump_currdefs (stderr);
1655 /* Dump SSA information to FILE. */
1657 void
1658 dump_tree_ssa (FILE *file)
1660 const char *funcname
1661 = lang_hooks.decl_printable_name (current_function_decl, 2);
1663 fprintf (file, "SSA renaming information for %s\n\n", funcname);
1665 dump_var_infos (file);
1666 dump_defs_stack (file, -1);
1667 dump_currdefs (file);
1668 dump_tree_ssa_stats (file);
1672 /* Dump SSA information to stderr. */
1674 DEBUG_FUNCTION void
1675 debug_tree_ssa (void)
1677 dump_tree_ssa (stderr);
1681 /* Dump statistics for the hash table HTAB. */
1683 static void
1684 htab_statistics (FILE *file, const hash_table<var_info_hasher> &htab)
1686 fprintf (file, "size %ld, %ld elements, %f collision/search ratio\n",
1687 (long) htab.size (),
1688 (long) htab.elements (),
1689 htab.collisions ());
1693 /* Dump SSA statistics on FILE. */
1695 void
1696 dump_tree_ssa_stats (FILE *file)
1698 if (var_infos)
1700 fprintf (file, "\nHash table statistics:\n");
1701 fprintf (file, " var_infos: ");
1702 htab_statistics (file, *var_infos);
1703 fprintf (file, "\n");
1708 /* Dump SSA statistics on stderr. */
1710 DEBUG_FUNCTION void
1711 debug_tree_ssa_stats (void)
1713 dump_tree_ssa_stats (stderr);
1717 /* Callback for htab_traverse to dump the VAR_INFOS hash table. */
1720 debug_var_infos_r (var_info_d **slot, FILE *file)
1722 struct var_info_d *info = *slot;
1724 fprintf (file, "VAR: ");
1725 print_generic_expr (file, info->var, dump_flags);
1726 bitmap_print (file, info->info.def_blocks.def_blocks,
1727 ", DEF_BLOCKS: { ", "}");
1728 bitmap_print (file, info->info.def_blocks.livein_blocks,
1729 ", LIVEIN_BLOCKS: { ", "}");
1730 bitmap_print (file, info->info.def_blocks.phi_blocks,
1731 ", PHI_BLOCKS: { ", "}\n");
1733 return 1;
1737 /* Dump the VAR_INFOS hash table on FILE. */
1739 void
1740 dump_var_infos (FILE *file)
1742 fprintf (file, "\n\nDefinition and live-in blocks:\n\n");
1743 if (var_infos)
1744 var_infos->traverse <FILE *, debug_var_infos_r> (file);
1748 /* Dump the VAR_INFOS hash table on stderr. */
1750 DEBUG_FUNCTION void
1751 debug_var_infos (void)
1753 dump_var_infos (stderr);
1757 /* Register NEW_NAME to be the new reaching definition for OLD_NAME. */
1759 static inline void
1760 register_new_update_single (tree new_name, tree old_name)
1762 common_info_p info = get_common_info (old_name);
1763 tree currdef = info->current_def;
1765 /* Push the current reaching definition into BLOCK_DEFS_STACK.
1766 This stack is later used by the dominator tree callbacks to
1767 restore the reaching definitions for all the variables
1768 defined in the block after a recursive visit to all its
1769 immediately dominated blocks. */
1770 block_defs_stack.reserve (2);
1771 block_defs_stack.quick_push (currdef);
1772 block_defs_stack.quick_push (old_name);
1774 /* Set the current reaching definition for OLD_NAME to be
1775 NEW_NAME. */
1776 info->current_def = new_name;
1780 /* Register NEW_NAME to be the new reaching definition for all the
1781 names in OLD_NAMES. Used by the incremental SSA update routines to
1782 replace old SSA names with new ones. */
1784 static inline void
1785 register_new_update_set (tree new_name, bitmap old_names)
1787 bitmap_iterator bi;
1788 unsigned i;
1790 EXECUTE_IF_SET_IN_BITMAP (old_names, 0, i, bi)
1791 register_new_update_single (new_name, ssa_name (i));
1796 /* If the operand pointed to by USE_P is a name in OLD_SSA_NAMES or
1797 it is a symbol marked for renaming, replace it with USE_P's current
1798 reaching definition. */
1800 static inline void
1801 maybe_replace_use (use_operand_p use_p)
1803 tree rdef = NULL_TREE;
1804 tree use = USE_FROM_PTR (use_p);
1805 tree sym = DECL_P (use) ? use : SSA_NAME_VAR (use);
1807 if (marked_for_renaming (sym))
1808 rdef = get_reaching_def (sym);
1809 else if (is_old_name (use))
1810 rdef = get_reaching_def (use);
1812 if (rdef && rdef != use)
1813 SET_USE (use_p, rdef);
1817 /* Same as maybe_replace_use, but without introducing default stmts,
1818 returning false to indicate a need to do so. */
1820 static inline bool
1821 maybe_replace_use_in_debug_stmt (use_operand_p use_p)
1823 tree rdef = NULL_TREE;
1824 tree use = USE_FROM_PTR (use_p);
1825 tree sym = DECL_P (use) ? use : SSA_NAME_VAR (use);
1827 if (marked_for_renaming (sym))
1828 rdef = get_var_info (sym)->info.current_def;
1829 else if (is_old_name (use))
1831 rdef = get_ssa_name_ann (use)->info.current_def;
1832 /* We can't assume that, if there's no current definition, the
1833 default one should be used. It could be the case that we've
1834 rearranged blocks so that the earlier definition no longer
1835 dominates the use. */
1836 if (!rdef && SSA_NAME_IS_DEFAULT_DEF (use))
1837 rdef = use;
1839 else
1840 rdef = use;
1842 if (rdef && rdef != use)
1843 SET_USE (use_p, rdef);
1845 return rdef != NULL_TREE;
1849 /* If the operand pointed to by DEF_P is an SSA name in NEW_SSA_NAMES
1850 or OLD_SSA_NAMES, or if it is a symbol marked for renaming,
1851 register it as the current definition for the names replaced by
1852 DEF_P. Returns whether the statement should be removed. */
1854 static inline bool
1855 maybe_register_def (def_operand_p def_p, gimple stmt,
1856 gimple_stmt_iterator gsi)
1858 tree def = DEF_FROM_PTR (def_p);
1859 tree sym = DECL_P (def) ? def : SSA_NAME_VAR (def);
1860 bool to_delete = false;
1862 /* If DEF is a naked symbol that needs renaming, create a new
1863 name for it. */
1864 if (marked_for_renaming (sym))
1866 if (DECL_P (def))
1868 if (gimple_clobber_p (stmt) && is_gimple_reg (sym))
1870 gcc_checking_assert (TREE_CODE (sym) == VAR_DECL);
1871 /* Replace clobber stmts with a default def. This new use of a
1872 default definition may make it look like SSA_NAMEs have
1873 conflicting lifetimes, so we need special code to let them
1874 coalesce properly. */
1875 to_delete = true;
1876 def = get_or_create_ssa_default_def (cfun, sym);
1878 else
1879 def = make_ssa_name (def, stmt);
1880 SET_DEF (def_p, def);
1882 tree tracked_var = target_for_debug_bind (sym);
1883 if (tracked_var)
1885 gimple note = gimple_build_debug_bind (tracked_var, def, stmt);
1886 /* If stmt ends the bb, insert the debug stmt on the single
1887 non-EH edge from the stmt. */
1888 if (gsi_one_before_end_p (gsi) && stmt_ends_bb_p (stmt))
1890 basic_block bb = gsi_bb (gsi);
1891 edge_iterator ei;
1892 edge e, ef = NULL;
1893 FOR_EACH_EDGE (e, ei, bb->succs)
1894 if (!(e->flags & EDGE_EH))
1896 gcc_checking_assert (!ef);
1897 ef = e;
1899 /* If there are other predecessors to ef->dest, then
1900 there must be PHI nodes for the modified
1901 variable, and therefore there will be debug bind
1902 stmts after the PHI nodes. The debug bind notes
1903 we'd insert would force the creation of a new
1904 block (diverging codegen) and be redundant with
1905 the post-PHI bind stmts, so don't add them.
1907 As for the exit edge, there wouldn't be redundant
1908 bind stmts, but there wouldn't be a PC to bind
1909 them to either, so avoid diverging the CFG. */
1910 if (ef && single_pred_p (ef->dest)
1911 && ef->dest != EXIT_BLOCK_PTR_FOR_FN (cfun))
1913 /* If there were PHI nodes in the node, we'd
1914 have to make sure the value we're binding
1915 doesn't need rewriting. But there shouldn't
1916 be PHI nodes in a single-predecessor block,
1917 so we just add the note. */
1918 gsi_insert_on_edge_immediate (ef, note);
1921 else
1922 gsi_insert_after (&gsi, note, GSI_SAME_STMT);
1926 register_new_update_single (def, sym);
1928 else
1930 /* If DEF is a new name, register it as a new definition
1931 for all the names replaced by DEF. */
1932 if (is_new_name (def))
1933 register_new_update_set (def, names_replaced_by (def));
1935 /* If DEF is an old name, register DEF as a new
1936 definition for itself. */
1937 if (is_old_name (def))
1938 register_new_update_single (def, def);
1941 return to_delete;
1945 /* Update every variable used in the statement pointed-to by SI. The
1946 statement is assumed to be in SSA form already. Names in
1947 OLD_SSA_NAMES used by SI will be updated to their current reaching
1948 definition. Names in OLD_SSA_NAMES or NEW_SSA_NAMES defined by SI
1949 will be registered as a new definition for their corresponding name
1950 in OLD_SSA_NAMES. Returns whether STMT should be removed. */
1952 static bool
1953 rewrite_update_stmt (gimple stmt, gimple_stmt_iterator gsi)
1955 use_operand_p use_p;
1956 def_operand_p def_p;
1957 ssa_op_iter iter;
1959 /* Only update marked statements. */
1960 if (!rewrite_uses_p (stmt) && !register_defs_p (stmt))
1961 return false;
1963 if (dump_file && (dump_flags & TDF_DETAILS))
1965 fprintf (dump_file, "Updating SSA information for statement ");
1966 print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
1969 /* Rewrite USES included in OLD_SSA_NAMES and USES whose underlying
1970 symbol is marked for renaming. */
1971 if (rewrite_uses_p (stmt))
1973 if (is_gimple_debug (stmt))
1975 bool failed = false;
1977 FOR_EACH_SSA_USE_OPERAND (use_p, stmt, iter, SSA_OP_USE)
1978 if (!maybe_replace_use_in_debug_stmt (use_p))
1980 failed = true;
1981 break;
1984 if (failed)
1986 /* DOM sometimes threads jumps in such a way that a
1987 debug stmt ends up referencing a SSA variable that no
1988 longer dominates the debug stmt, but such that all
1989 incoming definitions refer to the same definition in
1990 an earlier dominator. We could try to recover that
1991 definition somehow, but this will have to do for now.
1993 Introducing a default definition, which is what
1994 maybe_replace_use() would do in such cases, may
1995 modify code generation, for the otherwise-unused
1996 default definition would never go away, modifying SSA
1997 version numbers all over. */
1998 gimple_debug_bind_reset_value (stmt);
1999 update_stmt (stmt);
2002 else
2004 FOR_EACH_SSA_USE_OPERAND (use_p, stmt, iter, SSA_OP_ALL_USES)
2005 maybe_replace_use (use_p);
2009 /* Register definitions of names in NEW_SSA_NAMES and OLD_SSA_NAMES.
2010 Also register definitions for names whose underlying symbol is
2011 marked for renaming. */
2012 bool to_delete = false;
2013 if (register_defs_p (stmt))
2014 FOR_EACH_SSA_DEF_OPERAND (def_p, stmt, iter, SSA_OP_ALL_DEFS)
2015 to_delete |= maybe_register_def (def_p, stmt, gsi);
2017 return to_delete;
2021 /* Visit all the successor blocks of BB looking for PHI nodes. For
2022 every PHI node found, check if any of its arguments is in
2023 OLD_SSA_NAMES. If so, and if the argument has a current reaching
2024 definition, replace it. */
2026 static void
2027 rewrite_update_phi_arguments (basic_block bb)
2029 edge e;
2030 edge_iterator ei;
2031 unsigned i;
2033 FOR_EACH_EDGE (e, ei, bb->succs)
2035 gphi *phi;
2036 vec<gphi *> phis;
2038 if (!bitmap_bit_p (blocks_with_phis_to_rewrite, e->dest->index))
2039 continue;
2041 phis = phis_to_rewrite[e->dest->index];
2042 FOR_EACH_VEC_ELT (phis, i, phi)
2044 tree arg, lhs_sym, reaching_def = NULL;
2045 use_operand_p arg_p;
2047 gcc_checking_assert (rewrite_uses_p (phi));
2049 arg_p = PHI_ARG_DEF_PTR_FROM_EDGE (phi, e);
2050 arg = USE_FROM_PTR (arg_p);
2052 if (arg && !DECL_P (arg) && TREE_CODE (arg) != SSA_NAME)
2053 continue;
2055 lhs_sym = SSA_NAME_VAR (gimple_phi_result (phi));
2057 if (arg == NULL_TREE)
2059 /* When updating a PHI node for a recently introduced
2060 symbol we may find NULL arguments. That's why we
2061 take the symbol from the LHS of the PHI node. */
2062 reaching_def = get_reaching_def (lhs_sym);
2065 else
2067 tree sym = DECL_P (arg) ? arg : SSA_NAME_VAR (arg);
2069 if (marked_for_renaming (sym))
2070 reaching_def = get_reaching_def (sym);
2071 else if (is_old_name (arg))
2072 reaching_def = get_reaching_def (arg);
2075 /* Update the argument if there is a reaching def. */
2076 if (reaching_def)
2078 source_location locus;
2079 int arg_i = PHI_ARG_INDEX_FROM_USE (arg_p);
2081 SET_USE (arg_p, reaching_def);
2083 /* Virtual operands do not need a location. */
2084 if (virtual_operand_p (reaching_def))
2085 locus = UNKNOWN_LOCATION;
2086 else
2088 gimple stmt = SSA_NAME_DEF_STMT (reaching_def);
2089 gphi *other_phi = dyn_cast <gphi *> (stmt);
2091 /* Single element PHI nodes behave like copies, so get the
2092 location from the phi argument. */
2093 if (other_phi
2094 && gimple_phi_num_args (other_phi) == 1)
2095 locus = gimple_phi_arg_location (other_phi, 0);
2096 else
2097 locus = gimple_location (stmt);
2100 gimple_phi_arg_set_location (phi, arg_i, locus);
2104 if (e->flags & EDGE_ABNORMAL)
2105 SSA_NAME_OCCURS_IN_ABNORMAL_PHI (USE_FROM_PTR (arg_p)) = 1;
2110 class rewrite_update_dom_walker : public dom_walker
2112 public:
2113 rewrite_update_dom_walker (cdi_direction direction) : dom_walker (direction) {}
2115 virtual void before_dom_children (basic_block);
2116 virtual void after_dom_children (basic_block);
2119 /* Initialization of block data structures for the incremental SSA
2120 update pass. Create a block local stack of reaching definitions
2121 for new SSA names produced in this block (BLOCK_DEFS). Register
2122 new definitions for every PHI node in the block. */
2124 void
2125 rewrite_update_dom_walker::before_dom_children (basic_block bb)
2127 bool is_abnormal_phi;
2129 if (dump_file && (dump_flags & TDF_DETAILS))
2130 fprintf (dump_file, "Registering new PHI nodes in block #%d\n",
2131 bb->index);
2133 /* Mark the unwind point for this block. */
2134 block_defs_stack.safe_push (NULL_TREE);
2136 if (!bitmap_bit_p (blocks_to_update, bb->index))
2137 return;
2139 /* Mark the LHS if any of the arguments flows through an abnormal
2140 edge. */
2141 is_abnormal_phi = bb_has_abnormal_pred (bb);
2143 /* If any of the PHI nodes is a replacement for a name in
2144 OLD_SSA_NAMES or it's one of the names in NEW_SSA_NAMES, then
2145 register it as a new definition for its corresponding name. Also
2146 register definitions for names whose underlying symbols are
2147 marked for renaming. */
2148 for (gphi_iterator gsi = gsi_start_phis (bb); !gsi_end_p (gsi);
2149 gsi_next (&gsi))
2151 tree lhs, lhs_sym;
2152 gphi *phi = gsi.phi ();
2154 if (!register_defs_p (phi))
2155 continue;
2157 lhs = gimple_phi_result (phi);
2158 lhs_sym = SSA_NAME_VAR (lhs);
2160 if (marked_for_renaming (lhs_sym))
2161 register_new_update_single (lhs, lhs_sym);
2162 else
2165 /* If LHS is a new name, register a new definition for all
2166 the names replaced by LHS. */
2167 if (is_new_name (lhs))
2168 register_new_update_set (lhs, names_replaced_by (lhs));
2170 /* If LHS is an OLD name, register it as a new definition
2171 for itself. */
2172 if (is_old_name (lhs))
2173 register_new_update_single (lhs, lhs);
2176 if (is_abnormal_phi)
2177 SSA_NAME_OCCURS_IN_ABNORMAL_PHI (lhs) = 1;
2180 /* Step 2. Rewrite every variable used in each statement in the block. */
2181 if (bitmap_bit_p (interesting_blocks, bb->index))
2183 gcc_checking_assert (bitmap_bit_p (blocks_to_update, bb->index));
2184 for (gimple_stmt_iterator gsi = gsi_start_bb (bb); !gsi_end_p (gsi); )
2185 if (rewrite_update_stmt (gsi_stmt (gsi), gsi))
2186 gsi_remove (&gsi, true);
2187 else
2188 gsi_next (&gsi);
2191 /* Step 3. Update PHI nodes. */
2192 rewrite_update_phi_arguments (bb);
2195 /* Called after visiting block BB. Unwind BLOCK_DEFS_STACK to restore
2196 the current reaching definition of every name re-written in BB to
2197 the original reaching definition before visiting BB. This
2198 unwinding must be done in the opposite order to what is done in
2199 register_new_update_set. */
2201 void
2202 rewrite_update_dom_walker::after_dom_children (basic_block bb ATTRIBUTE_UNUSED)
2204 while (block_defs_stack.length () > 0)
2206 tree var = block_defs_stack.pop ();
2207 tree saved_def;
2209 /* NULL indicates the unwind stop point for this block (see
2210 rewrite_update_enter_block). */
2211 if (var == NULL)
2212 return;
2214 saved_def = block_defs_stack.pop ();
2215 get_common_info (var)->current_def = saved_def;
2220 /* Rewrite the actual blocks, statements, and PHI arguments, to be in SSA
2221 form.
2223 ENTRY indicates the block where to start. Every block dominated by
2224 ENTRY will be rewritten.
2226 WHAT indicates what actions will be taken by the renamer (see enum
2227 rewrite_mode).
2229 BLOCKS are the set of interesting blocks for the dominator walker
2230 to process. If this set is NULL, then all the nodes dominated
2231 by ENTRY are walked. Otherwise, blocks dominated by ENTRY that
2232 are not present in BLOCKS are ignored. */
2234 static void
2235 rewrite_blocks (basic_block entry, enum rewrite_mode what)
2237 /* Rewrite all the basic blocks in the program. */
2238 timevar_push (TV_TREE_SSA_REWRITE_BLOCKS);
2240 block_defs_stack.create (10);
2242 /* Recursively walk the dominator tree rewriting each statement in
2243 each basic block. */
2244 if (what == REWRITE_ALL)
2245 rewrite_dom_walker (CDI_DOMINATORS).walk (entry);
2246 else if (what == REWRITE_UPDATE)
2247 rewrite_update_dom_walker (CDI_DOMINATORS).walk (entry);
2248 else
2249 gcc_unreachable ();
2251 /* Debugging dumps. */
2252 if (dump_file && (dump_flags & TDF_STATS))
2254 dump_dfa_stats (dump_file);
2255 if (var_infos)
2256 dump_tree_ssa_stats (dump_file);
2259 block_defs_stack.release ();
2261 timevar_pop (TV_TREE_SSA_REWRITE_BLOCKS);
2264 class mark_def_dom_walker : public dom_walker
2266 public:
2267 mark_def_dom_walker (cdi_direction direction);
2268 ~mark_def_dom_walker ();
2270 virtual void before_dom_children (basic_block);
2272 private:
2273 /* Notice that this bitmap is indexed using variable UIDs, so it must be
2274 large enough to accommodate all the variables referenced in the
2275 function, not just the ones we are renaming. */
2276 bitmap m_kills;
2279 mark_def_dom_walker::mark_def_dom_walker (cdi_direction direction)
2280 : dom_walker (direction), m_kills (BITMAP_ALLOC (NULL))
2284 mark_def_dom_walker::~mark_def_dom_walker ()
2286 BITMAP_FREE (m_kills);
2289 /* Block processing routine for mark_def_sites. Clear the KILLS bitmap
2290 at the start of each block, and call mark_def_sites for each statement. */
2292 void
2293 mark_def_dom_walker::before_dom_children (basic_block bb)
2295 gimple_stmt_iterator gsi;
2297 bitmap_clear (m_kills);
2298 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
2299 mark_def_sites (bb, gsi_stmt (gsi), m_kills);
2302 /* Initialize internal data needed during renaming. */
2304 static void
2305 init_ssa_renamer (void)
2307 cfun->gimple_df->in_ssa_p = false;
2309 /* Allocate memory for the DEF_BLOCKS hash table. */
2310 gcc_assert (!var_infos);
2311 var_infos = new hash_table<var_info_hasher>
2312 (vec_safe_length (cfun->local_decls));
2314 bitmap_obstack_initialize (&update_ssa_obstack);
2318 /* Deallocate internal data structures used by the renamer. */
2320 static void
2321 fini_ssa_renamer (void)
2323 delete var_infos;
2324 var_infos = NULL;
2326 bitmap_obstack_release (&update_ssa_obstack);
2328 cfun->gimple_df->ssa_renaming_needed = 0;
2329 cfun->gimple_df->rename_vops = 0;
2330 cfun->gimple_df->in_ssa_p = true;
2333 /* Main entry point into the SSA builder. The renaming process
2334 proceeds in four main phases:
2336 1- Compute dominance frontier and immediate dominators, needed to
2337 insert PHI nodes and rename the function in dominator tree
2338 order.
2340 2- Find and mark all the blocks that define variables.
2342 3- Insert PHI nodes at dominance frontiers (insert_phi_nodes).
2344 4- Rename all the blocks (rewrite_blocks) and statements in the program.
2346 Steps 3 and 4 are done using the dominator tree walker
2347 (walk_dominator_tree). */
2349 namespace {
2351 const pass_data pass_data_build_ssa =
2353 GIMPLE_PASS, /* type */
2354 "ssa", /* name */
2355 OPTGROUP_NONE, /* optinfo_flags */
2356 TV_TREE_SSA_OTHER, /* tv_id */
2357 PROP_cfg, /* properties_required */
2358 PROP_ssa, /* properties_provided */
2359 0, /* properties_destroyed */
2360 0, /* todo_flags_start */
2361 TODO_remove_unused_locals, /* todo_flags_finish */
2364 class pass_build_ssa : public gimple_opt_pass
2366 public:
2367 pass_build_ssa (gcc::context *ctxt)
2368 : gimple_opt_pass (pass_data_build_ssa, ctxt)
2371 /* opt_pass methods: */
2372 virtual bool gate (function *fun)
2374 /* Do nothing for funcions that was produced already in SSA form. */
2375 return !(fun->curr_properties & PROP_ssa);
2378 virtual unsigned int execute (function *);
2380 }; // class pass_build_ssa
2382 unsigned int
2383 pass_build_ssa::execute (function *fun)
2385 bitmap_head *dfs;
2386 basic_block bb;
2387 unsigned i;
2389 /* Initialize operand data structures. */
2390 init_ssa_operands (fun);
2392 /* Initialize internal data needed by the renamer. */
2393 init_ssa_renamer ();
2395 /* Initialize the set of interesting blocks. The callback
2396 mark_def_sites will add to this set those blocks that the renamer
2397 should process. */
2398 interesting_blocks = sbitmap_alloc (last_basic_block_for_fn (fun));
2399 bitmap_clear (interesting_blocks);
2401 /* Initialize dominance frontier. */
2402 dfs = XNEWVEC (bitmap_head, last_basic_block_for_fn (fun));
2403 FOR_EACH_BB_FN (bb, fun)
2404 bitmap_initialize (&dfs[bb->index], &bitmap_default_obstack);
2406 /* 1- Compute dominance frontiers. */
2407 calculate_dominance_info (CDI_DOMINATORS);
2408 compute_dominance_frontiers (dfs);
2410 /* 2- Find and mark definition sites. */
2411 mark_def_dom_walker (CDI_DOMINATORS).walk (fun->cfg->x_entry_block_ptr);
2413 /* 3- Insert PHI nodes at dominance frontiers of definition blocks. */
2414 insert_phi_nodes (dfs);
2416 /* 4- Rename all the blocks. */
2417 rewrite_blocks (ENTRY_BLOCK_PTR_FOR_FN (fun), REWRITE_ALL);
2419 /* Free allocated memory. */
2420 FOR_EACH_BB_FN (bb, fun)
2421 bitmap_clear (&dfs[bb->index]);
2422 free (dfs);
2424 sbitmap_free (interesting_blocks);
2426 fini_ssa_renamer ();
2428 /* Try to get rid of all gimplifier generated temporaries by making
2429 its SSA names anonymous. This way we can garbage collect them
2430 all after removing unused locals which we do in our TODO. */
2431 for (i = 1; i < num_ssa_names; ++i)
2433 tree decl, name = ssa_name (i);
2434 if (!name
2435 || SSA_NAME_IS_DEFAULT_DEF (name))
2436 continue;
2437 decl = SSA_NAME_VAR (name);
2438 if (decl
2439 && TREE_CODE (decl) == VAR_DECL
2440 && !VAR_DECL_IS_VIRTUAL_OPERAND (decl)
2441 && DECL_IGNORED_P (decl))
2442 SET_SSA_NAME_VAR_OR_IDENTIFIER (name, DECL_NAME (decl));
2445 return 0;
2448 } // anon namespace
2450 gimple_opt_pass *
2451 make_pass_build_ssa (gcc::context *ctxt)
2453 return new pass_build_ssa (ctxt);
2457 /* Mark the definition of VAR at STMT and BB as interesting for the
2458 renamer. BLOCKS is the set of blocks that need updating. */
2460 static void
2461 mark_def_interesting (tree var, gimple stmt, basic_block bb, bool insert_phi_p)
2463 gcc_checking_assert (bitmap_bit_p (blocks_to_update, bb->index));
2464 set_register_defs (stmt, true);
2466 if (insert_phi_p)
2468 bool is_phi_p = gimple_code (stmt) == GIMPLE_PHI;
2470 set_def_block (var, bb, is_phi_p);
2472 /* If VAR is an SSA name in NEW_SSA_NAMES, this is a definition
2473 site for both itself and all the old names replaced by it. */
2474 if (TREE_CODE (var) == SSA_NAME && is_new_name (var))
2476 bitmap_iterator bi;
2477 unsigned i;
2478 bitmap set = names_replaced_by (var);
2479 if (set)
2480 EXECUTE_IF_SET_IN_BITMAP (set, 0, i, bi)
2481 set_def_block (ssa_name (i), bb, is_phi_p);
2487 /* Mark the use of VAR at STMT and BB as interesting for the
2488 renamer. INSERT_PHI_P is true if we are going to insert new PHI
2489 nodes. */
2491 static inline void
2492 mark_use_interesting (tree var, gimple stmt, basic_block bb, bool insert_phi_p)
2494 basic_block def_bb = gimple_bb (stmt);
2496 mark_block_for_update (def_bb);
2497 mark_block_for_update (bb);
2499 if (gimple_code (stmt) == GIMPLE_PHI)
2500 mark_phi_for_rewrite (def_bb, as_a <gphi *> (stmt));
2501 else
2503 set_rewrite_uses (stmt, true);
2505 if (is_gimple_debug (stmt))
2506 return;
2509 /* If VAR has not been defined in BB, then it is live-on-entry
2510 to BB. Note that we cannot just use the block holding VAR's
2511 definition because if VAR is one of the names in OLD_SSA_NAMES,
2512 it will have several definitions (itself and all the names that
2513 replace it). */
2514 if (insert_phi_p)
2516 struct def_blocks_d *db_p = get_def_blocks_for (get_common_info (var));
2517 if (!bitmap_bit_p (db_p->def_blocks, bb->index))
2518 set_livein_block (var, bb);
2523 /* Do a dominator walk starting at BB processing statements that
2524 reference symbols in SSA operands. This is very similar to
2525 mark_def_sites, but the scan handles statements whose operands may
2526 already be SSA names.
2528 If INSERT_PHI_P is true, mark those uses as live in the
2529 corresponding block. This is later used by the PHI placement
2530 algorithm to make PHI pruning decisions.
2532 FIXME. Most of this would be unnecessary if we could associate a
2533 symbol to all the SSA names that reference it. But that
2534 sounds like it would be expensive to maintain. Still, it
2535 would be interesting to see if it makes better sense to do
2536 that. */
2538 static void
2539 prepare_block_for_update (basic_block bb, bool insert_phi_p)
2541 basic_block son;
2542 edge e;
2543 edge_iterator ei;
2545 mark_block_for_update (bb);
2547 /* Process PHI nodes marking interesting those that define or use
2548 the symbols that we are interested in. */
2549 for (gphi_iterator si = gsi_start_phis (bb); !gsi_end_p (si);
2550 gsi_next (&si))
2552 gphi *phi = si.phi ();
2553 tree lhs_sym, lhs = gimple_phi_result (phi);
2555 if (TREE_CODE (lhs) == SSA_NAME
2556 && (! virtual_operand_p (lhs)
2557 || ! cfun->gimple_df->rename_vops))
2558 continue;
2560 lhs_sym = DECL_P (lhs) ? lhs : SSA_NAME_VAR (lhs);
2561 mark_for_renaming (lhs_sym);
2562 mark_def_interesting (lhs_sym, phi, bb, insert_phi_p);
2564 /* Mark the uses in phi nodes as interesting. It would be more correct
2565 to process the arguments of the phi nodes of the successor edges of
2566 BB at the end of prepare_block_for_update, however, that turns out
2567 to be significantly more expensive. Doing it here is conservatively
2568 correct -- it may only cause us to believe a value to be live in a
2569 block that also contains its definition, and thus insert a few more
2570 phi nodes for it. */
2571 FOR_EACH_EDGE (e, ei, bb->preds)
2572 mark_use_interesting (lhs_sym, phi, e->src, insert_phi_p);
2575 /* Process the statements. */
2576 for (gimple_stmt_iterator si = gsi_start_bb (bb); !gsi_end_p (si);
2577 gsi_next (&si))
2579 gimple stmt;
2580 ssa_op_iter i;
2581 use_operand_p use_p;
2582 def_operand_p def_p;
2584 stmt = gsi_stmt (si);
2586 if (cfun->gimple_df->rename_vops
2587 && gimple_vuse (stmt))
2589 tree use = gimple_vuse (stmt);
2590 tree sym = DECL_P (use) ? use : SSA_NAME_VAR (use);
2591 mark_for_renaming (sym);
2592 mark_use_interesting (sym, stmt, bb, insert_phi_p);
2595 FOR_EACH_SSA_USE_OPERAND (use_p, stmt, i, SSA_OP_USE)
2597 tree use = USE_FROM_PTR (use_p);
2598 if (!DECL_P (use))
2599 continue;
2600 mark_for_renaming (use);
2601 mark_use_interesting (use, stmt, bb, insert_phi_p);
2604 if (cfun->gimple_df->rename_vops
2605 && gimple_vdef (stmt))
2607 tree def = gimple_vdef (stmt);
2608 tree sym = DECL_P (def) ? def : SSA_NAME_VAR (def);
2609 mark_for_renaming (sym);
2610 mark_def_interesting (sym, stmt, bb, insert_phi_p);
2613 FOR_EACH_SSA_DEF_OPERAND (def_p, stmt, i, SSA_OP_DEF)
2615 tree def = DEF_FROM_PTR (def_p);
2616 if (!DECL_P (def))
2617 continue;
2618 mark_for_renaming (def);
2619 mark_def_interesting (def, stmt, bb, insert_phi_p);
2623 /* Now visit all the blocks dominated by BB. */
2624 for (son = first_dom_son (CDI_DOMINATORS, bb);
2625 son;
2626 son = next_dom_son (CDI_DOMINATORS, son))
2627 prepare_block_for_update (son, insert_phi_p);
2631 /* Helper for prepare_names_to_update. Mark all the use sites for
2632 NAME as interesting. BLOCKS and INSERT_PHI_P are as in
2633 prepare_names_to_update. */
2635 static void
2636 prepare_use_sites_for (tree name, bool insert_phi_p)
2638 use_operand_p use_p;
2639 imm_use_iterator iter;
2641 FOR_EACH_IMM_USE_FAST (use_p, iter, name)
2643 gimple stmt = USE_STMT (use_p);
2644 basic_block bb = gimple_bb (stmt);
2646 if (gimple_code (stmt) == GIMPLE_PHI)
2648 int ix = PHI_ARG_INDEX_FROM_USE (use_p);
2649 edge e = gimple_phi_arg_edge (as_a <gphi *> (stmt), ix);
2650 mark_use_interesting (name, stmt, e->src, insert_phi_p);
2652 else
2654 /* For regular statements, mark this as an interesting use
2655 for NAME. */
2656 mark_use_interesting (name, stmt, bb, insert_phi_p);
2662 /* Helper for prepare_names_to_update. Mark the definition site for
2663 NAME as interesting. BLOCKS and INSERT_PHI_P are as in
2664 prepare_names_to_update. */
2666 static void
2667 prepare_def_site_for (tree name, bool insert_phi_p)
2669 gimple stmt;
2670 basic_block bb;
2672 gcc_checking_assert (names_to_release == NULL
2673 || !bitmap_bit_p (names_to_release,
2674 SSA_NAME_VERSION (name)));
2676 stmt = SSA_NAME_DEF_STMT (name);
2677 bb = gimple_bb (stmt);
2678 if (bb)
2680 gcc_checking_assert (bb->index < last_basic_block_for_fn (cfun));
2681 mark_block_for_update (bb);
2682 mark_def_interesting (name, stmt, bb, insert_phi_p);
2687 /* Mark definition and use sites of names in NEW_SSA_NAMES and
2688 OLD_SSA_NAMES. INSERT_PHI_P is true if the caller wants to insert
2689 PHI nodes for newly created names. */
2691 static void
2692 prepare_names_to_update (bool insert_phi_p)
2694 unsigned i = 0;
2695 bitmap_iterator bi;
2696 sbitmap_iterator sbi;
2698 /* If a name N from NEW_SSA_NAMES is also marked to be released,
2699 remove it from NEW_SSA_NAMES so that we don't try to visit its
2700 defining basic block (which most likely doesn't exist). Notice
2701 that we cannot do the same with names in OLD_SSA_NAMES because we
2702 want to replace existing instances. */
2703 if (names_to_release)
2704 EXECUTE_IF_SET_IN_BITMAP (names_to_release, 0, i, bi)
2705 bitmap_clear_bit (new_ssa_names, i);
2707 /* First process names in NEW_SSA_NAMES. Otherwise, uses of old
2708 names may be considered to be live-in on blocks that contain
2709 definitions for their replacements. */
2710 EXECUTE_IF_SET_IN_BITMAP (new_ssa_names, 0, i, sbi)
2711 prepare_def_site_for (ssa_name (i), insert_phi_p);
2713 /* If an old name is in NAMES_TO_RELEASE, we cannot remove it from
2714 OLD_SSA_NAMES, but we have to ignore its definition site. */
2715 EXECUTE_IF_SET_IN_BITMAP (old_ssa_names, 0, i, sbi)
2717 if (names_to_release == NULL || !bitmap_bit_p (names_to_release, i))
2718 prepare_def_site_for (ssa_name (i), insert_phi_p);
2719 prepare_use_sites_for (ssa_name (i), insert_phi_p);
2724 /* Dump all the names replaced by NAME to FILE. */
2726 void
2727 dump_names_replaced_by (FILE *file, tree name)
2729 unsigned i;
2730 bitmap old_set;
2731 bitmap_iterator bi;
2733 print_generic_expr (file, name, 0);
2734 fprintf (file, " -> { ");
2736 old_set = names_replaced_by (name);
2737 EXECUTE_IF_SET_IN_BITMAP (old_set, 0, i, bi)
2739 print_generic_expr (file, ssa_name (i), 0);
2740 fprintf (file, " ");
2743 fprintf (file, "}\n");
2747 /* Dump all the names replaced by NAME to stderr. */
2749 DEBUG_FUNCTION void
2750 debug_names_replaced_by (tree name)
2752 dump_names_replaced_by (stderr, name);
2756 /* Dump SSA update information to FILE. */
2758 void
2759 dump_update_ssa (FILE *file)
2761 unsigned i = 0;
2762 bitmap_iterator bi;
2764 if (!need_ssa_update_p (cfun))
2765 return;
2767 if (new_ssa_names && bitmap_first_set_bit (new_ssa_names) >= 0)
2769 sbitmap_iterator sbi;
2771 fprintf (file, "\nSSA replacement table\n");
2772 fprintf (file, "N_i -> { O_1 ... O_j } means that N_i replaces "
2773 "O_1, ..., O_j\n\n");
2775 EXECUTE_IF_SET_IN_BITMAP (new_ssa_names, 0, i, sbi)
2776 dump_names_replaced_by (file, ssa_name (i));
2779 if (symbols_to_rename_set && !bitmap_empty_p (symbols_to_rename_set))
2781 fprintf (file, "\nSymbols to be put in SSA form\n");
2782 dump_decl_set (file, symbols_to_rename_set);
2783 fprintf (file, "\n");
2786 if (names_to_release && !bitmap_empty_p (names_to_release))
2788 fprintf (file, "\nSSA names to release after updating the SSA web\n\n");
2789 EXECUTE_IF_SET_IN_BITMAP (names_to_release, 0, i, bi)
2791 print_generic_expr (file, ssa_name (i), 0);
2792 fprintf (file, " ");
2794 fprintf (file, "\n");
2799 /* Dump SSA update information to stderr. */
2801 DEBUG_FUNCTION void
2802 debug_update_ssa (void)
2804 dump_update_ssa (stderr);
2808 /* Initialize data structures used for incremental SSA updates. */
2810 static void
2811 init_update_ssa (struct function *fn)
2813 /* Reserve more space than the current number of names. The calls to
2814 add_new_name_mapping are typically done after creating new SSA
2815 names, so we'll need to reallocate these arrays. */
2816 old_ssa_names = sbitmap_alloc (num_ssa_names + NAME_SETS_GROWTH_FACTOR);
2817 bitmap_clear (old_ssa_names);
2819 new_ssa_names = sbitmap_alloc (num_ssa_names + NAME_SETS_GROWTH_FACTOR);
2820 bitmap_clear (new_ssa_names);
2822 bitmap_obstack_initialize (&update_ssa_obstack);
2824 names_to_release = NULL;
2825 update_ssa_initialized_fn = fn;
2829 /* Deallocate data structures used for incremental SSA updates. */
2831 void
2832 delete_update_ssa (void)
2834 unsigned i;
2835 bitmap_iterator bi;
2837 sbitmap_free (old_ssa_names);
2838 old_ssa_names = NULL;
2840 sbitmap_free (new_ssa_names);
2841 new_ssa_names = NULL;
2843 BITMAP_FREE (symbols_to_rename_set);
2844 symbols_to_rename_set = NULL;
2845 symbols_to_rename.release ();
2847 if (names_to_release)
2849 EXECUTE_IF_SET_IN_BITMAP (names_to_release, 0, i, bi)
2850 release_ssa_name (ssa_name (i));
2851 BITMAP_FREE (names_to_release);
2854 clear_ssa_name_info ();
2856 fini_ssa_renamer ();
2858 if (blocks_with_phis_to_rewrite)
2859 EXECUTE_IF_SET_IN_BITMAP (blocks_with_phis_to_rewrite, 0, i, bi)
2861 vec<gphi *> phis = phis_to_rewrite[i];
2862 phis.release ();
2863 phis_to_rewrite[i].create (0);
2866 BITMAP_FREE (blocks_with_phis_to_rewrite);
2867 BITMAP_FREE (blocks_to_update);
2869 update_ssa_initialized_fn = NULL;
2873 /* Create a new name for OLD_NAME in statement STMT and replace the
2874 operand pointed to by DEF_P with the newly created name. If DEF_P
2875 is NULL then STMT should be a GIMPLE assignment.
2876 Return the new name and register the replacement mapping <NEW, OLD> in
2877 update_ssa's tables. */
2879 tree
2880 create_new_def_for (tree old_name, gimple stmt, def_operand_p def)
2882 tree new_name;
2884 timevar_push (TV_TREE_SSA_INCREMENTAL);
2886 if (!update_ssa_initialized_fn)
2887 init_update_ssa (cfun);
2889 gcc_assert (update_ssa_initialized_fn == cfun);
2891 new_name = duplicate_ssa_name (old_name, stmt);
2892 if (def)
2893 SET_DEF (def, new_name);
2894 else
2895 gimple_assign_set_lhs (stmt, new_name);
2897 if (gimple_code (stmt) == GIMPLE_PHI)
2899 basic_block bb = gimple_bb (stmt);
2901 /* If needed, mark NEW_NAME as occurring in an abnormal PHI node. */
2902 SSA_NAME_OCCURS_IN_ABNORMAL_PHI (new_name) = bb_has_abnormal_pred (bb);
2905 add_new_name_mapping (new_name, old_name);
2907 /* For the benefit of passes that will be updating the SSA form on
2908 their own, set the current reaching definition of OLD_NAME to be
2909 NEW_NAME. */
2910 get_ssa_name_ann (old_name)->info.current_def = new_name;
2912 timevar_pop (TV_TREE_SSA_INCREMENTAL);
2914 return new_name;
2918 /* Mark virtual operands of FN for renaming by update_ssa. */
2920 void
2921 mark_virtual_operands_for_renaming (struct function *fn)
2923 fn->gimple_df->ssa_renaming_needed = 1;
2924 fn->gimple_df->rename_vops = 1;
2927 /* Replace all uses of NAME by underlying variable and mark it
2928 for renaming. This assumes the defining statement of NAME is
2929 going to be removed. */
2931 void
2932 mark_virtual_operand_for_renaming (tree name)
2934 tree name_var = SSA_NAME_VAR (name);
2935 bool used = false;
2936 imm_use_iterator iter;
2937 use_operand_p use_p;
2938 gimple stmt;
2940 gcc_assert (VAR_DECL_IS_VIRTUAL_OPERAND (name_var));
2941 FOR_EACH_IMM_USE_STMT (stmt, iter, name)
2943 FOR_EACH_IMM_USE_ON_STMT (use_p, iter)
2944 SET_USE (use_p, name_var);
2945 used = true;
2947 if (used)
2948 mark_virtual_operands_for_renaming (cfun);
2951 /* Replace all uses of the virtual PHI result by its underlying variable
2952 and mark it for renaming. This assumes the PHI node is going to be
2953 removed. */
2955 void
2956 mark_virtual_phi_result_for_renaming (gphi *phi)
2958 if (dump_file && (dump_flags & TDF_DETAILS))
2960 fprintf (dump_file, "Marking result for renaming : ");
2961 print_gimple_stmt (dump_file, phi, 0, TDF_SLIM);
2962 fprintf (dump_file, "\n");
2965 mark_virtual_operand_for_renaming (gimple_phi_result (phi));
2968 /* Return true if there is any work to be done by update_ssa
2969 for function FN. */
2971 bool
2972 need_ssa_update_p (struct function *fn)
2974 gcc_assert (fn != NULL);
2975 return (update_ssa_initialized_fn == fn
2976 || (fn->gimple_df && fn->gimple_df->ssa_renaming_needed));
2979 /* Return true if name N has been registered in the replacement table. */
2981 bool
2982 name_registered_for_update_p (tree n ATTRIBUTE_UNUSED)
2984 if (!update_ssa_initialized_fn)
2985 return false;
2987 gcc_assert (update_ssa_initialized_fn == cfun);
2989 return is_new_name (n) || is_old_name (n);
2993 /* Mark NAME to be released after update_ssa has finished. */
2995 void
2996 release_ssa_name_after_update_ssa (tree name)
2998 gcc_assert (cfun && update_ssa_initialized_fn == cfun);
3000 if (names_to_release == NULL)
3001 names_to_release = BITMAP_ALLOC (NULL);
3003 bitmap_set_bit (names_to_release, SSA_NAME_VERSION (name));
3007 /* Insert new PHI nodes to replace VAR. DFS contains dominance
3008 frontier information. BLOCKS is the set of blocks to be updated.
3010 This is slightly different than the regular PHI insertion
3011 algorithm. The value of UPDATE_FLAGS controls how PHI nodes for
3012 real names (i.e., GIMPLE registers) are inserted:
3014 - If UPDATE_FLAGS == TODO_update_ssa, we are only interested in PHI
3015 nodes inside the region affected by the block that defines VAR
3016 and the blocks that define all its replacements. All these
3017 definition blocks are stored in DEF_BLOCKS[VAR]->DEF_BLOCKS.
3019 First, we compute the entry point to the region (ENTRY). This is
3020 given by the nearest common dominator to all the definition
3021 blocks. When computing the iterated dominance frontier (IDF), any
3022 block not strictly dominated by ENTRY is ignored.
3024 We then call the standard PHI insertion algorithm with the pruned
3025 IDF.
3027 - If UPDATE_FLAGS == TODO_update_ssa_full_phi, the IDF for real
3028 names is not pruned. PHI nodes are inserted at every IDF block. */
3030 static void
3031 insert_updated_phi_nodes_for (tree var, bitmap_head *dfs, bitmap blocks,
3032 unsigned update_flags)
3034 basic_block entry;
3035 struct def_blocks_d *db;
3036 bitmap idf, pruned_idf;
3037 bitmap_iterator bi;
3038 unsigned i;
3040 if (TREE_CODE (var) == SSA_NAME)
3041 gcc_checking_assert (is_old_name (var));
3042 else
3043 gcc_checking_assert (marked_for_renaming (var));
3045 /* Get all the definition sites for VAR. */
3046 db = find_def_blocks_for (var);
3048 /* No need to do anything if there were no definitions to VAR. */
3049 if (db == NULL || bitmap_empty_p (db->def_blocks))
3050 return;
3052 /* Compute the initial iterated dominance frontier. */
3053 idf = compute_idf (db->def_blocks, dfs);
3054 pruned_idf = BITMAP_ALLOC (NULL);
3056 if (TREE_CODE (var) == SSA_NAME)
3058 if (update_flags == TODO_update_ssa)
3060 /* If doing regular SSA updates for GIMPLE registers, we are
3061 only interested in IDF blocks dominated by the nearest
3062 common dominator of all the definition blocks. */
3063 entry = nearest_common_dominator_for_set (CDI_DOMINATORS,
3064 db->def_blocks);
3065 if (entry != ENTRY_BLOCK_PTR_FOR_FN (cfun))
3066 EXECUTE_IF_SET_IN_BITMAP (idf, 0, i, bi)
3067 if (BASIC_BLOCK_FOR_FN (cfun, i) != entry
3068 && dominated_by_p (CDI_DOMINATORS,
3069 BASIC_BLOCK_FOR_FN (cfun, i), entry))
3070 bitmap_set_bit (pruned_idf, i);
3072 else
3074 /* Otherwise, do not prune the IDF for VAR. */
3075 gcc_checking_assert (update_flags == TODO_update_ssa_full_phi);
3076 bitmap_copy (pruned_idf, idf);
3079 else
3081 /* Otherwise, VAR is a symbol that needs to be put into SSA form
3082 for the first time, so we need to compute the full IDF for
3083 it. */
3084 bitmap_copy (pruned_idf, idf);
3087 if (!bitmap_empty_p (pruned_idf))
3089 /* Make sure that PRUNED_IDF blocks and all their feeding blocks
3090 are included in the region to be updated. The feeding blocks
3091 are important to guarantee that the PHI arguments are renamed
3092 properly. */
3094 /* FIXME, this is not needed if we are updating symbols. We are
3095 already starting at the ENTRY block anyway. */
3096 bitmap_ior_into (blocks, pruned_idf);
3097 EXECUTE_IF_SET_IN_BITMAP (pruned_idf, 0, i, bi)
3099 edge e;
3100 edge_iterator ei;
3101 basic_block bb = BASIC_BLOCK_FOR_FN (cfun, i);
3103 FOR_EACH_EDGE (e, ei, bb->preds)
3104 if (e->src->index >= 0)
3105 bitmap_set_bit (blocks, e->src->index);
3108 insert_phi_nodes_for (var, pruned_idf, true);
3111 BITMAP_FREE (pruned_idf);
3112 BITMAP_FREE (idf);
3115 /* Sort symbols_to_rename after their DECL_UID. */
3117 static int
3118 insert_updated_phi_nodes_compare_uids (const void *a, const void *b)
3120 const_tree syma = *(const const_tree *)a;
3121 const_tree symb = *(const const_tree *)b;
3122 if (DECL_UID (syma) == DECL_UID (symb))
3123 return 0;
3124 return DECL_UID (syma) < DECL_UID (symb) ? -1 : 1;
3127 /* Given a set of newly created SSA names (NEW_SSA_NAMES) and a set of
3128 existing SSA names (OLD_SSA_NAMES), update the SSA form so that:
3130 1- The names in OLD_SSA_NAMES dominated by the definitions of
3131 NEW_SSA_NAMES are all re-written to be reached by the
3132 appropriate definition from NEW_SSA_NAMES.
3134 2- If needed, new PHI nodes are added to the iterated dominance
3135 frontier of the blocks where each of NEW_SSA_NAMES are defined.
3137 The mapping between OLD_SSA_NAMES and NEW_SSA_NAMES is setup by
3138 calling create_new_def_for to create new defs for names that the
3139 caller wants to replace.
3141 The caller cretaes the new names to be inserted and the names that need
3142 to be replaced by calling create_new_def_for for each old definition
3143 to be replaced. Note that the function assumes that the
3144 new defining statement has already been inserted in the IL.
3146 For instance, given the following code:
3148 1 L0:
3149 2 x_1 = PHI (0, x_5)
3150 3 if (x_1 < 10)
3151 4 if (x_1 > 7)
3152 5 y_2 = 0
3153 6 else
3154 7 y_3 = x_1 + x_7
3155 8 endif
3156 9 x_5 = x_1 + 1
3157 10 goto L0;
3158 11 endif
3160 Suppose that we insert new names x_10 and x_11 (lines 4 and 8).
3162 1 L0:
3163 2 x_1 = PHI (0, x_5)
3164 3 if (x_1 < 10)
3165 4 x_10 = ...
3166 5 if (x_1 > 7)
3167 6 y_2 = 0
3168 7 else
3169 8 x_11 = ...
3170 9 y_3 = x_1 + x_7
3171 10 endif
3172 11 x_5 = x_1 + 1
3173 12 goto L0;
3174 13 endif
3176 We want to replace all the uses of x_1 with the new definitions of
3177 x_10 and x_11. Note that the only uses that should be replaced are
3178 those at lines 5, 9 and 11. Also, the use of x_7 at line 9 should
3179 *not* be replaced (this is why we cannot just mark symbol 'x' for
3180 renaming).
3182 Additionally, we may need to insert a PHI node at line 11 because
3183 that is a merge point for x_10 and x_11. So the use of x_1 at line
3184 11 will be replaced with the new PHI node. The insertion of PHI
3185 nodes is optional. They are not strictly necessary to preserve the
3186 SSA form, and depending on what the caller inserted, they may not
3187 even be useful for the optimizers. UPDATE_FLAGS controls various
3188 aspects of how update_ssa operates, see the documentation for
3189 TODO_update_ssa*. */
3191 void
3192 update_ssa (unsigned update_flags)
3194 basic_block bb, start_bb;
3195 bitmap_iterator bi;
3196 unsigned i = 0;
3197 bool insert_phi_p;
3198 sbitmap_iterator sbi;
3199 tree sym;
3201 /* Only one update flag should be set. */
3202 gcc_assert (update_flags == TODO_update_ssa
3203 || update_flags == TODO_update_ssa_no_phi
3204 || update_flags == TODO_update_ssa_full_phi
3205 || update_flags == TODO_update_ssa_only_virtuals);
3207 if (!need_ssa_update_p (cfun))
3208 return;
3210 #ifdef ENABLE_CHECKING
3211 timevar_push (TV_TREE_STMT_VERIFY);
3213 bool err = false;
3215 FOR_EACH_BB_FN (bb, cfun)
3217 gimple_stmt_iterator gsi;
3218 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
3220 gimple stmt = gsi_stmt (gsi);
3222 ssa_op_iter i;
3223 use_operand_p use_p;
3224 FOR_EACH_SSA_USE_OPERAND (use_p, stmt, i, SSA_OP_ALL_USES)
3226 tree use = USE_FROM_PTR (use_p);
3227 if (TREE_CODE (use) != SSA_NAME)
3228 continue;
3230 if (SSA_NAME_IN_FREE_LIST (use))
3232 error ("statement uses released SSA name:");
3233 debug_gimple_stmt (stmt);
3234 fprintf (stderr, "The use of ");
3235 print_generic_expr (stderr, use, 0);
3236 fprintf (stderr," should have been replaced\n");
3237 err = true;
3243 if (err)
3244 internal_error ("cannot update SSA form");
3246 timevar_pop (TV_TREE_STMT_VERIFY);
3247 #endif
3249 timevar_push (TV_TREE_SSA_INCREMENTAL);
3251 if (dump_file && (dump_flags & TDF_DETAILS))
3252 fprintf (dump_file, "\nUpdating SSA:\n");
3254 if (!update_ssa_initialized_fn)
3255 init_update_ssa (cfun);
3256 else if (update_flags == TODO_update_ssa_only_virtuals)
3258 /* If we only need to update virtuals, remove all the mappings for
3259 real names before proceeding. The caller is responsible for
3260 having dealt with the name mappings before calling update_ssa. */
3261 bitmap_clear (old_ssa_names);
3262 bitmap_clear (new_ssa_names);
3265 gcc_assert (update_ssa_initialized_fn == cfun);
3267 blocks_with_phis_to_rewrite = BITMAP_ALLOC (NULL);
3268 if (!phis_to_rewrite.exists ())
3269 phis_to_rewrite.create (last_basic_block_for_fn (cfun) + 1);
3270 blocks_to_update = BITMAP_ALLOC (NULL);
3272 /* Ensure that the dominance information is up-to-date. */
3273 calculate_dominance_info (CDI_DOMINATORS);
3275 insert_phi_p = (update_flags != TODO_update_ssa_no_phi);
3277 /* If there are names defined in the replacement table, prepare
3278 definition and use sites for all the names in NEW_SSA_NAMES and
3279 OLD_SSA_NAMES. */
3280 if (bitmap_first_set_bit (new_ssa_names) >= 0)
3282 prepare_names_to_update (insert_phi_p);
3284 /* If all the names in NEW_SSA_NAMES had been marked for
3285 removal, and there are no symbols to rename, then there's
3286 nothing else to do. */
3287 if (bitmap_first_set_bit (new_ssa_names) < 0
3288 && !cfun->gimple_df->ssa_renaming_needed)
3289 goto done;
3292 /* Next, determine the block at which to start the renaming process. */
3293 if (cfun->gimple_df->ssa_renaming_needed)
3295 /* If we rename bare symbols initialize the mapping to
3296 auxiliar info we need to keep track of. */
3297 var_infos = new hash_table<var_info_hasher> (47);
3299 /* If we have to rename some symbols from scratch, we need to
3300 start the process at the root of the CFG. FIXME, it should
3301 be possible to determine the nearest block that had a
3302 definition for each of the symbols that are marked for
3303 updating. For now this seems more work than it's worth. */
3304 start_bb = ENTRY_BLOCK_PTR_FOR_FN (cfun);
3306 /* Traverse the CFG looking for existing definitions and uses of
3307 symbols in SSA operands. Mark interesting blocks and
3308 statements and set local live-in information for the PHI
3309 placement heuristics. */
3310 prepare_block_for_update (start_bb, insert_phi_p);
3312 #ifdef ENABLE_CHECKING
3313 for (i = 1; i < num_ssa_names; ++i)
3315 tree name = ssa_name (i);
3316 if (!name
3317 || virtual_operand_p (name))
3318 continue;
3320 /* For all but virtual operands, which do not have SSA names
3321 with overlapping life ranges, ensure that symbols marked
3322 for renaming do not have existing SSA names associated with
3323 them as we do not re-write them out-of-SSA before going
3324 into SSA for the remaining symbol uses. */
3325 if (marked_for_renaming (SSA_NAME_VAR (name)))
3327 fprintf (stderr, "Existing SSA name for symbol marked for "
3328 "renaming: ");
3329 print_generic_expr (stderr, name, TDF_SLIM);
3330 fprintf (stderr, "\n");
3331 internal_error ("SSA corruption");
3334 #endif
3336 else
3338 /* Otherwise, the entry block to the region is the nearest
3339 common dominator for the blocks in BLOCKS. */
3340 start_bb = nearest_common_dominator_for_set (CDI_DOMINATORS,
3341 blocks_to_update);
3344 /* If requested, insert PHI nodes at the iterated dominance frontier
3345 of every block, creating new definitions for names in OLD_SSA_NAMES
3346 and for symbols found. */
3347 if (insert_phi_p)
3349 bitmap_head *dfs;
3351 /* If the caller requested PHI nodes to be added, compute
3352 dominance frontiers. */
3353 dfs = XNEWVEC (bitmap_head, last_basic_block_for_fn (cfun));
3354 FOR_EACH_BB_FN (bb, cfun)
3355 bitmap_initialize (&dfs[bb->index], &bitmap_default_obstack);
3356 compute_dominance_frontiers (dfs);
3358 if (bitmap_first_set_bit (old_ssa_names) >= 0)
3360 sbitmap_iterator sbi;
3362 /* insert_update_phi_nodes_for will call add_new_name_mapping
3363 when inserting new PHI nodes, so the set OLD_SSA_NAMES
3364 will grow while we are traversing it (but it will not
3365 gain any new members). Copy OLD_SSA_NAMES to a temporary
3366 for traversal. */
3367 sbitmap tmp = sbitmap_alloc (SBITMAP_SIZE (old_ssa_names));
3368 bitmap_copy (tmp, old_ssa_names);
3369 EXECUTE_IF_SET_IN_BITMAP (tmp, 0, i, sbi)
3370 insert_updated_phi_nodes_for (ssa_name (i), dfs, blocks_to_update,
3371 update_flags);
3372 sbitmap_free (tmp);
3375 symbols_to_rename.qsort (insert_updated_phi_nodes_compare_uids);
3376 FOR_EACH_VEC_ELT (symbols_to_rename, i, sym)
3377 insert_updated_phi_nodes_for (sym, dfs, blocks_to_update,
3378 update_flags);
3380 FOR_EACH_BB_FN (bb, cfun)
3381 bitmap_clear (&dfs[bb->index]);
3382 free (dfs);
3384 /* Insertion of PHI nodes may have added blocks to the region.
3385 We need to re-compute START_BB to include the newly added
3386 blocks. */
3387 if (start_bb != ENTRY_BLOCK_PTR_FOR_FN (cfun))
3388 start_bb = nearest_common_dominator_for_set (CDI_DOMINATORS,
3389 blocks_to_update);
3392 /* Reset the current definition for name and symbol before renaming
3393 the sub-graph. */
3394 EXECUTE_IF_SET_IN_BITMAP (old_ssa_names, 0, i, sbi)
3395 get_ssa_name_ann (ssa_name (i))->info.current_def = NULL_TREE;
3397 FOR_EACH_VEC_ELT (symbols_to_rename, i, sym)
3398 get_var_info (sym)->info.current_def = NULL_TREE;
3400 /* Now start the renaming process at START_BB. */
3401 interesting_blocks = sbitmap_alloc (last_basic_block_for_fn (cfun));
3402 bitmap_clear (interesting_blocks);
3403 EXECUTE_IF_SET_IN_BITMAP (blocks_to_update, 0, i, bi)
3404 bitmap_set_bit (interesting_blocks, i);
3406 rewrite_blocks (start_bb, REWRITE_UPDATE);
3408 sbitmap_free (interesting_blocks);
3410 /* Debugging dumps. */
3411 if (dump_file)
3413 int c;
3414 unsigned i;
3416 dump_update_ssa (dump_file);
3418 fprintf (dump_file, "Incremental SSA update started at block: %d\n",
3419 start_bb->index);
3421 c = 0;
3422 EXECUTE_IF_SET_IN_BITMAP (blocks_to_update, 0, i, bi)
3423 c++;
3424 fprintf (dump_file, "Number of blocks in CFG: %d\n",
3425 last_basic_block_for_fn (cfun));
3426 fprintf (dump_file, "Number of blocks to update: %d (%3.0f%%)\n",
3427 c, PERCENT (c, last_basic_block_for_fn (cfun)));
3429 if (dump_flags & TDF_DETAILS)
3431 fprintf (dump_file, "Affected blocks:");
3432 EXECUTE_IF_SET_IN_BITMAP (blocks_to_update, 0, i, bi)
3433 fprintf (dump_file, " %u", i);
3434 fprintf (dump_file, "\n");
3437 fprintf (dump_file, "\n\n");
3440 /* Free allocated memory. */
3441 done:
3442 delete_update_ssa ();
3444 timevar_pop (TV_TREE_SSA_INCREMENTAL);