tree-into-ssa.c 82.5 KB
Newer Older
1
/* Rewrite a program in Normal form into SSA.
2
   Copyright (C) 2001, 2002, 2003, 2004, 2005 Free Software Foundation, Inc.
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
   Contributed by Diego Novillo <dnovillo@redhat.com>

This file is part of GCC.

GCC is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.

GCC is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with GCC; see the file COPYING.  If not, write to
Kelley Cook committed
19 20
the Free Software Foundation, 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.  */
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38

#include "config.h"
#include "system.h"
#include "coretypes.h"
#include "tm.h"
#include "tree.h"
#include "flags.h"
#include "rtl.h"
#include "tm_p.h"
#include "langhooks.h"
#include "hard-reg-set.h"
#include "basic-block.h"
#include "output.h"
#include "expr.h"
#include "function.h"
#include "diagnostic.h"
#include "bitmap.h"
#include "tree-flow.h"
39
#include "tree-gimple.h"
40 41 42 43 44 45 46 47
#include "tree-inline.h"
#include "varray.h"
#include "timevar.h"
#include "hashtab.h"
#include "tree-dump.h"
#include "tree-pass.h"
#include "cfgloop.h"
#include "domwalk.h"
48
#include "ggc.h"
Diego Novillo committed
49
#include "params.h"
50 51 52 53 54 55 56

/* This file builds the SSA form for a function as described in:
   R. Cytron, J. Ferrante, B. Rosen, M. Wegman, and K. Zadeck. Efficiently
   Computing Static Single Assignment Form and the Control Dependence
   Graph. ACM Transactions on Programming Languages and Systems,
   13(4):451-490, October 1991.  */

57 58 59
/* True if the code is in ssa form.  */
bool in_ssa_p;

60 61 62 63 64 65 66 67 68 69 70
/* Structure to map a variable VAR to the set of blocks that contain
   definitions for VAR.  */
struct def_blocks_d
{
  /* The variable.  */
  tree var;

  /* Blocks that contain definitions of VAR.  Bit I will be set if the
     Ith block contains a definition of VAR.  */
  bitmap def_blocks;

71
  /* Blocks that contain a PHI node for VAR.  */
72 73
  bitmap phi_blocks;

74 75 76 77 78
  /* Blocks where VAR is live-on-entry.  Similar semantics as
     DEF_BLOCKS.  */
  bitmap livein_blocks;
};

79

80 81 82 83 84 85 86 87 88
/* Each entry in DEF_BLOCKS contains an element of type STRUCT
   DEF_BLOCKS_D, mapping a variable VAR to a bitmap describing all the
   basic blocks where VAR is defined (assigned a new value).  It also
   contains a bitmap of all the blocks where VAR is live-on-entry
   (i.e., there is a use of VAR in block B without a preceding
   definition in B).  The live-on-entry information is used when
   computing PHI pruning heuristics.  */
static htab_t def_blocks;

89
/* Stack of trees used to restore the global currdefs to its original
90 91
   state after completing rewriting of a block and its dominator
   children.  Its elements have the following properties:
92

93 94
   - An SSA_NAME indicates that the current definition of the
     underlying variable should be set to the given SSA_NAME.
95

96 97
   - A _DECL node indicates that the underlying variable has no
     current definition.
98

99 100
   - A NULL node is used to mark the last node associated with the
     current block.
101

102 103
   - A NULL node at the top entry is used to mark the last node
     associated with the current block.  */
104
static VEC(tree,heap) *block_defs_stack;
105

106 107 108
/* Basic block vectors used in this file ought to be allocated in the
   heap.  We use pointer vector, because ints can be easily passed by
   value.  */
109 110
DEF_VEC_I(int);
DEF_VEC_ALLOC_I(int,heap);
111

112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154
/* Set of existing SSA names being replaced by update_ssa.  */
static sbitmap old_ssa_names;

/* Set of new SSA names being added by update_ssa.  Note that both
   NEW_SSA_NAMES and OLD_SSA_NAMES are dense bitmaps because most of
   the operations done on them are presence tests.  */
static sbitmap new_ssa_names;

/* Symbols whose SSA form needs to be updated or created for the first
   time.  */
static bitmap syms_to_rename;

/* Set of SSA names that have been marked to be released after they
   were registered in the replacement table.  They will be finally
   released after we finish updating the SSA web.  */
static bitmap names_to_release;

/* Growth factor for NEW_SSA_NAMES and OLD_SSA_NAMES.  These sets need
   to grow as the callers to register_new_name_mapping will typically
   create new names on the fly.  FIXME.  Currently set to 1/3 to avoid
   frequent reallocations but still need to find a reasonable growth
   strategy.  */
#define NAME_SETS_GROWTH_FACTOR	(MAX (3, num_ssa_names / 3))

/* Tuple used to represent replacement mappings.  */
struct repl_map_d
{
  tree name;
  bitmap set;
};

/* NEW -> OLD_SET replacement table.  If we are replacing several
   existing SSA names O_1, O_2, ..., O_j with a new name N_i,
   then REPL_TBL[N_i] = { O_1, O_2, ..., O_j }.  */
static htab_t repl_tbl;

/* true if register_new_name_mapping needs to initialize the data
   structures needed by update_ssa.  */
static bool need_to_initialize_update_ssa_p = true;

/* true if update_ssa needs to update virtual operands.  */
static bool need_to_update_vops_p = false;

Diego Novillo committed
155 156 157 158 159 160 161 162 163 164 165 166 167 168
/* Statistics kept by update_ssa to use in the virtual mapping
   heuristic.  If the number of virtual mappings is beyond certain
   threshold, the updater will switch from using the mappings into
   renaming the virtual symbols from scratch.  In some cases, the
   large number of name mappings for virtual names causes significant
   slowdowns in the PHI insertion code.  */
struct update_ssa_stats_d
{
  unsigned num_virtual_mappings;
  unsigned num_total_mappings;
  bitmap virtual_symbols;
  unsigned num_virtual_symbols;
};
static struct update_ssa_stats_d update_ssa_stats;
169

170 171 172
/* Global data to attach to the main dominator walk structure.  */
struct mark_def_sites_global_data
{
173 174
  /* This bitmap contains the variables which are set before they
     are used in a basic block.  */
175
  bitmap kills;
176 177 178

  /* Bitmap of names to rename.  */
  sbitmap names_to_rename;
179 180 181 182

  /* Set of blocks that mark_def_sites deems interesting for the
     renamer to process.  */
  sbitmap interesting_blocks;
183 184
};

185

186
/* Information stored for SSA names.  */
187 188 189 190 191 192 193 194 195 196
struct ssa_name_info
{
  /* This field indicates whether or not the variable may need PHI nodes.
     See the enum's definition for more detailed information about the
     states.  */
  ENUM_BITFIELD (need_phi_state) need_phi_state : 2;

  /* The actual definition of the ssa name.  */
  tree current_def;
};
197 198


199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
/* The main entry point to the SSA renamer (rewrite_blocks) may be
   called several times to do different, but related, tasks.
   Initially, we need it to rename the whole program into SSA form.
   At other times, we may need it to only rename into SSA newly
   exposed symbols.  Finally, we can also call it to incrementally fix
   an already built SSA web.  */
enum rewrite_mode {
    /* Convert the whole function into SSA form.  */
    REWRITE_ALL,

    /* Incrementally update the SSA web by replacing existing SSA
       names with new ones.  See update_ssa for details.  */
    REWRITE_UPDATE
};


215 216 217 218 219
/* Use TREE_VISITED to keep track of which statements we want to
   rename.  When renaming a subset of the variables, not all
   statements will be processed.  This is decided in mark_def_sites.  */
#define REWRITE_THIS_STMT(T)	TREE_VISITED (T)

220 221 222 223 224 225 226 227 228
/* Use the unsigned flag to keep track of which statements we want to
   visit when marking new definition sites.  This is slightly
   different than REWRITE_THIS_STMT: it's used by update_ssa to
   distinguish statements that need to have both uses and defs
   processed from those that only need to have their defs processed.
   Statements that define new SSA names only need to have their defs
   registered, but they don't need to have their uses renamed.  */
#define REGISTER_DEFS_IN_THIS_STMT(T)	(T)->common.unsigned_flag

229

Diego Novillo committed
230 231 232 233 234 235 236 237 238 239 240
/* Prototypes for debugging functions.  */
extern void dump_tree_ssa (FILE *);
extern void debug_tree_ssa (void);
extern void debug_def_blocks (void);
extern void dump_tree_ssa_stats (FILE *);
extern void debug_tree_ssa_stats (void);
void dump_update_ssa (FILE *);
void debug_update_ssa (void);
void dump_names_replaced_by (FILE *, tree);
void debug_names_replaced_by (tree);

241 242 243 244 245 246 247 248
/* Get the information associated with NAME.  */

static inline struct ssa_name_info *
get_ssa_name_ann (tree name)
{
  if (!SSA_NAME_AUX (name))
    SSA_NAME_AUX (name) = xcalloc (1, sizeof (struct ssa_name_info));

249
  return (struct ssa_name_info *) SSA_NAME_AUX (name);
250 251
}

252

253 254 255 256 257 258 259 260 261 262 263
/* Gets phi_state field for VAR.  */

static inline enum need_phi_state
get_phi_state (tree var)
{
  if (TREE_CODE (var) == SSA_NAME)
    return get_ssa_name_ann (var)->need_phi_state;
  else
    return var_ann (var)->need_phi_state;
}

264

265 266 267 268 269 270 271 272 273 274 275
/* Sets phi_state field for VAR to STATE.  */

static inline void
set_phi_state (tree var, enum need_phi_state state)
{
  if (TREE_CODE (var) == SSA_NAME)
    get_ssa_name_ann (var)->need_phi_state = state;
  else
    var_ann (var)->need_phi_state = state;
}

276

277 278
/* Return the current definition for VAR.  */

Diego Novillo committed
279
tree
280 281 282 283 284 285 286 287
get_current_def (tree var)
{
  if (TREE_CODE (var) == SSA_NAME)
    return get_ssa_name_ann (var)->current_def;
  else
    return var_ann (var)->current_def;
}

288

289 290
/* Sets current definition of VAR to DEF.  */

Diego Novillo committed
291
void
292 293 294 295 296 297 298 299
set_current_def (tree var, tree def)
{
  if (TREE_CODE (var) == SSA_NAME)
    get_ssa_name_ann (var)->current_def = def;
  else
    var_ann (var)->current_def = def;
}

300

301 302 303 304 305 306 307 308
/* Compute global livein information given the set of blockx where
   an object is locally live at the start of the block (LIVEIN)
   and the set of blocks where the object is defined (DEF_BLOCKS).

   Note: This routine augments the existing local livein information
   to include global livein (i.e., it modifies the underlying bitmap
   for LIVEIN).  */

309
void
310 311 312
compute_global_livein (bitmap livein, bitmap def_blocks)
{
  basic_block bb, *worklist, *tos;
313
  unsigned i;
314
  bitmap_iterator bi;
315 316

  tos = worklist
317
    = (basic_block *) xmalloc (sizeof (basic_block) * (last_basic_block + 1));
318

319
  EXECUTE_IF_SET_IN_BITMAP (livein, 0, i, bi)
320
    {
321 322
      *tos++ = BASIC_BLOCK (i);
    }
323 324 325 326 327

  /* Iterate until the worklist is empty.  */
  while (tos != worklist)
    {
      edge e;
328
      edge_iterator ei;
329 330 331 332 333

      /* Pull a block off the worklist.  */
      bb = *--tos;

      /* For each predecessor block.  */
334
      FOR_EACH_EDGE (e, ei, bb->preds)
335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353
	{
	  basic_block pred = e->src;
	  int pred_index = pred->index;

	  /* None of this is necessary for the entry block.  */
	  if (pred != ENTRY_BLOCK_PTR
	      && ! bitmap_bit_p (livein, pred_index)
	      && ! bitmap_bit_p (def_blocks, pred_index))
	    {
	      *tos++ = pred;
	      bitmap_set_bit (livein, pred_index);
	    }
	}
    }

  free (worklist);
}


354 355 356
/* Return the set of blocks where variable VAR is defined and the blocks
   where VAR is live on entry (livein).  If no entry is found in
   DEF_BLOCKS, a new one is created and returned.  */
357

358 359
static inline struct def_blocks_d *
get_def_blocks_for (tree var)
360
{
361 362
  struct def_blocks_d db, *db_p;
  void **slot;
363

364 365 366
  db.var = var;
  slot = htab_find_slot (def_blocks, (void *) &db, INSERT);
  if (*slot == NULL)
367
    {
368
      db_p = XNEW (struct def_blocks_d);
369 370 371 372 373
      db_p->var = var;
      db_p->def_blocks = BITMAP_ALLOC (NULL);
      db_p->phi_blocks = BITMAP_ALLOC (NULL);
      db_p->livein_blocks = BITMAP_ALLOC (NULL);
      *slot = (void *) db_p;
374
    }
375 376
  else
    db_p = (struct def_blocks_d *) *slot;
377

378
  return db_p;
379 380
}

381

382
/* Mark block BB as the definition site for variable VAR.  PHI_P is true if
383
   VAR is defined by a PHI node.  */
384 385

