OSDN Git Service

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