OSDN Git Service

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