static void
386
set_def_block (tree var, basic_block bb, bool phi_p)
387 388
{
  struct def_blocks_d *db_p;
389 390
  enum need_phi_state state;

391
  state = get_phi_state (var);
392 393 394 395
  db_p = get_def_blocks_for (var);

  /* Set the bit corresponding to the block where VAR is defined.  */
  bitmap_set_bit (db_p->def_blocks, bb->index);
396 397
  if (phi_p)
    bitmap_set_bit (db_p->phi_blocks, bb->index);
398

399
  /* Keep track of whether or not we may need to insert PHI nodes.
400 401 402

     If we are in the UNKNOWN state, then this is the first definition
     of VAR.  Additionally, we have not seen any uses of VAR yet, so
403
     we do not need a PHI node for this variable at this time (i.e.,
404 405 406 407 408 409 410 411
     transition to NEED_PHI_STATE_NO).

     If we are in any other state, then we either have multiple definitions
     of this variable occurring in different blocks or we saw a use of the
     variable which was not dominated by the block containing the
     definition(s).  In this case we may need a PHI node, so enter
     state NEED_PHI_STATE_MAYBE.  */
  if (state == NEED_PHI_STATE_UNKNOWN)
412
    set_phi_state (var, NEED_PHI_STATE_NO);
413
  else
414
    set_phi_state (var, NEED_PHI_STATE_MAYBE);
415 416 417 418 419 420 421 422 423
}


/* Mark block BB as having VAR live at the entry to BB.  */

static void
set_livein_block (tree var, basic_block bb)
{
  struct def_blocks_d *db_p;
424
  enum need_phi_state state = get_phi_state (var);
425 426 427 428 429 430

  db_p = get_def_blocks_for (var);

  /* Set the bit corresponding to the block where VAR is live in.  */
  bitmap_set_bit (db_p->livein_blocks, bb->index);

431
  /* Keep track of whether or not we may need to insert PHI nodes.
432 433 434 435 436 437 438 439 440 441 442 443

     If we reach here in NEED_PHI_STATE_NO, see if this use is dominated
     by the single block containing the definition(s) of this variable.  If
     it is, then we remain in NEED_PHI_STATE_NO, otherwise we transition to
     NEED_PHI_STATE_MAYBE.  */
  if (state == NEED_PHI_STATE_NO)
    {
      int def_block_index = bitmap_first_set_bit (db_p->def_blocks);

      if (def_block_index == -1
	  || ! dominated_by_p (CDI_DOMINATORS, bb,
	                       BASIC_BLOCK (def_block_index)))
444
	set_phi_state (var, NEED_PHI_STATE_MAYBE);
445 446
    }
  else
447
    set_phi_state (var, NEED_PHI_STATE_MAYBE);
448 449 450
}


451
/* Return true if symbol SYM is marked for renaming.  */
452

453 454
static inline bool
symbol_marked_for_renaming (tree sym)
455
{
456
  gcc_assert (DECL_P (sym));
Daniel Berlin committed
457
  return bitmap_bit_p (syms_to_rename, DECL_UID (sym));
458 459 460 461
}


/* Return true if NAME is in OLD_SSA_NAMES.  */
462

463 464 465
static inline bool
is_old_name (tree name)
{
Diego Novillo committed
466 467
  unsigned ver = SSA_NAME_VERSION (name);
  return ver < new_ssa_names->n_bits && TEST_BIT (old_ssa_names, ver);
468 469 470 471
}


/* Return true if NAME is in NEW_SSA_NAMES.  */
472

473 474 475
static inline bool
is_new_name (tree name)
{
Diego Novillo committed
476 477
  unsigned ver = SSA_NAME_VERSION (name);
  return ver < new_ssa_names->n_bits && TEST_BIT (new_ssa_names, ver);
478 479
}

480

481
/* Hashing and equality functions for REPL_TBL.  */
482

483 484
static hashval_t
repl_map_hash (const void *p)
485
{
486 487
  return htab_hash_pointer ((const void *)((const struct repl_map_d *)p)->name);
}
488

489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534
static int
repl_map_eq (const void *p1, const void *p2)
{
  return ((const struct repl_map_d *)p1)->name
	 == ((const struct repl_map_d *)p2)->name;
}

static void
repl_map_free (void *p)
{
  BITMAP_FREE (((struct repl_map_d *)p)->set);
  free (p);
}


/* Return the names replaced by NEW (i.e., REPL_TBL[NEW].SET).  */

static inline bitmap
names_replaced_by (tree new)
{
  struct repl_map_d m;
  void **slot;

  m.name = new;
  slot = htab_find_slot (repl_tbl, (void *) &m, NO_INSERT);

  /* If N was not registered in the replacement table, return NULL.  */
  if (slot == NULL || *slot == NULL)
    return NULL;

  return ((struct repl_map_d *) *slot)->set;
}


/* Add OLD to REPL_TBL[NEW].SET.  */

static inline void
add_to_repl_tbl (tree new, tree old)
{
  struct repl_map_d m, *mp;
  void **slot;

  m.name = new;
  slot = htab_find_slot (repl_tbl, (void *) &m, INSERT);
  if (*slot == NULL)
    {
535
      mp = XNEW (struct repl_map_d);
536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556
      mp->name = new;
      mp->set = BITMAP_ALLOC (NULL);
      *slot = (void *) mp;
    }
  else
    mp = (struct repl_map_d *) *slot;

  bitmap_set_bit (mp->set, SSA_NAME_VERSION (old));
}


/* Add a new mapping NEW -> OLD REPL_TBL.  Every entry N_i in REPL_TBL
   represents the set of names O_1 ... O_j replaced by N_i.  This is
   used by update_ssa and its helpers to introduce new SSA names in an
   already formed SSA web.  */

static void
add_new_name_mapping (tree new, tree old)
{
  timevar_push (TV_TREE_SSA_INCREMENTAL);

Diego Novillo committed
557 558 559
  /* OLD and NEW must be different SSA names for the same symbol.  */
  gcc_assert (new != old && SSA_NAME_VAR (new) == SSA_NAME_VAR (old));

560 561 562 563 564 565 566 567 568
  /* We may need to grow NEW_SSA_NAMES and OLD_SSA_NAMES because our
     caller may have created new names since the set was created.  */
  if (new_ssa_names->n_bits <= num_ssa_names - 1)
    {
      unsigned int new_sz = num_ssa_names + NAME_SETS_GROWTH_FACTOR;
      new_ssa_names = sbitmap_resize (new_ssa_names, new_sz, 0);
      old_ssa_names = sbitmap_resize (old_ssa_names, new_sz, 0);
    }

Diego Novillo committed
569 570
  /* If this mapping is for virtual names, we will need to update
     virtual operands.  */
571 572 573
  if (!is_gimple_reg (new))
    {
      tree sym;
Diego Novillo committed
574
      size_t uid;
575

Diego Novillo committed
576
      need_to_update_vops_p = true;
577

Diego Novillo committed
578 579 580 581 582 583 584
      /* Keep counts of virtual mappings and symbols to use in the
	 virtual mapping heuristic.  If we have large numbers of
	 virtual mappings for a relatively low number of symbols, it
	 will make more sense to rename the symbols from scratch.
	 Otherwise, the insertion of PHI nodes for each of the old
	 names in these mappings will be very slow.  */
      sym = SSA_NAME_VAR (new);
Daniel Berlin committed
585
      uid = DECL_UID (sym);
Diego Novillo committed
586 587
      update_ssa_stats.num_virtual_mappings++;
      if (!bitmap_bit_p (update_ssa_stats.virtual_symbols, uid))
588
	{
Diego Novillo committed
589 590
	  bitmap_set_bit (update_ssa_stats.virtual_symbols, uid);
	  update_ssa_stats.num_virtual_symbols++;
591 592 593 594 595
	}
    }

  /* Update the REPL_TBL table.  */
  add_to_repl_tbl (new, old);
596

597 598 599 600 601 602 603 604 605 606
  /* If OLD had already been registered as a new name, then all the
     names that OLD replaces should also be replaced by NEW.  */
  if (is_new_name (old))
    bitmap_ior_into (names_replaced_by (new), names_replaced_by (old));

  /* Register NEW and OLD in NEW_SSA_NAMES and OLD_SSA_NAMES,
     respectively.  */
  SET_BIT (new_ssa_names, SSA_NAME_VERSION (new));
  SET_BIT (old_ssa_names, SSA_NAME_VERSION (old));

Diego Novillo committed
607 608
  /* Update mapping counter to use in the virtual mapping heuristic.  */
  update_ssa_stats.num_total_mappings++;
609 610

  timevar_pop (TV_TREE_SSA_INCREMENTAL);
611
}
612 613


614 615 616
/* Call back for walk_dominator_tree used to collect definition sites
   for every variable in the function.  For every statement S in block
   BB:
617

618
   1- Variables defined by S in the DEFS of S are marked in the bitmap
619
      WALK_DATA->GLOBAL_DATA->KILLS.
620

621
   2- If S uses a variable VAR and there is no preceding kill of VAR,
622
      then it is marked in the LIVEIN_BLOCKS bitmap associated with VAR.
623

624 625 626
   This information is used to determine which variables are live
   across block boundaries to reduce the number of PHI nodes
   we create.  */
627

628 629 630 631 632
static void
mark_def_sites (struct dom_walk_data *walk_data,
		basic_block bb,
		block_stmt_iterator bsi)
{
633 634
  struct mark_def_sites_global_data *gd =
     (struct mark_def_sites_global_data *) walk_data->global_data;
635 636 637 638 639 640 641
  bitmap kills = gd->kills;
  tree stmt, def;
  use_operand_p use_p;
  def_operand_p def_p;
  ssa_op_iter iter;

  stmt = bsi_stmt (bsi);
642
  update_stmt_if_modified (stmt);
643

644
  REGISTER_DEFS_IN_THIS_STMT (stmt) = 0;
645 646 647 648 649
  REWRITE_THIS_STMT (stmt) = 0;

  /* If a variable is used before being set, then the variable is live
     across a block boundary, so mark it live-on-entry to BB.  */
  FOR_EACH_SSA_USE_OPERAND (use_p, stmt, iter,
650
			    SSA_OP_USE | SSA_OP_VUSE | SSA_OP_VMUSTKILL)
651
    {
652 653
      tree sym = USE_FROM_PTR (use_p);
      gcc_assert (DECL_P (sym));
Daniel Berlin committed
654
      if (!bitmap_bit_p (kills, DECL_UID (sym)))
655 656
	set_livein_block (sym, bb);
      REWRITE_THIS_STMT (stmt) = 1;
657 658 659 660 661 662 663 664 665
    }
  
  /* Note that virtual definitions are irrelevant for computing KILLS
     because a V_MAY_DEF does not constitute a killing definition of the
     variable.  However, the operand of a virtual definitions is a use
     of the variable, so it may cause the variable to be considered
     live-on-entry.  */
  FOR_EACH_SSA_MAYDEF_OPERAND (def_p, use_p, stmt, iter)
    {
666 667 668 669 670 671
      tree sym = USE_FROM_PTR (use_p);
      gcc_assert (DECL_P (sym));
      set_livein_block (sym, bb);
      set_def_block (sym, bb, false);
      REGISTER_DEFS_IN_THIS_STMT (stmt) = 1;
      REWRITE_THIS_STMT (stmt) = 1;
672 673 674 675 676
    }

  /* Now process the defs and must-defs made by this statement.  */
  FOR_EACH_SSA_TREE_OPERAND (def, stmt, iter, SSA_OP_DEF | SSA_OP_VMUSTDEF)
    {
677 678
      gcc_assert (DECL_P (def));
      set_def_block (def, bb, false);
Daniel Berlin committed
679
      bitmap_set_bit (kills, DECL_UID (def));
680
      REGISTER_DEFS_IN_THIS_STMT (stmt) = 1;
681
    }
682 683 684 685 686

  /* If we found the statement interesting then also mark the block BB
     as interesting.  */
  if (REWRITE_THIS_STMT (stmt) || REGISTER_DEFS_IN_THIS_STMT (stmt))
    SET_BIT (gd->interesting_blocks, bb->index);
687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703
}


/* Given a set of blocks with variable definitions (DEF_BLOCKS),
   return a bitmap with all the blocks in the iterated dominance
   frontier of the blocks in DEF_BLOCKS.  DFS contains dominance
   frontier information as returned by compute_dominance_frontiers.
   
   The resulting set of blocks are the potential sites where PHI nodes
   are needed.  The caller is responsible from freeing the memory
   allocated for the return value.  */

