cfganal.c 43.6 KB
Newer Older
1
/* Control flow graph analysis code for GNU compiler.
2
   Copyright (C) 1987-2016 Free Software Foundation, Inc.
3 4 5 6 7

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
8
Software Foundation; either version 3, or (at your option) any later
9 10 11 12 13 14 15 16
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
17 18
along with GCC; see the file COPYING3.  If not see
<http://www.gnu.org/licenses/>.  */
19 20

/* This file contains various simple utilities to analyze the CFG.  */
21

22 23
#include "config.h"
#include "system.h"
24
#include "coretypes.h"
25
#include "backend.h"
26
#include "cfghooks.h"
27
#include "timevar.h"
28
#include "cfganal.h"
29 30

/* Store the data structures necessary for depth-first search.  */
Trevor Saunders committed
31
struct depth_first_search_ds {
32 33 34 35 36 37 38 39 40 41 42
  /* stack for backtracking during the algorithm */
  basic_block *stack;

  /* number of edges in the stack.  That is, positions 0, ..., sp-1
     have edges.  */
  unsigned int sp;

  /* record of basic blocks already seen by depth-first search */
  sbitmap visited_blocks;
};

Trevor Saunders committed
43 44
static void flow_dfs_compute_reverse_init (depth_first_search_ds *);
static void flow_dfs_compute_reverse_add_bb (depth_first_search_ds *,
45
					     basic_block);
Trevor Saunders committed
46
static basic_block flow_dfs_compute_reverse_execute (depth_first_search_ds *,
47
						     basic_block);
Trevor Saunders committed
48
static void flow_dfs_compute_reverse_finish (depth_first_search_ds *);
49 50

/* Mark the back edges in DFS traversal.
51
   Return nonzero if a loop (natural or otherwise) is present.
52 53 54 55 56 57
   Inspired by Depth_First_Search_PP described in:

     Advanced Compiler Design and Implementation
     Steven Muchnick
     Morgan Kaufmann, 1997

58
   and heavily borrowed from pre_and_rev_post_order_compute.  */
59 60

bool
61
mark_dfs_back_edges (void)
62
{
63
  edge_iterator *stack;
64 65 66 67 68 69 70 71 72
  int *pre;
  int *post;
  int sp;
  int prenum = 1;
  int postnum = 1;
  sbitmap visited;
  bool found = false;

  /* Allocate the preorder and postorder number arrays.  */
73 74
  pre = XCNEWVEC (int, last_basic_block_for_fn (cfun));
  post = XCNEWVEC (int, last_basic_block_for_fn (cfun));
75 76

  /* Allocate stack for back-tracking up CFG.  */
77
  stack = XNEWVEC (edge_iterator, n_basic_blocks_for_fn (cfun) + 1);
78 79 80
  sp = 0;

  /* Allocate bitmap to track nodes that have been visited.  */
81
  visited = sbitmap_alloc (last_basic_block_for_fn (cfun));
82 83

  /* None of the nodes in the CFG have been visited yet.  */
84
  bitmap_clear (visited);
85 86

  /* Push the first edge on to the stack.  */
87
  stack[sp++] = ei_start (ENTRY_BLOCK_PTR_FOR_FN (cfun)->succs);
88 89 90

  while (sp)
    {
91
      edge_iterator ei;
92 93 94 95
      basic_block src;
      basic_block dest;

      /* Look at the edge on the top of the stack.  */
96 97 98 99
      ei = stack[sp - 1];
      src = ei_edge (ei)->src;
      dest = ei_edge (ei)->dest;
      ei_edge (ei)->flags &= ~EDGE_DFS_BACK;
100 101

      /* Check if the edge destination has been visited yet.  */
102 103
      if (dest != EXIT_BLOCK_PTR_FOR_FN (cfun) && ! bitmap_bit_p (visited,
								  dest->index))
104 105
	{
	  /* Mark that we have visited the destination.  */
106
	  bitmap_set_bit (visited, dest->index);
107

108
	  pre[dest->index] = prenum++;
109
	  if (EDGE_COUNT (dest->succs) > 0)
110 111 112
	    {
	      /* Since the DEST node has been visited for the first
		 time, check its successors.  */
113
	      stack[sp++] = ei_start (dest->succs);
114 115
	    }
	  else
116
	    post[dest->index] = postnum++;
117 118 119
	}
      else
	{
120 121
	  if (dest != EXIT_BLOCK_PTR_FOR_FN (cfun)
	      && src != ENTRY_BLOCK_PTR_FOR_FN (cfun)
122 123
	      && pre[src->index] >= pre[dest->index]
	      && post[dest->index] == 0)
124
	    ei_edge (ei)->flags |= EDGE_DFS_BACK, found = true;
125

126 127
	  if (ei_one_before_end_p (ei)
	      && src != ENTRY_BLOCK_PTR_FOR_FN (cfun))
128
	    post[src->index] = postnum++;
129

130 131
	  if (!ei_one_before_end_p (ei))
	    ei_next (&stack[sp - 1]);
132 133 134 135 136 137 138 139 140 141 142 143 144 145
	  else
	    sp--;
	}
    }

  free (pre);
  free (post);
  free (stack);
  sbitmap_free (visited);

  return found;
}

/* Find unreachable blocks.  An unreachable block will have 0 in
146
   the reachable bit in block->flags.  A nonzero value indicates the
147 148 149
   block is reachable.  */

void
150
find_unreachable_blocks (void)
151 152
{
  edge e;
153
  edge_iterator ei;
154
  basic_block *tos, *worklist, bb;
155

156
  tos = worklist = XNEWVEC (basic_block, n_basic_blocks_for_fn (cfun));
157 158 159

  /* Clear all the reachability flags.  */

160
  FOR_EACH_BB_FN (bb, cfun)
161
    bb->flags &= ~BB_REACHABLE;
162 163

  /* Add our starting points to the worklist.  Almost always there will
164
     be only one.  It isn't inconceivable that we might one day directly
165 166
     support Fortran alternate entry points.  */

167
  FOR_EACH_EDGE (e, ei, ENTRY_BLOCK_PTR_FOR_FN (cfun)->succs)
168 169 170 171 172 173 174 175 176 177 178 179 180
    {
      *tos++ = e->dest;

      /* Mark the block reachable.  */
      e->dest->flags |= BB_REACHABLE;
    }

  /* Iterate: find everything reachable from what we've already seen.  */

  while (tos != worklist)
    {
      basic_block b = *--tos;

181
      FOR_EACH_EDGE (e, ei, b->succs)
182 183 184 185 186 187 188 189 190
	{
	  basic_block dest = e->dest;

	  if (!(dest->flags & BB_REACHABLE))
	    {
	      *tos++ = dest;
	      dest->flags |= BB_REACHABLE;
	    }
	}
191 192 193 194
    }

  free (worklist);
}
195 196 197 198 199 200 201 202 203 204 205 206 207

/* Verify that there are no unreachable blocks in the current function.  */

void
verify_no_unreachable_blocks (void)
{
  find_unreachable_blocks ();

  basic_block bb;
  FOR_EACH_BB_FN (bb, cfun)
    gcc_assert ((bb->flags & BB_REACHABLE) != 0);
}

208 209 210 211 212 213 214 215 216 217 218 219 220 221 222

