OSDN Git Service

Daily bump.
[pf3gnuchains/gcc-fork.git] / gcc / tree-into-ssa.c
1 /* Rewrite a program in Normal form into SSA.
2    Copyright (C) 2001, 2002, 2003, 2004, 2005 Free Software Foundation, Inc.
3    Contributed by Diego Novillo <dnovillo@redhat.com>
4
5 This file is part of GCC.
6
7 GCC is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2, or (at your option)
10 any later version.
11
12 GCC is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING.  If not, write to
19 the Free Software Foundation, 59 Temple Place - Suite 330,
20 Boston, MA 02111-1307, USA.  */
21
22 #include "config.h"
23 #include "system.h"
24 #include "coretypes.h"
25 #include "tm.h"
26 #include "tree.h"
27 #include "flags.h"
28 #include "rtl.h"
29 #include "tm_p.h"
30 #include "langhooks.h"
31 #include "hard-reg-set.h"
32 #include "basic-block.h"
33 #include "output.h"
34 #include "errors.h"
35 #include "expr.h"
36 #include "function.h"
37 #include "diagnostic.h"
38 #include "bitmap.h"
39 #include "tree-flow.h"
40 #include "tree-gimple.h"
41 #include "tree-inline.h"
42 #include "varray.h"
43 #include "timevar.h"
44 #include "hashtab.h"
45 #include "tree-dump.h"
46 #include "tree-pass.h"
47 #include "cfgloop.h"
48 #include "domwalk.h"
49 #include "ggc.h"
50
51 /* This file builds the SSA form for a function as described in:
52    R. Cytron, J. Ferrante, B. Rosen, M. Wegman, and K. Zadeck. Efficiently
53    Computing Static Single Assignment Form and the Control Dependence
54    Graph. ACM Transactions on Programming Languages and Systems,
55    13(4):451-490, October 1991.  */
56
57 /* Structure to map a variable VAR to the set of blocks that contain
58    definitions for VAR.  */
59 struct def_blocks_d
60 {
61   /* The variable.  */
62   tree var;
63
64   /* Blocks that contain definitions of VAR.  Bit I will be set if the
65      Ith block contains a definition of VAR.  */
66   bitmap def_blocks;
67
68   /* Blocks that contain a PHI node for VAR.  */
69   bitmap phi_blocks;
70
71   /* Blocks where VAR is live-on-entry.  Similar semantics as
72      DEF_BLOCKS.  */
73   bitmap livein_blocks;
74 };
75
76
77 /* Each entry in DEF_BLOCKS contains an element of type STRUCT
78    DEF_BLOCKS_D, mapping a variable VAR to a bitmap describing all the
79    basic blocks where VAR is defined (assigned a new value).  It also
80    contains a bitmap of all the blocks where VAR is live-on-entry
81    (i.e., there is a use of VAR in block B without a preceding
82    definition in B).  The live-on-entry information is used when
83    computing PHI pruning heuristics.  */
84 static htab_t def_blocks;
85
86 /* Stack of trees used to restore the global currdefs to its original
87    state after completing rewriting of a block and its dominator children.
88
89    This vector is used in two contexts.  The first is rewriting of _DECL
90    nodes into SSA_NAMEs.  In that context its elements have the
91    following properties:
92
93      An SSA_NAME indicates that the current definition of the underlying
94      variable should be set to the given SSA_NAME.
95
96      A _DECL node indicates that the underlying variable has no current
97      definition.
98
99      A NULL node is used to mark the last node associated with the
100      current block. 
101
102    This vector is also used when rewriting an SSA_NAME which has multiple
103    definition sites into multiple SSA_NAMEs.  In that context entries come
104    in pairs.
105
106      The top entry is an SSA_NAME and the top-1 entry is the
107      current value for that SSA_NAME. 
108
109      A NULL node at the top entry is used to mark the last node associated
110      with the current block.  */
111 static VEC(tree_on_heap) *block_defs_stack;
112
113 /* Basic block vectors used in this file ought to be allocated in the heap.  */
114 DEF_VEC_MALLOC_P(int);
115
116 /* Global data to attach to the main dominator walk structure.  */
117 struct mark_def_sites_global_data
118 {
119   /* This sbitmap contains the variables which are set before they
120      are used in a basic block.  We keep it as a global variable
121      solely to avoid the overhead of allocating and deallocating
122      the bitmap.  */
123   bitmap kills;
124
125   /* Bitmap of names to rename.  */
126   sbitmap names_to_rename;
127 };
128
129
130 /* Information stored for ssa names.  */
131 struct ssa_name_info
132 {
133   /* This field indicates whether or not the variable may need PHI nodes.
134      See the enum's definition for more detailed information about the
135      states.  */
136   ENUM_BITFIELD (need_phi_state) need_phi_state : 2;
137
138   /* The actual definition of the ssa name.  */
139   tree current_def;
140 };
141
142
143 /* Use TREE_VISITED to keep track of which statements we want to
144    rename.  When renaming a subset of the variables, not all
145    statements will be processed.  This is decided in mark_def_sites.  */
146 #define REWRITE_THIS_STMT(T)    TREE_VISITED (T)
147
148
149 /* Get the information associated with NAME.  */
150
151 static inline struct ssa_name_info *
152 get_ssa_name_ann (tree name)
153 {
154   if (!SSA_NAME_AUX (name))
155     SSA_NAME_AUX (name) = xcalloc (1, sizeof (struct ssa_name_info));
156
157   return SSA_NAME_AUX (name);
158 }
159
160
161 /* Gets phi_state field for VAR.  */
162
163 static inline enum need_phi_state
164 get_phi_state (tree var)
165 {
166   if (TREE_CODE (var) == SSA_NAME)
167     return get_ssa_name_ann (var)->need_phi_state;
168   else
169     return var_ann (var)->need_phi_state;
170 }
171
172
173 /* Sets phi_state field for VAR to STATE.  */
174
175 static inline void
176 set_phi_state (tree var, enum need_phi_state state)
177 {
178   if (TREE_CODE (var) == SSA_NAME)
179     get_ssa_name_ann (var)->need_phi_state = state;
180   else
181     var_ann (var)->need_phi_state = state;
182 }
183
184
185 /* Return the current definition for VAR.  */
186
187 static inline tree
188 get_current_def (tree var)
189 {
190   if (TREE_CODE (var) == SSA_NAME)
191     return get_ssa_name_ann (var)->current_def;
192   else
193     return var_ann (var)->current_def;
194 }
195
196
197 /* Sets current definition of VAR to DEF.  */
198
199 static inline void
200 set_current_def (tree var, tree def)
201 {
202   if (TREE_CODE (var) == SSA_NAME)
203     get_ssa_name_ann (var)->current_def = def;
204   else
205     var_ann (var)->current_def = def;
206 }
207
208
209 /* Compute global livein information given the set of blockx where
210    an object is locally live at the start of the block (LIVEIN)
211    and the set of blocks where the object is defined (DEF_BLOCKS).
212
213    Note: This routine augments the existing local livein information
214    to include global livein (i.e., it modifies the underlying bitmap
215    for LIVEIN).  */
216
217 void
218 compute_global_livein (bitmap livein, bitmap def_blocks)
219 {
220   basic_block bb, *worklist, *tos;
221   unsigned i;
222   bitmap_iterator bi;
223
224   tos = worklist
225     = (basic_block *) xmalloc (sizeof (basic_block) * (n_basic_blocks + 1));
226
227   EXECUTE_IF_SET_IN_BITMAP (livein, 0, i, bi)
228     {
229       *tos++ = BASIC_BLOCK (i);
230     }
231
232   /* Iterate until the worklist is empty.  */
233   while (tos != worklist)
234     {
235       edge e;
236       edge_iterator ei;
237
238       /* Pull a block off the worklist.  */
239       bb = *--tos;
240
241       /* For each predecessor block.  */
242       FOR_EACH_EDGE (e, ei, bb->preds)
243         {
244           basic_block pred = e->src;
245           int pred_index = pred->index;
246
247           /* None of this is necessary for the entry block.  */
248           if (pred != ENTRY_BLOCK_PTR
249               && ! bitmap_bit_p (livein, pred_index)
250               && ! bitmap_bit_p (def_blocks, pred_index))
251             {
252               *tos++ = pred;
253               bitmap_set_bit (livein, pred_index);
254             }
255         }
256     }
257
258   free (worklist);
259 }
260
261
262 /* Return the set of blocks where variable VAR is defined and the blocks
263    where VAR is live on entry (livein).  If no entry is found in
264    DEF_BLOCKS, a new one is created and returned.  */
265
266 static inline struct def_blocks_d *
267 get_def_blocks_for (tree var)
268 {
269   struct def_blocks_d db, *db_p;
270   void **slot;
271
272   db.var = var;
273   slot = htab_find_slot (def_blocks, (void *) &db, INSERT);
274   if (*slot == NULL)
275     {
276       db_p = xmalloc (sizeof (*db_p));
277       db_p->var = var;
278       db_p->def_blocks = BITMAP_ALLOC (NULL);
279       db_p->phi_blocks = BITMAP_ALLOC (NULL);
280       db_p->livein_blocks = BITMAP_ALLOC (NULL);
281       *slot = (void *) db_p;
282     }
283   else
284     db_p = (struct def_blocks_d *) *slot;
285
286   return db_p;
287 }
288
289
290 /* Mark block BB as the definition site for variable VAR.  PHI_P is true if
291    VAR is defined by a PHI node.  IS_UPDATE is true if the caller is
292    updating an existing SSA form.  */
293
294 static void
295 set_def_block (tree var, basic_block bb, bool phi_p, bool is_update)
296 {
297   struct def_blocks_d *db_p;
298   enum need_phi_state state;
299
300   if (!is_update && TREE_CODE (var) == SSA_NAME)
301     var = SSA_NAME_VAR (var);
302
303   state = get_phi_state (var);
304   db_p = get_def_blocks_for (var);
305
306   /* Set the bit corresponding to the block where VAR is defined.  */
307   bitmap_set_bit (db_p->def_blocks, bb->index);
308   if (phi_p)
309     bitmap_set_bit (db_p->phi_blocks, bb->index);
310
311   /* Keep track of whether or not we may need to insert PHI nodes.
312
313      If we are in the UNKNOWN state, then this is the first definition
314      of VAR.  Additionally, we have not seen any uses of VAR yet, so
315      we do not need a PHI node for this variable at this time (i.e.,
316      transition to NEED_PHI_STATE_NO).
317
318      If we are in any other state, then we either have multiple definitions
319      of this variable occurring in different blocks or we saw a use of the
320      variable which was not dominated by the block containing the
321      definition(s).  In this case we may need a PHI node, so enter
322      state NEED_PHI_STATE_MAYBE.  */
323   if (state == NEED_PHI_STATE_UNKNOWN)
324     set_phi_state (var, NEED_PHI_STATE_NO);
325   else
326     set_phi_state (var, NEED_PHI_STATE_MAYBE);
327 }
328
329
330 /* Mark block BB as having VAR live at the entry to BB.  */
331
332 static void
333 set_livein_block (tree var, basic_block bb)
334 {
335   struct def_blocks_d *db_p;
336   enum need_phi_state state = get_phi_state (var);
337
338   db_p = get_def_blocks_for (var);
339
340   /* Set the bit corresponding to the block where VAR is live in.  */
341   bitmap_set_bit (db_p->livein_blocks, bb->index);
342
343   /* Keep track of whether or not we may need to insert PHI nodes.
344
345      If we reach here in NEED_PHI_STATE_NO, see if this use is dominated
346      by the single block containing the definition(s) of this variable.  If
347      it is, then we remain in NEED_PHI_STATE_NO, otherwise we transition to
348      NEED_PHI_STATE_MAYBE.  */
349   if (state == NEED_PHI_STATE_NO)
350     {
351       int def_block_index = bitmap_first_set_bit (db_p->def_blocks);
352
353       if (def_block_index == -1
354           || ! dominated_by_p (CDI_DOMINATORS, bb,
355                                BASIC_BLOCK (def_block_index)))
356         set_phi_state (var, NEED_PHI_STATE_MAYBE);
357     }
358   else
359     set_phi_state (var, NEED_PHI_STATE_MAYBE);
360 }
361
362
363 /* If the use operand pointed to by OP_P needs to be renamed, then strip away 
364    any SSA_NAME wrapping the operand, set *UID_P to the underlying variable's 
365    uid, and return true.  Otherwise return false.  If the operand was an 
366    SSA_NAME, change it to the stripped name.  */
367
368 static bool
369 prepare_use_operand_for_rename (use_operand_p op_p, size_t *uid_p)
370 {
371   tree use = USE_FROM_PTR (op_p);
372   tree var = (TREE_CODE (use) != SSA_NAME) ? use : SSA_NAME_VAR (use);
373   *uid_p = var_ann (var)->uid;
374
375   /* Ignore variables that don't need to be renamed.  */
376   if (vars_to_rename && !bitmap_bit_p (vars_to_rename, *uid_p))
377     return false;
378
379   /* The variable needs to be renamed.  If this is a use which already
380      has an SSA_NAME, then strip it off.
381
382      By not throwing away SSA_NAMEs on assignments, we avoid a lot of 
383      useless churn of SSA_NAMEs without having to overly complicate the
384      renamer.  */
385   if (TREE_CODE (use) == SSA_NAME)
386     SET_USE (op_p, var);
387
388   return true;
389 }
390
391
392 /* If the def variable DEF needs to be renamed, then strip away any SSA_NAME 
393    wrapping the operand, set *UID_P to the underlying variable's uid and return
394    true.  Otherwise return false.  */
395
396 static bool
397 prepare_def_operand_for_rename (tree def, size_t *uid_p)
398 {
399   tree var = (TREE_CODE (def) != SSA_NAME) ? def : SSA_NAME_VAR (def);
400   *uid_p = var_ann (var)->uid;
401
402   /* Ignore variables that don't need to be renamed.  */
403   if (vars_to_rename && !bitmap_bit_p (vars_to_rename, *uid_p))
404     return false;
405
406   return true;
407 }
408
409
410 /* Call back for walk_dominator_tree used to collect definition sites
411    for every variable in the function.  For every statement S in block
412    BB:
413
414    1- Variables defined by S in DEF_OPS(S) are marked in the bitmap
415       WALK_DATA->GLOBAL_DATA->KILLS.
416
417    2- If S uses a variable VAR and there is no preceding kill of VAR,
418       then it is marked in marked in the LIVEIN_BLOCKS bitmap
419       associated with VAR.
420
421    This information is used to determine which variables are live
422    across block boundaries to reduce the number of PHI nodes
423    we create.  */
424
425 static void
426 mark_def_sites (struct dom_walk_data *walk_data,
427                 basic_block bb,
428                 block_stmt_iterator bsi)
429 {
430   struct mark_def_sites_global_data *gd = walk_data->global_data;
431   bitmap kills = gd->kills;
432   size_t uid;
433   tree stmt, def;
434   use_operand_p use_p;
435   def_operand_p def_p;
436   ssa_op_iter iter;
437
438   /* Mark all the blocks that have definitions for each variable in the
439      VARS_TO_RENAME bitmap.  */
440   stmt = bsi_stmt (bsi);
441   update_stmt_if_modified (stmt);
442
443   REWRITE_THIS_STMT (stmt) = 0;
444
445   /* If a variable is used before being set, then the variable is live
446      across a block boundary, so mark it live-on-entry to BB.  */
447
448   FOR_EACH_SSA_USE_OPERAND (use_p, stmt, iter,
449                             SSA_OP_USE | SSA_OP_VUSE | SSA_OP_VMUSTDEFKILL)
450     {
451       if (prepare_use_operand_for_rename (use_p, &uid))
452         {
453           REWRITE_THIS_STMT (stmt) = 1;
454           if (!bitmap_bit_p (kills, uid))
455             set_livein_block (USE_FROM_PTR (use_p), bb);
456         }
457     }
458   
459   /* Note that virtual definitions are irrelevant for computing KILLS
460      because a V_MAY_DEF does not constitute a killing definition of the
461      variable.  However, the operand of a virtual definitions is a use
462      of the variable, so it may cause the variable to be considered
463      live-on-entry.  */
464   FOR_EACH_SSA_MAYDEF_OPERAND (def_p, use_p, stmt, iter)
465     {
466       if (prepare_use_operand_for_rename (use_p, &uid))
467         {
468           /* If we do not already have an SSA_NAME for our destination,
469              then set the destination to the source.  */
470           if (TREE_CODE (DEF_FROM_PTR (def_p)) != SSA_NAME)
471             SET_DEF (def_p, USE_FROM_PTR (use_p));
472             
473           set_livein_block (USE_FROM_PTR (use_p), bb);
474           set_def_block (DEF_FROM_PTR (def_p), bb, false, false);
475           REWRITE_THIS_STMT (stmt) = 1;
476         }
477     }
478
479   /* Now process the defs and must-defs made by this statement.  */
480   FOR_EACH_SSA_TREE_OPERAND (def, stmt, iter, SSA_OP_DEF | SSA_OP_VMUSTDEF)
481     {
482       if (prepare_def_operand_for_rename (def, &uid))
483         {
484           set_def_block (def, bb, false, false);
485           bitmap_set_bit (kills, uid);
486           REWRITE_THIS_STMT (stmt) = 1;
487         }
488     }
489 }
490
491
492 /* Given a set of blocks with variable definitions (DEF_BLOCKS),
493    return a bitmap with all the blocks in the iterated dominance
494    frontier of the blocks in DEF_BLOCKS.  DFS contains dominance
495    frontier information as returned by compute_dominance_frontiers.
496    
497    The resulting set of blocks are the potential sites where PHI nodes
498    are needed.  The caller is responsible from freeing the memory
499    allocated for the return value.  */
500
501 static bitmap
502 find_idf (bitmap def_blocks, bitmap *dfs)
503 {
504   bitmap_iterator bi;
505   unsigned bb_index;
506   VEC(int) *work_stack;
507   bitmap phi_insertion_points;
508
509   work_stack = VEC_alloc (int, n_basic_blocks);
510   phi_insertion_points = BITMAP_ALLOC (NULL);
511
512   /* Seed the work list with all the blocks in DEF_BLOCKS.  */
513   EXECUTE_IF_SET_IN_BITMAP (def_blocks, 0, bb_index, bi)
514     /* We use VEC_quick_push here for speed.  This is safe because we
515        know that the number of definition blocks is no greater than
516        the number of basic blocks, which is the initial capacity of
517        WORK_STACK.  */
518     VEC_quick_push (int, work_stack, bb_index);
519
520   /* Pop a block off the worklist, add every block that appears in
521      the original block's DF that we have not already processed to
522      the worklist.  Iterate until the worklist is empty.   Blocks
523      which are added to the worklist are potential sites for
524      PHI nodes.  */
525   while (VEC_length (int, work_stack) > 0)
526     {
527       bb_index = VEC_pop (int, work_stack);
528       
529       EXECUTE_IF_AND_COMPL_IN_BITMAP (dfs[bb_index], phi_insertion_points,
530                                       0, bb_index, bi)
531         {
532           /* Use a safe push because if there is a definition of VAR
533              in every basic block, then WORK_STACK may eventually have
534              more than N_BASIC_BLOCK entries.  */
535           VEC_safe_push (int, work_stack, bb_index);
536           bitmap_set_bit (phi_insertion_points, bb_index);
537         }
538     }
539
540   VEC_free (int, work_stack);
541
542   return phi_insertion_points;
543 }
544
545
546 /* Return the set of blocks where variable VAR is defined and the blocks
547    where VAR is live on entry (livein).  Return NULL, if no entry is
548    found in DEF_BLOCKS.  */
549
550 static inline struct def_blocks_d *
551 find_def_blocks_for (tree var)
552 {
553   struct def_blocks_d dm;
554   dm.var = var;
555   return (struct def_blocks_d *) htab_find (def_blocks, &dm);
556 }
557
558
559 /* Insert PHI nodes for variable VAR using the iterated dominance
560    frontier given in PHI_INSERTION_POINTS.  */
561
562 static void
563 insert_phi_nodes_for (tree var, bitmap phi_insertion_points)
564 {
565   unsigned bb_index;
566   edge e;
567   tree phi;
568   basic_block bb;
569   bitmap_iterator bi;
570   struct def_blocks_d *def_map;
571
572   def_map = find_def_blocks_for (var);
573
574   /* Remove the blocks where we already have PHI nodes for VAR.  */
575   bitmap_and_compl_into (phi_insertion_points, def_map->phi_blocks);
576
577   /* Now compute global livein for this variable.  Note this modifies
578      def_map->livein_blocks.  */
579   compute_global_livein (def_map->livein_blocks, def_map->def_blocks);
580
581   /* And insert the PHI nodes.  */
582   EXECUTE_IF_AND_IN_BITMAP (phi_insertion_points, def_map->livein_blocks,
583                             0, bb_index, bi)
584     {
585       bb = BASIC_BLOCK (bb_index);
586       phi = create_phi_node (var, bb);
587
588       /* If we are rewriting SSA names, add also the PHI arguments.  */
589       if (TREE_CODE (var) == SSA_NAME)
590         {
591           edge_iterator ei;
592           FOR_EACH_EDGE (e, ei, bb->preds)
593             add_phi_arg (phi, var, e);
594         }
595     }
596 }
597
598
599 /* Helper for insert_phi_nodes.  If VAR needs PHI nodes, insert them
600    at the dominance frontier (DFS) of blocks defining VAR.  */
601
602 static inline void
603 insert_phi_nodes_1 (tree var, bitmap *dfs)
604 {
605   struct def_blocks_d *def_map;
606   bitmap idf;
607
608   def_map = find_def_blocks_for (var);
609   if (def_map == NULL)
610     return;
611
612   idf = find_idf (def_map->def_blocks, dfs);
613
614   if (get_phi_state (var) != NEED_PHI_STATE_NO)
615     insert_phi_nodes_for (var, idf);
616
617   BITMAP_FREE (idf);
618 }
619
620
621 /* Insert PHI nodes at the dominance frontier of blocks with variable
622    definitions.  DFS contains the dominance frontier information for
623    the flowgraph.  PHI nodes will only be inserted at the dominance
624    frontier of definition blocks for variables whose NEED_PHI_STATE
625    annotation is marked as ``maybe'' or ``unknown'' (computed by
626    mark_def_sites).  If NAMES_TO_RENAME is not NULL, do the same but
627    for ssa name rewriting.  */
628
629 static void
630 insert_phi_nodes (bitmap *dfs, bitmap names_to_rename)
631 {
632   unsigned i;
633   bitmap_iterator bi;
634
635   timevar_push (TV_TREE_INSERT_PHI_NODES);
636
637   /* Iterate over all variables in VARS_TO_RENAME.  For each variable, add
638      to the work list all the blocks that have a definition for the
639      variable.  PHI nodes will be added to the dominance frontier blocks of
640      each definition block.  */
641   if (names_to_rename)
642     {
643       EXECUTE_IF_SET_IN_BITMAP (names_to_rename, 0, i, bi)
644         if (ssa_name (i))
645           insert_phi_nodes_1 (ssa_name (i), dfs);
646     }
647   else if (vars_to_rename)
648     {
649       EXECUTE_IF_SET_IN_BITMAP (vars_to_rename, 0, i, bi)
650         insert_phi_nodes_1 (referenced_var (i), dfs);
651     }
652   else
653     {
654       for (i = 0; i < num_referenced_vars; i++)
655         insert_phi_nodes_1 (referenced_var (i), dfs);
656     }
657
658   timevar_pop (TV_TREE_INSERT_PHI_NODES);
659 }
660
661
662 /* Register DEF (an SSA_NAME) to be a new definition for its underlying
663    variable (SSA_NAME_VAR (DEF)) and push VAR's current reaching definition
664    into the stack pointed by BLOCK_DEFS_P.  */
665
666 void
667 register_new_def (tree def, VEC (tree_on_heap) **block_defs_p)
668 {
669   tree var = SSA_NAME_VAR (def);
670   tree currdef;
671    
672   /* If this variable is set in a single basic block and all uses are
673      dominated by the set(s) in that single basic block, then there is
674      no reason to record anything for this variable in the block local
675      definition stacks.  Doing so just wastes time and memory.
676
677      This is the same test to prune the set of variables which may
678      need PHI nodes.  So we just use that information since it's already
679      computed and available for us to use.  */
680   if (get_phi_state (var) == NEED_PHI_STATE_NO)
681     {
682       set_current_def (var, def);
683       return;
684     }
685
686   currdef = get_current_def (var);
687
688   /* Push the current reaching definition into *BLOCK_DEFS_P.  This stack is
689      later used by the dominator tree callbacks to restore the reaching
690      definitions for all the variables defined in the block after a recursive
691      visit to all its immediately dominated blocks.  If there is no current
692      reaching definition, then just record the underlying _DECL node.  */
693   VEC_safe_push (tree_on_heap, *block_defs_p, currdef ? currdef : var);
694
695   /* Set the current reaching definition for VAR to be DEF.  */
696   set_current_def (var, def);
697 }
698
699
700 /* Perform a depth-first traversal of the dominator tree looking for
701    variables to rename.  BB is the block where to start searching.
702    Renaming is a five step process:
703
704    1- Every definition made by PHI nodes at the start of the blocks is
705       registered as the current definition for the corresponding variable.
706
707    2- Every statement in BB is rewritten.  USE and VUSE operands are
708       rewritten with their corresponding reaching definition.  DEF and
709       VDEF targets are registered as new definitions.
710       
711    3- All the PHI nodes in successor blocks of BB are visited.  The
712       argument corresponding to BB is replaced with its current reaching
713       definition.
714
715    4- Recursively rewrite every dominator child block of BB.
716
717    5- Restore (in reverse order) the current reaching definition for every
718       new definition introduced in this block.  This is done so that when
719       we return from the recursive call, all the current reaching
720       definitions are restored to the names that were valid in the
721       dominator parent of BB.  */
722
723 /* SSA Rewriting Step 1.  Initialization, create a block local stack
724    of reaching definitions for new SSA names produced in this block
725    (BLOCK_DEFS).  Register new definitions for every PHI node in the
726    block.  */
727
728 static void
729 rewrite_initialize_block (struct dom_walk_data *walk_data ATTRIBUTE_UNUSED,
730                           basic_block bb)
731 {
732   tree phi;
733
734   if (dump_file && (dump_flags & TDF_DETAILS))
735     fprintf (dump_file, "\n\nRenaming block #%d\n\n", bb->index);
736
737   /* Mark the unwind point for this block.  */
738   VEC_safe_push (tree_on_heap, block_defs_stack, NULL_TREE);
739
740   /* Step 1.  Register new definitions for every PHI node in the block.
741      Conceptually, all the PHI nodes are executed in parallel and each PHI
742      node introduces a new version for the associated variable.  */
743   for (phi = phi_nodes (bb); phi; phi = PHI_CHAIN (phi))
744     {
745       tree result = PHI_RESULT (phi);
746       register_new_def (result, &block_defs_stack);
747     }
748 }
749
750
751 /* Return the current definition for variable VAR.  If none is found,
752    create a new SSA name to act as the zeroth definition for VAR.  If VAR
753    is call clobbered and there exists a more recent definition of
754    GLOBAL_VAR, return the definition for GLOBAL_VAR.  This means that VAR
755    has been clobbered by a function call since its last assignment.  */
756
757 static tree
758 get_reaching_def (tree var)
759 {
760   tree default_d, currdef_var, avar;
761   
762   /* Lookup the current reaching definition for VAR.  */
763   default_d = NULL_TREE;
764   currdef_var = get_current_def (var);
765
766   /* If there is no reaching definition for VAR, create and register a
767      default definition for it (if needed).  */
768   if (currdef_var == NULL_TREE)
769     {
770       if (TREE_CODE (var) == SSA_NAME)
771         avar = SSA_NAME_VAR (var);
772       else
773         avar = var;
774
775       default_d = default_def (avar);
776       if (default_d == NULL_TREE)
777         {
778           default_d = make_ssa_name (avar, build_empty_stmt ());
779           set_default_def (avar, default_d);
780         }
781       set_current_def (var, default_d);
782     }
783
784   /* Return the current reaching definition for VAR, or the default
785      definition, if we had to create one.  */
786   return (currdef_var) ? currdef_var : default_d;
787 }
788
789
790 /* Replace the operand pointed by OP_P with its immediate reaching
791    definition.  */
792
793 static inline void
794 rewrite_operand (use_operand_p op_p)
795 {
796   tree var = USE_FROM_PTR (op_p);
797   if (TREE_CODE (var) != SSA_NAME)
798     SET_USE (op_p, get_reaching_def (var));
799   else
800     {
801 #if defined ENABLE_CHECKING
802       /* If we get to this point, VAR is an SSA_NAME.  If VAR's symbol
803          was marked for renaming, make sure that its reaching
804          definition is VAR itself.  Otherwise, something has gone
805          wrong.  */
806       tree sym = SSA_NAME_VAR (var);
807       if (bitmap_bit_p (vars_to_rename, var_ann (sym)->uid))
808         gcc_assert (var == get_reaching_def (SSA_NAME_VAR (var)));
809 #endif
810     }
811 }
812
813
814 /* SSA Rewriting Step 2.  Rewrite every variable used in each statement in
815    the block with its immediate reaching definitions.  Update the current
816    definition of a variable when a new real or virtual definition is found.  */
817
818 static void
819 rewrite_stmt (struct dom_walk_data *walk_data ATTRIBUTE_UNUSED,
820               basic_block bb ATTRIBUTE_UNUSED,
821               block_stmt_iterator si)
822 {
823   tree stmt;
824   use_operand_p use_p;
825   def_operand_p def_p;
826   ssa_op_iter iter;
827
828   stmt = bsi_stmt (si);
829
830   /* If mark_def_sites decided that we don't need to rewrite this
831      statement, ignore it.  */
832   if (!REWRITE_THIS_STMT (stmt))
833     return;
834
835   if (dump_file && (dump_flags & TDF_DETAILS))
836     {
837       fprintf (dump_file, "Renaming statement ");
838       print_generic_stmt (dump_file, stmt, TDF_SLIM);
839       fprintf (dump_file, "\n");
840     }
841
842   get_stmt_operands (stmt);
843
844   /* Step 1.  Rewrite USES and VUSES in the statement.  */
845   FOR_EACH_SSA_USE_OPERAND (use_p, stmt, iter, SSA_OP_ALL_USES | SSA_OP_ALL_KILLS)
846     rewrite_operand (use_p);
847
848   /* Step 2.  Register the statement's DEF and VDEF operands.  */
849   FOR_EACH_SSA_DEF_OPERAND (def_p, stmt, iter, SSA_OP_ALL_DEFS)
850     {
851       if (TREE_CODE (DEF_FROM_PTR (def_p)) != SSA_NAME)
852         SET_DEF (def_p, make_ssa_name (DEF_FROM_PTR (def_p), stmt));
853
854       /* FIXME: We shouldn't be registering new defs if the variable
855          doesn't need to be renamed.  */
856       register_new_def (DEF_FROM_PTR (def_p), &block_defs_stack);
857     }
858 }
859
860
861 /* SSA Rewriting Step 3.  Visit all the successor blocks of BB looking for
862    PHI nodes.  For every PHI node found, add a new argument containing the
863    current reaching definition for the variable and the edge through which
864    that definition is reaching the PHI node.  */
865
866 static void
867 rewrite_add_phi_arguments (struct dom_walk_data *walk_data ATTRIBUTE_UNUSED,
868                            basic_block bb)
869 {
870   edge e;
871   edge_iterator ei;
872
873   FOR_EACH_EDGE (e, ei, bb->succs)
874     {
875       tree phi;
876
877       for (phi = phi_nodes (e->dest); phi; phi = PHI_CHAIN (phi))
878         {
879           tree currdef;
880
881           /* If this PHI node has already been rewritten, then there is
882              nothing to do for this PHI or any following PHIs since we
883              always add new PHI nodes at the start of the PHI chain.  */
884           if (PHI_REWRITTEN (phi))
885             break;
886
887           currdef = get_reaching_def (SSA_NAME_VAR (PHI_RESULT (phi)));
888           add_phi_arg (phi, currdef, e);
889         }
890     }
891 }
892
893
894 /*  Rewrite existing virtual PHI arguments so that they have the correct
895     reaching definitions.  BB is the basic block whose successors contain the
896     PHI nodes we want to add arguments for.  */
897
898 static void
899 rewrite_virtual_phi_arguments (struct dom_walk_data *walk_data ATTRIBUTE_UNUSED,
900                                basic_block bb)
901 {
902   edge e;
903   use_operand_p op;
904   edge_iterator ei;
905
906   FOR_EACH_EDGE (e, ei, bb->succs)
907     {
908       tree phi;
909
910       if (e->dest == EXIT_BLOCK_PTR)
911         continue;
912
913       for (phi = phi_nodes (e->dest); phi; phi = PHI_CHAIN (phi))
914         {
915           tree result = PHI_RESULT (phi);
916           op = PHI_ARG_DEF_PTR_FROM_EDGE (phi, e);
917           
918           if (is_gimple_reg (result) 
919               || !bitmap_bit_p (vars_to_rename, 
920                                 var_ann (SSA_NAME_VAR (result))->uid))
921             continue;
922
923           SET_USE (op, get_reaching_def (SSA_NAME_VAR (result)));
924           if (e->flags & EDGE_ABNORMAL)
925             SSA_NAME_OCCURS_IN_ABNORMAL_PHI (USE_FROM_PTR (op)) = 1;
926         }
927     }
928 }
929
930
931 /* Called after visiting basic block BB.  Restore CURRDEFS to its
932    original value.  */
933
934 static void
935 rewrite_finalize_block (struct dom_walk_data *walk_data ATTRIBUTE_UNUSED,
936                         basic_block bb ATTRIBUTE_UNUSED)
937 {
938   /* Restore CURRDEFS to its original state.  */
939   while (VEC_length (tree_on_heap, block_defs_stack) > 0)
940     {
941       tree tmp = VEC_pop (tree_on_heap, block_defs_stack);
942       tree saved_def, var;
943
944       if (tmp == NULL_TREE)
945         break;
946
947       /* If we recorded an SSA_NAME, then make the SSA_NAME the current
948          definition of its underlying variable.  If we recorded anything
949          else, it must have been an _DECL node and its current reaching
950          definition must have been NULL.  */
951       if (TREE_CODE (tmp) == SSA_NAME)
952         {
953           saved_def = tmp;
954           var = SSA_NAME_VAR (saved_def);
955         }
956       else
957         {
958           saved_def = NULL;
959           var = tmp;
960         }
961                                                                                 
962       set_current_def (var, saved_def);
963     }
964 }
965
966
967 /* Dump SSA information to FILE.  */
968
969 void
970 dump_tree_ssa (FILE *file)
971 {
972   basic_block bb;
973   const char *funcname
974     = lang_hooks.decl_printable_name (current_function_decl, 2);
975
976   fprintf (file, "SSA information for %s\n\n", funcname);
977
978   FOR_EACH_BB (bb)
979     {
980       dump_bb (bb, file, 0);
981       fputs ("    ", file);
982       print_generic_stmt (file, phi_nodes (bb), dump_flags);
983       fputs ("\n\n", file);
984     }
985 }
986
987
988 /* Dump SSA information to stderr.  */
989
990 void
991 debug_tree_ssa (void)
992 {
993   dump_tree_ssa (stderr);
994 }
995
996
997 /* Dump statistics for the hash table HTAB.  */
998
999 static void
1000 htab_statistics (FILE *file, htab_t htab)
1001 {
1002   fprintf (file, "size %ld, %ld elements, %f collision/search ratio\n",
1003            (long) htab_size (htab),
1004            (long) htab_elements (htab),
1005            htab_collisions (htab));
1006 }
1007
1008
1009 /* Dump SSA statistics on FILE.  */
1010
1011 void
1012 dump_tree_ssa_stats (FILE *file)
1013 {
1014   fprintf (file, "\nHash table statistics:\n");
1015
1016   fprintf (file, "    def_blocks: ");
1017   htab_statistics (file, def_blocks);
1018
1019   fprintf (file, "\n");
1020 }
1021
1022
1023 /* Dump SSA statistics on stderr.  */
1024
1025 void
1026 debug_tree_ssa_stats (void)
1027 {
1028   dump_tree_ssa_stats (stderr);
1029 }
1030
1031
1032 /* Hashing and equality functions for DEF_BLOCKS.  */
1033
1034 static hashval_t
1035 def_blocks_hash (const void *p)
1036 {
1037   return htab_hash_pointer
1038         ((const void *)((const struct def_blocks_d *)p)->var);
1039 }
1040
1041 static int
1042 def_blocks_eq (const void *p1, const void *p2)
1043 {
1044   return ((const struct def_blocks_d *)p1)->var
1045          == ((const struct def_blocks_d *)p2)->var;
1046 }
1047
1048
1049 /* Free memory allocated by one entry in DEF_BLOCKS.  */
1050
1051 static void
1052 def_blocks_free (void *p)
1053 {
1054   struct def_blocks_d *entry = p;
1055   BITMAP_FREE (entry->def_blocks);
1056   BITMAP_FREE (entry->phi_blocks);
1057   BITMAP_FREE (entry->livein_blocks);
1058   free (entry);
1059 }
1060
1061
1062 /* Callback for htab_traverse to dump the DEF_BLOCKS hash table.  */
1063
1064 static int
1065 debug_def_blocks_r (void **slot, void *data ATTRIBUTE_UNUSED)
1066 {
1067   struct def_blocks_d *db_p = (struct def_blocks_d *) *slot;
1068   
1069   fprintf (stderr, "VAR: ");
1070   print_generic_expr (stderr, db_p->var, dump_flags);
1071   bitmap_print (stderr, db_p->def_blocks, ", DEF_BLOCKS: { ", "}");
1072   bitmap_print (stderr, db_p->livein_blocks, ", LIVEIN_BLOCKS: { ", "}\n");
1073
1074   return 1;
1075 }
1076
1077
1078 /* Dump the DEF_BLOCKS hash table on stderr.  */
1079
1080 void
1081 debug_def_blocks (void)
1082 {
1083   htab_traverse (def_blocks, debug_def_blocks_r, NULL);
1084 }
1085
1086
1087 /* If a variable V in VARS_TO_RENAME is a pointer, the renaming
1088    process will cause us to lose the name memory tags that may have
1089    been associated with the various SSA_NAMEs of V.  This means that
1090    the variables aliased to those name tags also need to be renamed
1091    again.
1092
1093    FIXME 1- We should either have a better scheme for renaming
1094             pointers that doesn't lose name tags or re-run alias
1095             analysis to recover points-to information.
1096
1097          2- Currently we just invalidate *all* the name tags.  This
1098             should be more selective.  */
1099
1100 static void
1101 invalidate_name_tags (bitmap vars_to_rename)
1102 {
1103   unsigned i;
1104   bool rename_name_tags_p;
1105   bitmap_iterator bi;
1106
1107   rename_name_tags_p = false;
1108   EXECUTE_IF_SET_IN_BITMAP (vars_to_rename, 0, i, bi)
1109     {
1110       if (POINTER_TYPE_P (TREE_TYPE (referenced_var (i))))
1111         {
1112           rename_name_tags_p = true;
1113           break;
1114         }
1115     }
1116
1117   if (rename_name_tags_p)
1118     for (i = 0; i < num_referenced_vars; i++)
1119       {
1120         var_ann_t ann = var_ann (referenced_var (i));
1121
1122         if (ann->mem_tag_kind == NAME_TAG)
1123           {
1124             size_t j;
1125             varray_type may_aliases = ann->may_aliases;
1126
1127             bitmap_set_bit (vars_to_rename, ann->uid);
1128             if (ann->may_aliases)
1129               for (j = 0; j < VARRAY_ACTIVE_SIZE (may_aliases); j++)
1130                 {
1131                   tree var = VARRAY_TREE (may_aliases, j);
1132                   bitmap_set_bit (vars_to_rename, var_ann (var)->uid);
1133                 }
1134           }
1135       }
1136 }
1137
1138
1139 /* Rewrite the actual blocks, statements, and PHI arguments, to be in SSA
1140    form.  FIX_VIRTUAL_PHIS is true if we should only be fixing up virtual
1141    PHI arguments, instead of adding new PHI arguments for just added PHI
1142    nodes.  */
1143
1144 static void
1145 rewrite_blocks (bool fix_virtual_phis)
1146 {
1147   struct dom_walk_data walk_data;
1148   
1149   /* Rewrite all the basic blocks in the program.  */
1150   timevar_push (TV_TREE_SSA_REWRITE_BLOCKS);
1151
1152   /* Setup callbacks for the generic dominator tree walker.  */
1153   walk_data.walk_stmts_backward = false;
1154   walk_data.dom_direction = CDI_DOMINATORS;
1155   walk_data.initialize_block_local_data = NULL;
1156   walk_data.before_dom_children_before_stmts = rewrite_initialize_block;
1157   walk_data.before_dom_children_walk_stmts = rewrite_stmt;
1158   walk_data.before_dom_children_after_stmts = NULL;
1159   if (!fix_virtual_phis)
1160     walk_data.before_dom_children_after_stmts = rewrite_add_phi_arguments;
1161   else
1162     walk_data.before_dom_children_after_stmts = rewrite_virtual_phi_arguments;
1163   
1164   walk_data.after_dom_children_before_stmts =  NULL;
1165   walk_data.after_dom_children_walk_stmts =  NULL;
1166   walk_data.after_dom_children_after_stmts =  rewrite_finalize_block;
1167   walk_data.global_data = NULL;
1168   walk_data.block_local_data_size = 0;
1169
1170   block_defs_stack = VEC_alloc (tree_on_heap, 10);
1171
1172   /* Initialize the dominator walker.  */
1173   init_walk_dominator_tree (&walk_data);
1174
1175   /* Recursively walk the dominator tree rewriting each statement in
1176      each basic block.  */
1177   walk_dominator_tree (&walk_data, ENTRY_BLOCK_PTR);
1178
1179   /* Finalize the dominator walker.  */
1180   fini_walk_dominator_tree (&walk_data);
1181
1182   /* Debugging dumps.  */
1183   if (dump_file && (dump_flags & TDF_STATS))
1184     {
1185       dump_dfa_stats (dump_file);
1186       dump_tree_ssa_stats (dump_file);
1187     }
1188
1189   htab_delete (def_blocks);
1190   def_blocks = NULL;
1191   
1192   VEC_free (tree_on_heap, block_defs_stack);
1193   block_defs_stack = NULL;
1194
1195   timevar_pop (TV_TREE_SSA_REWRITE_BLOCKS);
1196 }
1197
1198
1199 /* Block initialization routine for mark_def_sites.  Clear the 
1200    KILLS bitmap at the start of each block.  */
1201
1202 static void
1203 mark_def_sites_initialize_block (struct dom_walk_data *walk_data,
1204                                  basic_block bb ATTRIBUTE_UNUSED)
1205 {
1206   struct mark_def_sites_global_data *gd = walk_data->global_data;
1207   bitmap kills = gd->kills;
1208   bitmap_clear (kills);
1209 }
1210
1211
1212 /* Mark the definition site blocks for each variable, so that we know where
1213    the variable is actually live.  */
1214
1215 static void 
1216 mark_def_site_blocks (void)
1217 {
1218   size_t i;
1219   struct dom_walk_data walk_data;
1220   struct mark_def_sites_global_data mark_def_sites_global_data;
1221
1222   /* Allocate memory for the DEF_BLOCKS hash table.  */
1223   def_blocks = htab_create (VARRAY_ACTIVE_SIZE (referenced_vars),
1224                             def_blocks_hash, def_blocks_eq, def_blocks_free);
1225
1226   for (i = 0; i < num_referenced_vars; i++)
1227     set_current_def (referenced_var (i), NULL_TREE);
1228
1229   /* Ensure that the dominance information is OK.  */
1230   calculate_dominance_info (CDI_DOMINATORS);
1231
1232   /* Setup callbacks for the generic dominator tree walker to find and
1233      mark definition sites.  */
1234   walk_data.walk_stmts_backward = false;
1235   walk_data.dom_direction = CDI_DOMINATORS;
1236   walk_data.initialize_block_local_data = NULL;
1237   walk_data.before_dom_children_before_stmts = mark_def_sites_initialize_block;
1238   walk_data.before_dom_children_walk_stmts = mark_def_sites;
1239   walk_data.before_dom_children_after_stmts = NULL; 
1240   walk_data.after_dom_children_before_stmts =  NULL;
1241   walk_data.after_dom_children_walk_stmts =  NULL;
1242   walk_data.after_dom_children_after_stmts =  NULL;
1243
1244   /* Notice that this bitmap is indexed using variable UIDs, so it must be
1245      large enough to accommodate all the variables referenced in the
1246      function, not just the ones we are renaming.  */
1247   mark_def_sites_global_data.kills = BITMAP_ALLOC (NULL);
1248   walk_data.global_data = &mark_def_sites_global_data;
1249
1250   /* We do not have any local data.  */
1251   walk_data.block_local_data_size = 0;
1252
1253   /* Initialize the dominator walker.  */
1254   init_walk_dominator_tree (&walk_data);
1255
1256   /* Recursively walk the dominator tree.  */
1257   walk_dominator_tree (&walk_data, ENTRY_BLOCK_PTR);
1258
1259   /* Finalize the dominator walker.  */
1260   fini_walk_dominator_tree (&walk_data);
1261
1262   /* We no longer need this bitmap, clear and free it.  */
1263   BITMAP_FREE (mark_def_sites_global_data.kills);
1264 }
1265
1266
1267 /* Main entry point into the SSA builder.  The renaming process
1268    proceeds in five main phases:
1269
1270    1- If VARS_TO_RENAME has any entries, any existing PHI nodes for
1271       those variables are removed from the flow graph so that they can
1272       be computed again.
1273
1274    2- Compute dominance frontier, needed to insert PHI nodes and
1275       rename the function in dominator tree order.
1276
1277    3- Find and mark all the blocks that define variables
1278       (mark_def_site_blocks).
1279
1280    4- Insert PHI nodes at dominance frontiers (insert_phi_nodes).
1281
1282    5- Rename all the blocks (rewrite_blocks) and statements in the program.
1283
1284    Steps 3 and 5 are done using the dominator tree walker
1285    (walk_dominator_tree).
1286
1287    ALL is true if all variables should be renamed (otherwise just those
1288    mentioned in vars_to_rename are taken into account).  */
1289
1290 void
1291 rewrite_into_ssa (bool all)
1292 {
1293   bitmap *dfs;
1294   basic_block bb;
1295   bitmap old_vars_to_rename = vars_to_rename;
1296   
1297   timevar_push (TV_TREE_SSA_OTHER);
1298
1299   if (all)
1300     vars_to_rename = NULL;
1301   else
1302     {
1303       /* Initialize the array of variables to rename.  */
1304       gcc_assert (vars_to_rename);
1305
1306       if (bitmap_empty_p (vars_to_rename))
1307         {
1308           timevar_pop (TV_TREE_SSA_OTHER);
1309           return;
1310         }
1311       
1312       invalidate_name_tags (vars_to_rename);
1313
1314       /* Now remove all the existing PHI nodes (if any) for the variables
1315          that we are about to rename into SSA.  */
1316       remove_all_phi_nodes_for (vars_to_rename);
1317     }
1318
1319   mark_def_site_blocks ();
1320
1321   /* Initialize dominance frontier.  */
1322   dfs = (bitmap *) xmalloc (last_basic_block * sizeof (bitmap *));
1323   FOR_EACH_BB (bb)
1324     dfs[bb->index] = BITMAP_ALLOC (NULL);
1325
1326   /* Compute dominance frontiers.  */
1327   compute_dominance_frontiers (dfs);
1328
1329   /* Insert PHI nodes at dominance frontiers of definition blocks.  */
1330   insert_phi_nodes (dfs, NULL);
1331
1332   rewrite_blocks (false);
1333
1334   /* Free allocated memory.  */
1335   FOR_EACH_BB (bb)
1336     BITMAP_FREE (dfs[bb->index]);
1337   free (dfs);
1338
1339   vars_to_rename = old_vars_to_rename;
1340   timevar_pop (TV_TREE_SSA_OTHER);
1341 }
1342
1343
1344 /* Rewrites all variables into SSA.  */
1345
1346 static void
1347 rewrite_all_into_ssa (void)
1348 {
1349   init_ssa_operands ();
1350   rewrite_into_ssa (true);
1351 }
1352
1353 struct tree_opt_pass pass_build_ssa = 
1354 {
1355   "ssa",                                /* name */
1356   NULL,                                 /* gate */
1357   rewrite_all_into_ssa,                 /* execute */
1358   NULL,                                 /* sub */
1359   NULL,                                 /* next */
1360   0,                                    /* static_pass_number */
1361   0,                                    /* tv_id */
1362   PROP_cfg | PROP_referenced_vars,      /* properties_required */
1363   PROP_ssa,                             /* properties_provided */
1364   0,                                    /* properties_destroyed */
1365   0,                                    /* todo_flags_start */
1366   TODO_dump_func | TODO_verify_ssa,     /* todo_flags_finish */
1367   0                                     /* letter */
1368 };
1369
1370
1371 /* Rewrite the def-def chains of virtual operands so that they have
1372    the correct reaching definitions.  */
1373
1374 void
1375 rewrite_def_def_chains (void)
1376 {
1377   /* Ensure that the dominance information is OK.  */
1378   calculate_dominance_info (CDI_DOMINATORS);
1379   mark_def_site_blocks ();
1380   rewrite_blocks (true);
1381 }
1382
1383
1384
1385 /*---------------------------------------------------------------------------
1386     Functions to fix a program in invalid SSA form into valid SSA
1387     form.  The main entry point here is rewrite_ssa_into_ssa.
1388 ---------------------------------------------------------------------------*/
1389
1390 /* Called after visiting basic block BB.  Restore CURRDEFS to its
1391    original value.  */
1392
1393 static void
1394 ssa_rewrite_finalize_block (struct dom_walk_data *walk_data ATTRIBUTE_UNUSED,
1395                             basic_block bb ATTRIBUTE_UNUSED)
1396 {
1397
1398   /* Step 5.  Restore the current reaching definition for each variable
1399      referenced in the block (in reverse order).  */
1400   while (VEC_length (tree_on_heap, block_defs_stack) > 0)
1401     {
1402       tree var = VEC_pop (tree_on_heap, block_defs_stack);
1403       tree saved_def;
1404       
1405       if (var == NULL)
1406         break;
1407
1408       saved_def = VEC_pop (tree_on_heap, block_defs_stack);
1409       set_current_def (var, saved_def);
1410     }
1411 }
1412
1413
1414 /* Register DEF (an SSA_NAME) to be a new definition for the original
1415    ssa name VAR and push VAR's current reaching definition
1416    into the stack pointed by BLOCK_DEFS_P.  */
1417
1418 static void
1419 ssa_register_new_def (tree var, tree def)
1420 {
1421   tree currdef;
1422    
1423   /* If this variable is set in a single basic block and all uses are
1424      dominated by the set(s) in that single basic block, then there is
1425      nothing to do.  TODO we should not be called at all, and just
1426      keep the original name.  */
1427   if (get_phi_state (var) == NEED_PHI_STATE_NO)
1428     {
1429       set_current_def (var, def);
1430       return;
1431     }
1432
1433   currdef = get_current_def (var);
1434
1435   /* Push the current reaching definition into *BLOCK_DEFS_P.  This stack is
1436      later used by the dominator tree callbacks to restore the reaching
1437      definitions for all the variables defined in the block after a recursive
1438      visit to all its immediately dominated blocks.  */
1439   VEC_safe_push (tree_on_heap, block_defs_stack, currdef);
1440   VEC_safe_push (tree_on_heap, block_defs_stack, var);
1441
1442   /* Set the current reaching definition for VAR to be DEF.  */
1443   set_current_def (var, def);
1444 }
1445
1446
1447 /* Same as rewrite_stmt, for rewriting ssa names.  */
1448
1449 static void
1450 ssa_rewrite_stmt (struct dom_walk_data *walk_data,
1451                   basic_block bb ATTRIBUTE_UNUSED,
1452                   block_stmt_iterator si)
1453 {
1454   stmt_ann_t ann;
1455   tree stmt, var;
1456   ssa_op_iter iter;
1457   use_operand_p use_p;
1458   def_operand_p def_p;
1459   sbitmap names_to_rename = walk_data->global_data;
1460
1461   stmt = bsi_stmt (si);
1462   ann = stmt_ann (stmt);
1463
1464   if (dump_file && (dump_flags & TDF_DETAILS))
1465     {
1466       fprintf (dump_file, "Renaming statement ");
1467       print_generic_stmt (dump_file, stmt, TDF_SLIM);
1468       fprintf (dump_file, "\n");
1469     }
1470
1471   /* We have just scanned the code for operands.  No statement should
1472      be modified.  */
1473   gcc_assert (!ann->modified);
1474
1475   /* Step 1.  Rewrite USES and VUSES in the statement.  */
1476   FOR_EACH_SSA_USE_OPERAND (use_p, stmt, iter, SSA_OP_ALL_USES | SSA_OP_ALL_KILLS)
1477     {
1478       if (TEST_BIT (names_to_rename, SSA_NAME_VERSION (USE_FROM_PTR (use_p))))
1479         SET_USE (use_p, get_reaching_def (USE_FROM_PTR (use_p)));
1480     }
1481
1482   /* Step 2.  Register the statement's DEF and VDEF operands.  */
1483   FOR_EACH_SSA_DEF_OPERAND (def_p, stmt, iter, SSA_OP_ALL_DEFS)
1484     {
1485       var = DEF_FROM_PTR (def_p);
1486
1487       if (!TEST_BIT (names_to_rename, SSA_NAME_VERSION (var)))
1488         continue;
1489
1490       SET_DEF (def_p, duplicate_ssa_name (var, stmt));
1491       ssa_register_new_def (var, DEF_FROM_PTR (def_p));
1492     }
1493 }
1494
1495
1496 /* Ditto, for ssa name rewriting.  */
1497
1498 static void
1499 ssa_rewrite_phi_arguments (struct dom_walk_data *walk_data, basic_block bb)
1500 {
1501   edge e;
1502   sbitmap names_to_rename = walk_data->global_data;
1503   use_operand_p op;
1504   edge_iterator ei;
1505
1506   FOR_EACH_EDGE (e, ei, bb->succs)
1507     {
1508       tree phi;
1509
1510       if (e->dest == EXIT_BLOCK_PTR)
1511         continue;
1512
1513       for (phi = phi_nodes (e->dest); phi; phi = PHI_CHAIN (phi))
1514         {
1515           op = PHI_ARG_DEF_PTR_FROM_EDGE (phi, e);
1516           if (TREE_CODE (USE_FROM_PTR (op)) != SSA_NAME)
1517             continue;
1518           
1519           if (!TEST_BIT (names_to_rename, SSA_NAME_VERSION (USE_FROM_PTR (op))))
1520             continue; 
1521
1522           SET_USE (op, get_reaching_def (USE_FROM_PTR (op)));
1523           if (e->flags & EDGE_ABNORMAL)
1524             SSA_NAME_OCCURS_IN_ABNORMAL_PHI (USE_FROM_PTR (op)) = 1;
1525         }
1526     }
1527 }
1528
1529 /* Ditto, for rewriting ssa names.  */
1530
1531 static void
1532 ssa_rewrite_initialize_block (struct dom_walk_data *walk_data, basic_block bb)
1533 {
1534   tree phi, new_name;
1535   sbitmap names_to_rename = walk_data->global_data;
1536   edge e;
1537   bool abnormal_phi;
1538   edge_iterator ei;
1539
1540   if (dump_file && (dump_flags & TDF_DETAILS))
1541     fprintf (dump_file, "\n\nRenaming block #%d\n\n", bb->index);
1542
1543   /* Mark the unwind point for this block.  */
1544   VEC_safe_push (tree_on_heap, block_defs_stack, NULL_TREE);
1545
1546   FOR_EACH_EDGE (e, ei, bb->preds)
1547     if (e->flags & EDGE_ABNORMAL)
1548       break;
1549   abnormal_phi = (e != NULL);
1550
1551   /* Step 1.  Register new definitions for every PHI node in the block.
1552      Conceptually, all the PHI nodes are executed in parallel and each PHI
1553      node introduces a new version for the associated variable.  */
1554   for (phi = phi_nodes (bb); phi; phi = PHI_CHAIN (phi))
1555     {
1556       tree result = PHI_RESULT (phi);
1557
1558       if (TEST_BIT (names_to_rename, SSA_NAME_VERSION (result)))
1559         {
1560           new_name = duplicate_ssa_name (result, phi);
1561           SET_PHI_RESULT (phi, new_name);
1562
1563           if (abnormal_phi)
1564             SSA_NAME_OCCURS_IN_ABNORMAL_PHI (new_name) = 1;
1565           ssa_register_new_def (result, new_name);
1566         }
1567     }
1568 }
1569
1570
1571 /* Same as mark_def_sites, but works over SSA names.  */
1572
1573 static void
1574 ssa_mark_def_sites (struct dom_walk_data *walk_data,
1575                     basic_block bb,
1576                     block_stmt_iterator bsi)
1577 {
1578   struct mark_def_sites_global_data *gd = walk_data->global_data;
1579   bitmap kills = gd->kills;
1580   size_t uid, def_uid;
1581   tree stmt, use, def;
1582   ssa_op_iter iter;
1583
1584   /* Mark all the blocks that have definitions for each variable in the
1585      names_to_rename bitmap.  */
1586   stmt = bsi_stmt (bsi);
1587   update_stmt_if_modified (stmt);
1588
1589   /* If a variable is used before being set, then the variable is live
1590      across a block boundary, so mark it live-on-entry to BB.  */
1591   FOR_EACH_SSA_TREE_OPERAND (use, stmt, iter, SSA_OP_ALL_USES | SSA_OP_ALL_KILLS)
1592     {
1593       uid = SSA_NAME_VERSION (use);
1594
1595       if (TEST_BIT (gd->names_to_rename, uid)
1596           && !bitmap_bit_p (kills, uid))
1597         set_livein_block (use, bb);
1598     }
1599           
1600   /* Now process the definition made by this statement.  Mark the
1601      variables in KILLS.  */
1602   FOR_EACH_SSA_TREE_OPERAND (def, stmt, iter, SSA_OP_ALL_DEFS)
1603     {
1604       def_uid = SSA_NAME_VERSION (def);
1605
1606       if (TEST_BIT (gd->names_to_rename, def_uid))
1607         {
1608           set_def_block (def, bb, false, true);
1609           bitmap_set_bit (kills, def_uid);
1610         }
1611     }
1612 }
1613
1614
1615 /* Block initialization routine for mark_def_sites.  Clear the 
1616    KILLS bitmap at the start of each block.  */
1617
1618 static void
1619 ssa_mark_def_sites_initialize_block (struct dom_walk_data *walk_data,
1620                                      basic_block bb)
1621 {
1622   struct mark_def_sites_global_data *gd = walk_data->global_data;
1623   bitmap kills = gd->kills;
1624   tree phi, def;
1625   unsigned def_uid;
1626
1627   bitmap_clear (kills);
1628
1629   for (phi = phi_nodes (bb); phi; phi = PHI_CHAIN (phi))
1630     {
1631       def = PHI_RESULT (phi);
1632       def_uid = SSA_NAME_VERSION (def);
1633
1634       if (!TEST_BIT (gd->names_to_rename, def_uid))
1635         continue;
1636
1637       set_def_block (def, bb, true, true);
1638       bitmap_set_bit (kills, def_uid);
1639     }
1640 }
1641
1642 /* Marks ssa names used as arguments of phis at the end of BB.  */
1643
1644 static void
1645 ssa_mark_phi_uses (struct dom_walk_data *walk_data, basic_block bb)
1646 {
1647   struct mark_def_sites_global_data *gd = walk_data->global_data;
1648   bitmap kills = gd->kills;
1649   edge e;
1650   tree phi, use;
1651   unsigned uid;
1652   edge_iterator ei;
1653
1654   FOR_EACH_EDGE (e, ei, bb->succs)
1655     {
1656       if (e->dest == EXIT_BLOCK_PTR)
1657         continue;
1658
1659       for (phi = phi_nodes (e->dest); phi; phi = PHI_CHAIN (phi))
1660         {
1661           use = PHI_ARG_DEF_FROM_EDGE (phi, e);
1662           if (TREE_CODE (use) != SSA_NAME)
1663             continue;
1664
1665           uid = SSA_NAME_VERSION (use);
1666
1667           if (TEST_BIT (gd->names_to_rename, uid)
1668               && !bitmap_bit_p (kills, uid))
1669             set_livein_block (use, bb);
1670         }
1671     }
1672 }
1673        
1674    
1675 /* The marked ssa names may have more than one definition;
1676    add PHI nodes and rewrite them to fix this.  */
1677
1678 void
1679 rewrite_ssa_into_ssa (void)
1680 {
1681   bitmap *dfs;
1682   basic_block bb;
1683   struct dom_walk_data walk_data;
1684   struct mark_def_sites_global_data mark_def_sites_global_data;
1685   unsigned i;
1686   sbitmap snames_to_rename;
1687   bitmap to_rename;
1688   bitmap_iterator bi;
1689   
1690   if (!any_marked_for_rewrite_p ())
1691     return;
1692   to_rename = marked_ssa_names ();
1693
1694   timevar_push (TV_TREE_SSA_OTHER);
1695
1696   /* Allocate memory for the DEF_BLOCKS hash table.  */
1697   def_blocks = htab_create (num_ssa_names,
1698                             def_blocks_hash, def_blocks_eq, def_blocks_free);
1699
1700   /* Initialize dominance frontier and immediate dominator bitmaps. 
1701      Also count the number of predecessors for each block.  Doing so
1702      can save significant time during PHI insertion for large graphs.  */
1703   dfs = (bitmap *) xmalloc (last_basic_block * sizeof (bitmap *));
1704   FOR_EACH_BB (bb)
1705     dfs[bb->index] = BITMAP_ALLOC (NULL);
1706
1707   /* Ensure that the dominance information is OK.  */
1708   calculate_dominance_info (CDI_DOMINATORS);
1709
1710   /* Compute dominance frontiers.  */
1711   compute_dominance_frontiers (dfs);
1712
1713   /* Setup callbacks for the generic dominator tree walker to find and
1714      mark definition sites.  */
1715   walk_data.walk_stmts_backward = false;
1716   walk_data.dom_direction = CDI_DOMINATORS;
1717   walk_data.initialize_block_local_data = NULL;
1718   walk_data.before_dom_children_before_stmts
1719           = ssa_mark_def_sites_initialize_block;
1720   walk_data.before_dom_children_walk_stmts = ssa_mark_def_sites;
1721   walk_data.before_dom_children_after_stmts = ssa_mark_phi_uses; 
1722   walk_data.after_dom_children_before_stmts =  NULL;
1723   walk_data.after_dom_children_walk_stmts =  NULL;
1724   walk_data.after_dom_children_after_stmts =  NULL;
1725
1726   snames_to_rename = sbitmap_alloc (num_ssa_names);
1727   sbitmap_zero (snames_to_rename);
1728   EXECUTE_IF_SET_IN_BITMAP (to_rename, 0, i, bi)
1729     {
1730       SET_BIT (snames_to_rename, i);
1731       set_current_def (ssa_name (i), NULL_TREE);
1732     }
1733
1734   mark_def_sites_global_data.kills = BITMAP_ALLOC (NULL);
1735   mark_def_sites_global_data.names_to_rename = snames_to_rename;
1736   walk_data.global_data = &mark_def_sites_global_data;
1737
1738   block_defs_stack = VEC_alloc (tree_on_heap, 10);
1739
1740   /* We do not have any local data.  */
1741   walk_data.block_local_data_size = 0;
1742
1743   /* Initialize the dominator walker.  */
1744   init_walk_dominator_tree (&walk_data);
1745
1746   /* Recursively walk the dominator tree.  */
1747   walk_dominator_tree (&walk_data, ENTRY_BLOCK_PTR);
1748
1749   /* Finalize the dominator walker.  */
1750   fini_walk_dominator_tree (&walk_data);
1751
1752   /* We no longer need this bitmap, clear and free it.  */
1753   BITMAP_FREE (mark_def_sites_global_data.kills);
1754
1755   /* Insert PHI nodes at dominance frontiers of definition blocks.  */
1756   insert_phi_nodes (dfs, to_rename);
1757
1758   /* Rewrite all the basic blocks in the program.  */
1759   timevar_push (TV_TREE_SSA_REWRITE_BLOCKS);
1760
1761   /* Setup callbacks for the generic dominator tree walker.  */
1762   walk_data.walk_stmts_backward = false;
1763   walk_data.dom_direction = CDI_DOMINATORS;
1764   walk_data.initialize_block_local_data = NULL;
1765   walk_data.before_dom_children_before_stmts = ssa_rewrite_initialize_block;
1766   walk_data.before_dom_children_walk_stmts = ssa_rewrite_stmt;
1767   walk_data.before_dom_children_after_stmts = ssa_rewrite_phi_arguments;
1768   walk_data.after_dom_children_before_stmts = NULL;
1769   walk_data.after_dom_children_walk_stmts =  NULL;
1770   walk_data.after_dom_children_after_stmts =  ssa_rewrite_finalize_block;
1771   walk_data.global_data = snames_to_rename;
1772   walk_data.block_local_data_size = 0;
1773
1774   /* Initialize the dominator walker.  */
1775   init_walk_dominator_tree (&walk_data);
1776
1777   /* Recursively walk the dominator tree rewriting each statement in
1778      each basic block.  */
1779   walk_dominator_tree (&walk_data, ENTRY_BLOCK_PTR);
1780
1781   /* Finalize the dominator walker.  */
1782   fini_walk_dominator_tree (&walk_data);
1783
1784   unmark_all_for_rewrite ();
1785
1786   EXECUTE_IF_SET_IN_BITMAP (to_rename, 0, i, bi)
1787     {
1788       /* Free SSA_NAME_AUX.  We don't have to zero it because
1789          release_ssa_name will.  */
1790       if (SSA_NAME_AUX (ssa_name (i)))
1791         free (SSA_NAME_AUX (ssa_name (i)));
1792
1793       release_ssa_name (ssa_name (i));
1794     }
1795
1796   sbitmap_free (snames_to_rename);
1797
1798   timevar_pop (TV_TREE_SSA_REWRITE_BLOCKS);
1799
1800   /* Debugging dumps.  */
1801   if (dump_file && (dump_flags & TDF_STATS))
1802     {
1803       dump_dfa_stats (dump_file);
1804       dump_tree_ssa_stats (dump_file);
1805     }
1806
1807   /* Free allocated memory.  */
1808   FOR_EACH_BB (bb)
1809     BITMAP_FREE (dfs[bb->index]);
1810   free (dfs);
1811
1812   htab_delete (def_blocks);
1813
1814 #ifdef ENABLE_CHECKING
1815   for (i = 1; i < num_ssa_names; i++)
1816     {
1817       tree name = ssa_name (i);
1818       if (!name)
1819         continue;
1820
1821       gcc_assert (SSA_NAME_AUX (name) == NULL);
1822     }
1823 #endif
1824
1825   BITMAP_FREE (to_rename);
1826   
1827   VEC_free (tree_on_heap, block_defs_stack);
1828   block_defs_stack = NULL;
1829   timevar_pop (TV_TREE_SSA_OTHER);
1830 }