static bitmap
find_idf (bitmap def_blocks, bitmap *dfs)
{
  bitmap_iterator bi;
  unsigned bb_index;
704
  VEC(int,heap) *work_stack;
705 706
  bitmap phi_insertion_points;

707
  work_stack = VEC_alloc (int, heap, n_basic_blocks);
708 709 710 711
  phi_insertion_points = BITMAP_ALLOC (NULL);

  /* Seed the work list with all the blocks in DEF_BLOCKS.  */
  EXECUTE_IF_SET_IN_BITMAP (def_blocks, 0, bb_index, bi)
712 713 714 715 716
    /* We use VEC_quick_push here for speed.  This is safe because we
       know that the number of definition blocks is no greater than
       the number of basic blocks, which is the initial capacity of
       WORK_STACK.  */
    VEC_quick_push (int, work_stack, bb_index);
717 718 719 720 721 722

  /* Pop a block off the worklist, add every block that appears in
     the original block's DF that we have not already processed to
     the worklist.  Iterate until the worklist is empty.   Blocks
     which are added to the worklist are potential sites for
     PHI nodes.  */
723
  while (VEC_length (int, work_stack) > 0)
724
    {
725
      bb_index = VEC_pop (int, work_stack);
726 727 728 729 730 731 732 733

      /* Since the registration of NEW -> OLD name mappings is done
	 separately from the call to update_ssa, when updating the SSA
	 form, the basic blocks where new and/or old names are defined
	 may have disappeared by CFG cleanup calls.  In this case,
	 we may pull a non-existing block from the work stack.  */
      gcc_assert (bb_index < (unsigned) last_basic_block);

734
      EXECUTE_IF_AND_COMPL_IN_BITMAP (dfs[bb_index], phi_insertion_points,
735
	                              0, bb_index, bi)
736 737 738 739
	{
	  /* Use a safe push because if there is a definition of VAR
	     in every basic block, then WORK_STACK may eventually have
	     more than N_BASIC_BLOCK entries.  */
740
	  VEC_safe_push (int, heap, work_stack, bb_index);
741 742 743 744
	  bitmap_set_bit (phi_insertion_points, bb_index);
	}
    }

745
  VEC_free (int, heap, work_stack);
746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763

  return phi_insertion_points;
}


/* Return the set of blocks where variable VAR is defined and the blocks
   where VAR is live on entry (livein).  Return NULL, if no entry is
   found in DEF_BLOCKS.  */

static inline struct def_blocks_d *
find_def_blocks_for (tree var)
{
  struct def_blocks_d dm;
  dm.var = var;
  return (struct def_blocks_d *) htab_find (def_blocks, &dm);
}


764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780
/* Retrieve or create a default definition for symbol SYM.  */

static inline tree
get_default_def_for (tree sym)
{
  tree ddef = default_def (sym);

  if (ddef == NULL_TREE)
    {
      ddef = make_ssa_name (sym, build_empty_stmt ());
      set_default_def (sym, ddef);
    }

  return ddef;
}


781
/* Insert PHI nodes for variable VAR using the iterated dominance
782 783 784 785 786 787 788 789 790
   frontier given in PHI_INSERTION_POINTS.  If UPDATE_P is true, this
   function assumes that the caller is incrementally updating the SSA
   form, in which case (1) VAR is assumed to be an SSA name, (2) a new
   SSA name is created for VAR's symbol, and, (3) all the arguments
   for the newly created PHI node are set to VAR.

   PHI_INSERTION_POINTS is updated to reflect nodes that already had a
   PHI node for VAR.  On exit, only the nodes that received a PHI node
   for VAR will be present in PHI_INSERTION_POINTS.  */
791 792

static void
793
insert_phi_nodes_for (tree var, bitmap phi_insertion_points, bool update_p)
794 795 796 797 798 799 800 801 802
{
  unsigned bb_index;
  edge e;
  tree phi;
  basic_block bb;
  bitmap_iterator bi;
  struct def_blocks_d *def_map;

  def_map = find_def_blocks_for (var);
803
  gcc_assert (def_map);
804 805 806 807 808 809 810 811 812 813 814 815 816 817

  /* Remove the blocks where we already have PHI nodes for VAR.  */
  bitmap_and_compl_into (phi_insertion_points, def_map->phi_blocks);

  /* Now compute global livein for this variable.  Note this modifies
     def_map->livein_blocks.  */
  compute_global_livein (def_map->livein_blocks, def_map->def_blocks);

  /* And insert the PHI nodes.  */
  EXECUTE_IF_AND_IN_BITMAP (phi_insertion_points, def_map->livein_blocks,
			    0, bb_index, bi)
    {
      bb = BASIC_BLOCK (bb_index);

Diego Novillo committed
818
      if (update_p && TREE_CODE (var) == SSA_NAME)
819
	{
Diego Novillo committed
820 821 822 823
	  /* If we are rewriting SSA names, create the LHS of the PHI
	     node by duplicating VAR.  This is useful in the case of
	     pointers, to also duplicate pointer attributes (alias
	     information, in particular).  */
824
	  edge_iterator ei;
Diego Novillo committed
825
	  tree new_lhs;
826

Diego Novillo committed
827 828 829 830
	  phi = create_phi_node (var, bb);
	  new_lhs = duplicate_ssa_name (var, phi);
	  SET_PHI_RESULT (phi, new_lhs);
	  add_new_name_mapping (new_lhs, var);
831 832 833 834 835 836 837

	  /* Add VAR to every argument slot of PHI.  We need VAR in
	     every argument so that rewrite_update_phi_arguments knows
	     which name is this PHI node replacing.  If VAR is a
	     symbol marked for renaming, this is not necessary, the
	     renamer will use the symbol on the LHS to get its
	     reaching definition.  */
838 839 840
	  FOR_EACH_EDGE (e, ei, bb->preds)
	    add_phi_arg (phi, var, e);
	}
Diego Novillo committed
841 842 843 844 845
      else
	{
	  tree sym = DECL_P (var) ? var : SSA_NAME_VAR (var);
	  phi = create_phi_node (sym, bb);
	}
846 847 848 849

      /* Mark this PHI node as interesting for update_ssa.  */
      REGISTER_DEFS_IN_THIS_STMT (phi) = 1;
      REWRITE_THIS_STMT (phi) = 1;
850 851 852 853 854 855 856 857 858
    }
}


/* Insert PHI nodes at the dominance frontier of blocks with variable
   definitions.  DFS contains the dominance frontier information for
   the flowgraph.  PHI nodes will only be inserted at the dominance
   frontier of definition blocks for variables whose NEED_PHI_STATE
   annotation is marked as ``maybe'' or ``unknown'' (computed by
Diego Novillo committed
859
   mark_def_sites).  */
860 861

static void
Diego Novillo committed
862
insert_phi_nodes (bitmap *dfs)
863
{
Daniel Berlin committed
864 865
  referenced_var_iterator rvi;
  tree var;
866 867

  timevar_push (TV_TREE_INSERT_PHI_NODES);
Daniel Berlin committed
868 869
  
  FOR_EACH_REFERENCED_VAR (var, rvi)
870
    {
Diego Novillo committed
871 872
      struct def_blocks_d *def_map;
      bitmap idf;
873

Diego Novillo committed
874 875 876 877 878 879 880 881 882 883
      def_map = find_def_blocks_for (var);
      if (def_map == NULL)
	continue;

      if (get_phi_state (var) != NEED_PHI_STATE_NO)
	{
	  idf = find_idf (def_map->def_blocks, dfs);
	  insert_phi_nodes_for (var, idf, false);
	  BITMAP_FREE (idf);
	}
884
    }
885

886 887 888 889
  timevar_pop (TV_TREE_INSERT_PHI_NODES);
}


890 891
/* Register DEF (an SSA_NAME) to be a new definition for its underlying
   variable (SSA_NAME_VAR (DEF)) and push VAR's current reaching definition
892
   into the stack pointed to by BLOCK_DEFS_P.  */
893 894

void
895
register_new_def (tree def, VEC(tree,heap) **block_defs_p)
896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920
{
  tree var = SSA_NAME_VAR (def);
  tree currdef;
   
  /* If this variable is set in a single basic block and all uses are
     dominated by the set(s) in that single basic block, then there is
     no reason to record anything for this variable in the block local
     definition stacks.  Doing so just wastes time and memory.

     This is the same test to prune the set of variables which may
     need PHI nodes.  So we just use that information since it's already
     computed and available for us to use.  */
  if (get_phi_state (var) == NEED_PHI_STATE_NO)
    {
      set_current_def (var, def);
      return;
    }

  currdef = get_current_def (var);

  /* Push the current reaching definition into *BLOCK_DEFS_P.  This stack is
     later used by the dominator tree callbacks to restore the reaching
     definitions for all the variables defined in the block after a recursive
     visit to all its immediately dominated blocks.  If there is no current
     reaching definition, then just record the underlying _DECL node.  */
921
  VEC_safe_push (tree, heap, *block_defs_p, currdef ? currdef : var);
922 923 924 925 926 927

  /* Set the current reaching definition for VAR to be DEF.  */
  set_current_def (var, def);
}


928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956
/* Perform a depth-first traversal of the dominator tree looking for
   variables to rename.  BB is the block where to start searching.
   Renaming is a five step process:

   1- Every definition made by PHI nodes at the start of the blocks is
      registered as the current definition for the corresponding variable.

   2- Every statement in BB is rewritten.  USE and VUSE operands are
      rewritten with their corresponding reaching definition.  DEF and
      VDEF targets are registered as new definitions.
      
   3- All the PHI nodes in successor blocks of BB are visited.  The
      argument corresponding to BB is replaced with its current reaching
      definition.

   4- Recursively rewrite every dominator child block of BB.

   5- Restore (in reverse order) the current reaching definition for every
      new definition introduced in this block.  This is done so that when
      we return from the recursive call, all the current reaching
      definitions are restored to the names that were valid in the
      dominator parent of BB.  */

/* SSA Rewriting Step 1.  Initialization, create a block local stack
   of reaching definitions for new SSA names produced in this block
   (BLOCK_DEFS).  Register new definitions for every PHI node in the
   block.  */

static void
957 958
rewrite_initialize_block (struct dom_walk_data *walk_data ATTRIBUTE_UNUSED,
			  basic_block bb)
959 960 961 962 963 964
{
  tree phi;

  if (dump_file && (dump_flags & TDF_DETAILS))
    fprintf (dump_file, "\n\nRenaming block #%d\n\n", bb->index);

965
  /* Mark the unwind point for this block.  */
966
  VEC_safe_push (tree, heap, block_defs_stack, NULL_TREE);
967

968 969 970
  /* Step 1.  Register new definitions for every PHI node in the block.
     Conceptually, all the PHI nodes are executed in parallel and each PHI
     node introduces a new version for the associated variable.  */
971
  for (phi = phi_nodes (bb); phi; phi = PHI_CHAIN (phi))
972 973
    {
      tree result = PHI_RESULT (phi);
974
      register_new_def (result, &block_defs_stack);
975 976 977
    }
}

978

979 980 981 982 983
/* Return the current definition for variable VAR.  If none is found,
   create a new SSA name to act as the zeroth definition for VAR.  If VAR
   is call clobbered and there exists a more recent definition of
   GLOBAL_VAR, return the definition for GLOBAL_VAR.  This means that VAR
   has been clobbered by a function call since its last assignment.  */
984

985 986 987
static tree
get_reaching_def (tree var)
{
988
  tree currdef_var, avar;
989 990 991
  
  /* Lookup the current reaching definition for VAR.  */
  currdef_var = get_current_def (var);
992

993 994 995 996
  /* If there is no reaching definition for VAR, create and register a
     default definition for it (if needed).  */
  if (currdef_var == NULL_TREE)
    {
997 998 999
      avar = DECL_P (var) ? var : SSA_NAME_VAR (var);
      currdef_var = get_default_def_for (avar);
      set_current_def (var, currdef_var);
1000 1001 1002 1003
    }

  /* Return the current reaching definition for VAR, or the default
     definition, if we had to create one.  */
1004
  return currdef_var;
1005 1006 1007 1008 1009 1010
}


/* SSA Rewriting Step 2.  Rewrite every variable used in each statement in
   the block with its immediate reaching definitions.  Update the current
   definition of a variable when a new real or virtual definition is found.  */
1011 1012

static void
1013 1014 1015
rewrite_stmt (struct dom_walk_data *walk_data ATTRIBUTE_UNUSED,
	      basic_block bb ATTRIBUTE_UNUSED,
	      block_stmt_iterator si)
1016
{
1017 1018 1019 1020 1021 1022 1023 1024 1025
  tree stmt;
  use_operand_p use_p;
  def_operand_p def_p;
  ssa_op_iter iter;

  stmt = bsi_stmt (si);

  /* If mark_def_sites decided that we don't need to rewrite this
     statement, ignore it.  */
1026
  if (!REWRITE_THIS_STMT (stmt) && !REGISTER_DEFS_IN_THIS_STMT (stmt))
1027
    return;
1028 1029

  if (dump_file && (dump_flags & TDF_DETAILS))
1030 1031 1032 1033 1034
    {
      fprintf (dump_file, "Renaming statement ");
      print_generic_stmt (dump_file, stmt, TDF_SLIM);
      fprintf (dump_file, "\n");
    }
1035

1036
  /* Step 1.  Rewrite USES and VUSES in the statement.  */
1037 1038 1039 1040 1041 1042 1043 1044
  if (REWRITE_THIS_STMT (stmt))
    FOR_EACH_SSA_USE_OPERAND (use_p, stmt, iter,
	                      SSA_OP_ALL_USES|SSA_OP_ALL_KILLS)
      {
	tree var = USE_FROM_PTR (use_p);
	gcc_assert (DECL_P (var));
	SET_USE (use_p, get_reaching_def (var));
      }
1045

1046
  /* Step 2.  Register the statement's DEF and VDEF operands.  */
1047 1048 1049 1050 1051 1052 1053 1054
  if (REGISTER_DEFS_IN_THIS_STMT (stmt))
    FOR_EACH_SSA_DEF_OPERAND (def_p, stmt, iter, SSA_OP_ALL_DEFS)
      {
	tree var = DEF_FROM_PTR (def_p);
	gcc_assert (DECL_P (var));
	SET_DEF (def_p, make_ssa_name (var, stmt));
	register_new_def (DEF_FROM_PTR (def_p), &block_defs_stack);
      }
1055
}
1056