/* Functions to access an edge list with a vector representation.
   Enough data is kept such that given an index number, the
   pred and succ that edge represents can be determined, or
   given a pred and a succ, its index number can be returned.
   This allows algorithms which consume a lot of memory to
   represent the normally full matrix of edge (pred,succ) with a
   single indexed vector,  edge (EDGE_INDEX (pred, succ)), with no
   wasted space in the client code due to sparse flow graphs.  */

/* This functions initializes the edge list. Basically the entire
   flowgraph is processed, and all edges are assigned a number,
   and the data structure is filled in.  */

struct edge_list *
223
create_edge_list (void)
224 225 226 227
{
  struct edge_list *elist;
  edge e;
  int num_edges;
228
  basic_block bb;
229
  edge_iterator ei;
230 231 232

  /* Determine the number of edges in the flow graph by counting successor
     edges on each basic block.  */
233
  num_edges = 0;
234 235
  FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR_FOR_FN (cfun),
		  EXIT_BLOCK_PTR_FOR_FN (cfun), next_bb)
236
    {
237
      num_edges += EDGE_COUNT (bb->succs);
238
    }
239

240
  elist = XNEW (struct edge_list);
241
  elist->num_edges = num_edges;
242
  elist->index_to_edge = XNEWVEC (edge, num_edges);
243 244 245

  num_edges = 0;

246
  /* Follow successors of blocks, and register these edges.  */
247 248
  FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR_FOR_FN (cfun),
		  EXIT_BLOCK_PTR_FOR_FN (cfun), next_bb)
249
    FOR_EACH_EDGE (e, ei, bb->succs)
250
      elist->index_to_edge[num_edges++] = e;
251

252 253 254 255 256 257
  return elist;
}

/* This function free's memory associated with an edge list.  */

void
258
free_edge_list (struct edge_list *elist)
259 260 261 262 263 264 265 266 267 268
{
  if (elist)
    {
      free (elist->index_to_edge);
      free (elist);
    }
}

/* This function provides debug output showing an edge list.  */

269
DEBUG_FUNCTION void
270
print_edge_list (FILE *f, struct edge_list *elist)
271 272
{
  int x;
273

274
  fprintf (f, "Compressed edge list, %d BBs + entry & exit, and %d edges\n",
275
	   n_basic_blocks_for_fn (cfun), elist->num_edges);
276 277 278 279

  for (x = 0; x < elist->num_edges; x++)
    {
      fprintf (f, " %-4d - edge(", x);
280
      if (INDEX_EDGE_PRED_BB (elist, x) == ENTRY_BLOCK_PTR_FOR_FN (cfun))
281 282
	fprintf (f, "entry,");
      else
283
	fprintf (f, "%d,", INDEX_EDGE_PRED_BB (elist, x)->index);
284

285
      if (INDEX_EDGE_SUCC_BB (elist, x) == EXIT_BLOCK_PTR_FOR_FN (cfun))
286 287
	fprintf (f, "exit)\n");
      else
288
	fprintf (f, "%d)\n", INDEX_EDGE_SUCC_BB (elist, x)->index);
289 290 291 292 293 294 295
    }
}

/* This function provides an internal consistency check of an edge list,
   verifying that all edges are present, and that there are no
   extra edges.  */

296
DEBUG_FUNCTION void
297
verify_edge_list (FILE *f, struct edge_list *elist)
298
{
299
  int pred, succ, index;
300
  edge e;
301
  basic_block bb, p, s;
302
  edge_iterator ei;
303

304 305
  FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR_FOR_FN (cfun),
		  EXIT_BLOCK_PTR_FOR_FN (cfun), next_bb)
306
    {
307
      FOR_EACH_EDGE (e, ei, bb->succs)
308
	{
309 310
	  pred = e->src->index;
	  succ = e->dest->index;
311 312 313 314 315 316
	  index = EDGE_INDEX (elist, e->src, e->dest);
	  if (index == EDGE_INDEX_NO_EDGE)
	    {
	      fprintf (f, "*p* No index for edge from %d to %d\n", pred, succ);
	      continue;
	    }
317

318
	  if (INDEX_EDGE_PRED_BB (elist, index)->index != pred)
319
	    fprintf (f, "*p* Pred for index %d should be %d not %d\n",
320 321
		     index, pred, INDEX_EDGE_PRED_BB (elist, index)->index);
	  if (INDEX_EDGE_SUCC_BB (elist, index)->index != succ)
322
	    fprintf (f, "*p* Succ for index %d should be %d not %d\n",
323 324 325 326
		     index, succ, INDEX_EDGE_SUCC_BB (elist, index)->index);
	}
    }

327
  /* We've verified that all the edges are in the list, now lets make sure
328
     there are no spurious edges in the list.  This is an expensive check!  */
329

330 331 332
  FOR_BB_BETWEEN (p, ENTRY_BLOCK_PTR_FOR_FN (cfun),
		  EXIT_BLOCK_PTR_FOR_FN (cfun), next_bb)
    FOR_BB_BETWEEN (s, ENTRY_BLOCK_PTR_FOR_FN (cfun)->next_bb, NULL, next_bb)
333 334 335
      {
	int found_edge = 0;

336
	FOR_EACH_EDGE (e, ei, p->succs)
337 338 339 340 341
	  if (e->dest == s)
	    {
	      found_edge = 1;
	      break;
	    }
342

343
	FOR_EACH_EDGE (e, ei, s->preds)
344 345 346 347 348
	  if (e->src == p)
	    {
	      found_edge = 1;
	      break;
	    }
349

350
	if (EDGE_INDEX (elist, p, s)
351 352
	    == EDGE_INDEX_NO_EDGE && found_edge != 0)
	  fprintf (f, "*** Edge (%d, %d) appears to not have an index\n",
353 354
		   p->index, s->index);
	if (EDGE_INDEX (elist, p, s)
355 356
	    != EDGE_INDEX_NO_EDGE && found_edge == 0)
	  fprintf (f, "*** Edge (%d, %d) has index %d, but there is no edge\n",
357
		   p->index, s->index, EDGE_INDEX (elist, p, s));
358 359 360
      }
}

361 362 363 364 365 366 367 368

/* Functions to compute control dependences.  */

/* Indicate block BB is control dependent on an edge with index EDGE_INDEX.  */
void
control_dependences::set_control_dependence_map_bit (basic_block bb,
						     int edge_index)
{
369
  if (bb == ENTRY_BLOCK_PTR_FOR_FN (cfun))
370
    return;
371
  gcc_assert (bb != EXIT_BLOCK_PTR_FOR_FN (cfun));
372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387
  bitmap_set_bit (control_dependence_map[bb->index], edge_index);
}

/* Clear all control dependences for block BB.  */
void
control_dependences::clear_control_dependence_bitmap (basic_block bb)
{
  bitmap_clear (control_dependence_map[bb->index]);
}

/* Find the immediate postdominator PDOM of the specified basic block BLOCK.
   This function is necessary because some blocks have negative numbers.  */

static inline basic_block
find_pdom (basic_block block)
{
388
  gcc_assert (block != ENTRY_BLOCK_PTR_FOR_FN (cfun));
389

390 391
  if (block == EXIT_BLOCK_PTR_FOR_FN (cfun))
    return EXIT_BLOCK_PTR_FOR_FN (cfun);
392 393 394 395
  else
    {
      basic_block bb = get_immediate_dominator (CDI_POST_DOMINATORS, block);
      if (! bb)
396
	return EXIT_BLOCK_PTR_FOR_FN (cfun);
397 398 399 400 401 402 403 404 405 406 407 408 409
      return bb;
    }
}

