1 /*
   2  * Copyright 1997-2008 Sun Microsystems, Inc.  All Rights Reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
  20  * CA 95054 USA or visit www.sun.com if you need additional information or
  21  * have any questions.
  22  *
  23  */
  24 
  25 // Optimization - Graph Style
  26 
  27 #include "incls/_precompiled.incl"
  28 #include "incls/_block.cpp.incl"
  29 
  30 
  31 //-----------------------------------------------------------------------------
  32 void Block_Array::grow( uint i ) {
  33   assert(i >= Max(), "must be an overflow");
  34   debug_only(_limit = i+1);
  35   if( i < _size )  return;
  36   if( !_size ) {
  37     _size = 1;
  38     _blocks = (Block**)_arena->Amalloc( _size * sizeof(Block*) );
  39     _blocks[0] = NULL;
  40   }
  41   uint old = _size;
  42   while( i >= _size ) _size <<= 1;      // Double to fit
  43   _blocks = (Block**)_arena->Arealloc( _blocks, old*sizeof(Block*),_size*sizeof(Block*));
  44   Copy::zero_to_bytes( &_blocks[old], (_size-old)*sizeof(Block*) );
  45 }
  46 
  47 //=============================================================================
  48 void Block_List::remove(uint i) {
  49   assert(i < _cnt, "index out of bounds");
  50   Copy::conjoint_words_to_lower((HeapWord*)&_blocks[i+1], (HeapWord*)&_blocks[i], ((_cnt-i-1)*sizeof(Block*)));
  51   pop(); // shrink list by one block
  52 }
  53 
  54 void Block_List::insert(uint i, Block *b) {
  55   push(b); // grow list by one block
  56   Copy::conjoint_words_to_higher((HeapWord*)&_blocks[i], (HeapWord*)&_blocks[i+1], ((_cnt-i-1)*sizeof(Block*)));
  57   _blocks[i] = b;
  58 }
  59 
  60 #ifndef PRODUCT
  61 void Block_List::print() {
  62   for (uint i=0; i < size(); i++) {
  63     tty->print("B%d ", _blocks[i]->_pre_order);
  64   }
  65   tty->print("size = %d\n", size());
  66 }
  67 #endif
  68 
  69 //=============================================================================
  70 
  71 uint Block::code_alignment() {
  72   // Check for Root block
  73   if( _pre_order == 0 ) return CodeEntryAlignment;
  74   // Check for Start block
  75   if( _pre_order == 1 ) return InteriorEntryAlignment;
  76   // Check for loop alignment
  77   if (has_loop_alignment())  return loop_alignment();
  78 
  79   return 1;                     // no particular alignment
  80 }
  81 
  82 uint Block::compute_loop_alignment() {
  83   Node *h = head();
  84   if( h->is_Loop() && h->as_Loop()->is_inner_loop() )  {
  85     // Pre- and post-loops have low trip count so do not bother with
  86     // NOPs for align loop head.  The constants are hidden from tuning
  87     // but only because my "divide by 4" heuristic surely gets nearly
  88     // all possible gain (a "do not align at all" heuristic has a
  89     // chance of getting a really tiny gain).
  90     if( h->is_CountedLoop() && (h->as_CountedLoop()->is_pre_loop() ||
  91                                 h->as_CountedLoop()->is_post_loop()) )
  92       return (OptoLoopAlignment > 4) ? (OptoLoopAlignment>>2) : 1;
  93     // Loops with low backedge frequency should not be aligned.
  94     Node *n = h->in(LoopNode::LoopBackControl)->in(0);
  95     if( n->is_MachIf() && n->as_MachIf()->_prob < 0.01 ) {
  96       return 1;             // Loop does not loop, more often than not!
  97     }
  98     return OptoLoopAlignment; // Otherwise align loop head
  99   }
 100 
 101   return 1;                     // no particular alignment
 102 }
 103 
 104 //-----------------------------------------------------------------------------
 105 // Compute the size of first 'inst_cnt' instructions in this block.
 106 // Return the number of instructions left to compute if the block has
 107 // less then 'inst_cnt' instructions. Stop, and return 0 if sum_size
 108 // exceeds OptoLoopAlignment.
 109 uint Block::compute_first_inst_size(uint& sum_size, uint inst_cnt,
 110                                     PhaseRegAlloc* ra) {
 111   uint last_inst = _nodes.size();
 112   for( uint j = 0; j < last_inst && inst_cnt > 0; j++ ) {
 113     uint inst_size = _nodes[j]->size(ra);
 114     if( inst_size > 0 ) {
 115       inst_cnt--;
 116       uint sz = sum_size + inst_size;
 117       if( sz <= (uint)OptoLoopAlignment ) {
 118         // Compute size of instructions which fit into fetch buffer only
 119         // since all inst_cnt instructions will not fit even if we align them.
 120         sum_size = sz;
 121       } else {
 122         return 0;
 123       }
 124     }
 125   }
 126   return inst_cnt;
 127 }
 128 
 129 //-----------------------------------------------------------------------------
 130 uint Block::find_node( const Node *n ) const {
 131   for( uint i = 0; i < _nodes.size(); i++ ) {
 132     if( _nodes[i] == n )
 133       return i;
 134   }
 135   ShouldNotReachHere();
 136   return 0;
 137 }
 138 
 139 // Find and remove n from block list
 140 void Block::find_remove( const Node *n ) {
 141   _nodes.remove(find_node(n));
 142 }
 143 
 144 //------------------------------is_Empty---------------------------------------
 145 // Return empty status of a block.  Empty blocks contain only the head, other
 146 // ideal nodes, and an optional trailing goto.
 147 int Block::is_Empty() const {
 148 
 149   // Root or start block is not considered empty
 150   if (head()->is_Root() || head()->is_Start()) {
 151     return not_empty;
 152   }
 153 
 154   int success_result = completely_empty;
 155   int end_idx = _nodes.size()-1;
 156 
 157   // Check for ending goto
 158   if ((end_idx > 0) && (_nodes[end_idx]->is_Goto())) {
 159     success_result = empty_with_goto;
 160     end_idx--;
 161   }
 162 
 163   // Unreachable blocks are considered empty
 164   if (num_preds() <= 1) {
 165     return success_result;
 166   }
 167 
 168   // Ideal nodes are allowable in empty blocks: skip them  Only MachNodes
 169   // turn directly into code, because only MachNodes have non-trivial
 170   // emit() functions.
 171   while ((end_idx > 0) && !_nodes[end_idx]->is_Mach()) {
 172     end_idx--;
 173   }
 174 
 175   // No room for any interesting instructions?
 176   if (end_idx == 0) {
 177     return success_result;
 178   }
 179 
 180   return not_empty;
 181 }
 182 
 183 //------------------------------has_uncommon_code------------------------------
 184 // Return true if the block's code implies that it is not likely to be
 185 // executed infrequently.  Check to see if the block ends in a Halt or
 186 // a low probability call.
 187 bool Block::has_uncommon_code() const {
 188   Node* en = end();
 189 
 190   if (en->is_Goto())
 191     en = en->in(0);
 192   if (en->is_Catch())
 193     en = en->in(0);
 194   if (en->is_Proj() && en->in(0)->is_MachCall()) {
 195     MachCallNode* call = en->in(0)->as_MachCall();
 196     if (call->cnt() != COUNT_UNKNOWN && call->cnt() <= PROB_UNLIKELY_MAG(4)) {
 197       // This is true for slow-path stubs like new_{instance,array},
 198       // slow_arraycopy, complete_monitor_locking, uncommon_trap.
 199       // The magic number corresponds to the probability of an uncommon_trap,
 200       // even though it is a count not a probability.
 201       return true;
 202     }
 203   }
 204 
 205   int op = en->is_Mach() ? en->as_Mach()->ideal_Opcode() : en->Opcode();
 206   return op == Op_Halt;
 207 }
 208 
 209 //------------------------------is_uncommon------------------------------------
 210 // True if block is low enough frequency or guarded by a test which
 211 // mostly does not go here.
 212 bool Block::is_uncommon( Block_Array &bbs ) const {
 213   // Initial blocks must never be moved, so are never uncommon.
 214   if (head()->is_Root() || head()->is_Start())  return false;
 215 
 216   // Check for way-low freq
 217   if( _freq < BLOCK_FREQUENCY(0.00001f) ) return true;
 218 
 219   // Look for code shape indicating uncommon_trap or slow path
 220   if (has_uncommon_code()) return true;
 221 
 222   const float epsilon = 0.05f;
 223   const float guard_factor = PROB_UNLIKELY_MAG(4) / (1.f - epsilon);
 224   uint uncommon_preds = 0;
 225   uint freq_preds = 0;
 226   uint uncommon_for_freq_preds = 0;
 227 
 228   for( uint i=1; i<num_preds(); i++ ) {
 229     Block* guard = bbs[pred(i)->_idx];
 230     // Check to see if this block follows its guard 1 time out of 10000
 231     // or less.
 232     //
 233     // See list of magnitude-4 unlikely probabilities in cfgnode.hpp which
 234     // we intend to be "uncommon", such as slow-path TLE allocation,
 235     // predicted call failure, and uncommon trap triggers.
 236     //
 237     // Use an epsilon value of 5% to allow for variability in frequency
 238     // predictions and floating point calculations. The net effect is
 239     // that guard_factor is set to 9500.
 240     //
 241     // Ignore low-frequency blocks.
 242     // The next check is (guard->_freq < 1.e-5 * 9500.).
 243     if(guard->_freq*BLOCK_FREQUENCY(guard_factor) < BLOCK_FREQUENCY(0.00001f)) {
 244       uncommon_preds++;
 245     } else {
 246       freq_preds++;
 247       if( _freq < guard->_freq * guard_factor ) {
 248         uncommon_for_freq_preds++;
 249       }
 250     }
 251   }
 252   if( num_preds() > 1 &&
 253       // The block is uncommon if all preds are uncommon or
 254       (uncommon_preds == (num_preds()-1) ||
 255       // it is uncommon for all frequent preds.
 256        uncommon_for_freq_preds == freq_preds) ) {
 257     return true;
 258   }
 259   return false;
 260 }
 261 
 262 //------------------------------dump-------------------------------------------
 263 #ifndef PRODUCT
 264 void Block::dump_bidx(const Block* orig) const {
 265   if (_pre_order) tty->print("B%d",_pre_order);
 266   else tty->print("N%d", head()->_idx);
 267 
 268   if (Verbose && orig != this) {
 269     // Dump the original block's idx
 270     tty->print(" (");
 271     orig->dump_bidx(orig);
 272     tty->print(")");
 273   }
 274 }
 275 
 276 void Block::dump_pred(const Block_Array *bbs, Block* orig) const {
 277   if (is_connector()) {
 278     for (uint i=1; i<num_preds(); i++) {
 279       Block *p = ((*bbs)[pred(i)->_idx]);
 280       p->dump_pred(bbs, orig);
 281     }
 282   } else {
 283     dump_bidx(orig);
 284     tty->print(" ");
 285   }
 286 }
 287 
 288 void Block::dump_head( const Block_Array *bbs ) const {
 289   // Print the basic block
 290   dump_bidx(this);
 291   tty->print(": #\t");
 292 
 293   // Print the incoming CFG edges and the outgoing CFG edges
 294   for( uint i=0; i<_num_succs; i++ ) {
 295     non_connector_successor(i)->dump_bidx(_succs[i]);
 296     tty->print(" ");
 297   }
 298   tty->print("<- ");
 299   if( head()->is_block_start() ) {
 300     for (uint i=1; i<num_preds(); i++) {
 301       Node *s = pred(i);
 302       if (bbs) {
 303         Block *p = (*bbs)[s->_idx];
 304         p->dump_pred(bbs, p);
 305       } else {
 306         while (!s->is_block_start())
 307           s = s->in(0);
 308         tty->print("N%d ", s->_idx );
 309       }
 310     }
 311   } else
 312     tty->print("BLOCK HEAD IS JUNK  ");
 313 
 314   // Print loop, if any
 315   const Block *bhead = this;    // Head of self-loop
 316   Node *bh = bhead->head();
 317   if( bbs && bh->is_Loop() && !head()->is_Root() ) {
 318     LoopNode *loop = bh->as_Loop();
 319     const Block *bx = (*bbs)[loop->in(LoopNode::LoopBackControl)->_idx];
 320     while (bx->is_connector()) {
 321       bx = (*bbs)[bx->pred(1)->_idx];
 322     }
 323     tty->print("\tLoop: B%d-B%d ", bhead->_pre_order, bx->_pre_order);
 324     // Dump any loop-specific bits, especially for CountedLoops.
 325     loop->dump_spec(tty);
 326   } else if (has_loop_alignment()) {
 327     tty->print(" top-of-loop");
 328   }
 329   tty->print(" Freq: %g",_freq);
 330   if( Verbose || WizardMode ) {
 331     tty->print(" IDom: %d/#%d", _idom ? _idom->_pre_order : 0, _dom_depth);
 332     tty->print(" RegPressure: %d",_reg_pressure);
 333     tty->print(" IHRP Index: %d",_ihrp_index);
 334     tty->print(" FRegPressure: %d",_freg_pressure);
 335     tty->print(" FHRP Index: %d",_fhrp_index);
 336   }
 337   tty->print_cr("");
 338 }
 339 
 340 void Block::dump() const { dump(0); }
 341 
 342 void Block::dump( const Block_Array *bbs ) const {
 343   dump_head(bbs);
 344   uint cnt = _nodes.size();
 345   for( uint i=0; i<cnt; i++ )
 346     _nodes[i]->dump();
 347   tty->print("\n");
 348 }
 349 #endif
 350 
 351 //=============================================================================
 352 //------------------------------PhaseCFG---------------------------------------
 353 PhaseCFG::PhaseCFG( Arena *a, RootNode *r, Matcher &m ) :
 354   Phase(CFG),
 355   _bbs(a),
 356   _root(r)
 357 #ifndef PRODUCT
 358   , _trace_opto_pipelining(TraceOptoPipelining || C->method_has_option("TraceOptoPipelining"))
 359 #endif
 360 {
 361   ResourceMark rm;
 362   // I'll need a few machine-specific GotoNodes.  Make an Ideal GotoNode,
 363   // then Match it into a machine-specific Node.  Then clone the machine
 364   // Node on demand.
 365   Node *x = new (C, 1) GotoNode(NULL);
 366   x->init_req(0, x);
 367   _goto = m.match_tree(x);
 368   assert(_goto != NULL, "");
 369   _goto->set_req(0,_goto);
 370 
 371   // Build the CFG in Reverse Post Order
 372   _num_blocks = build_cfg();
 373   _broot = _bbs[_root->_idx];
 374 }
 375 
 376 //------------------------------build_cfg--------------------------------------
 377 // Build a proper looking CFG.  Make every block begin with either a StartNode
 378 // or a RegionNode.  Make every block end with either a Goto, If or Return.
 379 // The RootNode both starts and ends it's own block.  Do this with a recursive
 380 // backwards walk over the control edges.
 381 uint PhaseCFG::build_cfg() {
 382   Arena *a = Thread::current()->resource_area();
 383   VectorSet visited(a);
 384 
 385   // Allocate stack with enough space to avoid frequent realloc
 386   Node_Stack nstack(a, C->unique() >> 1);
 387   nstack.push(_root, 0);
 388   uint sum = 0;                 // Counter for blocks
 389 
 390   while (nstack.is_nonempty()) {
 391     // node and in's index from stack's top
 392     // 'np' is _root (see above) or RegionNode, StartNode: we push on stack
 393     // only nodes which point to the start of basic block (see below).
 394     Node *np = nstack.node();
 395     // idx > 0, except for the first node (_root) pushed on stack
 396     // at the beginning when idx == 0.
 397     // We will use the condition (idx == 0) later to end the build.
 398     uint idx = nstack.index();
 399     Node *proj = np->in(idx);
 400     const Node *x = proj->is_block_proj();
 401     // Does the block end with a proper block-ending Node?  One of Return,
 402     // If or Goto? (This check should be done for visited nodes also).
 403     if (x == NULL) {                    // Does not end right...
 404       Node *g = _goto->clone(); // Force it to end in a Goto
 405       g->set_req(0, proj);
 406       np->set_req(idx, g);
 407       x = proj = g;
 408     }
 409     if (!visited.test_set(x->_idx)) { // Visit this block once
 410       // Skip any control-pinned middle'in stuff
 411       Node *p = proj;
 412       do {
 413         proj = p;                   // Update pointer to last Control
 414         p = p->in(0);               // Move control forward
 415       } while( !p->is_block_proj() &&
 416                !p->is_block_start() );
 417       // Make the block begin with one of Region or StartNode.
 418       if( !p->is_block_start() ) {
 419         RegionNode *r = new (C, 2) RegionNode( 2 );
 420         r->init_req(1, p);         // Insert RegionNode in the way
 421         proj->set_req(0, r);        // Insert RegionNode in the way
 422         p = r;
 423       }
 424       // 'p' now points to the start of this basic block
 425 
 426       // Put self in array of basic blocks
 427       Block *bb = new (_bbs._arena) Block(_bbs._arena,p);
 428       _bbs.map(p->_idx,bb);
 429       _bbs.map(x->_idx,bb);
 430       if( x != p )                  // Only for root is x == p
 431         bb->_nodes.push((Node*)x);
 432 
 433       // Now handle predecessors
 434       ++sum;                        // Count 1 for self block
 435       uint cnt = bb->num_preds();
 436       for (int i = (cnt - 1); i > 0; i-- ) { // For all predecessors
 437         Node *prevproj = p->in(i);  // Get prior input
 438         assert( !prevproj->is_Con(), "dead input not removed" );
 439         // Check to see if p->in(i) is a "control-dependent" CFG edge -
 440         // i.e., it splits at the source (via an IF or SWITCH) and merges
 441         // at the destination (via a many-input Region).
 442         // This breaks critical edges.  The RegionNode to start the block
 443         // will be added when <p,i> is pulled off the node stack
 444         if ( cnt > 2 ) {             // Merging many things?
 445           assert( prevproj== bb->pred(i),"");
 446           if(prevproj->is_block_proj() != prevproj) { // Control-dependent edge?
 447             // Force a block on the control-dependent edge
 448             Node *g = _goto->clone();       // Force it to end in a Goto
 449             g->set_req(0,prevproj);
 450             p->set_req(i,g);
 451           }
 452         }
 453         nstack.push(p, i);  // 'p' is RegionNode or StartNode
 454       }
 455     } else { // Post-processing visited nodes
 456       nstack.pop();                 // remove node from stack
 457       // Check if it the fist node pushed on stack at the beginning.
 458       if (idx == 0) break;          // end of the build
 459       // Find predecessor basic block
 460       Block *pb = _bbs[x->_idx];
 461       // Insert into nodes array, if not already there
 462       if( !_bbs.lookup(proj->_idx) ) {
 463         assert( x != proj, "" );
 464         // Map basic block of projection
 465         _bbs.map(proj->_idx,pb);
 466         pb->_nodes.push(proj);
 467       }
 468       // Insert self as a child of my predecessor block
 469       pb->_succs.map(pb->_num_succs++, _bbs[np->_idx]);
 470       assert( pb->_nodes[ pb->_nodes.size() - pb->_num_succs ]->is_block_proj(),
 471               "too many control users, not a CFG?" );
 472     }
 473   }
 474   // Return number of basic blocks for all children and self
 475   return sum;
 476 }
 477 
 478 //------------------------------insert_goto_at---------------------------------
 479 // Inserts a goto & corresponding basic block between
 480 // block[block_no] and its succ_no'th successor block
 481 void PhaseCFG::insert_goto_at(uint block_no, uint succ_no) {
 482   // get block with block_no
 483   assert(block_no < _num_blocks, "illegal block number");
 484   Block* in  = _blocks[block_no];
 485   // get successor block succ_no
 486   assert(succ_no < in->_num_succs, "illegal successor number");
 487   Block* out = in->_succs[succ_no];
 488   // Compute frequency of the new block. Do this before inserting
 489   // new block in case succ_prob() needs to infer the probability from
 490   // surrounding blocks.
 491   float freq = in->_freq * in->succ_prob(succ_no);
 492   // get ProjNode corresponding to the succ_no'th successor of the in block
 493   ProjNode* proj = in->_nodes[in->_nodes.size() - in->_num_succs + succ_no]->as_Proj();
 494   // create region for basic block
 495   RegionNode* region = new (C, 2) RegionNode(2);
 496   region->init_req(1, proj);
 497   // setup corresponding basic block
 498   Block* block = new (_bbs._arena) Block(_bbs._arena, region);
 499   _bbs.map(region->_idx, block);
 500   C->regalloc()->set_bad(region->_idx);
 501   // add a goto node
 502   Node* gto = _goto->clone(); // get a new goto node
 503   gto->set_req(0, region);
 504   // add it to the basic block
 505   block->_nodes.push(gto);
 506   _bbs.map(gto->_idx, block);
 507   C->regalloc()->set_bad(gto->_idx);
 508   // hook up successor block
 509   block->_succs.map(block->_num_succs++, out);
 510   // remap successor's predecessors if necessary
 511   for (uint i = 1; i < out->num_preds(); i++) {
 512     if (out->pred(i) == proj) out->head()->set_req(i, gto);
 513   }
 514   // remap predecessor's successor to new block
 515   in->_succs.map(succ_no, block);
 516   // Set the frequency of the new block
 517   block->_freq = freq;
 518   // add new basic block to basic block list
 519   _blocks.insert(block_no + 1, block);
 520   _num_blocks++;
 521 }
 522 
 523 //------------------------------no_flip_branch---------------------------------
 524 // Does this block end in a multiway branch that cannot have the default case
 525 // flipped for another case?
 526 static bool no_flip_branch( Block *b ) {
 527   int branch_idx = b->_nodes.size() - b->_num_succs-1;
 528   if( branch_idx < 1 ) return false;
 529   Node *bra = b->_nodes[branch_idx];
 530   if( bra->is_Catch() )
 531     return true;
 532   if( bra->is_Mach() ) {
 533     if( bra->is_MachNullCheck() )
 534       return true;
 535     int iop = bra->as_Mach()->ideal_Opcode();
 536     if( iop == Op_FastLock || iop == Op_FastUnlock )
 537       return true;
 538   }
 539   return false;
 540 }
 541 
 542 //------------------------------convert_NeverBranch_to_Goto--------------------
 543 // Check for NeverBranch at block end.  This needs to become a GOTO to the
 544 // true target.  NeverBranch are treated as a conditional branch that always
 545 // goes the same direction for most of the optimizer and are used to give a
 546 // fake exit path to infinite loops.  At this late stage they need to turn
 547 // into Goto's so that when you enter the infinite loop you indeed hang.
 548 void PhaseCFG::convert_NeverBranch_to_Goto(Block *b) {
 549   // Find true target
 550   int end_idx = b->end_idx();
 551   int idx = b->_nodes[end_idx+1]->as_Proj()->_con;
 552   Block *succ = b->_succs[idx];
 553   Node* gto = _goto->clone(); // get a new goto node
 554   gto->set_req(0, b->head());
 555   Node *bp = b->_nodes[end_idx];
 556   b->_nodes.map(end_idx,gto); // Slam over NeverBranch
 557   _bbs.map(gto->_idx, b);
 558   C->regalloc()->set_bad(gto->_idx);
 559   b->_nodes.pop();              // Yank projections
 560   b->_nodes.pop();              // Yank projections
 561   b->_succs.map(0,succ);        // Map only successor
 562   b->_num_succs = 1;
 563   // remap successor's predecessors if necessary
 564   uint j;
 565   for( j = 1; j < succ->num_preds(); j++)
 566     if( succ->pred(j)->in(0) == bp )
 567       succ->head()->set_req(j, gto);
 568   // Kill alternate exit path
 569   Block *dead = b->_succs[1-idx];
 570   for( j = 1; j < dead->num_preds(); j++)
 571     if( dead->pred(j)->in(0) == bp )
 572       break;
 573   // Scan through block, yanking dead path from
 574   // all regions and phis.
 575   dead->head()->del_req(j);
 576   for( int k = 1; dead->_nodes[k]->is_Phi(); k++ )
 577     dead->_nodes[k]->del_req(j);
 578 }
 579 
 580 //------------------------------move_to_next-----------------------------------
 581 // Helper function to move block bx to the slot following b_index. Return
 582 // true if the move is successful, otherwise false
 583 bool PhaseCFG::move_to_next(Block* bx, uint b_index) {
 584   if (bx == NULL) return false;
 585 
 586   // Return false if bx is already scheduled.
 587   uint bx_index = bx->_pre_order;
 588   if ((bx_index <= b_index) && (_blocks[bx_index] == bx)) {
 589     return false;
 590   }
 591 
 592   // Find the current index of block bx on the block list
 593   bx_index = b_index + 1;
 594   while( bx_index < _num_blocks && _blocks[bx_index] != bx ) bx_index++;
 595   assert(_blocks[bx_index] == bx, "block not found");
 596 
 597   // If the previous block conditionally falls into bx, return false,
 598   // because moving bx will create an extra jump.
 599   for(uint k = 1; k < bx->num_preds(); k++ ) {
 600     Block* pred = _bbs[bx->pred(k)->_idx];
 601     if (pred == _blocks[bx_index-1]) {
 602       if (pred->_num_succs != 1) {
 603         return false;
 604       }
 605     }
 606   }
 607 
 608   // Reinsert bx just past block 'b'
 609   _blocks.remove(bx_index);
 610   _blocks.insert(b_index + 1, bx);
 611   return true;
 612 }
 613 
 614 //------------------------------move_to_end------------------------------------
 615 // Move empty and uncommon blocks to the end.
 616 void PhaseCFG::move_to_end(Block *b, uint i) {
 617   int e = b->is_Empty();
 618   if (e != Block::not_empty) {
 619     if (e == Block::empty_with_goto) {
 620       // Remove the goto, but leave the block.
 621       b->_nodes.pop();
 622     }
 623     // Mark this block as a connector block, which will cause it to be
 624     // ignored in certain functions such as non_connector_successor().
 625     b->set_connector();
 626   }
 627   // Move the empty block to the end, and don't recheck.
 628   _blocks.remove(i);
 629   _blocks.push(b);
 630 }
 631 
 632 //---------------------------set_loop_alignment--------------------------------
 633 // Set loop alignment for every block
 634 void PhaseCFG::set_loop_alignment() {
 635   uint last = _num_blocks;
 636   assert( _blocks[0] == _broot, "" );
 637 
 638   for (uint i = 1; i < last; i++ ) {
 639     Block *b = _blocks[i];
 640     if (b->head()->is_Loop()) {
 641       b->set_loop_alignment(b);
 642     }
 643   }
 644 }
 645 
 646 //-----------------------------remove_empty------------------------------------
 647 // Make empty basic blocks to be "connector" blocks, Move uncommon blocks
 648 // to the end.
 649 void PhaseCFG::remove_empty() {
 650   // Move uncommon blocks to the end
 651   uint last = _num_blocks;
 652   assert( _blocks[0] == _broot, "" );
 653 
 654   for (uint i = 1; i < last; i++) {
 655     Block *b = _blocks[i];
 656     if (b->is_connector()) break;
 657 
 658     // Check for NeverBranch at block end.  This needs to become a GOTO to the
 659     // true target.  NeverBranch are treated as a conditional branch that
 660     // always goes the same direction for most of the optimizer and are used
 661     // to give a fake exit path to infinite loops.  At this late stage they
 662     // need to turn into Goto's so that when you enter the infinite loop you
 663     // indeed hang.
 664     if( b->_nodes[b->end_idx()]->Opcode() == Op_NeverBranch )
 665       convert_NeverBranch_to_Goto(b);
 666 
 667     // Look for uncommon blocks and move to end.
 668     if (!C->do_freq_based_layout()) {
 669       if( b->is_uncommon(_bbs) ) {
 670         move_to_end(b, i);
 671         last--;                   // No longer check for being uncommon!
 672         if( no_flip_branch(b) ) { // Fall-thru case must follow?
 673           b = _blocks[i];         // Find the fall-thru block
 674           move_to_end(b, i);
 675           last--;
 676         }
 677         i--;                      // backup block counter post-increment
 678       }
 679     }
 680   }
 681 
 682   // Move empty blocks to the end
 683   last = _num_blocks;
 684   for (uint i = 1; i < last; i++) {
 685     Block *b = _blocks[i];
 686     if (b->is_Empty() != Block::not_empty) {
 687       move_to_end(b, i);
 688       last--;
 689       i--;
 690     }
 691   } // End of for all blocks
 692 }
 693 
 694 //-----------------------------fixup_flow--------------------------------------
 695 // Fix up the final control flow for basic blocks.
 696 void PhaseCFG::fixup_flow() {
 697   // Fixup final control flow for the blocks.  Remove jump-to-next
 698   // block.  If neither arm of a IF follows the conditional branch, we
 699   // have to add a second jump after the conditional.  We place the
 700   // TRUE branch target in succs[0] for both GOTOs and IFs.
 701   for (uint i=0; i < _num_blocks; i++) {
 702     Block *b = _blocks[i];
 703     b->_pre_order = i;          // turn pre-order into block-index
 704 
 705     // Connector blocks need no further processing.
 706     if (b->is_connector()) {
 707       assert((i+1) == _num_blocks || _blocks[i+1]->is_connector(),
 708              "All connector blocks should sink to the end");
 709       continue;
 710     }
 711     assert(b->is_Empty() != Block::completely_empty,
 712            "Empty blocks should be connectors");
 713 
 714     Block *bnext = (i < _num_blocks-1) ? _blocks[i+1] : NULL;
 715     Block *bs0 = b->non_connector_successor(0);
 716 
 717     // Check for multi-way branches where I cannot negate the test to
 718     // exchange the true and false targets.
 719     if( no_flip_branch( b ) ) {
 720       // Find fall through case - if must fall into its target
 721       int branch_idx = b->_nodes.size() - b->_num_succs;
 722       for (uint j2 = 0; j2 < b->_num_succs; j2++) {
 723         const ProjNode* p = b->_nodes[branch_idx + j2]->as_Proj();
 724         if (p->_con == 0) {
 725           // successor j2 is fall through case
 726           if (b->non_connector_successor(j2) != bnext) {
 727             // but it is not the next block => insert a goto
 728             insert_goto_at(i, j2);
 729           }
 730           // Put taken branch in slot 0
 731           if( j2 == 0 && b->_num_succs == 2) {
 732             // Flip targets in succs map
 733             Block *tbs0 = b->_succs[0];
 734             Block *tbs1 = b->_succs[1];
 735             b->_succs.map( 0, tbs1 );
 736             b->_succs.map( 1, tbs0 );
 737           }
 738           break;
 739         }
 740       }
 741       // Remove all CatchProjs
 742       for (uint j1 = 0; j1 < b->_num_succs; j1++) b->_nodes.pop();
 743 
 744     } else if (b->_num_succs == 1) {
 745       // Block ends in a Goto?
 746       if (bnext == bs0) {
 747         // We fall into next block; remove the Goto
 748         b->_nodes.pop();
 749       }
 750 
 751     } else if( b->_num_succs == 2 ) { // Block ends in a If?
 752       // Get opcode of 1st projection (matches _succs[0])
 753       // Note: Since this basic block has 2 exits, the last 2 nodes must
 754       //       be projections (in any order), the 3rd last node must be
 755       //       the IfNode (we have excluded other 2-way exits such as
 756       //       CatchNodes already).
 757       MachNode *iff   = b->_nodes[b->_nodes.size()-3]->as_Mach();
 758       ProjNode *proj0 = b->_nodes[b->_nodes.size()-2]->as_Proj();
 759       ProjNode *proj1 = b->_nodes[b->_nodes.size()-1]->as_Proj();
 760 
 761       // Assert that proj0 and succs[0] match up. Similarly for proj1 and succs[1].
 762       assert(proj0->raw_out(0) == b->_succs[0]->head(), "Mismatch successor 0");
 763       assert(proj1->raw_out(0) == b->_succs[1]->head(), "Mismatch successor 1");
 764 
 765       Block *bs1 = b->non_connector_successor(1);
 766 
 767       // Check for neither successor block following the current
 768       // block ending in a conditional. If so, move one of the
 769       // successors after the current one, provided that the
 770       // successor was previously unscheduled, but moveable
 771       // (i.e., all paths to it involve a branch).
 772       if( !C->do_freq_based_layout() && bnext != bs0 && bnext != bs1 ) {
 773         // Choose the more common successor based on the probability
 774         // of the conditional branch.
 775         Block *bx = bs0;
 776         Block *by = bs1;
 777 
 778         // _prob is the probability of taking the true path. Make
 779         // p the probability of taking successor #1.
 780         float p = iff->as_MachIf()->_prob;
 781         if( proj0->Opcode() == Op_IfTrue ) {
 782           p = 1.0 - p;
 783         }
 784 
 785         // Prefer successor #1 if p > 0.5
 786         if (p > PROB_FAIR) {
 787           bx = bs1;
 788           by = bs0;
 789         }
 790 
 791         // Attempt the more common successor first
 792         if (move_to_next(bx, i)) {
 793           bnext = bx;
 794         } else if (move_to_next(by, i)) {
 795           bnext = by;
 796         }
 797       }
 798 
 799       // Check for conditional branching the wrong way.  Negate
 800       // conditional, if needed, so it falls into the following block
 801       // and branches to the not-following block.
 802 
 803       // Check for the next block being in succs[0].  We are going to branch
 804       // to succs[0], so we want the fall-thru case as the next block in
 805       // succs[1].
 806       if (bnext == bs0) {
 807         // Fall-thru case in succs[0], so flip targets in succs map
 808         Block *tbs0 = b->_succs[0];
 809         Block *tbs1 = b->_succs[1];
 810         b->_succs.map( 0, tbs1 );
 811         b->_succs.map( 1, tbs0 );
 812         // Flip projection for each target
 813         { ProjNode *tmp = proj0; proj0 = proj1; proj1 = tmp; }
 814 
 815       } else if( bnext != bs1 ) {
 816         // Need a double-branch
 817         // The existing conditional branch need not change.
 818         // Add a unconditional branch to the false target.
 819         // Alas, it must appear in its own block and adding a
 820         // block this late in the game is complicated.  Sigh.
 821         insert_goto_at(i, 1);
 822       }
 823 
 824       // Make sure we TRUE branch to the target
 825       if( proj0->Opcode() == Op_IfFalse ) {
 826         iff->negate();
 827       }
 828 
 829       b->_nodes.pop();          // Remove IfFalse & IfTrue projections
 830       b->_nodes.pop();
 831 
 832     } else {
 833       // Multi-exit block, e.g. a switch statement
 834       // But we don't need to do anything here
 835     }
 836   } // End of for all blocks
 837 }
 838 
 839 
 840 //------------------------------dump-------------------------------------------
 841 #ifndef PRODUCT
 842 void PhaseCFG::_dump_cfg( const Node *end, VectorSet &visited  ) const {
 843   const Node *x = end->is_block_proj();
 844   assert( x, "not a CFG" );
 845 
 846   // Do not visit this block again
 847   if( visited.test_set(x->_idx) ) return;
 848 
 849   // Skip through this block
 850   const Node *p = x;
 851   do {
 852     p = p->in(0);               // Move control forward
 853     assert( !p->is_block_proj() || p->is_Root(), "not a CFG" );
 854   } while( !p->is_block_start() );
 855 
 856   // Recursively visit
 857   for( uint i=1; i<p->req(); i++ )
 858     _dump_cfg(p->in(i),visited);
 859 
 860   // Dump the block
 861   _bbs[p->_idx]->dump(&_bbs);
 862 }
 863 
 864 void PhaseCFG::dump( ) const {
 865   tty->print("\n--- CFG --- %d BBs\n",_num_blocks);
 866   if( _blocks.size() ) {        // Did we do basic-block layout?
 867     for( uint i=0; i<_num_blocks; i++ )
 868       _blocks[i]->dump(&_bbs);
 869   } else {                      // Else do it with a DFS
 870     VectorSet visited(_bbs._arena);
 871     _dump_cfg(_root,visited);
 872   }
 873 }
 874 
 875 void PhaseCFG::dump_headers() {
 876   for( uint i = 0; i < _num_blocks; i++ ) {
 877     if( _blocks[i] == NULL ) continue;
 878     _blocks[i]->dump_head(&_bbs);
 879   }
 880 }
 881 
 882 void PhaseCFG::verify( ) const {
 883   // Verify sane CFG
 884   for( uint i = 0; i < _num_blocks; i++ ) {
 885     Block *b = _blocks[i];
 886     uint cnt = b->_nodes.size();
 887     uint j;
 888     for( j = 0; j < cnt; j++ ) {
 889       Node *n = b->_nodes[j];
 890       assert( _bbs[n->_idx] == b, "" );
 891       if( j >= 1 && n->is_Mach() &&
 892           n->as_Mach()->ideal_Opcode() == Op_CreateEx ) {
 893         assert( j == 1 || b->_nodes[j-1]->is_Phi(),
 894                 "CreateEx must be first instruction in block" );
 895       }
 896       for( uint k = 0; k < n->req(); k++ ) {
 897         Node *use = n->in(k);
 898         if( use && use != n ) {
 899           assert( _bbs[use->_idx] || use->is_Con(),
 900                   "must have block; constants for debug info ok" );
 901         }
 902       }
 903     }
 904 
 905     j = b->end_idx();
 906     Node *bp = (Node*)b->_nodes[b->_nodes.size()-1]->is_block_proj();
 907     assert( bp, "last instruction must be a block proj" );
 908     assert( bp == b->_nodes[j], "wrong number of successors for this block" );
 909     if( bp->is_Catch() ) {
 910       while( b->_nodes[--j]->Opcode() == Op_MachProj ) ;
 911       assert( b->_nodes[j]->is_Call(), "CatchProj must follow call" );
 912     }
 913     else if( bp->is_Mach() && bp->as_Mach()->ideal_Opcode() == Op_If ) {
 914       assert( b->_num_succs == 2, "Conditional branch must have two targets");
 915     }
 916   }
 917 }
 918 #endif
 919 
 920 //=============================================================================
 921 //------------------------------UnionFind--------------------------------------
 922 UnionFind::UnionFind( uint max ) : _cnt(max), _max(max), _indices(NEW_RESOURCE_ARRAY(uint,max)) {
 923   Copy::zero_to_bytes( _indices, sizeof(uint)*max );
 924 }
 925 
 926 void UnionFind::extend( uint from_idx, uint to_idx ) {
 927   _nesting.check();
 928   if( from_idx >= _max ) {
 929     uint size = 16;
 930     while( size <= from_idx ) size <<=1;
 931     _indices = REALLOC_RESOURCE_ARRAY( uint, _indices, _max, size );
 932     _max = size;
 933   }
 934   while( _cnt <= from_idx ) _indices[_cnt++] = 0;
 935   _indices[from_idx] = to_idx;
 936 }
 937 
 938 void UnionFind::reset( uint max ) {
 939   assert( max <= max_uint, "Must fit within uint" );
 940   // Force the Union-Find mapping to be at least this large
 941   extend(max,0);
 942   // Initialize to be the ID mapping.
 943   for( uint i=0; i<max; i++ ) map(i,i);
 944 }
 945 
 946 //------------------------------Find_compress----------------------------------
 947 // Straight out of Tarjan's union-find algorithm
 948 uint UnionFind::Find_compress( uint idx ) {
 949   uint cur  = idx;
 950   uint next = lookup(cur);
 951   while( next != cur ) {        // Scan chain of equivalences
 952     assert( next < cur, "always union smaller" );
 953     cur = next;                 // until find a fixed-point
 954     next = lookup(cur);
 955   }
 956   // Core of union-find algorithm: update chain of
 957   // equivalences to be equal to the root.
 958   while( idx != next ) {
 959     uint tmp = lookup(idx);
 960     map(idx, next);
 961     idx = tmp;
 962   }
 963   return idx;
 964 }
 965 
 966 //------------------------------Find_const-------------------------------------
 967 // Like Find above, but no path compress, so bad asymptotic behavior
 968 uint UnionFind::Find_const( uint idx ) const {
 969   if( idx == 0 ) return idx;    // Ignore the zero idx
 970   // Off the end?  This can happen during debugging dumps
 971   // when data structures have not finished being updated.
 972   if( idx >= _max ) return idx;
 973   uint next = lookup(idx);
 974   while( next != idx ) {        // Scan chain of equivalences
 975     idx = next;                 // until find a fixed-point
 976     next = lookup(idx);
 977   }
 978   return next;
 979 }
 980 
 981 //------------------------------Union------------------------------------------
 982 // union 2 sets together.
 983 void UnionFind::Union( uint idx1, uint idx2 ) {
 984   uint src = Find(idx1);
 985   uint dst = Find(idx2);
 986   assert( src, "" );
 987   assert( dst, "" );
 988   assert( src < _max, "oob" );
 989   assert( dst < _max, "oob" );
 990   assert( src < dst, "always union smaller" );
 991   map(dst,src);
 992 }
 993 
 994 #ifndef PRODUCT
 995 static void edge_dump(GrowableArray<CFGEdge *> *edges) {
 996   tty->print_cr("---- Edges ----");
 997   for (int i = 0; i < edges->length(); i++) {
 998     CFGEdge *e = edges->at(i);
 999     if (e != NULL) {
1000       edges->at(i)->dump();
1001     }
1002   }
1003 }
1004 
1005 static void trace_dump(Trace *traces[], int count) {
1006   tty->print_cr("---- Traces ----");
1007   for (int i = 0; i < count; i++) {
1008     Trace *tr = traces[i];
1009     if (tr != NULL) {
1010       tr->dump();
1011     }
1012   }
1013 }
1014 
1015 void Trace::dump( ) const {
1016   tty->print_cr("Trace (freq %f)", first_block()->_freq);
1017   for (Block *b = first_block(); b != NULL; b = next(b)) {
1018     tty->print("  B%d", b->_pre_order);
1019     if (b->head()->is_Loop()) {
1020       tty->print(" (L%d)", b->compute_loop_alignment());
1021     }
1022     if (b->has_loop_alignment()) {
1023       tty->print(" (T%d)", b->code_alignment());
1024     }
1025   }
1026   tty->cr();
1027 }
1028 
1029 void CFGEdge::dump( ) const {
1030   tty->print(" B%d  -->  B%d  Freq: %f  out:%3d%%  in:%3d%%  State: ",
1031              from()->_pre_order, to()->_pre_order, freq(), _from_pct, _to_pct);
1032   switch(state()) {
1033   case connected:
1034     tty->print("connected");
1035     break;
1036   case open:
1037     tty->print("open");
1038     break;
1039   case interior:
1040     tty->print("interior");
1041     break;
1042   }
1043   if (infrequent()) {
1044     tty->print("  infrequent");
1045   }
1046   tty->cr();
1047 }
1048 #endif
1049 
1050 //=============================================================================
1051 
1052 //------------------------------edge_order-------------------------------------
1053 // Comparison function for edges
1054 static int edge_order(CFGEdge **e0, CFGEdge **e1) {
1055   float freq0 = (*e0)->freq();
1056   float freq1 = (*e1)->freq();
1057   if (freq0 != freq1) {
1058     return freq0 > freq1 ? -1 : 1;
1059   }
1060 
1061   int dist0 = (*e0)->to()->_rpo - (*e0)->from()->_rpo;
1062   int dist1 = (*e1)->to()->_rpo - (*e1)->from()->_rpo;
1063 
1064   return dist1 - dist0;
1065 }
1066 
1067 //------------------------------trace_frequency_order--------------------------
1068 // Comparison function for edges
1069 static int trace_frequency_order(const void *p0, const void *p1) {
1070   Trace *tr0 = *(Trace **) p0;
1071   Trace *tr1 = *(Trace **) p1;
1072   Block *b0 = tr0->first_block();
1073   Block *b1 = tr1->first_block();
1074 
1075   // The trace of connector blocks goes at the end;
1076   // we only expect one such trace
1077   if (b0->is_connector() != b1->is_connector()) {
1078     return b1->is_connector() ? -1 : 1;
1079   }
1080 
1081   // Pull more frequently executed blocks to the beginning
1082   float freq0 = b0->_freq;
1083   float freq1 = b1->_freq;
1084   if (freq0 != freq1) {
1085     return freq0 > freq1 ? -1 : 1;
1086   }
1087 
1088   int diff = tr0->first_block()->_rpo - tr1->first_block()->_rpo;
1089 
1090   return diff;
1091 }
1092 
1093 //------------------------------find_edges-------------------------------------
1094 // Find edges of interest, i.e, those which can fall through. Presumes that
1095 // edges which don't fall through are of low frequency and can be generally
1096 // ignored.  Initialize the list of traces.
1097 void PhaseBlockLayout::find_edges()
1098 {
1099   // Walk the blocks, creating edges and Traces
1100   uint i;
1101   Trace *tr = NULL;
1102   for (i = 0; i < _cfg._num_blocks; i++) {
1103     Block *b = _cfg._blocks[i];
1104     tr = new Trace(b, next, prev);
1105     traces[tr->id()] = tr;
1106 
1107     // All connector blocks should be at the end of the list
1108     if (b->is_connector()) break;
1109 
1110     // If this block and the next one have a one-to-one successor
1111     // predecessor relationship, simply append the next block
1112     int nfallthru = b->num_fall_throughs();
1113     while (nfallthru == 1 &&
1114            b->succ_fall_through(0)) {
1115       Block *n = b->_succs[0];
1116 
1117       // Skip over single-entry connector blocks, we don't want to
1118       // add them to the trace.
1119       while (n->is_connector() && n->num_preds() == 1) {
1120         n = n->_succs[0];
1121       }
1122 
1123       // We see a merge point, so stop search for the next block
1124       if (n->num_preds() != 1) break;
1125 
1126       i++;
1127       assert(n = _cfg._blocks[i], "expecting next block");
1128       tr->append(n);
1129       uf->map(n->_pre_order, tr->id());
1130       traces[n->_pre_order] = NULL;
1131       nfallthru = b->num_fall_throughs();
1132       b = n;
1133     }
1134 
1135     if (nfallthru > 0) {
1136       // Create a CFGEdge for each outgoing
1137       // edge that could be a fall-through.
1138       for (uint j = 0; j < b->_num_succs; j++ ) {
1139         if (b->succ_fall_through(j)) {
1140           Block *target = b->non_connector_successor(j);
1141           float freq = b->_freq * b->succ_prob(j);
1142           int from_pct = (int) ((100 * freq) / b->_freq);
1143           int to_pct = (int) ((100 * freq) / target->_freq);
1144           edges->append(new CFGEdge(b, target, freq, from_pct, to_pct));
1145         }
1146       }
1147     }
1148   }
1149 
1150   // Group connector blocks into one trace
1151   for (i++; i < _cfg._num_blocks; i++) {
1152     Block *b = _cfg._blocks[i];
1153     assert(b->is_connector(), "connector blocks at the end");
1154     tr->append(b);
1155     uf->map(b->_pre_order, tr->id());
1156     traces[b->_pre_order] = NULL;
1157   }
1158 }
1159 
1160 //------------------------------union_traces----------------------------------
1161 // Union two traces together in uf, and null out the trace in the list
1162 void PhaseBlockLayout::union_traces(Trace* updated_trace, Trace* old_trace)
1163 {
1164   uint old_id = old_trace->id();
1165   uint updated_id = updated_trace->id();
1166 
1167   uint lo_id = updated_id;
1168   uint hi_id = old_id;
1169 
1170   // If from is greater than to, swap values to meet
1171   // UnionFind guarantee.
1172   if (updated_id > old_id) {
1173     lo_id = old_id;
1174     hi_id = updated_id;
1175 
1176     // Fix up the trace ids
1177     traces[lo_id] = traces[updated_id];
1178     updated_trace->set_id(lo_id);
1179   }
1180 
1181   // Union the lower with the higher and remove the pointer
1182   // to the higher.
1183   uf->Union(lo_id, hi_id);
1184   traces[hi_id] = NULL;
1185 }
1186 
1187 //------------------------------grow_traces-------------------------------------
1188 // Append traces together via the most frequently executed edges
1189 void PhaseBlockLayout::grow_traces()
1190 {
1191   // Order the edges, and drive the growth of Traces via the most
1192   // frequently executed edges.
1193   edges->sort(edge_order);
1194   for (int i = 0; i < edges->length(); i++) {
1195     CFGEdge *e = edges->at(i);
1196 
1197     if (e->state() != CFGEdge::open) continue;
1198 
1199     Block *src_block = e->from();
1200     Block *targ_block = e->to();
1201 
1202     // Don't grow traces along backedges?
1203     if (!BlockLayoutRotateLoops) {
1204       if (targ_block->_rpo <= src_block->_rpo) {
1205         targ_block->set_loop_alignment(targ_block);
1206         continue;
1207       }
1208     }
1209 
1210     Trace *src_trace = trace(src_block);
1211     Trace *targ_trace = trace(targ_block);
1212 
1213     // If the edge in question can join two traces at their ends,
1214     // append one trace to the other.
1215    if (src_trace->last_block() == src_block) {
1216       if (src_trace == targ_trace) {
1217         e->set_state(CFGEdge::interior);
1218         if (targ_trace->backedge(e)) {
1219           // Reset i to catch any newly eligible edge
1220           // (Or we could remember the first "open" edge, and reset there)
1221           i = 0;
1222         }
1223       } else if (targ_trace->first_block() == targ_block) {
1224         e->set_state(CFGEdge::connected);
1225         src_trace->append(targ_trace);
1226         union_traces(src_trace, targ_trace);
1227       }
1228     }
1229   }
1230 }
1231 
1232 //------------------------------merge_traces-----------------------------------
1233 // Embed one trace into another, if the fork or join points are sufficiently
1234 // balanced.
1235 void PhaseBlockLayout::merge_traces(bool fall_thru_only)
1236 {
1237   // Walk the edge list a another time, looking at unprocessed edges.
1238   // Fold in diamonds
1239   for (int i = 0; i < edges->length(); i++) {
1240     CFGEdge *e = edges->at(i);
1241 
1242     if (e->state() != CFGEdge::open) continue;
1243     if (fall_thru_only) {
1244       if (e->infrequent()) continue;
1245     }
1246 
1247     Block *src_block = e->from();
1248     Trace *src_trace = trace(src_block);
1249     bool src_at_tail = src_trace->last_block() == src_block;
1250 
1251     Block *targ_block  = e->to();
1252     Trace *targ_trace  = trace(targ_block);
1253     bool targ_at_start = targ_trace->first_block() == targ_block;
1254 
1255     if (src_trace == targ_trace) {
1256       // This may be a loop, but we can't do much about it.
1257       e->set_state(CFGEdge::interior);
1258       continue;
1259     }
1260 
1261     if (fall_thru_only) {
1262       // If the edge links the middle of two traces, we can't do anything.
1263       // Mark the edge and continue.
1264       if (!src_at_tail & !targ_at_start) {
1265         continue;
1266       }
1267 
1268       // Don't grow traces along backedges?
1269       if (!BlockLayoutRotateLoops && (targ_block->_rpo <= src_block->_rpo)) {
1270           continue;
1271       }
1272 
1273       // If both ends of the edge are available, why didn't we handle it earlier?
1274       assert(src_at_tail ^ targ_at_start, "Should have caught this edge earlier.");
1275 
1276       if (targ_at_start) {
1277         // Insert the "targ" trace in the "src" trace if the insertion point
1278         // is a two way branch.
1279         // Better profitability check possible, but may not be worth it.
1280         // Someday, see if the this "fork" has an associated "join";
1281         // then make a policy on merging this trace at the fork or join.
1282         // For example, other things being equal, it may be better to place this
1283         // trace at the join point if the "src" trace ends in a two-way, but
1284         // the insertion point is one-way.
1285         assert(src_block->num_fall_throughs() == 2, "unexpected diamond");
1286         e->set_state(CFGEdge::connected);
1287         src_trace->insert_after(src_block, targ_trace);
1288         union_traces(src_trace, targ_trace);
1289       } else if (src_at_tail) {
1290         if (src_trace != trace(_cfg._broot)) {
1291           e->set_state(CFGEdge::connected);
1292           targ_trace->insert_before(targ_block, src_trace);
1293           union_traces(targ_trace, src_trace);
1294         }
1295       }
1296     } else if (e->state() == CFGEdge::open) {
1297       // Append traces, even without a fall-thru connection.
1298       // But leave root entry at the begining of the block list.
1299       if (targ_trace != trace(_cfg._broot)) {
1300         e->set_state(CFGEdge::connected);
1301         src_trace->append(targ_trace);
1302         union_traces(src_trace, targ_trace);
1303       }
1304     }
1305   }
1306 }
1307 
1308 //----------------------------reorder_traces-----------------------------------
1309 // Order the sequence of the traces in some desirable way, and fixup the
1310 // jumps at the end of each block.
1311 void PhaseBlockLayout::reorder_traces(int count)
1312 {
1313   ResourceArea *area = Thread::current()->resource_area();
1314   Trace ** new_traces = NEW_ARENA_ARRAY(area, Trace *, count);
1315   Block_List worklist;
1316   int new_count = 0;
1317 
1318   // Compact the traces.
1319   for (int i = 0; i < count; i++) {
1320     Trace *tr = traces[i];
1321     if (tr != NULL) {
1322       new_traces[new_count++] = tr;
1323     }
1324   }
1325 
1326   // The entry block should be first on the new trace list.
1327   Trace *tr = trace(_cfg._broot);
1328   assert(tr == new_traces[0], "entry trace misplaced");
1329 
1330   // Sort the new trace list by frequency
1331   qsort(new_traces + 1, new_count - 1, sizeof(new_traces[0]), trace_frequency_order);
1332 
1333   // Patch up the successor blocks
1334   _cfg._blocks.reset();
1335   _cfg._num_blocks = 0;
1336   for (int i = 0; i < new_count; i++) {
1337     Trace *tr = new_traces[i];
1338     if (tr != NULL) {
1339       tr->fixup_blocks(_cfg);
1340     }
1341   }
1342 }
1343 
1344 //------------------------------PhaseBlockLayout-------------------------------
1345 // Order basic blocks based on frequency
1346 PhaseBlockLayout::PhaseBlockLayout(PhaseCFG &cfg) :
1347   Phase(BlockLayout),
1348   _cfg(cfg)
1349 {
1350   ResourceMark rm;
1351   ResourceArea *area = Thread::current()->resource_area();
1352 
1353   // List of traces
1354   int size = _cfg._num_blocks + 1;
1355   traces = NEW_ARENA_ARRAY(area, Trace *, size);
1356   memset(traces, 0, size*sizeof(Trace*));
1357   next = NEW_ARENA_ARRAY(area, Block *, size);
1358   memset(next,   0, size*sizeof(Block *));
1359   prev = NEW_ARENA_ARRAY(area, Block *, size);
1360   memset(prev  , 0, size*sizeof(Block *));
1361 
1362   // List of edges
1363   edges = new GrowableArray<CFGEdge*>;
1364 
1365   // Mapping block index --> block_trace
1366   uf = new UnionFind(size);
1367   uf->reset(size);
1368 
1369   // Find edges and create traces.
1370   find_edges();
1371 
1372   // Grow traces at their ends via most frequent edges.
1373   grow_traces();
1374 
1375   // Merge one trace into another, but only at fall-through points.
1376   // This may make diamonds and other related shapes in a trace.
1377   merge_traces(true);
1378 
1379   // Run merge again, allowing two traces to be catenated, even if
1380   // one does not fall through into the other. This appends loosely
1381   // related traces to be near each other.
1382   merge_traces(false);
1383 
1384   // Re-order all the remaining traces by frequency
1385   reorder_traces(size);
1386 
1387   assert(_cfg._num_blocks >= (uint) (size - 1), "number of blocks can not shrink");
1388 }
1389 
1390 
1391 //------------------------------backedge---------------------------------------
1392 // Edge e completes a loop in a trace. If the target block is head of the
1393 // loop, rotate the loop block so that the loop ends in a conditional branch.
1394 bool Trace::backedge(CFGEdge *e) {
1395   bool loop_rotated = false;
1396   Block *src_block  = e->from();
1397   Block *targ_block    = e->to();
1398 
1399   assert(last_block() == src_block, "loop discovery at back branch");
1400   if (first_block() == targ_block) {
1401     if (BlockLayoutRotateLoops && last_block()->num_fall_throughs() < 2) {
1402       // Find the last block in the trace that has a conditional
1403       // branch.
1404       Block *b;
1405       for (b = last_block(); b != NULL; b = prev(b)) {
1406         if (b->num_fall_throughs() == 2) {
1407           break;
1408         }
1409       }
1410 
1411       if (b != last_block() && b != NULL) {
1412         loop_rotated = true;
1413 
1414         // Rotate the loop by doing two-part linked-list surgery.
1415         append(first_block());
1416         break_loop_after(b);
1417       }
1418     }
1419 
1420     // Backbranch to the top of a trace
1421     // Scroll foward through the trace from the targ_block. If we find
1422     // a loop head before another loop top, use the the loop head alignment.
1423     for (Block *b = targ_block; b != NULL; b = next(b)) {
1424       if (b->has_loop_alignment()) {
1425         break;
1426       }
1427       if (b->head()->is_Loop()) {
1428         targ_block = b;
1429         break;
1430       }
1431     }
1432 
1433     first_block()->set_loop_alignment(targ_block);
1434 
1435   } else {
1436     // Backbranch into the middle of a trace
1437     targ_block->set_loop_alignment(targ_block);
1438   }
1439 
1440   return loop_rotated;
1441 }
1442 
1443 //------------------------------fixup_blocks-----------------------------------
1444 // push blocks onto the CFG list
1445 // ensure that blocks have the correct two-way branch sense
1446 void Trace::fixup_blocks(PhaseCFG &cfg) {
1447   Block *last = last_block();
1448   for (Block *b = first_block(); b != NULL; b = next(b)) {
1449     cfg._blocks.push(b);
1450     cfg._num_blocks++;
1451     if (!b->is_connector()) {
1452       int nfallthru = b->num_fall_throughs();
1453       if (b != last) {
1454         if (nfallthru == 2) {
1455           // Ensure that the sense of the branch is correct
1456           Block *bnext = next(b);
1457           Block *bs0 = b->non_connector_successor(0);
1458 
1459           MachNode *iff = b->_nodes[b->_nodes.size()-3]->as_Mach();
1460           ProjNode *proj0 = b->_nodes[b->_nodes.size()-2]->as_Proj();
1461           ProjNode *proj1 = b->_nodes[b->_nodes.size()-1]->as_Proj();
1462 
1463           if (bnext == bs0) {
1464             // Fall-thru case in succs[0], should be in succs[1]
1465 
1466             // Flip targets in _succs map
1467             Block *tbs0 = b->_succs[0];
1468             Block *tbs1 = b->_succs[1];
1469             b->_succs.map( 0, tbs1 );
1470             b->_succs.map( 1, tbs0 );
1471 
1472             // Flip projections to match targets
1473             b->_nodes.map(b->_nodes.size()-2, proj1);
1474             b->_nodes.map(b->_nodes.size()-1, proj0);
1475           }
1476         }
1477       }
1478     }
1479   }
1480 }