1057

1058 1059 1060
/* SSA Rewriting Step 3.  Visit all the successor blocks of BB looking for
   PHI nodes.  For every PHI node found, add a new argument containing the
   current reaching definition for the variable and the edge through which
1061
   that definition is reaching the PHI node.  */
1062 1063 1064 1065 1066 1067

static void
rewrite_add_phi_arguments (struct dom_walk_data *walk_data ATTRIBUTE_UNUSED,
			   basic_block bb)
{
  edge e;
1068
  edge_iterator ei;
1069

1070
  FOR_EACH_EDGE (e, ei, bb->succs)
1071 1072 1073
    {
      tree phi;

1074
      for (phi = phi_nodes (e->dest); phi; phi = PHI_CHAIN (phi))
1075 1076 1077
	{
	  tree currdef;
	  currdef = get_reaching_def (SSA_NAME_VAR (PHI_RESULT (phi)));
1078
	  add_phi_arg (phi, currdef, e);
1079 1080 1081 1082
	}
    }
}

1083 1084 1085

/* Called after visiting basic block BB.  Restore CURRDEFS to its
   original value.  */
1086 1087

static void
1088
rewrite_finalize_block (struct dom_walk_data *walk_data ATTRIBUTE_UNUSED,
1089 1090
			basic_block bb ATTRIBUTE_UNUSED)
{
1091
  /* Restore CURRDEFS to its original state.  */
1092
  while (VEC_length (tree, block_defs_stack) > 0)
1093
    {
1094
      tree tmp = VEC_pop (tree, block_defs_stack);
1095 1096
      tree saved_def, var;

1097 1098 1099 1100 1101 1102 1103
      if (tmp == NULL_TREE)
	break;

      /* If we recorded an SSA_NAME, then make the SSA_NAME the current
	 definition of its underlying variable.  If we recorded anything
	 else, it must have been an _DECL node and its current reaching
	 definition must have been NULL.  */
1104 1105 1106 1107 1108 1109 1110 1111 1112 1113
      if (TREE_CODE (tmp) == SSA_NAME)
	{
	  saved_def = tmp;
	  var = SSA_NAME_VAR (saved_def);
	}
      else
	{
	  saved_def = NULL;
	  var = tmp;
	}
1114
                                                                                
1115
      set_current_def (var, saved_def);
1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126
    }
}


/* Dump SSA information to FILE.  */

void
dump_tree_ssa (FILE *file)
{
  basic_block bb;
  const char *funcname
1127
    = lang_hooks.decl_printable_name (current_function_decl, 2);
1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149

  fprintf (file, "SSA information for %s\n\n", funcname);

  FOR_EACH_BB (bb)
    {
      dump_bb (bb, file, 0);
      fputs ("    ", file);
      print_generic_stmt (file, phi_nodes (bb), dump_flags);
      fputs ("\n\n", file);
    }
}


/* Dump SSA information to stderr.  */

void
debug_tree_ssa (void)
{
  dump_tree_ssa (stderr);
}


1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161
/* Dump statistics for the hash table HTAB.  */

static void
htab_statistics (FILE *file, htab_t htab)
{
  fprintf (file, "size %ld, %ld elements, %f collision/search ratio\n",
	   (long) htab_size (htab),
	   (long) htab_elements (htab),
	   htab_collisions (htab));
}


1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184
/* Dump SSA statistics on FILE.  */

void
dump_tree_ssa_stats (FILE *file)
{
  fprintf (file, "\nHash table statistics:\n");

  fprintf (file, "    def_blocks: ");
  htab_statistics (file, def_blocks);

  fprintf (file, "\n");
}


/* Dump SSA statistics on stderr.  */

void
debug_tree_ssa_stats (void)
{
  dump_tree_ssa_stats (stderr);
}


1185
/* Hashing and equality functions for DEF_BLOCKS.  */
1186

1187 1188
static hashval_t
def_blocks_hash (const void *p)
1189
{
1190 1191 1192 1193 1194 1195 1196 1197 1198
  return htab_hash_pointer
	((const void *)((const struct def_blocks_d *)p)->var);
}

static int
def_blocks_eq (const void *p1, const void *p2)
{
  return ((const struct def_blocks_d *)p1)->var
	 == ((const struct def_blocks_d *)p2)->var;
1199 1200 1201
}


1202
/* Free memory allocated by one entry in DEF_BLOCKS.  */
1203 1204

static void
1205
def_blocks_free (void *p)
1206
{
1207
  struct def_blocks_d *entry = (struct def_blocks_d *) p;
1208 1209 1210 1211 1212
  BITMAP_FREE (entry->def_blocks);
  BITMAP_FREE (entry->phi_blocks);
  BITMAP_FREE (entry->livein_blocks);
  free (entry);
}
1213 1214


1215
/* Callback for htab_traverse to dump the DEF_BLOCKS hash table.  */
1216

1217 1218 1219 1220 1221 1222 1223 1224 1225
static int
debug_def_blocks_r (void **slot, void *data ATTRIBUTE_UNUSED)
{
  struct def_blocks_d *db_p = (struct def_blocks_d *) *slot;
  
  fprintf (stderr, "VAR: ");
  print_generic_expr (stderr, db_p->var, dump_flags);
  bitmap_print (stderr, db_p->def_blocks, ", DEF_BLOCKS: { ", "}");
  bitmap_print (stderr, db_p->livein_blocks, ", LIVEIN_BLOCKS: { ", "}\n");
1226

1227 1228
  return 1;
}
1229 1230


1231
/* Dump the DEF_BLOCKS hash table on stderr.  */
1232

1233 1234 1235 1236 1237
void
debug_def_blocks (void)
{
  htab_traverse (def_blocks, debug_def_blocks_r, NULL);
}
1238

1239

1240
/* Register NEW_NAME to be the new reaching definition for OLD_NAME.  */
1241

1242 1243 1244 1245
static inline void
register_new_update_single (tree new_name, tree old_name)
{
  tree currdef = get_current_def (old_name);
1246

1247 1248 1249 1250 1251
  /* Push the current reaching definition into *BLOCK_DEFS_P.
     This stack is later used by the dominator tree callbacks to
     restore the reaching definitions for all the variables
     defined in the block after a recursive visit to all its
     immediately dominated blocks.  */
1252 1253 1254
  VEC_reserve (tree, heap, block_defs_stack, 2);
  VEC_quick_push (tree, block_defs_stack, currdef);
  VEC_quick_push (tree, block_defs_stack, old_name);
1255

1256 1257 1258 1259
  /* Set the current reaching definition for OLD_NAME to be
     NEW_NAME.  */
  set_current_def (old_name, new_name);
}
1260

1261

1262 1263 1264
/* Register NEW_NAME to be the new reaching definition for all the
   names in OLD_NAMES.  Used by the incremental SSA update routines to
   replace old SSA names with new ones.  */
1265

1266 1267 1268 1269 1270
static inline void
register_new_update_set (tree new_name, bitmap old_names)
{
  bitmap_iterator bi;
  unsigned i;
1271

1272 1273
  EXECUTE_IF_SET_IN_BITMAP (old_names, 0, i, bi)
    register_new_update_single (new_name, ssa_name (i));
1274 1275
}

1276

1277 1278 1279 1280
/* Initialization of block data structures for the incremental SSA
   update pass.  Create a block local stack of reaching definitions
   for new SSA names produced in this block (BLOCK_DEFS).  Register
   new definitions for every PHI node in the block.  */
1281 1282

static void
1283 1284
rewrite_update_init_block (struct dom_walk_data *walk_data ATTRIBUTE_UNUSED,
		           basic_block bb)
1285
{
1286 1287 1288 1289
  edge e;
  edge_iterator ei;
  tree phi;
  bool is_abnormal_phi;
1290

1291 1292 1293
  if (dump_file && (dump_flags & TDF_DETAILS))
    fprintf (dump_file, "\n\nRegistering new PHI nodes in block #%d\n\n",
	     bb->index);
1294

1295
  /* Mark the unwind point for this block.  */
1296
  VEC_safe_push (tree, heap, block_defs_stack, NULL_TREE);
1297

1298 1299 1300 1301 1302 1303 1304 1305 1306
  /* Mark the LHS if any of the arguments flows through an abnormal
     edge.  */
  is_abnormal_phi = false;
  FOR_EACH_EDGE (e, ei, bb->preds)
    if (e->flags & EDGE_ABNORMAL)
      {
	is_abnormal_phi = true;
	break;
      }
1307

1308 1309 1310 1311 1312 1313
  /* If any of the PHI nodes is a replacement for a name in
     OLD_SSA_NAMES or it's one of the names in NEW_SSA_NAMES, then
     register it as a new definition for its corresponding name.  Also
     register definitions for names whose underlying symbols are
     marked for renaming.  */
  for (phi = phi_nodes (bb); phi; phi = PHI_CHAIN (phi))
1314
    {
1315
      tree lhs, lhs_sym;
1316

1317 1318 1319 1320 1321
      if (!REGISTER_DEFS_IN_THIS_STMT (phi))
	continue;
      
      lhs = PHI_RESULT (phi);
      lhs_sym = SSA_NAME_VAR (lhs);
1322

1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340
      if (symbol_marked_for_renaming (lhs_sym))
	register_new_update_single (lhs, lhs_sym);
      else
	{
	  /* If LHS is a new name, register a new definition for all
	     the names replaced by LHS.  */
	  if (is_new_name (lhs))
	    register_new_update_set (lhs, names_replaced_by (lhs));
	  
	  /* If LHS is an OLD name, register it as a new definition
	     for itself.  */
	  if (is_old_name (lhs))
	    register_new_update_single (lhs, lhs);
	}

      if (is_abnormal_phi)
	SSA_NAME_OCCURS_IN_ABNORMAL_PHI (lhs) = 1;
    }
1341 1342
}

1343

1344 1345 1346 1347 1348 1349 1350 1351 1352 1353
/* Called after visiting block BB.  Unwind BLOCK_DEFS_STACK to restore
   the current reaching definition of every name re-written in BB to
   the original reaching definition before visiting BB.  This
   unwinding must be done in the opposite order to what is done in
   register_new_update_set.  */

static void
rewrite_update_fini_block (struct dom_walk_data *walk_data ATTRIBUTE_UNUSED,
			   basic_block bb ATTRIBUTE_UNUSED)
{
1354
  while (VEC_length (tree, block_defs_stack) > 0)
1355
    {
1356
      tree var = VEC_pop (tree, block_defs_stack);
1357 1358 1359 1360 1361 1362 1363
      tree saved_def;
      
      /* NULL indicates the unwind stop point for this block (see
	 rewrite_update_init_block).  */
      if (var == NULL)
	return;

1364
      saved_def = VEC_pop (tree, block_defs_stack);
1365 1366 1367 1368 1369
      set_current_def (var, saved_def);
    }
}


Diego Novillo committed
1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428
/* If the operand pointed to by USE_P is a name in OLD_SSA_NAMES or
   it is a symbol marked for renaming, replace it with USE_P's current
   reaching definition.  */

static inline void
maybe_replace_use (use_operand_p use_p)
{
  tree rdef = NULL_TREE;
  tree use = USE_FROM_PTR (use_p);
  tree sym = DECL_P (use) ? use : SSA_NAME_VAR (use);

  if (symbol_marked_for_renaming (sym))
    rdef = get_reaching_def (sym);
  else if (is_old_name (use))
    rdef = get_reaching_def (use);

  if (rdef && rdef != use)
    SET_USE (use_p, rdef);
}


/* If the operand pointed to by DEF_P is an SSA name in NEW_SSA_NAMES
   or OLD_SSA_NAMES, or if it is a symbol marked for renaming,
   register it as the current definition for the names replaced by
   DEF_P.  */

static inline void
maybe_register_def (def_operand_p def_p, tree stmt)
{
  tree def = DEF_FROM_PTR (def_p);
  tree sym = DECL_P (def) ? def : SSA_NAME_VAR (def);

  /* If DEF is a naked symbol that needs renaming, create a
     new name for it.  */
  if (symbol_marked_for_renaming (sym))
    {
      if (DECL_P (def))
	{
	  def = make_ssa_name (def, stmt);
	  SET_DEF (def_p, def);
	}

      register_new_update_single (def, sym);
    }
  else
    {
      /* If DEF is a new name, register it as a new definition
	 for all the names replaced by DEF.  */
      if (is_new_name (def))
	register_new_update_set (def, names_replaced_by (def));

      /* If DEF is an old name, register DEF as a new
	 definition for itself.  */
      if (is_old_name (def))
	register_new_update_single (def, def);
    }
}


1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465
/* Update every variable used in the statement pointed-to by SI.  The
   statement is assumed to be in SSA form already.  Names in
   OLD_SSA_NAMES used by SI will be updated to their current reaching
   definition.  Names in OLD_SSA_NAMES or NEW_SSA_NAMES defined by SI
   will be registered as a new definition for their corresponding name
   in OLD_SSA_NAMES.  */