/* Determine all blocks' control dependences on the given edge with edge_list
   EL index EDGE_INDEX, ala Morgan, Section 3.6.  */

void
control_dependences::find_control_dependence (int edge_index)
{
  basic_block current_block;
  basic_block ending_block;

410 411
  gcc_assert (INDEX_EDGE_PRED_BB (m_el, edge_index)
	      != EXIT_BLOCK_PTR_FOR_FN (cfun));
412

413 414
  if (INDEX_EDGE_PRED_BB (m_el, edge_index) == ENTRY_BLOCK_PTR_FOR_FN (cfun))
    ending_block = single_succ (ENTRY_BLOCK_PTR_FOR_FN (cfun));
415
  else
416
    ending_block = find_pdom (INDEX_EDGE_PRED_BB (m_el, edge_index));
417

418
  for (current_block = INDEX_EDGE_SUCC_BB (m_el, edge_index);
419 420
       current_block != ending_block
       && current_block != EXIT_BLOCK_PTR_FOR_FN (cfun);
421 422
       current_block = find_pdom (current_block))
    {
423
      edge e = INDEX_EDGE (m_el, edge_index);
424 425 426 427 428 429 430 431 432 433 434 435 436 437 438

      /* For abnormal edges, we don't make current_block control
	 dependent because instructions that throw are always necessary
	 anyway.  */
      if (e->flags & EDGE_ABNORMAL)
	continue;

      set_control_dependence_map_bit (current_block, edge_index);
    }
}

/* Record all blocks' control dependences on all edges in the edge
   list EL, ala Morgan, Section 3.6.  */

control_dependences::control_dependences (struct edge_list *edges)
439
  : m_el (edges)
440 441
{
  timevar_push (TV_CONTROL_DEPENDENCES);
442 443
  control_dependence_map.create (last_basic_block_for_fn (cfun));
  for (int i = 0; i < last_basic_block_for_fn (cfun); ++i)
444
    control_dependence_map.quick_push (BITMAP_ALLOC (NULL));
445
  for (int i = 0; i < NUM_EDGES (m_el); ++i)
446 447 448 449 450 451 452 453
    find_control_dependence (i);
  timevar_pop (TV_CONTROL_DEPENDENCES);
}

/* Free control dependences and the associated edge list.  */

control_dependences::~control_dependences ()
{
454
  for (unsigned i = 0; i < control_dependence_map.length (); ++i)
455 456
    BITMAP_FREE (control_dependence_map[i]);
  control_dependence_map.release ();
457
  free_edge_list (m_el);
458 459 460 461 462 463 464 465 466 467 468 469 470 471 472
}

/* Returns the bitmap of edges the basic-block I is dependent on.  */

bitmap
control_dependences::get_edges_dependent_on (int i)
{
  return control_dependence_map[i];
}

/* Returns the edge with index I from the edge list.  */

edge
control_dependences::get_edge (int i)
{
473
  return INDEX_EDGE (m_el, i);
474 475 476
}


477 478 479 480 481 482 483
/* Given PRED and SUCC blocks, return the edge which connects the blocks.
   If no such edge exists, return NULL.  */

edge
find_edge (basic_block pred, basic_block succ)
{
  edge e;
484
  edge_iterator ei;
485

486 487 488 489 490 491 492 493 494 495 496 497
  if (EDGE_COUNT (pred->succs) <= EDGE_COUNT (succ->preds))
    {
      FOR_EACH_EDGE (e, ei, pred->succs)
	if (e->dest == succ)
	  return e;
    }
  else
    {
      FOR_EACH_EDGE (e, ei, succ->preds)
	if (e->src == pred)
	  return e;
    }
498 499 500 501

  return NULL;
}

502 503 504 505
/* This routine will determine what, if any, edge there is between
   a specified predecessor and successor.  */

int
506
find_edge_index (struct edge_list *edge_list, basic_block pred, basic_block succ)
507 508
{
  int x;
509

510
  for (x = 0; x < NUM_EDGES (edge_list); x++)
511 512 513 514
    if (INDEX_EDGE_PRED_BB (edge_list, x) == pred
	&& INDEX_EDGE_SUCC_BB (edge_list, x) == succ)
      return x;

515 516 517
  return (EDGE_INDEX_NO_EDGE);
}

518 519
/* This routine will remove any fake predecessor edges for a basic block.
   When the edge is removed, it is also removed from whatever successor
520 521 522
   list it is in.  */

static void
523
remove_fake_predecessors (basic_block bb)
524 525
{
  edge e;
526
  edge_iterator ei;
527

528
  for (ei = ei_start (bb->preds); (e = ei_safe_edge (ei)); )
529
    {
530 531 532 533
      if ((e->flags & EDGE_FAKE) == EDGE_FAKE)
	remove_edge (e);
      else
	ei_next (&ei);
534 535 536 537 538 539 540 541
    }
}

/* This routine will remove all fake edges from the flow graph.  If
   we remove all fake successors, it will automatically remove all
   fake predecessors.  */

void
542
remove_fake_edges (void)
543
{
544
  basic_block bb;
545

546
  FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR_FOR_FN (cfun)->next_bb, NULL, next_bb)
547
    remove_fake_predecessors (bb);
548 549
}

550 551 552 553 554
/* This routine will remove all fake edges to the EXIT_BLOCK.  */

void
remove_fake_exit_edges (void)
{
555
  remove_fake_predecessors (EXIT_BLOCK_PTR_FOR_FN (cfun));
556 557 558
}


559 560 561 562 563
/* This function will add a fake edge between any block which has no
   successors, and the exit block. Some data flow equations require these
   edges to exist.  */

void
564
add_noreturn_fake_exit_edges (void)
565
{
566
  basic_block bb;
567

568
  FOR_EACH_BB_FN (bb, cfun)
569
    if (EDGE_COUNT (bb->succs) == 0)
570
      make_single_succ_edge (bb, EXIT_BLOCK_PTR_FOR_FN (cfun), EDGE_FAKE);
571 572 573 574 575 576 577 578 579 580 581 582 583 584
}

/* This function adds a fake edge between any infinite loops to the
   exit block.  Some optimizations require a path from each node to
   the exit node.

   See also Morgan, Figure 3.10, pp. 82-83.

   The current implementation is ugly, not attempting to minimize the
   number of inserted fake edges.  To reduce the number of fake edges
   to insert, add fake edges from _innermost_ loops containing only
   nodes not reachable from the exit block.  */

void
585
connect_infinite_loops_to_exit (void)
586
{
587
  basic_block unvisited_block = EXIT_BLOCK_PTR_FOR_FN (cfun);
588
  basic_block deadend_block;
Trevor Saunders committed
589
  depth_first_search_ds dfs_ds;
590 591 592 593

  /* Perform depth-first search in the reverse graph to find nodes
     reachable from the exit block.  */
  flow_dfs_compute_reverse_init (&dfs_ds);
594
  flow_dfs_compute_reverse_add_bb (&dfs_ds, EXIT_BLOCK_PTR_FOR_FN (cfun));
595 596 597 598

  /* Repeatedly add fake edges, updating the unreachable nodes.  */
  while (1)
    {
599 600
      unvisited_block = flow_dfs_compute_reverse_execute (&dfs_ds,
							  unvisited_block);
601 602
      if (!unvisited_block)
	break;
603

604
      deadend_block = dfs_find_deadend (unvisited_block);
605
      make_edge (deadend_block, EXIT_BLOCK_PTR_FOR_FN (cfun), EDGE_FAKE);
606
      flow_dfs_compute_reverse_add_bb (&dfs_ds, deadend_block);
607 608 609 610 611 612
    }

  flow_dfs_compute_reverse_finish (&dfs_ds);
  return;
}

613
/* Compute reverse top sort order.  This is computing a post order
Mike Stump committed
614
   numbering of the graph.  If INCLUDE_ENTRY_EXIT is true, then
615 616
   ENTRY_BLOCK and EXIT_BLOCK are included.  If DELETE_UNREACHABLE is
   true, unreachable blocks are deleted.  */
617

618
int
H.J. Lu committed
619
post_order_compute (int *post_order, bool include_entry_exit,
620
		    bool delete_unreachable)
621
{
622
  edge_iterator *stack;
623
  int sp;
624
  int post_order_num = 0;
625
  sbitmap visited;
626
  int count;
627

628 629 630
  if (include_entry_exit)
    post_order[post_order_num++] = EXIT_BLOCK;

631
  /* Allocate stack for back-tracking up CFG.  */
632
  stack = XNEWVEC (edge_iterator, n_basic_blocks_for_fn (cfun) + 1);
633 634 635
  sp = 0;

  /* Allocate bitmap to track nodes that have been visited.  */
636
  visited = sbitmap_alloc (last_basic_block_for_fn (cfun));
637 638

  /* None of the nodes in the CFG have been visited yet.  */
639
  bitmap_clear (visited);
640 641

  /* Push the first edge on to the stack.  */
642
  stack[sp++] = ei_start (ENTRY_BLOCK_PTR_FOR_FN (cfun)->succs);
643 644 645

  while (sp)
    {
646
      edge_iterator ei;
647 648 649 650
      basic_block src;
      basic_block dest;

      /* Look at the edge on the top of the stack.  */
651 652 653
      ei = stack[sp - 1];
      src = ei_edge (ei)->src;
      dest = ei_edge (ei)->dest;
654 655

      /* Check if the edge destination has been visited yet.  */
656 657
      if (dest != EXIT_BLOCK_PTR_FOR_FN (cfun)
	  && ! bitmap_bit_p (visited, dest->index))
658 659
	{
	  /* Mark that we have visited the destination.  */
660
	  bitmap_set_bit (visited, dest->index);
661

662
	  if (EDGE_COUNT (dest->succs) > 0)
663 664
	    /* Since the DEST node has been visited for the first
	       time, check its successors.  */
665
	    stack[sp++] = ei_start (dest->succs);
666
	  else
667
	    post_order[post_order_num++] = dest->index;
668 669 670
	}
      else
	{
671 672
	  if (ei_one_before_end_p (ei)
	      && src != ENTRY_BLOCK_PTR_FOR_FN (cfun))
673
	    post_order[post_order_num++] = src->index;
674

675 676
	  if (!ei_one_before_end_p (ei))
	    ei_next (&stack[sp - 1]);
677 678 679 680 681
	  else
	    sp--;
	}
    }

682
  if (include_entry_exit)
683 684 685 686
    {
      post_order[post_order_num++] = ENTRY_BLOCK;
      count = post_order_num;
    }
H.J. Lu committed
687
  else
688
    count = post_order_num + 2;
H.J. Lu committed
689

690 691
  /* Delete the unreachable blocks if some were found and we are
     supposed to do it.  */
692
  if (delete_unreachable && (count != n_basic_blocks_for_fn (cfun)))
693 694 695
    {
      basic_block b;
      basic_block next_bb;
696 697
      for (b = ENTRY_BLOCK_PTR_FOR_FN (cfun)->next_bb; b
	   != EXIT_BLOCK_PTR_FOR_FN (cfun); b = next_bb)
698 699
	{
	  next_bb = b->next_bb;
H.J. Lu committed
700

701
	  if (!(bitmap_bit_p (visited, b->index)))
702 703
	    delete_basic_block (b);
	}
H.J. Lu committed
704

705 706 707 708 709 710 711 712 713
      tidy_fallthru_edges ();
    }

  free (stack);
  sbitmap_free (visited);
  return post_order_num;
}


714 715 716
/* Helper routine for inverted_post_order_compute
   flow_dfs_compute_reverse_execute, and the reverse-CFG
   deapth first search in dominance.c.
717 718 719 720 721 722 723
   BB has to belong to a region of CFG
   unreachable by inverted traversal from the exit.
   i.e. there's no control flow path from ENTRY to EXIT
   that contains this BB.
   This can happen in two cases - if there's an infinite loop
   or if there's a block that has no successor
   (call to a function with no return).
H.J. Lu committed
724 725
   Some RTL passes deal with this condition by
   calling connect_infinite_loops_to_exit () and/or
726 727 728 729 730 731 732 733 734 735
   add_noreturn_fake_exit_edges ().
   However, those methods involve modifying the CFG itself
   which may not be desirable.
   Hence, we deal with the infinite loop/no return cases
   by identifying a unique basic block that can reach all blocks
   in such a region by inverted traversal.
   This function returns a basic block that guarantees
   that all blocks in the region are reachable
   by starting an inverted traversal from the returned block.  */

736
basic_block
737 738
dfs_find_deadend (basic_block bb)
{
739
  bitmap visited = BITMAP_ALLOC (NULL);
740 741 742 743

  for (;;)
    {
      if (EDGE_COUNT (bb->succs) == 0
744
	  || ! bitmap_set_bit (visited, bb->index))
745
        {
746
          BITMAP_FREE (visited);
747 748 749 750 751 752 753 754 755 756 757 758 759 760 761
          return bb;
        }

      bb = EDGE_SUCC (bb, 0)->dest;
    }

  gcc_unreachable ();
}


/* Compute the reverse top sort order of the inverted CFG
   i.e. starting from the exit block and following the edges backward
   (from successors to predecessors).
   This ordering can be used for forward dataflow problems among others.

762 763 764
   Optionally if START_POINTS is specified, start from exit block and all
   basic blocks in START_POINTS.  This is used by CD-DCE.

765 766 767 768 769 770 771 772
   This function assumes that all blocks in the CFG are reachable
   from the ENTRY (but not necessarily from EXIT).

   If there's an infinite loop,
   a simple inverted traversal starting from the blocks
   with no successors can't visit all blocks.
   To solve this problem, we first do inverted traversal
   starting from the blocks with no successor.
H.J. Lu committed
773
   And if there's any block left that's not visited by the regular
774 775
   inverted traversal from EXIT,
   those blocks are in such problematic region.
H.J. Lu committed
776
   Among those, we find one block that has
777
   any visited predecessor (which is an entry into such a region),
H.J. Lu committed
778
   and start looking for a "dead end" from that block
779 780 781
   and do another inverted traversal from that block.  */

int
782 783
inverted_post_order_compute (int *post_order,
			     sbitmap *start_points)