static void
rewrite_update_stmt (struct dom_walk_data *walk_data ATTRIBUTE_UNUSED,
		     basic_block bb ATTRIBUTE_UNUSED,
		     block_stmt_iterator si)
{
  stmt_ann_t ann;
  tree stmt;
  use_operand_p use_p;
  def_operand_p def_p;
  ssa_op_iter iter;

  stmt = bsi_stmt (si);
  ann = stmt_ann (stmt);

  /* Only update marked statements.  */
  if (!REWRITE_THIS_STMT (stmt) && !REGISTER_DEFS_IN_THIS_STMT (stmt))
    return;

  if (dump_file && (dump_flags & TDF_DETAILS))
    {
      fprintf (dump_file, "Updating SSA information for statement ");
      print_generic_stmt (dump_file, stmt, TDF_SLIM);
      fprintf (dump_file, "\n");
    }

  /* Rewrite USES included in OLD_SSA_NAMES and USES whose underlying
     symbol is marked for renaming.  */
  if (REWRITE_THIS_STMT (stmt))
    {
      FOR_EACH_SSA_USE_OPERAND (use_p, stmt, iter, SSA_OP_USE)
Diego Novillo committed
1466
	maybe_replace_use (use_p);
1467 1468 1469 1470

      if (need_to_update_vops_p)
	FOR_EACH_SSA_USE_OPERAND (use_p, stmt, iter,
				  SSA_OP_VIRTUAL_USES | SSA_OP_VIRTUAL_KILLS)
Diego Novillo committed
1471
	  maybe_replace_use (use_p);
1472 1473 1474 1475 1476 1477 1478 1479
    }

  /* Register definitions of names in NEW_SSA_NAMES and OLD_SSA_NAMES.
     Also register definitions for names whose underlying symbol is
     marked for renaming.  */
  if (REGISTER_DEFS_IN_THIS_STMT (stmt))
    {
      FOR_EACH_SSA_DEF_OPERAND (def_p, stmt, iter, SSA_OP_DEF)
Diego Novillo committed
1480
	maybe_register_def (def_p, stmt);
1481 1482 1483

      if (need_to_update_vops_p)
	FOR_EACH_SSA_DEF_OPERAND (def_p, stmt, iter, SSA_OP_VIRTUAL_DEFS)
Diego Novillo committed
1484
	  maybe_register_def (def_p, stmt);
1485 1486 1487 1488
    }
}


1489
/* Replace the operand pointed to by USE_P with USE's current reaching
Diego Novillo committed
1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500
   definition.  */

static inline void
replace_use (use_operand_p use_p, tree use)
{
  tree rdef = get_reaching_def (use);
  if (rdef != use)
    SET_USE (use_p, rdef);
}


1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609
/* Visit all the successor blocks of BB looking for PHI nodes.  For
   every PHI node found, check if any of its arguments is in
   OLD_SSA_NAMES.  If so, and if the argument has a current reaching
   definition, replace it.  */

static void
rewrite_update_phi_arguments (struct dom_walk_data *walk_data ATTRIBUTE_UNUSED,
			      basic_block bb)
{
  edge e;
  edge_iterator ei;

  FOR_EACH_EDGE (e, ei, bb->succs)
    {
      tree phi;

      for (phi = phi_nodes (e->dest); phi; phi = PHI_CHAIN (phi))
	{
	  tree arg;
	  use_operand_p arg_p;

	  /* Skip PHI nodes that are not marked for rewrite.  */
	  if (!REWRITE_THIS_STMT (phi))
	    continue;

	  arg_p = PHI_ARG_DEF_PTR_FROM_EDGE (phi, e);
	  arg = USE_FROM_PTR (arg_p);

	  if (arg && !DECL_P (arg) && TREE_CODE (arg) != SSA_NAME)
	    continue;

	  if (arg == NULL_TREE)
	    {
	      /* When updating a PHI node for a recently introduced
		 symbol we may find NULL arguments.  That's why we
		 take the symbol from the LHS of the PHI node.  */
	      replace_use (arg_p, SSA_NAME_VAR (PHI_RESULT (phi)));
	    }
	  else
	    {
	      tree sym = DECL_P (arg) ? arg : SSA_NAME_VAR (arg);

	      if (symbol_marked_for_renaming (sym))
		replace_use (arg_p, sym);
	      else if (is_old_name (arg))
		replace_use (arg_p, arg);
	    }

	  if (e->flags & EDGE_ABNORMAL)
	    SSA_NAME_OCCURS_IN_ABNORMAL_PHI (USE_FROM_PTR (arg_p)) = 1;
	}
    }
}


/* Rewrite the actual blocks, statements, and PHI arguments, to be in SSA
   form.  

   ENTRY indicates the block where to start.  Every block dominated by
      ENTRY will be rewritten.

   WHAT indicates what actions will be taken by the renamer (see enum
      rewrite_mode).

   BLOCKS are the set of interesting blocks for the dominator walker
      to process.  If this set is NULL, then all the nodes dominated
      by ENTRY are walked.  Otherwise, blocks dominated by ENTRY that
      are not present in BLOCKS are ignored.  */

static void
rewrite_blocks (basic_block entry, enum rewrite_mode what, sbitmap blocks)
{
  struct dom_walk_data walk_data;
  
  /* Rewrite all the basic blocks in the program.  */
  timevar_push (TV_TREE_SSA_REWRITE_BLOCKS);

  /* Setup callbacks for the generic dominator tree walker.  */
  memset (&walk_data, 0, sizeof (walk_data));

  walk_data.dom_direction = CDI_DOMINATORS;
  walk_data.interesting_blocks = blocks;

  if (what == REWRITE_UPDATE)
    walk_data.before_dom_children_before_stmts = rewrite_update_init_block;
  else
    walk_data.before_dom_children_before_stmts = rewrite_initialize_block;

  if (what == REWRITE_ALL)
    walk_data.before_dom_children_walk_stmts = rewrite_stmt;
  else if (what == REWRITE_UPDATE)
    walk_data.before_dom_children_walk_stmts = rewrite_update_stmt;
  else
    gcc_unreachable ();

  if (what == REWRITE_ALL)
    walk_data.before_dom_children_after_stmts = rewrite_add_phi_arguments;
  else if (what == REWRITE_UPDATE)
    walk_data.before_dom_children_after_stmts = rewrite_update_phi_arguments;
  else
    gcc_unreachable ();
  
  if (what == REWRITE_ALL)
    walk_data.after_dom_children_after_stmts =  rewrite_finalize_block;
  else if (what == REWRITE_UPDATE)
    walk_data.after_dom_children_after_stmts = rewrite_update_fini_block;
  else
    gcc_unreachable ();

1610
  block_defs_stack = VEC_alloc (tree, heap, 10);
1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635

  /* Initialize the dominator walker.  */
  init_walk_dominator_tree (&walk_data);

  /* Recursively walk the dominator tree rewriting each statement in
     each basic block.  */
  walk_dominator_tree (&walk_data, entry);

  /* Finalize the dominator walker.  */
  fini_walk_dominator_tree (&walk_data);

  /* Debugging dumps.  */
  if (dump_file && (dump_flags & TDF_STATS))
    {
      dump_dfa_stats (dump_file);
      if (def_blocks)
	dump_tree_ssa_stats (dump_file);
    }

  if (def_blocks)
    {
      htab_delete (def_blocks);
      def_blocks = NULL;
    }
  
1636
  VEC_free (tree, heap, block_defs_stack);
1637 1638 1639 1640 1641 1642 1643

  timevar_pop (TV_TREE_SSA_REWRITE_BLOCKS);
}


/* Block initialization routine for mark_def_sites.  Clear the 
   KILLS bitmap at the start of each block.  */
1644

1645
static void
1646 1647
mark_def_sites_initialize_block (struct dom_walk_data *walk_data,
				 basic_block bb ATTRIBUTE_UNUSED)
1648
{
1649 1650
  struct mark_def_sites_global_data *gd =
     (struct mark_def_sites_global_data *) walk_data->global_data;
1651 1652 1653
  bitmap kills = gd->kills;
  bitmap_clear (kills);
}
1654 1655


1656 1657 1658 1659 1660 1661
/* Mark the definition site blocks for each variable, so that we know
   where the variable is actually live.

   INTERESTING_BLOCKS will be filled in with all the blocks that
      should be processed by the renamer.  It is assumed to be
      initialized and zeroed by the caller.  */
1662

1663 1664
static void
mark_def_site_blocks (sbitmap interesting_blocks)
1665 1666 1667
{
  struct dom_walk_data walk_data;
  struct mark_def_sites_global_data mark_def_sites_global_data;
Daniel Berlin committed
1668 1669
  referenced_var_iterator rvi;
  tree var;
1670

1671
  /* Allocate memory for the DEF_BLOCKS hash table.  */
Daniel Berlin committed
1672
  def_blocks = htab_create (num_referenced_vars,
1673
			    def_blocks_hash, def_blocks_eq, def_blocks_free);
Daniel Berlin committed
1674 1675
  FOR_EACH_REFERENCED_VAR(var, rvi)
    set_current_def (var, NULL_TREE);
1676

1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687
  /* Setup callbacks for the generic dominator tree walker to find and
     mark definition sites.  */
  walk_data.walk_stmts_backward = false;
  walk_data.dom_direction = CDI_DOMINATORS;
  walk_data.initialize_block_local_data = NULL;
  walk_data.before_dom_children_before_stmts = mark_def_sites_initialize_block;
  walk_data.before_dom_children_walk_stmts = mark_def_sites;
  walk_data.before_dom_children_after_stmts = NULL; 
  walk_data.after_dom_children_before_stmts =  NULL;
  walk_data.after_dom_children_walk_stmts =  NULL;
  walk_data.after_dom_children_after_stmts =  NULL;
1688
  walk_data.interesting_blocks = NULL;
1689

1690 1691 1692 1693
  /* Notice that this bitmap is indexed using variable UIDs, so it must be
     large enough to accommodate all the variables referenced in the
     function, not just the ones we are renaming.  */
  mark_def_sites_global_data.kills = BITMAP_ALLOC (NULL);
1694 1695 1696 1697

  /* Create the set of interesting blocks that will be filled by
     mark_def_sites.  */
  mark_def_sites_global_data.interesting_blocks = interesting_blocks;
1698
  walk_data.global_data = &mark_def_sites_global_data;
1699

1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713
  /* We do not have any local data.  */
  walk_data.block_local_data_size = 0;

  /* Initialize the dominator walker.  */
  init_walk_dominator_tree (&walk_data);

  /* Recursively walk the dominator tree.  */
  walk_dominator_tree (&walk_data, ENTRY_BLOCK_PTR);

  /* Finalize the dominator walker.  */
  fini_walk_dominator_tree (&walk_data);

  /* We no longer need this bitmap, clear and free it.  */
  BITMAP_FREE (mark_def_sites_global_data.kills);
1714 1715 1716
}


1717
/* Main entry point into the SSA builder.  The renaming process
1718
   proceeds in four main phases:
1719

1720 1721 1722
   1- Compute dominance frontier and immediate dominators, needed to
      insert PHI nodes and rename the function in dominator tree
      order.
1723

1724
   2- Find and mark all the blocks that define variables
1725
      (mark_def_site_blocks).
1726

1727
   3- Insert PHI nodes at dominance frontiers (insert_phi_nodes).
1728

1729
   4- Rename all the blocks (rewrite_blocks) and statements in the program.
1730

1731
   Steps 3 and 4 are done using the dominator tree walker
1732
   (walk_dominator_tree).  */
1733

1734 1735
static void
rewrite_into_ssa (void)
1736
{
1737 1738
  bitmap *dfs;
  basic_block bb;
1739
  sbitmap interesting_blocks;
1740
  
1741
  timevar_push (TV_TREE_SSA_OTHER);
1742

1743 1744
  /* Initialize operand data structures.  */
  init_ssa_operands ();
1745

1746 1747 1748 1749 1750
  /* Initialize the set of interesting blocks.  The callback
     mark_def_sites will add to this set those blocks that the renamer
     should process.  */
  interesting_blocks = sbitmap_alloc (last_basic_block);
  sbitmap_zero (interesting_blocks);
1751

1752
  /* Initialize dominance frontier.  */
1753
  dfs = (bitmap *) xmalloc (last_basic_block * sizeof (bitmap));
1754 1755
  FOR_EACH_BB (bb)
    dfs[bb->index] = BITMAP_ALLOC (NULL);
1756

1757 1758
  /* 1- Compute dominance frontiers.  */
  calculate_dominance_info (CDI_DOMINATORS);
1759
  compute_dominance_frontiers (dfs);
1760

1761 1762 1763 1764
  /* 2- Find and mark definition sites.  */
  mark_def_site_blocks (interesting_blocks);

  /* 3- Insert PHI nodes at dominance frontiers of definition blocks.  */
Diego Novillo committed
1765
  insert_phi_nodes (dfs);
1766

1767 1768
  /* 4- Rename all the blocks.  */
  rewrite_blocks (ENTRY_BLOCK_PTR, REWRITE_ALL, interesting_blocks);
1769

1770 1771 1772 1773
  /* Free allocated memory.  */
  FOR_EACH_BB (bb)
    BITMAP_FREE (dfs[bb->index]);
  free (dfs);
1774
  sbitmap_free (interesting_blocks);
1775

1776
  timevar_pop (TV_TREE_SSA_OTHER);
1777
  in_ssa_p = true;
1778 1779 1780
}