784 785 786 787 788 789 790
{
  basic_block bb;
  edge_iterator *stack;
  int sp;
  int post_order_num = 0;
  sbitmap visited;

791 792
  if (flag_checking)
    verify_no_unreachable_blocks ();
793

794
  /* Allocate stack for back-tracking up CFG.  */
795
  stack = XNEWVEC (edge_iterator, n_basic_blocks_for_fn (cfun) + 1);
796 797 798
  sp = 0;

  /* Allocate bitmap to track nodes that have been visited.  */
799
  visited = sbitmap_alloc (last_basic_block_for_fn (cfun));
800 801

  /* None of the nodes in the CFG have been visited yet.  */
802
  bitmap_clear (visited);
803

804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819
  if (start_points)
    {
      FOR_ALL_BB_FN (bb, cfun)
        if (bitmap_bit_p (*start_points, bb->index)
	    && EDGE_COUNT (bb->preds) > 0)
	  {
            stack[sp++] = ei_start (bb->preds);
            bitmap_set_bit (visited, bb->index);
	  }
      if (EDGE_COUNT (EXIT_BLOCK_PTR_FOR_FN (cfun)->preds))
	{
          stack[sp++] = ei_start (EXIT_BLOCK_PTR_FOR_FN (cfun)->preds);
          bitmap_set_bit (visited, EXIT_BLOCK_PTR_FOR_FN (cfun)->index);
	}
    }
  else
820
  /* Put all blocks that have no successor into the initial work list.  */
821
  FOR_ALL_BB_FN (bb, cfun)
822 823 824
    if (EDGE_COUNT (bb->succs) == 0)
      {
        /* Push the initial edge on to the stack.  */
H.J. Lu committed
825
        if (EDGE_COUNT (bb->preds) > 0)
826 827
          {
            stack[sp++] = ei_start (bb->preds);
828
            bitmap_set_bit (visited, bb->index);
829 830 831
          }
      }

H.J. Lu committed
832
  do
833 834 835 836 837 838 839 840 841 842 843 844 845 846 847
    {
      bool has_unvisited_bb = false;

      /* The inverted traversal loop. */
      while (sp)
        {
          edge_iterator ei;
          basic_block pred;

          /* Look at the edge on the top of the stack.  */
          ei = stack[sp - 1];
          bb = ei_edge (ei)->dest;
          pred = ei_edge (ei)->src;

          /* Check if the predecessor has been visited yet.  */
848
          if (! bitmap_bit_p (visited, pred->index))
849 850
            {
              /* Mark that we have visited the destination.  */
851
              bitmap_set_bit (visited, pred->index);
852 853 854 855 856 857 858 859 860 861

              if (EDGE_COUNT (pred->preds) > 0)
                /* Since the predecessor node has been visited for the first
                   time, check its predecessors.  */
                stack[sp++] = ei_start (pred->preds);
              else
                post_order[post_order_num++] = pred->index;
            }
          else
            {
862 863
	      if (bb != EXIT_BLOCK_PTR_FOR_FN (cfun)
		  && ei_one_before_end_p (ei))
864 865 866 867 868 869 870 871 872
                post_order[post_order_num++] = bb->index;

              if (!ei_one_before_end_p (ei))
                ei_next (&stack[sp - 1]);
              else
                sp--;
            }
        }

H.J. Lu committed
873
      /* Detect any infinite loop and activate the kludge.
874 875
         Note that this doesn't check EXIT_BLOCK itself
         since EXIT_BLOCK is always added after the outer do-while loop.  */
876 877
      FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR_FOR_FN (cfun),
		      EXIT_BLOCK_PTR_FOR_FN (cfun), next_bb)
878
        if (!bitmap_bit_p (visited, bb->index))
879 880 881 882 883 884 885 886 887 888 889 890
          {
            has_unvisited_bb = true;

            if (EDGE_COUNT (bb->preds) > 0)
              {
                edge_iterator ei;
                edge e;
                basic_block visited_pred = NULL;

                /* Find an already visited predecessor.  */
                FOR_EACH_EDGE (e, ei, bb->preds)
                  {
891
                    if (bitmap_bit_p (visited, e->src->index))
892 893 894 895 896 897 898
                      visited_pred = e->src;
                  }

                if (visited_pred)
                  {
                    basic_block be = dfs_find_deadend (bb);
                    gcc_assert (be != NULL);
899
                    bitmap_set_bit (visited, be->index);
900 901 902 903 904 905 906 907
                    stack[sp++] = ei_start (be->preds);
                    break;
                  }
              }
          }

      if (has_unvisited_bb && sp == 0)
        {
H.J. Lu committed
908
          /* No blocks are reachable from EXIT at all.
909
             Find a dead-end from the ENTRY, and restart the iteration. */
910
	  basic_block be = dfs_find_deadend (ENTRY_BLOCK_PTR_FOR_FN (cfun));
911
          gcc_assert (be != NULL);
912
          bitmap_set_bit (visited, be->index);
913 914 915
          stack[sp++] = ei_start (be->preds);
        }

H.J. Lu committed
916
      /* The only case the below while fires is
917 918 919 920 921 922
         when there's an infinite loop.  */
    }
  while (sp);

  /* EXIT_BLOCK is always included.  */
  post_order[post_order_num++] = EXIT_BLOCK;
923

924 925
  free (stack);
  sbitmap_free (visited);
926
  return post_order_num;
927 928
}

929 930 931 932 933
/* Compute the depth first search order of FN and store in the array
   PRE_ORDER if nonzero.  If REV_POST_ORDER is nonzero, return the
   reverse completion number for each node.  Returns the number of nodes
   visited.  A depth first search tries to get as far away from the starting
   point as quickly as possible.
934

935 936 937 938 939
   In case the function has unreachable blocks the number of nodes
   visited does not include them.

   pre_order is a really a preorder numbering of the graph.
   rev_post_order is really a reverse postorder numbering of the graph.  */
940 941

int
942 943 944
pre_and_rev_post_order_compute_fn (struct function *fn,
				   int *pre_order, int *rev_post_order,
				   bool include_entry_exit)
945
{
946
  edge_iterator *stack;
947
  int sp;
948
  int pre_order_num = 0;
949
  int rev_post_order_num = n_basic_blocks_for_fn (cfun) - 1;
950 951 952
  sbitmap visited;

  /* Allocate stack for back-tracking up CFG.  */
953
  stack = XNEWVEC (edge_iterator, n_basic_blocks_for_fn (cfun) + 1);
954 955
  sp = 0;

956 957 958 959 960 961
  if (include_entry_exit)
    {
      if (pre_order)
	pre_order[pre_order_num] = ENTRY_BLOCK;
      pre_order_num++;
      if (rev_post_order)
962
	rev_post_order[rev_post_order_num--] = EXIT_BLOCK;
963
    }
H.J. Lu committed
964
  else
965 966
    rev_post_order_num -= NUM_FIXED_BLOCKS;

967
  /* Allocate bitmap to track nodes that have been visited.  */
968
  visited = sbitmap_alloc (last_basic_block_for_fn (cfun));
969 970

  /* None of the nodes in the CFG have been visited yet.  */
971
  bitmap_clear (visited);
972 973

  /* Push the first edge on to the stack.  */
974
  stack[sp++] = ei_start (ENTRY_BLOCK_PTR_FOR_FN (fn)->succs);
975 976 977

  while (sp)
    {
978
      edge_iterator ei;
979 980 981 982
      basic_block src;
      basic_block dest;

      /* Look at the edge on the top of the stack.  */
983 984 985
      ei = stack[sp - 1];
      src = ei_edge (ei)->src;
      dest = ei_edge (ei)->dest;
986 987

      /* Check if the edge destination has been visited yet.  */
988
      if (dest != EXIT_BLOCK_PTR_FOR_FN (fn)
989
	  && ! bitmap_bit_p (visited, dest->index))
990 991
	{
	  /* Mark that we have visited the destination.  */
992
	  bitmap_set_bit (visited, dest->index);
993

994 995
	  if (pre_order)
	    pre_order[pre_order_num] = dest->index;
996

997
	  pre_order_num++;
998

999
	  if (EDGE_COUNT (dest->succs) > 0)
1000 1001
	    /* Since the DEST node has been visited for the first
	       time, check its successors.  */
1002
	    stack[sp++] = ei_start (dest->succs);
1003
	  else if (rev_post_order)
1004 1005
	    /* There are no successors for the DEST node so assign
	       its reverse completion number.  */
1006
	    rev_post_order[rev_post_order_num--] = dest->index;
1007 1008 1009
	}
      else
	{
1010
	  if (ei_one_before_end_p (ei)
1011
	      && src != ENTRY_BLOCK_PTR_FOR_FN (fn)
1012
	      && rev_post_order)
1013 1014
	    /* There are no more successors for the SRC node
	       so assign its reverse completion number.  */
1015
	    rev_post_order[rev_post_order_num--] = src->index;
1016

1017 1018
	  if (!ei_one_before_end_p (ei))
	    ei_next (&stack[sp - 1]);
1019 1020 1021 1022 1023 1024 1025 1026
	  else
	    sp--;
	}
    }

  free (stack);
  sbitmap_free (visited);

1027 1028 1029 1030 1031 1032
  if (include_entry_exit)
    {
      if (pre_order)
	pre_order[pre_order_num] = EXIT_BLOCK;
      pre_order_num++;
      if (rev_post_order)
1033
	rev_post_order[rev_post_order_num--] = ENTRY_BLOCK;
1034
    }
1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050

  return pre_order_num;
}

/* Like pre_and_rev_post_order_compute_fn but operating on the
   current function and asserting that all nodes were visited.  */

int
pre_and_rev_post_order_compute (int *pre_order, int *rev_post_order,
				bool include_entry_exit)
{
  int pre_order_num
    = pre_and_rev_post_order_compute_fn (cfun, pre_order, rev_post_order,
					 include_entry_exit);
  if (include_entry_exit)
    /* The number of nodes visited should be the number of blocks.  */
1051
    gcc_assert (pre_order_num == n_basic_blocks_for_fn (cfun));
1052 1053 1054
  else
    /* The number of nodes visited should be the number of blocks minus
       the entry and exit blocks which are not visited here.  */
1055 1056
    gcc_assert (pre_order_num
		== (n_basic_blocks_for_fn (cfun) - NUM_FIXED_BLOCKS));
1057

1058
  return pre_order_num;
1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087
}

/* Compute the depth first search order on the _reverse_ graph and
   store in the array DFS_ORDER, marking the nodes visited in VISITED.
   Returns the number of nodes visited.

   The computation is split into three pieces:

   flow_dfs_compute_reverse_init () creates the necessary data
   structures.

   flow_dfs_compute_reverse_add_bb () adds a basic block to the data
   structures.  The block will start the search.

   flow_dfs_compute_reverse_execute () continues (or starts) the
   search using the block on the top of the stack, stopping when the
   stack is empty.

   flow_dfs_compute_reverse_finish () destroys the necessary data
   structures.

   Thus, the user will probably call ..._init(), call ..._add_bb() to
   add a beginning basic block to the stack, call ..._execute(),
   possibly add another bb to the stack and again call ..._execute(),
   ..., and finally call _finish().  */

/* Initialize the data structures used for depth-first search on the
   reverse graph.  If INITIALIZE_STACK is nonzero, the exit block is
   added to the basic block stack.  DATA is the current depth-first
1088
   search context.  If INITIALIZE_STACK is nonzero, there is an
1089 1090 1091
   element on the stack.  */

static void
Trevor Saunders committed
1092
flow_dfs_compute_reverse_init (depth_first_search_ds *data)
1093 1094
{
  /* Allocate stack for back-tracking up CFG.  */
1095
  data->stack = XNEWVEC (basic_block, n_basic_blocks_for_fn (cfun));
1096 1097 1098
  data->sp = 0;

  /* Allocate bitmap to track nodes that have been visited.  */
1099
  data->visited_blocks = sbitmap_alloc (last_basic_block_for_fn (cfun));
1100 1101

  /* None of the nodes in the CFG have been visited yet.  */
1102
  bitmap_clear (data->visited_blocks);
1103 1104 1105 1106 1107 1108 1109 1110 1111

  return;
}

/* Add the specified basic block to the top of the dfs data
   structures.  When the search continues, it will start at the
   block.  */

static void
Trevor Saunders committed
1112
flow_dfs_compute_reverse_add_bb (depth_first_search_ds *data, basic_block bb)
1113 1114
{
  data->stack[data->sp++] = bb;
1115
  bitmap_set_bit (data->visited_blocks, bb->index);
1116 1117
}

1118 1119 1120 1121
/* Continue the depth-first search through the reverse graph starting with the
   block at the stack's top and ending when the stack is empty.  Visited nodes
   are marked.  Returns an unvisited basic block, or NULL if there is none
   available.  */
1122 1123

static basic_block
Trevor Saunders committed
1124
flow_dfs_compute_reverse_execute (depth_first_search_ds *data,
1125
				  basic_block last_unvisited)
1126 1127 1128
{
  basic_block bb;
  edge e;
1129
  edge_iterator ei;
1130 1131 1132 1133

  while (data->sp > 0)
    {
      bb = data->stack[--data->sp];
1134

1135
      /* Perform depth-first search on adjacent vertices.  */
1136
      FOR_EACH_EDGE (e, ei, bb->preds)
1137
	if (!bitmap_bit_p (data->visited_blocks, e->src->index))
1138
	  flow_dfs_compute_reverse_add_bb (data, e->src);
1139 1140 1141
    }

  /* Determine if there are unvisited basic blocks.  */
1142
  FOR_BB_BETWEEN (bb, last_unvisited, NULL, prev_bb)
1143
    if (!bitmap_bit_p (data->visited_blocks, bb->index))
1144
      return bb;
1145

1146 1147 1148 1149 1150 1151 1152
  return NULL;
}

/* Destroy the data structures needed for depth-first search on the
   reverse graph.  */

static void
Trevor Saunders committed
1153
flow_dfs_compute_reverse_finish (depth_first_search_ds *data)
1154 1155 1156 1157
{
  free (data->stack);
  sbitmap_free (data->visited_blocks);
}
1158 1159 1160 1161 1162

/* Performs dfs search from BB over vertices satisfying PREDICATE;
   if REVERSE, go against direction of edges.  Returns number of blocks
   found and their list in RSLT.  RSLT can contain at most RSLT_MAX items.  */
int
1163
dfs_enumerate_from (basic_block bb, int reverse,
1164 1165
		    bool (*predicate) (const_basic_block, const void *),
		    basic_block *rslt, int rslt_max, const void *data)