1781
struct tree_opt_pass pass_build_ssa = 
1782
{
1783 1784
  "ssa",				/* name */
  NULL,					/* gate */
1785
  rewrite_into_ssa,			/* execute */
1786 1787 1788 1789 1790 1791 1792 1793
  NULL,					/* sub */
  NULL,					/* next */
  0,					/* static_pass_number */
  0,					/* tv_id */
  PROP_cfg | PROP_referenced_vars,	/* properties_required */
  PROP_ssa,				/* properties_provided */
  0,					/* properties_destroyed */
  0,					/* todo_flags_start */
1794 1795 1796
  TODO_dump_func
    | TODO_verify_ssa
    | TODO_remove_unused_locals,	/* todo_flags_finish */
1797 1798
  0					/* letter */
};
1799 1800


1801 1802
/* Mark the definition of VAR at STMT and BB as interesting for the
   renamer.  BLOCKS is the set of blocks that need updating.  */
1803

1804 1805 1806
static void
mark_def_interesting (tree var, tree stmt, basic_block bb, bitmap blocks,
		      bool insert_phi_p)
1807
{
1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849
  REGISTER_DEFS_IN_THIS_STMT (stmt) = 1;
  bitmap_set_bit (blocks, bb->index);

  if (insert_phi_p)
    {
      bool is_phi_p = TREE_CODE (stmt) == PHI_NODE;

      set_def_block (var, bb, is_phi_p);

      /* If VAR is an SSA name in NEW_SSA_NAMES, this is a definition
	 site for both itself and all the old names replaced by it.  */
      if (TREE_CODE (var) == SSA_NAME && is_new_name (var))
	{
	  bitmap_iterator bi;
	  unsigned i;
	  bitmap set = names_replaced_by (var);
	  if (set)
	    EXECUTE_IF_SET_IN_BITMAP (set, 0, i, bi)
	      set_def_block (ssa_name (i), bb, is_phi_p);
	}
    }
}


/* Mark the use of VAR at STMT and BB as interesting for the
   renamer.  INSERT_PHI_P is true if we are going to insert new PHI
   nodes.  BLOCKS is the set of blocks that need updating.  */

static inline void
mark_use_interesting (tree var, tree stmt, basic_block bb, bitmap blocks,
		      bool insert_phi_p)
{
  REWRITE_THIS_STMT (stmt) = 1;
  bitmap_set_bit (blocks, bb->index);

  /* If VAR has not been defined in BB, then it is live-on-entry
     to BB.  Note that we cannot just use the block holding VAR's
     definition because if VAR is one of the names in OLD_SSA_NAMES,
     it will have several definitions (itself and all the names that
     replace it).  */
  if (insert_phi_p)
    {
Diego Novillo committed
1850
      struct def_blocks_d *db_p = get_def_blocks_for (var);
1851 1852 1853 1854 1855 1856 1857
      if (!bitmap_bit_p (db_p->def_blocks, bb->index))
	set_livein_block (var, bb);
    }
}


/* Do a dominator walk starting at BB processing statements that
Diego Novillo committed
1858 1859 1860 1861
   reference symbols in SYMS_TO_RENAME.  This is very similar to
   mark_def_sites, but the scan handles statements whose operands may
   already be SSA names.  Blocks that contain defs or uses of symbols
   in SYMS_TO_RENAME are added to BLOCKS.
1862

Diego Novillo committed
1863 1864 1865
   If INSERT_PHI_P is true, mark those uses as live in the
   corresponding block.  This is later used by the PHI placement
   algorithm to make PHI pruning decisions.  */
1866 1867

static void
Diego Novillo committed
1868
prepare_block_for_update (basic_block bb, bitmap blocks, bool insert_phi_p)
1869 1870 1871 1872 1873 1874
{
  basic_block son;
  block_stmt_iterator si;
  tree phi;

  /* Process PHI nodes marking interesting those that define or use
Diego Novillo committed
1875
     the symbols that we are interested in.  */
1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902
  for (phi = phi_nodes (bb); phi; phi = PHI_CHAIN (phi))
    {
      tree lhs_sym, lhs = PHI_RESULT (phi);

      lhs_sym = DECL_P (lhs) ? lhs : SSA_NAME_VAR (lhs);

      if (symbol_marked_for_renaming (lhs_sym))
	{
	  mark_use_interesting (lhs_sym, phi, bb, blocks, insert_phi_p);
	  mark_def_interesting (lhs_sym, phi, bb, blocks, insert_phi_p);
	}
    }

  /* Process the statements.  */
  for (si = bsi_start (bb); !bsi_end_p (si); bsi_next (&si))
    {
      tree stmt;
      ssa_op_iter i;
      use_operand_p use_p;
      def_operand_p def_p;
      
      stmt = bsi_stmt (si);

      FOR_EACH_SSA_USE_OPERAND (use_p, stmt, i, SSA_OP_USE)
	{
	  tree use = USE_FROM_PTR (use_p);
	  tree sym = DECL_P (use) ? use : SSA_NAME_VAR (use);
Diego Novillo committed
1903
	  if (symbol_marked_for_renaming (sym))
1904 1905 1906 1907 1908 1909 1910 1911
	    mark_use_interesting (use, stmt, bb, blocks, insert_phi_p);
	}

      FOR_EACH_SSA_DEF_OPERAND (def_p, stmt, i, SSA_OP_DEF)
	{
	  tree def = DEF_FROM_PTR (def_p);
	  tree sym = DECL_P (def) ? def : SSA_NAME_VAR (def);

Diego Novillo committed
1912
	  if (symbol_marked_for_renaming (sym))
1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938
	    mark_def_interesting (def, stmt, bb, blocks, insert_phi_p);
	}

      FOR_EACH_SSA_DEF_OPERAND (def_p, stmt, i, SSA_OP_VIRTUAL_DEFS)
	{
	  tree def = DEF_FROM_PTR (def_p);
	  tree sym = DECL_P (def) ? def : SSA_NAME_VAR (def);

	  if (symbol_marked_for_renaming (sym))
	    {
	      mark_use_interesting (sym, stmt, bb, blocks, insert_phi_p);
	      mark_def_interesting (sym, stmt, bb, blocks, insert_phi_p);
	    }
	}

      FOR_EACH_SSA_USE_OPERAND (use_p, stmt, i, SSA_OP_VUSE)
	{
	  tree use = USE_FROM_PTR (use_p);
	  tree sym = DECL_P (use) ? use : SSA_NAME_VAR (use);

	  if (symbol_marked_for_renaming (sym))
	    mark_use_interesting (sym, stmt, bb, blocks, insert_phi_p);
	}
    }

  /* Now visit all the blocks dominated by BB.  */
Diego Novillo committed
1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002
  for (son = first_dom_son (CDI_DOMINATORS, bb);
      son;
      son = next_dom_son (CDI_DOMINATORS, son))
    prepare_block_for_update (son, blocks, insert_phi_p);
}


/* Helper for prepare_names_to_update.  Mark all the use sites for
   NAME as interesting.  BLOCKS and INSERT_PHI_P are as in
   prepare_names_to_update.  */

static void
prepare_use_sites_for (tree name, bitmap blocks, bool insert_phi_p)
{
  use_operand_p use_p;
  imm_use_iterator iter;

  FOR_EACH_IMM_USE_FAST (use_p, iter, name)
    {
      tree stmt = USE_STMT (use_p);
      basic_block bb = bb_for_stmt (stmt);

      if (TREE_CODE (stmt) == PHI_NODE)
	{
	  /* Mark this use of NAME interesting for the renamer.
	     Notice that we explicitly call mark_use_interesting with
	     INSERT_PHI_P == false.

	     This is to avoid marking NAME as live-in in this block
	     BB. If we were to mark NAME live-in to BB, then NAME
	     would be considered live-in through ALL incoming edges to
	     BB which is not what we want.  Since we are updating the
	     SSA form for NAME, we don't really know what other names
	     of NAME are coming in through other edges into BB.

	     If we considered NAME live-in at BB, then the PHI
	     placement algorithm may try to insert PHI nodes in blocks
	     that are not only unnecessary but also the renamer would
	     not know how to fill in.  */
	  mark_use_interesting (name, stmt, bb, blocks, false);

	  /* As discussed above, we only want to mark NAME live-in
	     through the edge corresponding to its slot inside the PHI
	     argument list.  So, we look for the block BB1 where NAME
	     is flowing through.  If BB1 does not contain a definition
	     of NAME, then consider NAME live-in at BB1.  */
	  if (insert_phi_p)
	    {
	      int ix = PHI_ARG_INDEX_FROM_USE (use_p);
	      edge e = PHI_ARG_EDGE (stmt, ix);
	      basic_block bb1 = e->src;
	      struct def_blocks_d *db = get_def_blocks_for (name);

	      if (!bitmap_bit_p (db->def_blocks, bb1->index))
		set_livein_block (name, bb1);
	    }
	}
      else
	{
	  /* For regular statements, mark this as an interesting use
	     for NAME.  */
	  mark_use_interesting (name, stmt, bb, blocks, insert_phi_p);
	}
    }
2003 2004 2005
}


Diego Novillo committed
2006 2007 2008
/* Helper for prepare_names_to_update.  Mark the definition site for
   NAME as interesting.  BLOCKS and INSERT_PHI_P are as in
   prepare_names_to_update.  */
2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028

static void
prepare_def_site_for (tree name, bitmap blocks, bool insert_phi_p)
{
  tree stmt;
  basic_block bb;

  gcc_assert (names_to_release == NULL
	      || !bitmap_bit_p (names_to_release, SSA_NAME_VERSION (name)));

  stmt = SSA_NAME_DEF_STMT (name);
  bb = bb_for_stmt (stmt);
  if (bb)
    {
      gcc_assert (bb->index < last_basic_block);
      mark_def_interesting (name, stmt, bb, blocks, insert_phi_p);
    }
}


Diego Novillo committed
2029 2030 2031 2032
/* Mark definition and use sites of names in NEW_SSA_NAMES and
   OLD_SSA_NAMES.  Add each definition block to BLOCKS.  INSERT_PHI_P
   is true if the caller wants to insert PHI nodes for newly created
   names.  */
2033 2034

static void
Diego Novillo committed
2035
prepare_names_to_update (bitmap blocks, bool insert_phi_p)
2036
{
2037
  unsigned i = 0;
2038
  bitmap_iterator bi;
2039
  sbitmap_iterator sbi;
2040 2041 2042 2043 2044 2045 2046 2047 2048 2049

  /* If a name N from NEW_SSA_NAMES is also marked to be released,
     remove it from NEW_SSA_NAMES so that we don't try to visit its
     defining basic block (which most likely doesn't exist).  Notice
     that we cannot do the same with names in OLD_SSA_NAMES because we
     want to replace existing instances.  */
  if (names_to_release)
    EXECUTE_IF_SET_IN_BITMAP (names_to_release, 0, i, bi)
      RESET_BIT (new_ssa_names, i);

Diego Novillo committed
2050 2051 2052
  /* First process names in NEW_SSA_NAMES.  Otherwise, uses of old
     names may be considered to be live-in on blocks that contain
     definitions for their replacements.  */
2053 2054
  EXECUTE_IF_SET_IN_SBITMAP (new_ssa_names, 0, i, sbi)
    prepare_def_site_for (ssa_name (i), blocks, insert_phi_p);
Diego Novillo committed
2055

2056 2057
  /* If an old name is in NAMES_TO_RELEASE, we cannot remove it from
     OLD_SSA_NAMES, but we have to ignore its definition site.  */
2058
  EXECUTE_IF_SET_IN_SBITMAP (old_ssa_names, 0, i, sbi)
Diego Novillo committed
2059 2060 2061 2062
    {
      if (names_to_release == NULL || !bitmap_bit_p (names_to_release, i))
	prepare_def_site_for (ssa_name (i), blocks, insert_phi_p);
      prepare_use_sites_for (ssa_name (i), blocks, insert_phi_p);
2063
    }
2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098
}


/* Dump all the names replaced by NAME to FILE.  */

void
dump_names_replaced_by (FILE *file, tree name)
{
  unsigned i;
  bitmap old_set;
  bitmap_iterator bi;

  print_generic_expr (file, name, 0);
  fprintf (file, " -> { ");

  old_set = names_replaced_by (name);
  EXECUTE_IF_SET_IN_BITMAP (old_set, 0, i, bi)
    {
      print_generic_expr (file, ssa_name (i), 0);
      fprintf (file, " ");
    }

  fprintf (file, "}\n");
}


/* Dump all the names replaced by NAME to stderr.  */

void
debug_names_replaced_by (tree name)
{
  dump_names_replaced_by (stderr, name);
}


Diego Novillo committed
2099
/* Dump SSA update information to FILE.  */
2100 2101

void
Diego Novillo committed
2102
dump_update_ssa (FILE *file)
2103
{
2104
  unsigned i = 0;
2105 2106 2107 2108 2109 2110 2111
  bitmap_iterator bi;

  if (!need_ssa_update_p ())
    return;

  if (new_ssa_names && sbitmap_first_set_bit (new_ssa_names) >= 0)
    {
2112 2113
      sbitmap_iterator sbi;

2114 2115 2116 2117
      fprintf (file, "\nSSA replacement table\n");
      fprintf (file, "N_i -> { O_1 ... O_j } means that N_i replaces "
	             "O_1, ..., O_j\n\n");

2118 2119
      EXECUTE_IF_SET_IN_SBITMAP (new_ssa_names, 0, i, sbi)
	dump_names_replaced_by (file, ssa_name (i));
Diego Novillo committed
2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131

      fprintf (file, "\n");
      fprintf (file, "Number of virtual NEW -> OLD mappings: %7u\n",
	       update_ssa_stats.num_virtual_mappings);
      fprintf (file, "Number of real NEW -> OLD mappings:    %7u\n",
	       update_ssa_stats.num_total_mappings
	       - update_ssa_stats.num_virtual_mappings);
      fprintf (file, "Number of total NEW -> OLD mappings:   %7u\n",
	       update_ssa_stats.num_total_mappings);

      fprintf (file, "\nNumber of virtual symbols: %u\n",
	       update_ssa_stats.num_virtual_symbols);
2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157
    }

  if (syms_to_rename && !bitmap_empty_p (syms_to_rename))
    {
      fprintf (file, "\n\nSymbols to be put in SSA form\n\n");
      EXECUTE_IF_SET_IN_BITMAP (syms_to_rename, 0, i, bi)
	{
	  print_generic_expr (file, referenced_var (i), 0);
	  fprintf (file, " ");
	}
    }

  if (names_to_release && !bitmap_empty_p (names_to_release))
    {
      fprintf (file, "\n\nSSA names to release after updating the SSA web\n\n");
      EXECUTE_IF_SET_IN_BITMAP (names_to_release, 0, i, bi)
	{
	  print_generic_expr (file, ssa_name (i), 0);
	  fprintf (file, " ");
	}
    }

  fprintf (file, "\n\n");
}


Diego Novillo committed
2158
/* Dump SSA update information to stderr.  */
2159 2160

void
Diego Novillo committed
2161
debug_update_ssa (void)
2162
{
Diego Novillo committed
2163
  dump_update_ssa (stderr);
2164 2165 2166 2167 2168 2169 2170 2171
}


/* Initialize data structures used for incremental SSA updates.  */

static void
init_update_ssa (void)
{
Diego Novillo committed
2172
  /* Reserve more space than the current number of names.  The calls to
2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185
     add_new_name_mapping are typically done after creating new SSA
     names, so we'll need to reallocate these arrays.  */
  old_ssa_names = sbitmap_alloc (num_ssa_names + NAME_SETS_GROWTH_FACTOR);
  sbitmap_zero (old_ssa_names);

  new_ssa_names = sbitmap_alloc (num_ssa_names + NAME_SETS_GROWTH_FACTOR);
  sbitmap_zero (new_ssa_names);

  repl_tbl = htab_create (20, repl_map_hash, repl_map_eq, repl_map_free);
  need_to_initialize_update_ssa_p = false;
  need_to_update_vops_p = false;
  syms_to_rename = BITMAP_ALLOC (NULL);
  names_to_release = NULL;
Diego Novillo committed
2186 2187
  memset (&update_ssa_stats, 0, sizeof (update_ssa_stats));
  update_ssa_stats.virtual_symbols = BITMAP_ALLOC (NULL);
2188 2189 2190 2191 2192
}


/* Deallocate data structures used for incremental SSA updates.  */

Diego Novillo committed
2193
void
2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210
delete_update_ssa (void)
{
  unsigned i;
  bitmap_iterator bi;

  sbitmap_free (old_ssa_names);
  old_ssa_names = NULL;

  sbitmap_free (new_ssa_names);
  new_ssa_names = NULL;

  htab_delete (repl_tbl);
  repl_tbl = NULL;

  need_to_initialize_update_ssa_p = true;
  need_to_update_vops_p = false;
  BITMAP_FREE (syms_to_rename);
Diego Novillo committed
2211
  BITMAP_FREE (update_ssa_stats.virtual_symbols);
2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292

  if (names_to_release)
    {
      EXECUTE_IF_SET_IN_BITMAP (names_to_release, 0, i, bi)
	release_ssa_name (ssa_name (i));
      BITMAP_FREE (names_to_release);
    }

  for (i = 1; i < num_ssa_names; i++)
    {
      tree n = ssa_name (i);

      if (n)
	{
	  free (SSA_NAME_AUX (n));
	  SSA_NAME_AUX (n) = NULL;
	}
    }
}


/* Create a new name for OLD_NAME in statement STMT and replace the
   operand pointed to by DEF_P with the newly created name.  Return
   the new name and register the replacement mapping <NEW, OLD> in
   update_ssa's tables.  */

tree
create_new_def_for (tree old_name, tree stmt, def_operand_p def)
{
  tree new_name = duplicate_ssa_name (old_name, stmt);

  SET_DEF (def, new_name);

  if (TREE_CODE (stmt) == PHI_NODE)
    {
      edge e;
      edge_iterator ei;
      basic_block bb = bb_for_stmt (stmt);

      /* If needed, mark NEW_NAME as occurring in an abnormal PHI node. */
      FOR_EACH_EDGE (e, ei, bb->preds)
	if (e->flags & EDGE_ABNORMAL)
	  {
	    SSA_NAME_OCCURS_IN_ABNORMAL_PHI (new_name) = 1;
	    break;
	  }
    }

  register_new_name_mapping (new_name, old_name);

  /* For the benefit of passes that will be updating the SSA form on
     their own, set the current reaching definition of OLD_NAME to be
     NEW_NAME.  */
  set_current_def (old_name, new_name);

  return new_name;
}


/* Register name NEW to be a replacement for name OLD.  This function
   must be called for every replacement that should be performed by
   update_ssa.  */

void
register_new_name_mapping (tree new, tree old)
{
  if (need_to_initialize_update_ssa_p)
    init_update_ssa ();

  add_new_name_mapping (new, old);
}


/* Register symbol SYM to be renamed by update_ssa.  */

void
mark_sym_for_renaming (tree sym)
{
  if (need_to_initialize_update_ssa_p)
    init_update_ssa ();

Daniel Berlin committed
2293
  bitmap_set_bit (syms_to_rename, DECL_UID (sym));
2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307

  if (!is_gimple_reg (sym))
    need_to_update_vops_p = true;
}


/* Register all the symbols in SET to be renamed by update_ssa.  */

void
mark_set_for_renaming (bitmap set)
{
  bitmap_iterator bi;
  unsigned i;

Diego Novillo committed
2308 2309 2310
  if (bitmap_empty_p (set))
    return;

2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352
  if (need_to_initialize_update_ssa_p)
    init_update_ssa ();

  bitmap_ior_into (syms_to_rename, set);

  EXECUTE_IF_SET_IN_BITMAP (set, 0, i, bi)
    if (!is_gimple_reg (referenced_var (i)))
      {
	need_to_update_vops_p = true;
	break;
      }
}


/* Return true if there is any work to be done by update_ssa.  */

bool
need_ssa_update_p (void)
{
  return syms_to_rename || old_ssa_names || new_ssa_names;
}


/* Return true if name N has been registered in the replacement table.  */

bool
name_registered_for_update_p (tree n)
{
  if (!need_ssa_update_p ())
    return false;

  return is_new_name (n)
         || is_old_name (n)
	 || symbol_marked_for_renaming (SSA_NAME_VAR (n));
}


/* Return the set of all the SSA names marked to be replaced.  */

bitmap
ssa_names_to_replace (void)
{
2353
  unsigned i = 0;
2354
  bitmap ret;
2355
  sbitmap_iterator sbi;
2356 2357
  
  ret = BITMAP_ALLOC (NULL);
2358 2359
  EXECUTE_IF_SET_IN_SBITMAP (old_ssa_names, 0, i, sbi)
    bitmap_set_bit (ret, i);
2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388

  return ret;
}


/* Mark NAME to be released after update_ssa has finished.  */

void
release_ssa_name_after_update_ssa (tree name)
{
  gcc_assert (!need_to_initialize_update_ssa_p);

  if (names_to_release == NULL)
    names_to_release = BITMAP_ALLOC (NULL);

  bitmap_set_bit (names_to_release, SSA_NAME_VERSION (name));
}


/* Insert new PHI nodes to replace VAR.  DFS contains dominance
   frontier information.  BLOCKS is the set of blocks to be updated.

   This is slightly different than the regular PHI insertion
   algorithm.  The value of UPDATE_FLAGS controls how PHI nodes for
   real names (i.e., GIMPLE registers) are inserted:
 
   - If UPDATE_FLAGS == TODO_update_ssa, we are only interested in PHI
     nodes inside the region affected by the block that defines VAR
     and the blocks that define all its replacements.  All these
Diego Novillo committed
2389
     definition blocks are stored in DEF_BLOCKS[VAR]->DEF_BLOCKS.
2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486

     First, we compute the entry point to the region (ENTRY).  This is
     given by the nearest common dominator to all the definition
     blocks. When computing the iterated dominance frontier (IDF), any
     block not strictly dominated by ENTRY is ignored.

     We then call the standard PHI insertion algorithm with the pruned
     IDF.

   - If UPDATE_FLAGS == TODO_update_ssa_full_phi, the IDF for real
     names is not pruned.  PHI nodes are inserted at every IDF block.  */

static void
insert_updated_phi_nodes_for (tree var, bitmap *dfs, bitmap blocks,
                              unsigned update_flags)
{
  basic_block entry;
  struct def_blocks_d *db;
  bitmap idf, pruned_idf;
  bitmap_iterator bi;
  unsigned i;

#if defined ENABLE_CHECKING
  if (TREE_CODE (var) == SSA_NAME)
    gcc_assert (is_old_name (var));
  else
    gcc_assert (symbol_marked_for_renaming (var));
#endif

  /* Get all the definition sites for VAR.  */
  db = find_def_blocks_for (var);

  /* No need to do anything if there were no definitions to VAR.  */
  if (db == NULL || bitmap_empty_p (db->def_blocks))
    return;

  /* Compute the initial iterated dominance frontier.  */
  idf = find_idf (db->def_blocks, dfs);
  pruned_idf = BITMAP_ALLOC (NULL);

  if (TREE_CODE (var) == SSA_NAME)
    {
      if (update_flags == TODO_update_ssa)
	{
	  /* If doing regular SSA updates for GIMPLE registers, we are
	     only interested in IDF blocks dominated by the nearest
	     common dominator of all the definition blocks.  */
	  entry = nearest_common_dominator_for_set (CDI_DOMINATORS,
						    db->def_blocks);

	  if (entry != ENTRY_BLOCK_PTR)
	    EXECUTE_IF_SET_IN_BITMAP (idf, 0, i, bi)
	      if (BASIC_BLOCK (i) != entry
		  && dominated_by_p (CDI_DOMINATORS, BASIC_BLOCK (i), entry))
		bitmap_set_bit (pruned_idf, i);
	}
      else
	{
	  /* Otherwise, do not prune the IDF for VAR.  */
	  gcc_assert (update_flags == TODO_update_ssa_full_phi);
	  bitmap_copy (pruned_idf, idf);
	}
    }
  else
    {
      /* Otherwise, VAR is a symbol that needs to be put into SSA form
	 for the first time, so we need to compute the full IDF for
	 it.  */
      bitmap_copy (pruned_idf, idf);
    }

  if (!bitmap_empty_p (pruned_idf))
    {
      /* Make sure that PRUNED_IDF blocks and all their feeding blocks
	 are included in the region to be updated.  The feeding blocks
	 are important to guarantee that the PHI arguments are renamed
	 properly.  */
      bitmap_ior_into (blocks, pruned_idf);
      EXECUTE_IF_SET_IN_BITMAP (pruned_idf, 0, i, bi)
	{
	  edge e;
	  edge_iterator ei;
	  basic_block bb = BASIC_BLOCK (i);

	  FOR_EACH_EDGE (e, ei, bb->preds)
	    if (e->src->index >= 0)
	      bitmap_set_bit (blocks, e->src->index);
	}

      insert_phi_nodes_for (var, pruned_idf, true);
    }

  BITMAP_FREE (pruned_idf);
  BITMAP_FREE (idf);
}


Diego Novillo committed
2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524
/* Heuristic to determine whether SSA name mappings for virtual names
   should be discarded and their symbols rewritten from scratch.  When
   there is a large number of mappings for virtual names, the
   insertion of PHI nodes for the old names in the mappings takes
   considerable more time than if we inserted PHI nodes for the
   symbols instead.

   Currently the heuristic takes these stats into account:

   	- Number of mappings for virtual SSA names.
	- Number of distinct virtual symbols involved in those mappings.

   If the number of virtual mappings is much larger than the number of
   virtual symbols, then it will be faster to compute PHI insertion
   spots for the symbols.  Even if this involves traversing the whole
   CFG, which is what happens when symbols are renamed from scratch.  */

static bool
switch_virtuals_to_full_rewrite_p (void)
{
  if (update_ssa_stats.num_virtual_mappings < (unsigned) MIN_VIRTUAL_MAPPINGS)
    return false;

  if (update_ssa_stats.num_virtual_mappings
      > (unsigned) VIRTUAL_MAPPINGS_TO_SYMS_RATIO
        * update_ssa_stats.num_virtual_symbols)
    return true;

  return false;
}


/* Remove every virtual mapping and mark all the affected virtual
   symbols for renaming.  */