1166 1167 1168
{
  basic_block *st, lbb;
  int sp = 0, tv = 0;
1169 1170 1171 1172 1173 1174 1175 1176 1177 1178
  unsigned size;

  /* A bitmap to keep track of visited blocks.  Allocating it each time
     this function is called is not possible, since dfs_enumerate_from
     is often used on small (almost) disjoint parts of cfg (bodies of
     loops), and allocating a large sbitmap would lead to quadratic
     behavior.  */
  static sbitmap visited;
  static unsigned v_size;

1179 1180 1181
#define MARK_VISITED(BB) (bitmap_set_bit (visited, (BB)->index))
#define UNMARK_VISITED(BB) (bitmap_clear_bit (visited, (BB)->index))
#define VISITED_P(BB) (bitmap_bit_p (visited, (BB)->index))
1182 1183

  /* Resize the VISITED sbitmap if necessary.  */
1184
  size = last_basic_block_for_fn (cfun);
1185 1186 1187 1188 1189 1190 1191
  if (size < 10)
    size = 10;

  if (!visited)
    {

      visited = sbitmap_alloc (size);
1192
      bitmap_clear (visited);
1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203
      v_size = size;
    }
  else if (v_size < size)
    {
      /* Ensure that we increase the size of the sbitmap exponentially.  */
      if (2 * v_size > size)
	size = 2 * v_size;

      visited = sbitmap_resize (visited, size, 0);
      v_size = size;
    }
1204

1205
  st = XNEWVEC (basic_block, rslt_max);
1206
  rslt[tv++] = st[sp++] = bb;
1207
  MARK_VISITED (bb);
1208 1209 1210
  while (sp)
    {
      edge e;
1211
      edge_iterator ei;
1212 1213
      lbb = st[--sp];
      if (reverse)
Mike Stump committed
1214
	{
1215
	  FOR_EACH_EDGE (e, ei, lbb->preds)
1216
	    if (!VISITED_P (e->src) && predicate (e->src, data))
1217
	      {
Mike Stump committed
1218 1219 1220
		gcc_assert (tv != rslt_max);
		rslt[tv++] = st[sp++] = e->src;
		MARK_VISITED (e->src);
1221
	      }
Mike Stump committed
1222
	}
1223
      else
Mike Stump committed
1224
	{
1225
	  FOR_EACH_EDGE (e, ei, lbb->succs)
1226
	    if (!VISITED_P (e->dest) && predicate (e->dest, data))
1227
	      {
Mike Stump committed
1228 1229 1230
		gcc_assert (tv != rslt_max);
		rslt[tv++] = st[sp++] = e->dest;
		MARK_VISITED (e->dest);
1231 1232 1233 1234 1235
	      }
	}
    }
  free (st);
  for (sp = 0; sp < tv; sp++)
1236
    UNMARK_VISITED (rslt[sp]);
1237
  return tv;
1238 1239 1240
#undef MARK_VISITED
#undef UNMARK_VISITED
#undef VISITED_P
1241
}
1242 1243


1244
/* Compute dominance frontiers, ala Harvey, Ferrante, et al.
Mike Stump committed
1245

1246
   This algorithm can be found in Timothy Harvey's PhD thesis, at
1247
   http://www.cs.rice.edu/~harv/dissertation.pdf in the section on iterative
1248
   dominance algorithms.
1249

1250
   First, we identify each join point, j (any node with more than one
Mike Stump committed
1251
   incoming edge is a join point).
1252

1253
   We then examine each predecessor, p, of j and walk up the dominator tree
Mike Stump committed
1254 1255
   starting at p.

1256 1257 1258 1259 1260 1261
   We stop the walk when we reach j's immediate dominator - j is in the
   dominance frontier of each of  the nodes in the walk, except for j's
   immediate dominator. Intuitively, all of the rest of j's dominators are
   shared by j's predecessors as well.
   Since they dominate j, they will not have j in their dominance frontiers.

Mike Stump committed
1262
   The number of nodes touched by this algorithm is equal to the size
1263 1264
   of the dominance frontiers, no more, no less.
*/
1265 1266 1267


static void
1268
compute_dominance_frontiers_1 (bitmap_head *frontiers)
1269
{
1270
  edge p;
1271
  edge_iterator ei;
1272
  basic_block b;
1273
  FOR_EACH_BB_FN (b, cfun)
1274
    {
1275
      if (EDGE_COUNT (b->preds) >= 2)
1276
	{
1277 1278 1279 1280
	  FOR_EACH_EDGE (p, ei, b->preds)
	    {
	      basic_block runner = p->src;
	      basic_block domsb;
1281
	      if (runner == ENTRY_BLOCK_PTR_FOR_FN (cfun))
1282
		continue;
Mike Stump committed
1283

1284 1285 1286
	      domsb = get_immediate_dominator (CDI_DOMINATORS, b);
	      while (runner != domsb)
		{
1287
		  if (!bitmap_set_bit (&frontiers[runner->index],
1288
				       b->index))
1289
		    break;
1290 1291 1292 1293
		  runner = get_immediate_dominator (CDI_DOMINATORS,
						    runner);
		}
	    }
1294
	}
1295
    }
Mike Stump committed
1296 1297
}

1298 1299

void
1300
compute_dominance_frontiers (bitmap_head *frontiers)
1301 1302 1303
{
  timevar_push (TV_DOM_FRONTIERS);

1304
  compute_dominance_frontiers_1 (frontiers);
1305 1306 1307

  timevar_pop (TV_DOM_FRONTIERS);
}
1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318

/* 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 for freeing the memory
   allocated for the return value.  */

bitmap
1319
compute_idf (bitmap def_blocks, bitmap_head *dfs)
1320 1321 1322 1323 1324
{
  bitmap_iterator bi;
  unsigned bb_index, i;
  bitmap phi_insertion_points;

1325
  /* Each block can appear at most twice on the work-stack.  */
Trevor Saunders committed
1326
  auto_vec<int> work_stack (2 * n_basic_blocks_for_fn (cfun));
1327 1328 1329
  phi_insertion_points = BITMAP_ALLOC (NULL);

  /* Seed the work list with all the blocks in DEF_BLOCKS.  We use
1330
     vec::quick_push here for speed.  This is safe because we know that
1331 1332 1333
     the number of definition blocks is no greater than the number of
     basic blocks, which is the initial capacity of WORK_STACK.  */
  EXECUTE_IF_SET_IN_BITMAP (def_blocks, 0, bb_index, bi)
1334
    work_stack.quick_push (bb_index);
1335 1336 1337 1338 1339 1340

  /* 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.  */
1341
  while (work_stack.length () > 0)
1342
    {
1343
      bb_index = work_stack.pop ();
1344 1345 1346 1347 1348 1349

      /* 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.  */
1350 1351
      gcc_checking_assert (bb_index
			   < (unsigned) last_basic_block_for_fn (cfun));
1352

1353
      EXECUTE_IF_AND_COMPL_IN_BITMAP (&dfs[bb_index], phi_insertion_points,
1354 1355
	                              0, i, bi)
	{
1356
	  work_stack.quick_push (i);
1357 1358 1359 1360 1361 1362 1363
	  bitmap_set_bit (phi_insertion_points, i);
	}
    }

  return phi_insertion_points;
}

1364 1365 1366 1367 1368 1369
/* Intersection and union of preds/succs for sbitmap based data flow
   solvers.  All four functions defined below take the same arguments:
   B is the basic block to perform the operation for.  DST is the
   target sbitmap, i.e. the result.  SRC is an sbitmap vector of size
   last_basic_block so that it can be indexed with basic block indices.
   DST may be (but does not have to be) SRC[B->index].  */
1370

1371 1372 1373 1374
/* Set the bitmap DST to the intersection of SRC of successors of
   basic block B.  */

void
1375
bitmap_intersection_of_succs (sbitmap dst, sbitmap *src, basic_block b)
1376 1377 1378 1379 1380 1381 1382 1383 1384 1385
{
  unsigned int set_size = dst->size;
  edge e;
  unsigned ix;

  gcc_assert (!dst->popcount);

  for (e = NULL, ix = 0; ix < EDGE_COUNT (b->succs); ix++)
    {
      e = EDGE_SUCC (b, ix);
1386
      if (e->dest == EXIT_BLOCK_PTR_FOR_FN (cfun))
1387 1388
	continue;

1389
      bitmap_copy (dst, src[e->dest->index]);
1390 1391 1392 1393
      break;
    }

  if (e == 0)
1394
    bitmap_ones (dst);
1395 1396 1397 1398 1399 1400 1401
  else
    for (++ix; ix < EDGE_COUNT (b->succs); ix++)
      {
	unsigned int i;
	SBITMAP_ELT_TYPE *p, *r;

	e = EDGE_SUCC (b, ix);
1402
	if (e->dest == EXIT_BLOCK_PTR_FOR_FN (cfun))
1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415
	  continue;

	p = src[e->dest->index]->elms;
	r = dst->elms;
	for (i = 0; i < set_size; i++)
	  *r++ &= *p++;
      }
}

/* Set the bitmap DST to the intersection of SRC of predecessors of
   basic block B.  */

void
1416
bitmap_intersection_of_preds (sbitmap dst, sbitmap *src, basic_block b)
1417 1418 1419 1420 1421 1422 1423 1424 1425 1426
{
  unsigned int set_size = dst->size;
  edge e;
  unsigned ix;

  gcc_assert (!dst->popcount);

  for (e = NULL, ix = 0; ix < EDGE_COUNT (b->preds); ix++)
    {
      e = EDGE_PRED (b, ix);
1427
      if (e->src == ENTRY_BLOCK_PTR_FOR_FN (cfun))
1428 1429
	continue;

1430
      bitmap_copy (dst, src[e->src->index]);
1431 1432 1433 1434
      break;
    }

  if (e == 0)
1435
    bitmap_ones (dst);
1436 1437 1438 1439 1440 1441 1442
  else
    for (++ix; ix < EDGE_COUNT (b->preds); ix++)
      {
	unsigned int i;
	SBITMAP_ELT_TYPE *p, *r;

	e = EDGE_PRED (b, ix);
1443
	if (e->src == ENTRY_BLOCK_PTR_FOR_FN (cfun))
1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456
	  continue;

	p = src[e->src->index]->elms;
	r = dst->elms;
	for (i = 0; i < set_size; i++)
	  *r++ &= *p++;
      }
}

/* Set the bitmap DST to the union of SRC of successors of
   basic block B.  */

void
1457
bitmap_union_of_succs (sbitmap dst, sbitmap *src, basic_block b)
1458 1459 1460 1461 1462 1463 1464 1465 1466 1467
{
  unsigned int set_size = dst->size;
  edge e;
  unsigned ix;

  gcc_assert (!dst->popcount);

  for (ix = 0; ix < EDGE_COUNT (b->succs); ix++)
    {
      e = EDGE_SUCC (b, ix);
1468
      if (e->dest == EXIT_BLOCK_PTR_FOR_FN (cfun))
1469 1470
	continue;

1471
      bitmap_copy (dst, src[e->dest->index]);
1472 1473 1474 1475
      break;
    }

  if (ix == EDGE_COUNT (b->succs))
1476
    bitmap_clear (dst);
1477 1478 1479 1480 1481 1482 1483
  else
    for (ix++; ix < EDGE_COUNT (b->succs); ix++)
      {
	unsigned int i;
	SBITMAP_ELT_TYPE *p, *r;

	e = EDGE_SUCC (b, ix);
1484
	if (e->dest == EXIT_BLOCK_PTR_FOR_FN (cfun))
1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497
	  continue;

	p = src[e->dest->index]->elms;
	r = dst->elms;
	for (i = 0; i < set_size; i++)
	  *r++ |= *p++;
      }
}

/* Set the bitmap DST to the union of SRC of predecessors of
   basic block B.  */

void
1498
bitmap_union_of_preds (sbitmap dst, sbitmap *src, basic_block b)
1499 1500 1501 1502 1503 1504 1505 1506 1507 1508
{
  unsigned int set_size = dst->size;
  edge e;
  unsigned ix;

  gcc_assert (!dst->popcount);

  for (ix = 0; ix < EDGE_COUNT (b->preds); ix++)
    {
      e = EDGE_PRED (b, ix);
1509
      if (e->src== ENTRY_BLOCK_PTR_FOR_FN (cfun))
1510 1511
	continue;

1512
      bitmap_copy (dst, src[e->src->index]);
1513 1514 1515 1516
      break;
    }

  if (ix == EDGE_COUNT (b->preds))
1517
    bitmap_clear (dst);
1518 1519 1520 1521 1522 1523 1524
  else
    for (ix++; ix < EDGE_COUNT (b->preds); ix++)
      {
	unsigned int i;
	SBITMAP_ELT_TYPE *p, *r;

	e = EDGE_PRED (b, ix);
1525
	if (e->src == ENTRY_BLOCK_PTR_FOR_FN (cfun))
1526 1527 1528 1529 1530 1531 1532 1533
	  continue;

	p = src[e->src->index]->elms;
	r = dst->elms;
	for (i = 0; i < set_size; i++)
	  *r++ |= *p++;
      }
}
1534 1535 1536 1537 1538 1539 1540 1541 1542

/* Returns the list of basic blocks in the function in an order that guarantees
   that if a block X has just a single predecessor Y, then Y is after X in the
   ordering.  */

basic_block *
single_pred_before_succ_order (void)
{
  basic_block x, y;
1543 1544
  basic_block *order = XNEWVEC (basic_block, n_basic_blocks_for_fn (cfun));
  unsigned n = n_basic_blocks_for_fn (cfun) - NUM_FIXED_BLOCKS;
1545
  unsigned np, i;
1546
  sbitmap visited = sbitmap_alloc (last_basic_block_for_fn (cfun));
1547 1548 1549 1550 1551 1552

#define MARK_VISITED(BB) (bitmap_set_bit (visited, (BB)->index))
#define VISITED_P(BB) (bitmap_bit_p (visited, (BB)->index))

  bitmap_clear (visited);

1553
  MARK_VISITED (ENTRY_BLOCK_PTR_FOR_FN (cfun));
1554
  FOR_EACH_BB_FN (x, cfun)
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
    {
      if (VISITED_P (x))
	continue;

      /* Walk the predecessors of x as long as they have precisely one
	 predecessor and add them to the list, so that they get stored
	 after x.  */
      for (y = x, np = 1;
	   single_pred_p (y) && !VISITED_P (single_pred (y));
	   y = single_pred (y))
	np++;
      for (y = x, i = n - np;
	   single_pred_p (y) && !VISITED_P (single_pred (y));
	   y = single_pred (y), i++)
	{
	  order[i] = y;
	  MARK_VISITED (y);
	}
      order[i] = y;
      MARK_VISITED (y);

      gcc_assert (i == n - 1);
      n -= np;
    }

  sbitmap_free (visited);
  gcc_assert (n == 0);
  return order;

#undef MARK_VISITED
#undef VISITED_P
}