static void
switch_virtuals_to_full_rewrite (void)
{
2525
  unsigned i = 0;
2526
  sbitmap_iterator sbi;
Diego Novillo committed
2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541

  if (dump_file)
    {
      fprintf (dump_file, "\nEnabled virtual name mapping heuristic.\n");
      fprintf (dump_file, "\tNumber of virtual mappings:       %7u\n",
	       update_ssa_stats.num_virtual_mappings);
      fprintf (dump_file, "\tNumber of unique virtual symbols: %7u\n",
	       update_ssa_stats.num_virtual_symbols);
      fprintf (dump_file, "Updating FUD-chains from top of CFG will be "
	                  "faster than processing\nthe name mappings.\n\n");
    }

  /* Remove all virtual names from NEW_SSA_NAMES and OLD_SSA_NAMES.
     Note that it is not really necessary to remove the mappings from
     REPL_TBL, that would only waste time.  */
2542
  EXECUTE_IF_SET_IN_SBITMAP (new_ssa_names, 0, i, sbi)
Diego Novillo committed
2543
    if (!is_gimple_reg (ssa_name (i)))
2544
      RESET_BIT (new_ssa_names, i);
Diego Novillo committed
2545

2546
  EXECUTE_IF_SET_IN_SBITMAP (old_ssa_names, 0, i, sbi)
Diego Novillo committed
2547
    if (!is_gimple_reg (ssa_name (i)))
2548
      RESET_BIT (old_ssa_names, i);
Diego Novillo committed
2549 2550 2551 2552 2553

  bitmap_ior_into (syms_to_rename, update_ssa_stats.virtual_symbols);
}


2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620
/* Given a set of newly created SSA names (NEW_SSA_NAMES) and a set of
   existing SSA names (OLD_SSA_NAMES), update the SSA form so that:

   1- The names in OLD_SSA_NAMES dominated by the definitions of
      NEW_SSA_NAMES are all re-written to be reached by the
      appropriate definition from NEW_SSA_NAMES.

   2- If needed, new PHI nodes are added to the iterated dominance
      frontier of the blocks where each of NEW_SSA_NAMES are defined.

   The mapping between OLD_SSA_NAMES and NEW_SSA_NAMES is setup by
   calling register_new_name_mapping for every pair of names that the
   caller wants to replace.

   The caller identifies the new names that have been inserted and the
   names that need to be replaced by calling register_new_name_mapping
   for every pair <NEW, OLD>.  Note that the function assumes that the
   new names have already been inserted in the IL.

   For instance, given the following code:

     1	L0:
     2	x_1 = PHI (0, x_5)
     3	if (x_1 < 10)
     4	  if (x_1 > 7)
     5	    y_2 = 0
     6	  else
     7	    y_3 = x_1 + x_7
     8	  endif
     9	  x_5 = x_1 + 1
     10   goto L0;
     11	endif

   Suppose that we insert new names x_10 and x_11 (lines 4 and 8).

     1	L0:
     2	x_1 = PHI (0, x_5)
     3	if (x_1 < 10)
     4	  x_10 = ...
     5	  if (x_1 > 7)
     6	    y_2 = 0
     7	  else
     8	    x_11 = ...
     9	    y_3 = x_1 + x_7
     10	  endif
     11	  x_5 = x_1 + 1
     12	  goto L0;
     13	endif

   We want to replace all the uses of x_1 with the new definitions of
   x_10 and x_11.  Note that the only uses that should be replaced are
   those at lines 5, 9 and 11.  Also, the use of x_7 at line 9 should
   *not* be replaced (this is why we cannot just mark symbol 'x' for
   renaming).

   Additionally, we may need to insert a PHI node at line 11 because
   that is a merge point for x_10 and x_11.  So the use of x_1 at line
   11 will be replaced with the new PHI node.  The insertion of PHI
   nodes is optional.  They are not strictly necessary to preserve the
   SSA form, and depending on what the caller inserted, they may not
   even be useful for the optimizers.  UPDATE_FLAGS controls various
   aspects of how update_ssa operates, see the documentation for
   TODO_update_ssa*.  */

void
update_ssa (unsigned update_flags)
{
2621
  bitmap blocks;
2622 2623
  basic_block bb, start_bb;
  bitmap_iterator bi;
2624
  unsigned i = 0;
2625 2626
  sbitmap tmp;
  bool insert_phi_p;
2627
  sbitmap_iterator sbi;
2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643

  if (!need_ssa_update_p ())
    return;

  timevar_push (TV_TREE_SSA_INCREMENTAL);

  /* Ensure that the dominance information is up-to-date.  */
  calculate_dominance_info (CDI_DOMINATORS);

  /* Only one update flag should be set.  */
  gcc_assert (update_flags == TODO_update_ssa
              || update_flags == TODO_update_ssa_no_phi
	      || update_flags == TODO_update_ssa_full_phi
	      || update_flags == TODO_update_ssa_only_virtuals);

  /* If we only need to update virtuals, remove all the mappings for
Diego Novillo committed
2644 2645
     real names before proceeding.  The caller is responsible for
     having dealt with the name mappings before calling update_ssa.  */
2646 2647 2648 2649 2650 2651 2652
  if (update_flags == TODO_update_ssa_only_virtuals)
    {
      sbitmap_zero (old_ssa_names);
      sbitmap_zero (new_ssa_names);
      htab_empty (repl_tbl);
    }

Diego Novillo committed
2653
  insert_phi_p = (update_flags != TODO_update_ssa_no_phi);
2654 2655 2656

  if (insert_phi_p)
    {
2657 2658
      /* If the caller requested PHI nodes to be added, initialize
	 live-in information data structures (DEF_BLOCKS).  */
2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673

      /* For each SSA name N, the DEF_BLOCKS table describes where the
	 name is defined, which blocks have PHI nodes for N, and which
	 blocks have uses of N (i.e., N is live-on-entry in those
	 blocks).  */
      def_blocks = htab_create (num_ssa_names, def_blocks_hash,
				def_blocks_eq, def_blocks_free);
    }
  else
    {
      def_blocks = NULL;
    }

  blocks = BITMAP_ALLOC (NULL);

Diego Novillo committed
2674 2675 2676
  /* Clear the REWRITE_THIS_STMT and REGISTER_DEFS_IN_THIS_STMT flags
     for every statement and PHI node.  */
  FOR_EACH_BB (bb)
2677
    {
Diego Novillo committed
2678 2679
      block_stmt_iterator si;
      tree phi;
2680

Diego Novillo committed
2681 2682 2683 2684 2685 2686 2687 2688 2689
      for (phi = phi_nodes (bb); phi; phi = PHI_CHAIN (phi))
	{
	  REWRITE_THIS_STMT (phi) = 0;
	  REGISTER_DEFS_IN_THIS_STMT (phi) = 0;
	}

      for (si = bsi_start (bb); !bsi_end_p (si); bsi_next (&si))
	{
	  tree stmt = bsi_stmt (si);
2690 2691 2692 2693
	  /* We are going to use the operand cache API, such as
	     SET_USE, SET_DEF, and FOR_EACH_IMM_USE_FAST.  The operand
	     cache for each statement should be up-to-date.  */
	  gcc_assert (!stmt_modified_p (stmt));
Diego Novillo committed
2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733
	  REWRITE_THIS_STMT (stmt) = 0;
	  REGISTER_DEFS_IN_THIS_STMT (stmt) = 0;
	}
    }

  /* Heuristic to avoid massive slow downs when the replacement
     mappings include lots of virtual names.  */
  if (insert_phi_p && switch_virtuals_to_full_rewrite_p ())
    switch_virtuals_to_full_rewrite ();

  /* If there are names defined in the replacement table, prepare
     definition and use sites for all the names in NEW_SSA_NAMES and
     OLD_SSA_NAMES.  */
  if (sbitmap_first_set_bit (new_ssa_names) >= 0)
    {
      prepare_names_to_update (blocks, insert_phi_p);

      /* If all the names in NEW_SSA_NAMES had been marked for
	 removal, and there are no symbols to rename, then there's
	 nothing else to do.  */
      if (sbitmap_first_set_bit (new_ssa_names) < 0
	  && bitmap_empty_p (syms_to_rename))
	goto done;
    }

  /* Next, determine the block at which to start the renaming process.  */
  if (!bitmap_empty_p (syms_to_rename))
    {
      /* If we have to rename some symbols from scratch, we need to
	 start the process at the root of the CFG.  FIXME, it should
	 be possible to determine the nearest block that had a
	 definition for each of the symbols that are marked for
	 updating.  For now this seems more work than it's worth.  */
      start_bb = ENTRY_BLOCK_PTR;

      /* Traverse the CFG looking for definitions and uses of symbols
	 in SYMS_TO_RENAME.  Mark interesting blocks and statements
	 and set local live-in information for the PHI placement
	 heuristics.  */
      prepare_block_for_update (start_bb, blocks, insert_phi_p);
2734 2735
    }
  else
Diego Novillo committed
2736 2737 2738 2739 2740
    {
      /* Otherwise, the entry block to the region is the nearest
	 common dominator for the blocks in BLOCKS.  */
      start_bb = nearest_common_dominator_for_set (CDI_DOMINATORS, blocks);
    }
2741 2742

  /* If requested, insert PHI nodes at the iterated dominance frontier
Diego Novillo committed
2743
     of every block, creating new definitions for names in OLD_SSA_NAMES
2744 2745 2746
     and for symbols in SYMS_TO_RENAME.  */
  if (insert_phi_p)
    {
2747 2748 2749 2750
      bitmap *dfs;

      /* If the caller requested PHI nodes to be added, compute
	 dominance frontiers.  */
2751
      dfs = XNEWVEC (bitmap, last_basic_block);
2752 2753 2754 2755
      FOR_EACH_BB (bb)
	dfs[bb->index] = BITMAP_ALLOC (NULL);
      compute_dominance_frontiers (dfs);

2756 2757
      if (sbitmap_first_set_bit (old_ssa_names) >= 0)
	{
2758 2759
	  sbitmap_iterator sbi;

Diego Novillo committed
2760 2761 2762 2763 2764
	  /* insert_update_phi_nodes_for will call add_new_name_mapping
	     when inserting new PHI nodes, so the set OLD_SSA_NAMES
	     will grow while we are traversing it (but it will not
	     gain any new members).  Copy OLD_SSA_NAMES to a temporary
	     for traversal.  */
2765 2766
	  sbitmap tmp = sbitmap_alloc (old_ssa_names->n_bits);
	  sbitmap_copy (tmp, old_ssa_names);
2767
	  EXECUTE_IF_SET_IN_SBITMAP (tmp, 0, i, sbi)
2768
	    insert_updated_phi_nodes_for (ssa_name (i), dfs, blocks,
2769
	                                  update_flags);
2770 2771 2772 2773 2774
	  sbitmap_free (tmp);
	}

      EXECUTE_IF_SET_IN_BITMAP (syms_to_rename, 0, i, bi)
	insert_updated_phi_nodes_for (referenced_var (i), dfs, blocks,
Daniel Berlin committed
2775
	    		              update_flags);
2776

2777 2778 2779 2780
      FOR_EACH_BB (bb)
	BITMAP_FREE (dfs[bb->index]);
      free (dfs);

2781 2782 2783 2784 2785 2786 2787 2788 2789
      /* Insertion of PHI nodes may have added blocks to the region.
	 We need to re-compute START_BB to include the newly added
	 blocks.  */
      if (start_bb != ENTRY_BLOCK_PTR)
	start_bb = nearest_common_dominator_for_set (CDI_DOMINATORS, blocks);
    }

  /* Reset the current definition for name and symbol before renaming
     the sub-graph.  */
2790 2791
  EXECUTE_IF_SET_IN_SBITMAP (old_ssa_names, 0, i, sbi)
    set_current_def (ssa_name (i), NULL_TREE);
2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811

  EXECUTE_IF_SET_IN_BITMAP (syms_to_rename, 0, i, bi)
    set_current_def (referenced_var (i), NULL_TREE);

  /* Now start the renaming process at START_BB.  */
  tmp = sbitmap_alloc (last_basic_block);
  sbitmap_zero (tmp);
  EXECUTE_IF_SET_IN_BITMAP (blocks, 0, i, bi)
    SET_BIT (tmp, i);

  rewrite_blocks (start_bb, REWRITE_UPDATE, tmp);

  sbitmap_free (tmp);

  /* Debugging dumps.  */
  if (dump_file)
    {
      int c;
      unsigned i;

Diego Novillo committed
2812
      dump_update_ssa (dump_file);
2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835

      fprintf (dump_file, "Incremental SSA update started at block: %d\n\n",
	       start_bb->index);

      c = 0;
      EXECUTE_IF_SET_IN_BITMAP (blocks, 0, i, bi)
	c++;
      fprintf (dump_file, "Number of blocks in CFG: %d\n", last_basic_block);
      fprintf (dump_file, "Number of blocks to update: %d (%3.0f%%)\n\n",
	       c, PERCENT (c, last_basic_block));

      if (dump_flags & TDF_DETAILS)
	{
	  fprintf (dump_file, "Affected blocks: ");
	  EXECUTE_IF_SET_IN_BITMAP (blocks, 0, i, bi)
	    fprintf (dump_file, "%u ", i);
	  fprintf (dump_file, "\n");
	}

      fprintf (dump_file, "\n\n");
    }

  /* Free allocated memory.  */
Diego Novillo committed
2836
done:
2837 2838 2839 2840 2841
  BITMAP_FREE (blocks);
  delete_update_ssa ();

  timevar_pop (TV_TREE_SSA_INCREMENTAL);
}