1 /*
   2  * Copyright 2000-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 #include "incls/_precompiled.incl"
  26 #include "incls/_chaitin.cpp.incl"
  27 
  28 //=============================================================================
  29 
  30 #ifndef PRODUCT
  31 void LRG::dump( ) const {
  32   ttyLocker ttyl;
  33   tty->print("%d ",num_regs());
  34   _mask.dump();
  35   if( _msize_valid ) {
  36     if( mask_size() == compute_mask_size() ) tty->print(", #%d ",_mask_size);
  37     else tty->print(", #!!!_%d_vs_%d ",_mask_size,_mask.Size());
  38   } else {
  39     tty->print(", #?(%d) ",_mask.Size());
  40   }
  41 
  42   tty->print("EffDeg: ");
  43   if( _degree_valid ) tty->print( "%d ", _eff_degree );
  44   else tty->print("? ");
  45 
  46   if( is_multidef() ) {
  47     tty->print("MultiDef ");
  48     if (_defs != NULL) {
  49       tty->print("(");
  50       for (int i = 0; i < _defs->length(); i++) {
  51         tty->print("N%d ", _defs->at(i)->_idx);
  52       }
  53       tty->print(") ");
  54     }
  55   }
  56   else if( _def == 0 ) tty->print("Dead ");
  57   else tty->print("Def: N%d ",_def->_idx);
  58 
  59   tty->print("Cost:%4.2g Area:%4.2g Score:%4.2g ",_cost,_area, score());
  60   // Flags
  61   if( _is_oop ) tty->print("Oop ");
  62   if( _is_float ) tty->print("Float ");
  63   if( _was_spilled1 ) tty->print("Spilled ");
  64   if( _was_spilled2 ) tty->print("Spilled2 ");
  65   if( _direct_conflict ) tty->print("Direct_conflict ");
  66   if( _fat_proj ) tty->print("Fat ");
  67   if( _was_lo ) tty->print("Lo ");
  68   if( _has_copy ) tty->print("Copy ");
  69   if( _at_risk ) tty->print("Risk ");
  70 
  71   if( _must_spill ) tty->print("Must_spill ");
  72   if( _is_bound ) tty->print("Bound ");
  73   if( _msize_valid ) {
  74     if( _degree_valid && lo_degree() ) tty->print("Trivial ");
  75   }
  76 
  77   tty->cr();
  78 }
  79 #endif
  80 
  81 //------------------------------score------------------------------------------
  82 // Compute score from cost and area.  Low score is best to spill.
  83 static double raw_score( double cost, double area ) {
  84   return cost - (area*RegisterCostAreaRatio) * 1.52588e-5;
  85 }
  86 
  87 double LRG::score() const {
  88   // Scale _area by RegisterCostAreaRatio/64K then subtract from cost.
  89   // Bigger area lowers score, encourages spilling this live range.
  90   // Bigger cost raise score, prevents spilling this live range.
  91   // (Note: 1/65536 is the magic constant below; I dont trust the C optimizer
  92   // to turn a divide by a constant into a multiply by the reciprical).
  93   double score = raw_score( _cost, _area);
  94 
  95   // Account for area.  Basically, LRGs covering large areas are better
  96   // to spill because more other LRGs get freed up.
  97   if( _area == 0.0 )            // No area?  Then no progress to spill
  98     return 1e35;
  99 
 100   if( _was_spilled2 )           // If spilled once before, we are unlikely
 101     return score + 1e30;        // to make progress again.
 102 
 103   if( _cost >= _area*3.0 )      // Tiny area relative to cost
 104     return score + 1e17;        // Probably no progress to spill
 105 
 106   if( (_cost+_cost) >= _area*3.0 ) // Small area relative to cost
 107     return score + 1e10;        // Likely no progress to spill
 108 
 109   return score;
 110 }
 111 
 112 //------------------------------LRG_List---------------------------------------
 113 LRG_List::LRG_List( uint max ) : _cnt(max), _max(max), _lidxs(NEW_RESOURCE_ARRAY(uint,max)) {
 114   memset( _lidxs, 0, sizeof(uint)*max );
 115 }
 116 
 117 void LRG_List::extend( uint nidx, uint lidx ) {
 118   _nesting.check();
 119   if( nidx >= _max ) {
 120     uint size = 16;
 121     while( size <= nidx ) size <<=1;
 122     _lidxs = REALLOC_RESOURCE_ARRAY( uint, _lidxs, _max, size );
 123     _max = size;
 124   }
 125   while( _cnt <= nidx )
 126     _lidxs[_cnt++] = 0;
 127   _lidxs[nidx] = lidx;
 128 }
 129 
 130 #define NUMBUCKS 3
 131 
 132 //------------------------------Chaitin----------------------------------------
 133 PhaseChaitin::PhaseChaitin(uint unique, PhaseCFG &cfg, Matcher &matcher)
 134   : PhaseRegAlloc(unique, cfg, matcher,
 135 #ifndef PRODUCT
 136        print_chaitin_statistics
 137 #else
 138        NULL
 139 #endif
 140        ),
 141     _names(unique), _uf_map(unique),
 142     _maxlrg(0), _live(0),
 143     _spilled_once(Thread::current()->resource_area()),
 144     _spilled_twice(Thread::current()->resource_area()),
 145     _lo_degree(0), _lo_stk_degree(0), _hi_degree(0), _simplified(0),
 146     _oldphi(unique)
 147 #ifndef PRODUCT
 148   , _trace_spilling(TraceSpilling || C->method_has_option("TraceSpilling"))
 149 #endif
 150 {
 151   NOT_PRODUCT( Compile::TracePhase t3("ctorChaitin", &_t_ctorChaitin, TimeCompiler); )
 152   uint i,j;
 153   // Build a list of basic blocks, sorted by frequency
 154   _blks = NEW_RESOURCE_ARRAY( Block *, _cfg._num_blocks );
 155   // Experiment with sorting strategies to speed compilation
 156   double  cutoff = BLOCK_FREQUENCY(1.0); // Cutoff for high frequency bucket
 157   Block **buckets[NUMBUCKS];             // Array of buckets
 158   uint    buckcnt[NUMBUCKS];             // Array of bucket counters
 159   double  buckval[NUMBUCKS];             // Array of bucket value cutoffs
 160   for( i = 0; i < NUMBUCKS; i++ ) {
 161     buckets[i] = NEW_RESOURCE_ARRAY( Block *, _cfg._num_blocks );
 162     buckcnt[i] = 0;
 163     // Bump by three orders of magnitude each time
 164     cutoff *= 0.001;
 165     buckval[i] = cutoff;
 166     for( j = 0; j < _cfg._num_blocks; j++ ) {
 167       buckets[i][j] = NULL;
 168     }
 169   }
 170   // Sort blocks into buckets
 171   for( i = 0; i < _cfg._num_blocks; i++ ) {
 172     for( j = 0; j < NUMBUCKS; j++ ) {
 173       if( (j == NUMBUCKS-1) || (_cfg._blocks[i]->_freq > buckval[j]) ) {
 174         // Assign block to end of list for appropriate bucket
 175         buckets[j][buckcnt[j]++] = _cfg._blocks[i];
 176         break;                      // kick out of inner loop
 177       }
 178     }
 179   }
 180   // Dump buckets into final block array
 181   uint blkcnt = 0;
 182   for( i = 0; i < NUMBUCKS; i++ ) {
 183     for( j = 0; j < buckcnt[i]; j++ ) {
 184       _blks[blkcnt++] = buckets[i][j];
 185     }
 186   }
 187 
 188   assert(blkcnt == _cfg._num_blocks, "Block array not totally filled");
 189 }
 190 
 191 void PhaseChaitin::Register_Allocate() {
 192 
 193   // Above the OLD FP (and in registers) are the incoming arguments.  Stack
 194   // slots in this area are called "arg_slots".  Above the NEW FP (and in
 195   // registers) is the outgoing argument area; above that is the spill/temp
 196   // area.  These are all "frame_slots".  Arg_slots start at the zero
 197   // stack_slots and count up to the known arg_size.  Frame_slots start at
 198   // the stack_slot #arg_size and go up.  After allocation I map stack
 199   // slots to actual offsets.  Stack-slots in the arg_slot area are biased
 200   // by the frame_size; stack-slots in the frame_slot area are biased by 0.
 201 
 202   _trip_cnt = 0;
 203   _alternate = 0;
 204   _matcher._allocation_started = true;
 205 
 206   ResourceArea live_arena;      // Arena for liveness & IFG info
 207   ResourceMark rm(&live_arena);
 208 
 209   // Need live-ness for the IFG; need the IFG for coalescing.  If the
 210   // liveness is JUST for coalescing, then I can get some mileage by renaming
 211   // all copy-related live ranges low and then using the max copy-related
 212   // live range as a cut-off for LIVE and the IFG.  In other words, I can
 213   // build a subset of LIVE and IFG just for copies.
 214   PhaseLive live(_cfg,_names,&live_arena);
 215 
 216   // Need IFG for coalescing and coloring
 217   PhaseIFG ifg( &live_arena );
 218   _ifg = &ifg;
 219 
 220   if (C->unique() > _names.Size())  _names.extend(C->unique()-1, 0);
 221 
 222   // Come out of SSA world to the Named world.  Assign (virtual) registers to
 223   // Nodes.  Use the same register for all inputs and the output of PhiNodes
 224   // - effectively ending SSA form.  This requires either coalescing live
 225   // ranges or inserting copies.  For the moment, we insert "virtual copies"
 226   // - we pretend there is a copy prior to each Phi in predecessor blocks.
 227   // We will attempt to coalesce such "virtual copies" before we manifest
 228   // them for real.
 229   de_ssa();
 230 
 231 #ifdef ASSERT
 232   // Veify the graph before RA.
 233   if( VerifyOpto || VerifyRegisterAllocator ) {
 234     _cfg.verify();
 235   }
 236 #endif
 237   // Collect exception blocks.
 238   Block_List ex_blocks;
 239   collect_ex_blocks(ex_blocks);
 240 
 241   {
 242     NOT_PRODUCT( Compile::TracePhase t3("computeLive", &_t_computeLive, TimeCompiler); )
 243     _live = NULL;                 // Mark live as being not available
 244     rm.reset_to_mark();           // Reclaim working storage
 245     IndexSet::reset_memory(C, &live_arena);
 246     ifg.init(_maxlrg);            // Empty IFG
 247     gather_lrg_masks( false );    // Collect LRG masks
 248     live.compute( _maxlrg );      // Compute liveness
 249     _live = &live;                // Mark LIVE as being available
 250   }
 251 
 252   // Base pointers are currently "used" by instructions which define new
 253   // derived pointers.  This makes base pointers live up to the where the
 254   // derived pointer is made, but not beyond.  Really, they need to be live
 255   // across any GC point where the derived value is live.  So this code looks
 256   // at all the GC points, and "stretches" the live range of any base pointer
 257   // to the GC point.
 258   if( stretch_base_pointer_live_ranges(&live_arena) ) {
 259     NOT_PRODUCT( Compile::TracePhase t3("computeLive (sbplr)", &_t_computeLive, TimeCompiler); )
 260     // Since some live range stretched, I need to recompute live
 261     _live = NULL;
 262     rm.reset_to_mark();         // Reclaim working storage
 263     IndexSet::reset_memory(C, &live_arena);
 264     ifg.init(_maxlrg);
 265     gather_lrg_masks( false );
 266     live.compute( _maxlrg );
 267     _live = &live;
 268   }
 269 
 270   // Fixup exception blocks before ifg.
 271   fixup_ex_blocks(ex_blocks);
 272 
 273   // Create the interference graph using virtual copies
 274   build_ifg_virtual( );  // Include stack slots this time
 275 
 276   // Aggressive (but pessimistic) copy coalescing.
 277   // This pass works on virtual copies.  Any virtual copies which are not
 278   // coalesced get manifested as actual copies
 279   {
 280     // The IFG is/was triangular.  I am 'squaring it up' so Union can run
 281     // faster.  Union requires a 'for all' operation which is slow on the
 282     // triangular adjacency matrix (quick reminder: the IFG is 'sparse' -
 283     // meaning I can visit all the Nodes neighbors less than a Node in time
 284     // O(# of neighbors), but I have to visit all the Nodes greater than a
 285     // given Node and search them for an instance, i.e., time O(#MaxLRG)).
 286     _ifg->SquareUp();
 287 
 288     PhaseAggressiveCoalesce coalesce( *this );
 289     coalesce.coalesce_driver( );
 290     // Insert un-coalesced copies.  Visit all Phis.  Where inputs to a Phi do
 291     // not match the Phi itself, insert a copy.
 292     coalesce.insert_copies(_matcher);
 293   }
 294 
 295   // After aggressive coalesce, attempt a first cut at coloring.
 296   // To color, we need the IFG and for that we need LIVE.
 297   {
 298     NOT_PRODUCT( Compile::TracePhase t3("computeLive", &_t_computeLive, TimeCompiler); )
 299     _live = NULL;
 300     rm.reset_to_mark();           // Reclaim working storage
 301     IndexSet::reset_memory(C, &live_arena);
 302     ifg.init(_maxlrg);
 303     gather_lrg_masks( true );
 304     live.compute( _maxlrg );
 305     _live = &live;
 306   }
 307 
 308   // Build physical interference graph
 309   uint must_spill = 0;
 310   must_spill = build_ifg_physical( &live_arena );
 311   // If we have a guaranteed spill, might as well spill now
 312   if( must_spill ) {
 313     if( !_maxlrg ) return;
 314     // Bail out if unique gets too large (ie - unique > MaxNodeLimit)
 315     C->check_node_count(10*must_spill, "out of nodes before split");
 316     if (C->failing())  return;
 317     _maxlrg = Split( _maxlrg );        // Split spilling LRG everywhere
 318     // Bail out if unique gets too large (ie - unique > MaxNodeLimit - 2*NodeLimitFudgeFactor)
 319     // or we failed to split
 320     C->check_node_count(2*NodeLimitFudgeFactor, "out of nodes after physical split");
 321     if (C->failing())  return;
 322 
 323     // Fixup exception blocks after Split.
 324     fixup_ex_blocks(ex_blocks);
 325 
 326 #ifdef ASSERT
 327     if( VerifyOpto || VerifyRegisterAllocator ) {
 328       _cfg.verify();
 329       verify_base_ptrs(&live_arena);
 330     }
 331 #endif
 332     NOT_PRODUCT( C->verify_graph_edges(); )
 333 
 334     compact();                  // Compact LRGs; return new lower max lrg
 335 
 336     {
 337       NOT_PRODUCT( Compile::TracePhase t3("computeLive", &_t_computeLive, TimeCompiler); )
 338       _live = NULL;
 339       rm.reset_to_mark();         // Reclaim working storage
 340       IndexSet::reset_memory(C, &live_arena);
 341       ifg.init(_maxlrg);          // Build a new interference graph
 342       gather_lrg_masks( true );   // Collect intersect mask
 343       live.compute( _maxlrg );    // Compute LIVE
 344       _live = &live;
 345     }
 346     build_ifg_physical( &live_arena );
 347     _ifg->SquareUp();
 348     _ifg->Compute_Effective_Degree();
 349     // Only do conservative coalescing if requested
 350     if( OptoCoalesce ) {
 351       // Conservative (and pessimistic) copy coalescing of those spills
 352       PhaseConservativeCoalesce coalesce( *this );
 353       // If max live ranges greater than cutoff, don't color the stack.
 354       // This cutoff can be larger than below since it is only done once.
 355       coalesce.coalesce_driver( );
 356     }
 357     compress_uf_map_for_nodes();
 358 
 359 #ifdef ASSERT
 360     if( VerifyOpto || VerifyRegisterAllocator ) _ifg->verify(this);
 361 #endif
 362   } else {
 363     ifg.SquareUp();
 364     ifg.Compute_Effective_Degree();
 365 #ifdef ASSERT
 366     set_was_low();
 367 #endif
 368   }
 369 
 370   // Prepare for Simplify & Select
 371   cache_lrg_info();           // Count degree of LRGs
 372 
 373   // Simplify the InterFerence Graph by removing LRGs of low degree.
 374   // LRGs of low degree are trivially colorable.
 375   Simplify();
 376 
 377   // Select colors by re-inserting LRGs back into the IFG in reverse order.
 378   // Return whether or not something spills.
 379   uint spills = Select( );
 380 
 381   // If we spill, split and recycle the entire thing
 382   while( spills ) {
 383     if( _trip_cnt++ > 24 ) {
 384       DEBUG_ONLY( dump_for_spill_split_recycle(); )
 385       if( _trip_cnt > 27 ) {
 386         C->record_method_not_compilable("failed spill-split-recycle sanity check");
 387         return;
 388       }
 389     }
 390 
 391     if( !_maxlrg ) return;
 392     _maxlrg = Split( _maxlrg );        // Split spilling LRG everywhere
 393     // Bail out if unique gets too large (ie - unique > MaxNodeLimit - 2*NodeLimitFudgeFactor)
 394     C->check_node_count(2*NodeLimitFudgeFactor, "out of nodes after split");
 395     if (C->failing())  return;
 396 
 397     // Fixup exception blocks after Split.
 398     fixup_ex_blocks(ex_blocks);
 399 
 400 #ifdef ASSERT
 401     if( VerifyOpto || VerifyRegisterAllocator ) {
 402       _cfg.verify();
 403       verify_base_ptrs(&live_arena);
 404     }
 405 #endif
 406 
 407     compact();                  // Compact LRGs; return new lower max lrg
 408 
 409     // Nuke the live-ness and interference graph and LiveRanGe info
 410     {
 411       NOT_PRODUCT( Compile::TracePhase t3("computeLive", &_t_computeLive, TimeCompiler); )
 412       _live = NULL;
 413       rm.reset_to_mark();         // Reclaim working storage
 414       IndexSet::reset_memory(C, &live_arena);
 415       ifg.init(_maxlrg);
 416 
 417       // Create LiveRanGe array.
 418       // Intersect register masks for all USEs and DEFs
 419       gather_lrg_masks( true );
 420       live.compute( _maxlrg );
 421       _live = &live;
 422     }
 423     must_spill = build_ifg_physical( &live_arena );
 424     _ifg->SquareUp();
 425     _ifg->Compute_Effective_Degree();
 426 
 427     // Only do conservative coalescing if requested
 428     if( OptoCoalesce ) {
 429       // Conservative (and pessimistic) copy coalescing
 430       PhaseConservativeCoalesce coalesce( *this );
 431       // Check for few live ranges determines how aggressive coalesce is.
 432       coalesce.coalesce_driver( );
 433     }
 434     compress_uf_map_for_nodes();
 435 #ifdef ASSERT
 436     if( VerifyOpto || VerifyRegisterAllocator ) _ifg->verify(this);
 437 #endif
 438     cache_lrg_info();           // Count degree of LRGs
 439 
 440     // Simplify the InterFerence Graph by removing LRGs of low degree.
 441     // LRGs of low degree are trivially colorable.
 442     Simplify();
 443 
 444     // Select colors by re-inserting LRGs back into the IFG in reverse order.
 445     // Return whether or not something spills.
 446     spills = Select( );
 447   }
 448 
 449   // Count number of Simplify-Select trips per coloring success.
 450   _allocator_attempts += _trip_cnt + 1;
 451   _allocator_successes += 1;
 452 
 453   // Peephole remove copies
 454   post_allocate_copy_removal();
 455 
 456   // Fixup exception blocks at the end of RA.
 457   fixup_ex_blocks(ex_blocks);
 458 
 459 #ifdef ASSERT
 460   if( VerifyOpto || VerifyRegisterAllocator ) {
 461     _cfg.verify();
 462     verify_base_ptrs(&live_arena);
 463   }
 464 #endif
 465 
 466   // max_reg is past the largest *register* used.
 467   // Convert that to a frame_slot number.
 468   if( _max_reg <= _matcher._new_SP )
 469     _framesize = C->out_preserve_stack_slots();
 470   else _framesize = _max_reg -_matcher._new_SP;
 471   assert((int)(_matcher._new_SP+_framesize) >= (int)_matcher._out_arg_limit, "framesize must be large enough");
 472 
 473   // This frame must preserve the required fp alignment
 474   _framesize = round_to(_framesize, Matcher::stack_alignment_in_slots());
 475   assert( _framesize >= 0 && _framesize <= 1000000, "sanity check" );
 476 #ifndef PRODUCT
 477   _total_framesize += _framesize;
 478   if( (int)_framesize > _max_framesize )
 479     _max_framesize = _framesize;
 480 #endif
 481 
 482   // Convert CISC spills
 483   fixup_spills();
 484 
 485   // Log regalloc results
 486   CompileLog* log = Compile::current()->log();
 487   if (log != NULL) {
 488     log->elem("regalloc attempts='%d' success='%d'", _trip_cnt, !C->failing());
 489   }
 490 
 491   if (C->failing())  return;
 492 
 493   NOT_PRODUCT( C->verify_graph_edges(); )
 494 
 495   // Move important info out of the live_arena to longer lasting storage.
 496   alloc_node_regs(_names.Size());
 497   for( uint i=0; i < _names.Size(); i++ ) {
 498     if( _names[i] ) {           // Live range associated with Node?
 499       LRG &lrg = lrgs( _names[i] );
 500       if( lrg.num_regs() == 1 ) {
 501         _node_regs[i].set1( lrg.reg() );
 502       } else {                  // Must be a register-pair
 503         if( !lrg._fat_proj ) {  // Must be aligned adjacent register pair
 504           // Live ranges record the highest register in their mask.
 505           // We want the low register for the AD file writer's convenience.
 506           _node_regs[i].set2( OptoReg::add(lrg.reg(),-1) );
 507         } else {                // Misaligned; extract 2 bits
 508           OptoReg::Name hi = lrg.reg(); // Get hi register
 509           lrg.Remove(hi);       // Yank from mask
 510           int lo = lrg.mask().find_first_elem(); // Find lo
 511           _node_regs[i].set_pair( hi, lo );
 512         }
 513       }
 514       if( lrg._is_oop ) _node_oops.set(i);
 515     } else {
 516       _node_regs[i].set_bad();
 517     }
 518   }
 519 
 520   // Done!
 521   _live = NULL;
 522   _ifg = NULL;
 523   C->set_indexSet_arena(NULL);  // ResourceArea is at end of scope
 524 }
 525 
 526 //------------------------------de_ssa-----------------------------------------
 527 void PhaseChaitin::de_ssa() {
 528   // Set initial Names for all Nodes.  Most Nodes get the virtual register
 529   // number.  A few get the ZERO live range number.  These do not
 530   // get allocated, but instead rely on correct scheduling to ensure that
 531   // only one instance is simultaneously live at a time.
 532   uint lr_counter = 1;
 533   for( uint i = 0; i < _cfg._num_blocks; i++ ) {
 534     Block *b = _cfg._blocks[i];
 535     uint cnt = b->_nodes.size();
 536 
 537     // Handle all the normal Nodes in the block
 538     for( uint j = 0; j < cnt; j++ ) {
 539       Node *n = b->_nodes[j];
 540       // Pre-color to the zero live range, or pick virtual register
 541       const RegMask &rm = n->out_RegMask();
 542       _names.map( n->_idx, rm.is_NotEmpty() ? lr_counter++ : 0 );
 543     }
 544   }
 545   // Reset the Union-Find mapping to be identity
 546   reset_uf_map(lr_counter);
 547 }
 548 
 549 
 550 //------------------------------gather_lrg_masks-------------------------------
 551 // Gather LiveRanGe information, including register masks.  Modification of
 552 // cisc spillable in_RegMasks should not be done before AggressiveCoalesce.
 553 void PhaseChaitin::gather_lrg_masks( bool after_aggressive ) {
 554 
 555   // Nail down the frame pointer live range
 556   uint fp_lrg = n2lidx(_cfg._root->in(1)->in(TypeFunc::FramePtr));
 557   lrgs(fp_lrg)._cost += 1e12;   // Cost is infinite
 558 
 559   // For all blocks
 560   for( uint i = 0; i < _cfg._num_blocks; i++ ) {
 561     Block *b = _cfg._blocks[i];
 562 
 563     // For all instructions
 564     for( uint j = 1; j < b->_nodes.size(); j++ ) {
 565       Node *n = b->_nodes[j];
 566       uint input_edge_start =1; // Skip control most nodes
 567       if( n->is_Mach() ) input_edge_start = n->as_Mach()->oper_input_base();
 568       uint idx = n->is_Copy();
 569 
 570       // Get virtual register number, same as LiveRanGe index
 571       uint vreg = n2lidx(n);
 572       LRG &lrg = lrgs(vreg);
 573       if( vreg ) {              // No vreg means un-allocable (e.g. memory)
 574 
 575         // Collect has-copy bit
 576         if( idx ) {
 577           lrg._has_copy = 1;
 578           uint clidx = n2lidx(n->in(idx));
 579           LRG &copy_src = lrgs(clidx);
 580           copy_src._has_copy = 1;
 581         }
 582 
 583         // Check for float-vs-int live range (used in register-pressure
 584         // calculations)
 585         const Type *n_type = n->bottom_type();
 586         if( n_type->is_floatingpoint() )
 587           lrg._is_float = 1;
 588 
 589         // Check for twice prior spilling.  Once prior spilling might have
 590         // spilled 'soft', 2nd prior spill should have spilled 'hard' and
 591         // further spilling is unlikely to make progress.
 592         if( _spilled_once.test(n->_idx) ) {
 593           lrg._was_spilled1 = 1;
 594           if( _spilled_twice.test(n->_idx) )
 595             lrg._was_spilled2 = 1;
 596         }
 597 
 598 #ifndef PRODUCT
 599         if (trace_spilling() && lrg._def != NULL) {
 600           // collect defs for MultiDef printing
 601           if (lrg._defs == NULL) {
 602             lrg._defs = new (_ifg->_arena) GrowableArray<Node*>();
 603             lrg._defs->append(lrg._def);
 604           }
 605           lrg._defs->append(n);
 606         }
 607 #endif
 608 
 609         // Check for a single def LRG; these can spill nicely
 610         // via rematerialization.  Flag as NULL for no def found
 611         // yet, or 'n' for single def or -1 for many defs.
 612         lrg._def = lrg._def ? NodeSentinel : n;
 613 
 614         // Limit result register mask to acceptable registers
 615         const RegMask &rm = n->out_RegMask();
 616         lrg.AND( rm );
 617         // Check for bound register masks
 618         const RegMask &lrgmask = lrg.mask();
 619         if( lrgmask.is_bound1() || lrgmask.is_bound2() )
 620           lrg._is_bound = 1;
 621 
 622         // Check for maximum frequency value
 623         if( lrg._maxfreq < b->_freq )
 624           lrg._maxfreq = b->_freq;
 625 
 626         int ireg = n->ideal_reg();
 627         assert( !n->bottom_type()->isa_oop_ptr() || ireg == Op_RegP,
 628                 "oops must be in Op_RegP's" );
 629         // Check for oop-iness, or long/double
 630         // Check for multi-kill projection
 631         switch( ireg ) {
 632         case MachProjNode::fat_proj:
 633           // Fat projections have size equal to number of registers killed
 634           lrg.set_num_regs(rm.Size());
 635           lrg.set_reg_pressure(lrg.num_regs());
 636           lrg._fat_proj = 1;
 637           lrg._is_bound = 1;
 638           break;
 639         case Op_RegP:
 640 #ifdef _LP64
 641           lrg.set_num_regs(2);  // Size is 2 stack words
 642 #else
 643           lrg.set_num_regs(1);  // Size is 1 stack word
 644 #endif
 645           // Register pressure is tracked relative to the maximum values
 646           // suggested for that platform, INTPRESSURE and FLOATPRESSURE,
 647           // and relative to other types which compete for the same regs.
 648           //
 649           // The following table contains suggested values based on the
 650           // architectures as defined in each .ad file.
 651           // INTPRESSURE and FLOATPRESSURE may be tuned differently for
 652           // compile-speed or performance.
 653           // Note1:
 654           // SPARC and SPARCV9 reg_pressures are at 2 instead of 1
 655           // since .ad registers are defined as high and low halves.
 656           // These reg_pressure values remain compatible with the code
 657           // in is_high_pressure() which relates get_invalid_mask_size(),
 658           // Block::_reg_pressure and INTPRESSURE, FLOATPRESSURE.
 659           // Note2:
 660           // SPARC -d32 has 24 registers available for integral values,
 661           // but only 10 of these are safe for 64-bit longs.
 662           // Using set_reg_pressure(2) for both int and long means
 663           // the allocator will believe it can fit 26 longs into
 664           // registers.  Using 2 for longs and 1 for ints means the
 665           // allocator will attempt to put 52 integers into registers.
 666           // The settings below limit this problem to methods with
 667           // many long values which are being run on 32-bit SPARC.
 668           //
 669           // ------------------- reg_pressure --------------------
 670           // Each entry is reg_pressure_per_value,number_of_regs
 671           //         RegL  RegI  RegFlags   RegF RegD    INTPRESSURE  FLOATPRESSURE
 672           // IA32     2     1     1          1    1          6           6
 673           // IA64     1     1     1          1    1         50          41
 674           // SPARC    2     2     2          2    2         48 (24)     52 (26)
 675           // SPARCV9  2     2     2          2    2         48 (24)     52 (26)
 676           // AMD64    1     1     1          1    1         14          15
 677           // -----------------------------------------------------
 678 #if defined(SPARC)
 679           lrg.set_reg_pressure(2);  // use for v9 as well
 680 #else
 681           lrg.set_reg_pressure(1);  // normally one value per register
 682 #endif
 683           if( n_type->isa_oop_ptr() ) {
 684             lrg._is_oop = 1;
 685           }
 686           break;
 687         case Op_RegL:           // Check for long or double
 688         case Op_RegD:
 689           lrg.set_num_regs(2);
 690           // Define platform specific register pressure
 691 #ifdef SPARC
 692           lrg.set_reg_pressure(2);
 693 #elif defined(IA32)
 694           if( ireg == Op_RegL ) {
 695             lrg.set_reg_pressure(2);
 696           } else {
 697             lrg.set_reg_pressure(1);
 698           }
 699 #else
 700           lrg.set_reg_pressure(1);  // normally one value per register
 701 #endif
 702           // If this def of a double forces a mis-aligned double,
 703           // flag as '_fat_proj' - really flag as allowing misalignment
 704           // AND changes how we count interferences.  A mis-aligned
 705           // double can interfere with TWO aligned pairs, or effectively
 706           // FOUR registers!
 707           if( rm.is_misaligned_Pair() ) {
 708             lrg._fat_proj = 1;
 709             lrg._is_bound = 1;
 710           }
 711           break;
 712         case Op_RegF:
 713         case Op_RegI:
 714         case Op_RegN:
 715         case Op_RegFlags:
 716         case 0:                 // not an ideal register
 717           lrg.set_num_regs(1);
 718 #ifdef SPARC
 719           lrg.set_reg_pressure(2);
 720 #else
 721           lrg.set_reg_pressure(1);
 722 #endif
 723           break;
 724         default:
 725           ShouldNotReachHere();
 726         }
 727       }
 728 
 729       // Now do the same for inputs
 730       uint cnt = n->req();
 731       // Setup for CISC SPILLING
 732       uint inp = (uint)AdlcVMDeps::Not_cisc_spillable;
 733       if( UseCISCSpill && after_aggressive ) {
 734         inp = n->cisc_operand();
 735         if( inp != (uint)AdlcVMDeps::Not_cisc_spillable )
 736           // Convert operand number to edge index number
 737           inp = n->as_Mach()->operand_index(inp);
 738       }
 739       // Prepare register mask for each input
 740       for( uint k = input_edge_start; k < cnt; k++ ) {
 741         uint vreg = n2lidx(n->in(k));
 742         if( !vreg ) continue;
 743 
 744         // If this instruction is CISC Spillable, add the flags
 745         // bit to its appropriate input
 746         if( UseCISCSpill && after_aggressive && inp == k ) {
 747 #ifndef PRODUCT
 748           if( TraceCISCSpill ) {
 749             tty->print("  use_cisc_RegMask: ");
 750             n->dump();
 751           }
 752 #endif
 753           n->as_Mach()->use_cisc_RegMask();
 754         }
 755 
 756         LRG &lrg = lrgs(vreg);
 757         // // Testing for floating point code shape
 758         // Node *test = n->in(k);
 759         // if( test->is_Mach() ) {
 760         //   MachNode *m = test->as_Mach();
 761         //   int  op = m->ideal_Opcode();
 762         //   if (n->is_Call() && (op == Op_AddF || op == Op_MulF) ) {
 763         //     int zzz = 1;
 764         //   }
 765         // }
 766 
 767         // Limit result register mask to acceptable registers.
 768         // Do not limit registers from uncommon uses before
 769         // AggressiveCoalesce.  This effectively pre-virtual-splits
 770         // around uncommon uses of common defs.
 771         const RegMask &rm = n->in_RegMask(k);
 772         if( !after_aggressive &&
 773           _cfg._bbs[n->in(k)->_idx]->_freq > 1000*b->_freq ) {
 774           // Since we are BEFORE aggressive coalesce, leave the register
 775           // mask untrimmed by the call.  This encourages more coalescing.
 776           // Later, AFTER aggressive, this live range will have to spill
 777           // but the spiller handles slow-path calls very nicely.
 778         } else {
 779           lrg.AND( rm );
 780         }
 781         // Check for bound register masks
 782         const RegMask &lrgmask = lrg.mask();
 783         if( lrgmask.is_bound1() || lrgmask.is_bound2() )
 784           lrg._is_bound = 1;
 785         // If this use of a double forces a mis-aligned double,
 786         // flag as '_fat_proj' - really flag as allowing misalignment
 787         // AND changes how we count interferences.  A mis-aligned
 788         // double can interfere with TWO aligned pairs, or effectively
 789         // FOUR registers!
 790         if( lrg.num_regs() == 2 && !lrg._fat_proj && rm.is_misaligned_Pair() ) {
 791           lrg._fat_proj = 1;
 792           lrg._is_bound = 1;
 793         }
 794         // if the LRG is an unaligned pair, we will have to spill
 795         // so clear the LRG's register mask if it is not already spilled
 796         if ( !n->is_SpillCopy() &&
 797                (lrg._def == NULL || lrg.is_multidef() || !lrg._def->is_SpillCopy()) &&
 798                lrgmask.is_misaligned_Pair()) {
 799           lrg.Clear();
 800         }
 801 
 802         // Check for maximum frequency value
 803         if( lrg._maxfreq < b->_freq )
 804           lrg._maxfreq = b->_freq;
 805 
 806       } // End for all allocated inputs
 807     } // end for all instructions
 808   } // end for all blocks
 809 
 810   // Final per-liverange setup
 811   for( uint i2=0; i2<_maxlrg; i2++ ) {
 812     LRG &lrg = lrgs(i2);
 813     if( lrg.num_regs() == 2 && !lrg._fat_proj )
 814       lrg.ClearToPairs();
 815     lrg.compute_set_mask_size();
 816     if( lrg.not_free() ) {      // Handle case where we lose from the start
 817       lrg.set_reg(OptoReg::Name(LRG::SPILL_REG));
 818       lrg._direct_conflict = 1;
 819     }
 820     lrg.set_degree(0);          // no neighbors in IFG yet
 821   }
 822 }
 823 
 824 //------------------------------set_was_low------------------------------------
 825 // Set the was-lo-degree bit.  Conservative coalescing should not change the
 826 // colorability of the graph.  If any live range was of low-degree before
 827 // coalescing, it should Simplify.  This call sets the was-lo-degree bit.
 828 // The bit is checked in Simplify.
 829 void PhaseChaitin::set_was_low() {
 830 #ifdef ASSERT
 831   for( uint i = 1; i < _maxlrg; i++ ) {
 832     int size = lrgs(i).num_regs();
 833     uint old_was_lo = lrgs(i)._was_lo;
 834     lrgs(i)._was_lo = 0;
 835     if( lrgs(i).lo_degree() ) {
 836       lrgs(i)._was_lo = 1;      // Trivially of low degree
 837     } else {                    // Else check the Brigg's assertion
 838       // Brigg's observation is that the lo-degree neighbors of a
 839       // hi-degree live range will not interfere with the color choices
 840       // of said hi-degree live range.  The Simplify reverse-stack-coloring
 841       // order takes care of the details.  Hence you do not have to count
 842       // low-degree neighbors when determining if this guy colors.
 843       int briggs_degree = 0;
 844       IndexSet *s = _ifg->neighbors(i);
 845       IndexSetIterator elements(s);
 846       uint lidx;
 847       while((lidx = elements.next()) != 0) {
 848         if( !lrgs(lidx).lo_degree() )
 849           briggs_degree += MAX2(size,lrgs(lidx).num_regs());
 850       }
 851       if( briggs_degree < lrgs(i).degrees_of_freedom() )
 852         lrgs(i)._was_lo = 1;    // Low degree via the briggs assertion
 853     }
 854     assert(old_was_lo <= lrgs(i)._was_lo, "_was_lo may not decrease");
 855   }
 856 #endif
 857 }
 858 
 859 #define REGISTER_CONSTRAINED 16
 860 
 861 //------------------------------cache_lrg_info---------------------------------
 862 // Compute cost/area ratio, in case we spill.  Build the lo-degree list.
 863 void PhaseChaitin::cache_lrg_info( ) {
 864 
 865   for( uint i = 1; i < _maxlrg; i++ ) {
 866     LRG &lrg = lrgs(i);
 867 
 868     // Check for being of low degree: means we can be trivially colored.
 869     // Low degree, dead or must-spill guys just get to simplify right away
 870     if( lrg.lo_degree() ||
 871        !lrg.alive() ||
 872         lrg._must_spill ) {
 873       // Split low degree list into those guys that must get a
 874       // register and those that can go to register or stack.
 875       // The idea is LRGs that can go register or stack color first when
 876       // they have a good chance of getting a register.  The register-only
 877       // lo-degree live ranges always get a register.
 878       OptoReg::Name hi_reg = lrg.mask().find_last_elem();
 879       if( OptoReg::is_stack(hi_reg)) { // Can go to stack?
 880         lrg._next = _lo_stk_degree;
 881         _lo_stk_degree = i;
 882       } else {
 883         lrg._next = _lo_degree;
 884         _lo_degree = i;
 885       }
 886     } else {                    // Else high degree
 887       lrgs(_hi_degree)._prev = i;
 888       lrg._next = _hi_degree;
 889       lrg._prev = 0;
 890       _hi_degree = i;
 891     }
 892   }
 893 }
 894 
 895 //------------------------------Pre-Simplify-----------------------------------
 896 // Simplify the IFG by removing LRGs of low degree that have NO copies
 897 void PhaseChaitin::Pre_Simplify( ) {
 898 
 899   // Warm up the lo-degree no-copy list
 900   int lo_no_copy = 0;
 901   for( uint i = 1; i < _maxlrg; i++ ) {
 902     if( (lrgs(i).lo_degree() && !lrgs(i)._has_copy) ||
 903         !lrgs(i).alive() ||
 904         lrgs(i)._must_spill ) {
 905       lrgs(i)._next = lo_no_copy;
 906       lo_no_copy = i;
 907     }
 908   }
 909 
 910   while( lo_no_copy ) {
 911     uint lo = lo_no_copy;
 912     lo_no_copy = lrgs(lo)._next;
 913     int size = lrgs(lo).num_regs();
 914 
 915     // Put the simplified guy on the simplified list.
 916     lrgs(lo)._next = _simplified;
 917     _simplified = lo;
 918 
 919     // Yank this guy from the IFG.
 920     IndexSet *adj = _ifg->remove_node( lo );
 921 
 922     // If any neighbors' degrees fall below their number of
 923     // allowed registers, then put that neighbor on the low degree
 924     // list.  Note that 'degree' can only fall and 'numregs' is
 925     // unchanged by this action.  Thus the two are equal at most once,
 926     // so LRGs hit the lo-degree worklists at most once.
 927     IndexSetIterator elements(adj);
 928     uint neighbor;
 929     while ((neighbor = elements.next()) != 0) {
 930       LRG *n = &lrgs(neighbor);
 931       assert( _ifg->effective_degree(neighbor) == n->degree(), "" );
 932 
 933       // Check for just becoming of-low-degree
 934       if( n->just_lo_degree() && !n->_has_copy ) {
 935         assert(!(*_ifg->_yanked)[neighbor],"Cannot move to lo degree twice");
 936         // Put on lo-degree list
 937         n->_next = lo_no_copy;
 938         lo_no_copy = neighbor;
 939       }
 940     }
 941   } // End of while lo-degree no_copy worklist not empty
 942 
 943   // No more lo-degree no-copy live ranges to simplify
 944 }
 945 
 946 //------------------------------Simplify---------------------------------------
 947 // Simplify the IFG by removing LRGs of low degree.
 948 void PhaseChaitin::Simplify( ) {
 949 
 950   while( 1 ) {                  // Repeat till simplified it all
 951     // May want to explore simplifying lo_degree before _lo_stk_degree.
 952     // This might result in more spills coloring into registers during
 953     // Select().
 954     while( _lo_degree || _lo_stk_degree ) {
 955       // If possible, pull from lo_stk first
 956       uint lo;
 957       if( _lo_degree ) {
 958         lo = _lo_degree;
 959         _lo_degree = lrgs(lo)._next;
 960       } else {
 961         lo = _lo_stk_degree;
 962         _lo_stk_degree = lrgs(lo)._next;
 963       }
 964 
 965       // Put the simplified guy on the simplified list.
 966       lrgs(lo)._next = _simplified;
 967       _simplified = lo;
 968       // If this guy is "at risk" then mark his current neighbors
 969       if( lrgs(lo)._at_risk ) {
 970         IndexSetIterator elements(_ifg->neighbors(lo));
 971         uint datum;
 972         while ((datum = elements.next()) != 0) {
 973           lrgs(datum)._risk_bias = lo;
 974         }
 975       }
 976 
 977       // Yank this guy from the IFG.
 978       IndexSet *adj = _ifg->remove_node( lo );
 979 
 980       // If any neighbors' degrees fall below their number of
 981       // allowed registers, then put that neighbor on the low degree
 982       // list.  Note that 'degree' can only fall and 'numregs' is
 983       // unchanged by this action.  Thus the two are equal at most once,
 984       // so LRGs hit the lo-degree worklist at most once.
 985       IndexSetIterator elements(adj);
 986       uint neighbor;
 987       while ((neighbor = elements.next()) != 0) {
 988         LRG *n = &lrgs(neighbor);
 989 #ifdef ASSERT
 990         if( VerifyOpto || VerifyRegisterAllocator ) {
 991           assert( _ifg->effective_degree(neighbor) == n->degree(), "" );
 992         }
 993 #endif
 994 
 995         // Check for just becoming of-low-degree just counting registers.
 996         // _must_spill live ranges are already on the low degree list.
 997         if( n->just_lo_degree() && !n->_must_spill ) {
 998           assert(!(*_ifg->_yanked)[neighbor],"Cannot move to lo degree twice");
 999           // Pull from hi-degree list
1000           uint prev = n->_prev;
1001           uint next = n->_next;
1002           if( prev ) lrgs(prev)._next = next;
1003           else _hi_degree = next;
1004           lrgs(next)._prev = prev;
1005           n->_next = _lo_degree;
1006           _lo_degree = neighbor;
1007         }
1008       }
1009     } // End of while lo-degree/lo_stk_degree worklist not empty
1010 
1011     // Check for got everything: is hi-degree list empty?
1012     if( !_hi_degree ) break;
1013 
1014     // Time to pick a potential spill guy
1015     uint lo_score = _hi_degree;
1016     double score = lrgs(lo_score).score();
1017     double area = lrgs(lo_score)._area;
1018 
1019     // Find cheapest guy
1020     debug_only( int lo_no_simplify=0; );
1021     for( uint i = _hi_degree; i; i = lrgs(i)._next ) {
1022       assert( !(*_ifg->_yanked)[i], "" );
1023       // It's just vaguely possible to move hi-degree to lo-degree without
1024       // going through a just-lo-degree stage: If you remove a double from
1025       // a float live range it's degree will drop by 2 and you can skip the
1026       // just-lo-degree stage.  It's very rare (shows up after 5000+ methods
1027       // in -Xcomp of Java2Demo).  So just choose this guy to simplify next.
1028       if( lrgs(i).lo_degree() ) {
1029         lo_score = i;
1030         break;
1031       }
1032       debug_only( if( lrgs(i)._was_lo ) lo_no_simplify=i; );
1033       double iscore = lrgs(i).score();
1034       double iarea = lrgs(i)._area;
1035 
1036       // Compare cost/area of i vs cost/area of lo_score.  Smaller cost/area
1037       // wins.  Ties happen because all live ranges in question have spilled
1038       // a few times before and the spill-score adds a huge number which
1039       // washes out the low order bits.  We are choosing the lesser of 2
1040       // evils; in this case pick largest area to spill.
1041       if( iscore < score ||
1042           (iscore == score && iarea > area && lrgs(lo_score)._was_spilled2) ) {
1043         lo_score = i;
1044         score = iscore;
1045         area = iarea;
1046       }
1047     }
1048     LRG *lo_lrg = &lrgs(lo_score);
1049     // The live range we choose for spilling is either hi-degree, or very
1050     // rarely it can be low-degree.  If we choose a hi-degree live range
1051     // there better not be any lo-degree choices.
1052     assert( lo_lrg->lo_degree() || !lo_no_simplify, "Live range was lo-degree before coalesce; should simplify" );
1053 
1054     // Pull from hi-degree list
1055     uint prev = lo_lrg->_prev;
1056     uint next = lo_lrg->_next;
1057     if( prev ) lrgs(prev)._next = next;
1058     else _hi_degree = next;
1059     lrgs(next)._prev = prev;
1060     // Jam him on the lo-degree list, despite his high degree.
1061     // Maybe he'll get a color, and maybe he'll spill.
1062     // Only Select() will know.
1063     lrgs(lo_score)._at_risk = true;
1064     _lo_degree = lo_score;
1065     lo_lrg->_next = 0;
1066 
1067   } // End of while not simplified everything
1068 
1069 }
1070 
1071 //------------------------------bias_color-------------------------------------
1072 // Choose a color using the biasing heuristic
1073 OptoReg::Name PhaseChaitin::bias_color( LRG &lrg, int chunk ) {
1074 
1075   // Check for "at_risk" LRG's
1076   uint risk_lrg = Find(lrg._risk_bias);
1077   if( risk_lrg != 0 ) {
1078     // Walk the colored neighbors of the "at_risk" candidate
1079     // Choose a color which is both legal and already taken by a neighbor
1080     // of the "at_risk" candidate in order to improve the chances of the
1081     // "at_risk" candidate of coloring
1082     IndexSetIterator elements(_ifg->neighbors(risk_lrg));
1083     uint datum;
1084     while ((datum = elements.next()) != 0) {
1085       OptoReg::Name reg = lrgs(datum).reg();
1086       // If this LRG's register is legal for us, choose it
1087       if( reg >= chunk && reg < chunk + RegMask::CHUNK_SIZE &&
1088           lrg.mask().Member(OptoReg::add(reg,-chunk)) &&
1089           (lrg.num_regs()==1 || // either size 1
1090            (reg&1) == 1) )      // or aligned (adjacent reg is available since we already cleared-to-pairs)
1091         return reg;
1092     }
1093   }
1094 
1095   uint copy_lrg = Find(lrg._copy_bias);
1096   if( copy_lrg != 0 ) {
1097     // If he has a color,
1098     if( !(*(_ifg->_yanked))[copy_lrg] ) {
1099       OptoReg::Name reg = lrgs(copy_lrg).reg();
1100       //  And it is legal for you,
1101       if( reg >= chunk && reg < chunk + RegMask::CHUNK_SIZE &&
1102           lrg.mask().Member(OptoReg::add(reg,-chunk)) &&
1103           (lrg.num_regs()==1 || // either size 1
1104            (reg&1) == 1) )      // or aligned (adjacent reg is available since we already cleared-to-pairs)
1105         return reg;
1106     } else if( chunk == 0 ) {
1107       // Choose a color which is legal for him
1108       RegMask tempmask = lrg.mask();
1109       tempmask.AND(lrgs(copy_lrg).mask());
1110       OptoReg::Name reg;
1111       if( lrg.num_regs() == 1 ) {
1112         reg = tempmask.find_first_elem();
1113       } else {
1114         tempmask.ClearToPairs();
1115         reg = tempmask.find_first_pair();
1116       }
1117       if( OptoReg::is_valid(reg) )
1118         return reg;
1119     }
1120   }
1121 
1122   // If no bias info exists, just go with the register selection ordering
1123   if( lrg.num_regs() == 2 ) {
1124     // Find an aligned pair
1125     return OptoReg::add(lrg.mask().find_first_pair(),chunk);
1126   }
1127 
1128   // CNC - Fun hack.  Alternate 1st and 2nd selection.  Enables post-allocate
1129   // copy removal to remove many more copies, by preventing a just-assigned
1130   // register from being repeatedly assigned.
1131   OptoReg::Name reg = lrg.mask().find_first_elem();
1132   if( (++_alternate & 1) && OptoReg::is_valid(reg) ) {
1133     // This 'Remove; find; Insert' idiom is an expensive way to find the
1134     // SECOND element in the mask.
1135     lrg.Remove(reg);
1136     OptoReg::Name reg2 = lrg.mask().find_first_elem();
1137     lrg.Insert(reg);
1138     if( OptoReg::is_reg(reg2))
1139       reg = reg2;
1140   }
1141   return OptoReg::add( reg, chunk );
1142 }
1143 
1144 //------------------------------choose_color-----------------------------------
1145 // Choose a color in the current chunk
1146 OptoReg::Name PhaseChaitin::choose_color( LRG &lrg, int chunk ) {
1147   assert( C->in_preserve_stack_slots() == 0 || chunk != 0 || lrg._is_bound || lrg.mask().is_bound1() || !lrg.mask().Member(OptoReg::Name(_matcher._old_SP-1)), "must not allocate stack0 (inside preserve area)");
1148   assert(C->out_preserve_stack_slots() == 0 || chunk != 0 || lrg._is_bound || lrg.mask().is_bound1() || !lrg.mask().Member(OptoReg::Name(_matcher._old_SP+0)), "must not allocate stack0 (inside preserve area)");
1149 
1150   if( lrg.num_regs() == 1 ||    // Common Case
1151       !lrg._fat_proj )          // Aligned+adjacent pairs ok
1152     // Use a heuristic to "bias" the color choice
1153     return bias_color(lrg, chunk);
1154 
1155   assert( lrg.num_regs() >= 2, "dead live ranges do not color" );
1156 
1157   // Fat-proj case or misaligned double argument.
1158   assert(lrg.compute_mask_size() == lrg.num_regs() ||
1159          lrg.num_regs() == 2,"fat projs exactly color" );
1160   assert( !chunk, "always color in 1st chunk" );
1161   // Return the highest element in the set.
1162   return lrg.mask().find_last_elem();
1163 }
1164 
1165 //------------------------------Select-----------------------------------------
1166 // Select colors by re-inserting LRGs back into the IFG.  LRGs are re-inserted
1167 // in reverse order of removal.  As long as nothing of hi-degree was yanked,
1168 // everything going back is guaranteed a color.  Select that color.  If some
1169 // hi-degree LRG cannot get a color then we record that we must spill.
1170 uint PhaseChaitin::Select( ) {
1171   uint spill_reg = LRG::SPILL_REG;
1172   _max_reg = OptoReg::Name(0);  // Past max register used
1173   while( _simplified ) {
1174     // Pull next LRG from the simplified list - in reverse order of removal
1175     uint lidx = _simplified;
1176     LRG *lrg = &lrgs(lidx);
1177     _simplified = lrg->_next;
1178 
1179 
1180 #ifndef PRODUCT
1181     if (trace_spilling()) {
1182       ttyLocker ttyl;
1183       tty->print_cr("L%d selecting degree %d degrees_of_freedom %d", lidx, lrg->degree(),
1184                     lrg->degrees_of_freedom());
1185       lrg->dump();
1186     }
1187 #endif
1188 
1189     // Re-insert into the IFG
1190     _ifg->re_insert(lidx);
1191     if( !lrg->alive() ) continue;
1192     // capture allstackedness flag before mask is hacked
1193     const int is_allstack = lrg->mask().is_AllStack();
1194 
1195     // Yeah, yeah, yeah, I know, I know.  I can refactor this
1196     // to avoid the GOTO, although the refactored code will not
1197     // be much clearer.  We arrive here IFF we have a stack-based
1198     // live range that cannot color in the current chunk, and it
1199     // has to move into the next free stack chunk.
1200     int chunk = 0;              // Current chunk is first chunk
1201     retry_next_chunk:
1202 
1203     // Remove neighbor colors
1204     IndexSet *s = _ifg->neighbors(lidx);
1205 
1206     debug_only(RegMask orig_mask = lrg->mask();)
1207     IndexSetIterator elements(s);
1208     uint neighbor;
1209     while ((neighbor = elements.next()) != 0) {
1210       // Note that neighbor might be a spill_reg.  In this case, exclusion
1211       // of its color will be a no-op, since the spill_reg chunk is in outer
1212       // space.  Also, if neighbor is in a different chunk, this exclusion
1213       // will be a no-op.  (Later on, if lrg runs out of possible colors in
1214       // its chunk, a new chunk of color may be tried, in which case
1215       // examination of neighbors is started again, at retry_next_chunk.)
1216       LRG &nlrg = lrgs(neighbor);
1217       OptoReg::Name nreg = nlrg.reg();
1218       // Only subtract masks in the same chunk
1219       if( nreg >= chunk && nreg < chunk + RegMask::CHUNK_SIZE ) {
1220 #ifndef PRODUCT
1221         uint size = lrg->mask().Size();
1222         RegMask rm = lrg->mask();
1223 #endif
1224         lrg->SUBTRACT(nlrg.mask());
1225 #ifndef PRODUCT
1226         if (trace_spilling() && lrg->mask().Size() != size) {
1227           ttyLocker ttyl;
1228           tty->print("L%d ", lidx);
1229           rm.dump();
1230           tty->print(" intersected L%d ", neighbor);
1231           nlrg.mask().dump();
1232           tty->print(" removed ");
1233           rm.SUBTRACT(lrg->mask());
1234           rm.dump();
1235           tty->print(" leaving ");
1236           lrg->mask().dump();
1237           tty->cr();
1238         }
1239 #endif
1240       }
1241     }
1242     //assert(is_allstack == lrg->mask().is_AllStack(), "nbrs must not change AllStackedness");
1243     // Aligned pairs need aligned masks
1244     if( lrg->num_regs() == 2 && !lrg->_fat_proj )
1245       lrg->ClearToPairs();
1246 
1247     // Check if a color is available and if so pick the color
1248     OptoReg::Name reg = choose_color( *lrg, chunk );
1249 #ifdef SPARC
1250     debug_only(lrg->compute_set_mask_size());
1251     assert(lrg->num_regs() != 2 || lrg->is_bound() || is_even(reg-1), "allocate all doubles aligned");
1252 #endif
1253 
1254     //---------------
1255     // If we fail to color and the AllStack flag is set, trigger
1256     // a chunk-rollover event
1257     if(!OptoReg::is_valid(OptoReg::add(reg,-chunk)) && is_allstack) {
1258       // Bump register mask up to next stack chunk
1259       chunk += RegMask::CHUNK_SIZE;
1260       lrg->Set_All();
1261 
1262       goto retry_next_chunk;
1263     }
1264 
1265     //---------------
1266     // Did we get a color?
1267     else if( OptoReg::is_valid(reg)) {
1268 #ifndef PRODUCT
1269       RegMask avail_rm = lrg->mask();
1270 #endif
1271 
1272       // Record selected register
1273       lrg->set_reg(reg);
1274 
1275       if( reg >= _max_reg )     // Compute max register limit
1276         _max_reg = OptoReg::add(reg,1);
1277       // Fold reg back into normal space
1278       reg = OptoReg::add(reg,-chunk);
1279 
1280       // If the live range is not bound, then we actually had some choices
1281       // to make.  In this case, the mask has more bits in it than the colors
1282       // choosen.  Restrict the mask to just what was picked.
1283       if( lrg->num_regs() == 1 ) { // Size 1 live range
1284         lrg->Clear();           // Clear the mask
1285         lrg->Insert(reg);       // Set regmask to match selected reg
1286         lrg->set_mask_size(1);
1287       } else if( !lrg->_fat_proj ) {
1288         // For pairs, also insert the low bit of the pair
1289         assert( lrg->num_regs() == 2, "unbound fatproj???" );
1290         lrg->Clear();           // Clear the mask
1291         lrg->Insert(reg);       // Set regmask to match selected reg
1292         lrg->Insert(OptoReg::add(reg,-1));
1293         lrg->set_mask_size(2);
1294       } else {                  // Else fatproj
1295         // mask must be equal to fatproj bits, by definition
1296       }
1297 #ifndef PRODUCT
1298       if (trace_spilling()) {
1299         ttyLocker ttyl;
1300         tty->print("L%d selected ", lidx);
1301         lrg->mask().dump();
1302         tty->print(" from ");
1303         avail_rm.dump();
1304         tty->cr();
1305       }
1306 #endif
1307       // Note that reg is the highest-numbered register in the newly-bound mask.
1308     } // end color available case
1309 
1310     //---------------
1311     // Live range is live and no colors available
1312     else {
1313       assert( lrg->alive(), "" );
1314       assert( !lrg->_fat_proj || lrg->is_multidef() ||
1315               lrg->_def->outcnt() > 0, "fat_proj cannot spill");
1316       assert( !orig_mask.is_AllStack(), "All Stack does not spill" );
1317 
1318       // Assign the special spillreg register
1319       lrg->set_reg(OptoReg::Name(spill_reg++));
1320       // Do not empty the regmask; leave mask_size lying around
1321       // for use during Spilling
1322 #ifndef PRODUCT
1323       if( trace_spilling() ) {
1324         ttyLocker ttyl;
1325         tty->print("L%d spilling with neighbors: ", lidx);
1326         s->dump();
1327         debug_only(tty->print(" original mask: "));
1328         debug_only(orig_mask.dump());
1329         dump_lrg(lidx);
1330       }
1331 #endif
1332     } // end spill case
1333 
1334   }
1335 
1336   return spill_reg-LRG::SPILL_REG;      // Return number of spills
1337 }
1338 
1339 
1340 //------------------------------copy_was_spilled-------------------------------
1341 // Copy 'was_spilled'-edness from the source Node to the dst Node.
1342 void PhaseChaitin::copy_was_spilled( Node *src, Node *dst ) {
1343   if( _spilled_once.test(src->_idx) ) {
1344     _spilled_once.set(dst->_idx);
1345     lrgs(Find(dst))._was_spilled1 = 1;
1346     if( _spilled_twice.test(src->_idx) ) {
1347       _spilled_twice.set(dst->_idx);
1348       lrgs(Find(dst))._was_spilled2 = 1;
1349     }
1350   }
1351 }
1352 
1353 //------------------------------set_was_spilled--------------------------------
1354 // Set the 'spilled_once' or 'spilled_twice' flag on a node.
1355 void PhaseChaitin::set_was_spilled( Node *n ) {
1356   if( _spilled_once.test_set(n->_idx) )
1357     _spilled_twice.set(n->_idx);
1358 }
1359 
1360 //------------------------------fixup_spills-----------------------------------
1361 // Convert Ideal spill instructions into proper FramePtr + offset Loads and
1362 // Stores.  Use-def chains are NOT preserved, but Node->LRG->reg maps are.
1363 void PhaseChaitin::fixup_spills() {
1364   // This function does only cisc spill work.
1365   if( !UseCISCSpill ) return;
1366 
1367   NOT_PRODUCT( Compile::TracePhase t3("fixupSpills", &_t_fixupSpills, TimeCompiler); )
1368 
1369   // Grab the Frame Pointer
1370   Node *fp = _cfg._broot->head()->in(1)->in(TypeFunc::FramePtr);
1371 
1372   // For all blocks
1373   for( uint i = 0; i < _cfg._num_blocks; i++ ) {
1374     Block *b = _cfg._blocks[i];
1375 
1376     // For all instructions in block
1377     uint last_inst = b->end_idx();
1378     for( uint j = 1; j <= last_inst; j++ ) {
1379       Node *n = b->_nodes[j];
1380 
1381       // Dead instruction???
1382       assert( n->outcnt() != 0 ||// Nothing dead after post alloc
1383               C->top() == n ||  // Or the random TOP node
1384               n->is_Proj(),     // Or a fat-proj kill node
1385               "No dead instructions after post-alloc" );
1386 
1387       int inp = n->cisc_operand();
1388       if( inp != AdlcVMDeps::Not_cisc_spillable ) {
1389         // Convert operand number to edge index number
1390         MachNode *mach = n->as_Mach();
1391         inp = mach->operand_index(inp);
1392         Node *src = n->in(inp);   // Value to load or store
1393         LRG &lrg_cisc = lrgs( Find_const(src) );
1394         OptoReg::Name src_reg = lrg_cisc.reg();
1395         // Doubles record the HIGH register of an adjacent pair.
1396         src_reg = OptoReg::add(src_reg,1-lrg_cisc.num_regs());
1397         if( OptoReg::is_stack(src_reg) ) { // If input is on stack
1398           // This is a CISC Spill, get stack offset and construct new node
1399 #ifndef PRODUCT
1400           if( TraceCISCSpill ) {
1401             tty->print("    reg-instr:  ");
1402             n->dump();
1403           }
1404 #endif
1405           int stk_offset = reg2offset(src_reg);
1406           // Bailout if we might exceed node limit when spilling this instruction
1407           C->check_node_count(0, "out of nodes fixing spills");
1408           if (C->failing())  return;
1409           // Transform node
1410           MachNode *cisc = mach->cisc_version(stk_offset, C)->as_Mach();
1411           cisc->set_req(inp,fp);          // Base register is frame pointer
1412           if( cisc->oper_input_base() > 1 && mach->oper_input_base() <= 1 ) {
1413             assert( cisc->oper_input_base() == 2, "Only adding one edge");
1414             cisc->ins_req(1,src);         // Requires a memory edge
1415           }
1416           b->_nodes.map(j,cisc);          // Insert into basic block
1417           n->subsume_by(cisc); // Correct graph
1418           //
1419           ++_used_cisc_instructions;
1420 #ifndef PRODUCT
1421           if( TraceCISCSpill ) {
1422             tty->print("    cisc-instr: ");
1423             cisc->dump();
1424           }
1425 #endif
1426         } else {
1427 #ifndef PRODUCT
1428           if( TraceCISCSpill ) {
1429             tty->print("    using reg-instr: ");
1430             n->dump();
1431           }
1432 #endif
1433           ++_unused_cisc_instructions;    // input can be on stack
1434         }
1435       }
1436 
1437     } // End of for all instructions
1438 
1439   } // End of for all blocks
1440 }
1441 
1442 
1443 //------------------------------collect_ex_blocks-----------------------------
1444 // Collect blocks with CreateEx.
1445 void PhaseChaitin::collect_ex_blocks(Block_List& ex_blocks) {
1446   // For all blocks
1447   for( uint i = 0; i < _cfg._num_blocks; i++ ) {
1448     Block* b = _cfg._blocks[i];
1449     uint last_inst = b->end_idx();
1450     for( uint insidx = 1; insidx < last_inst; insidx++ ) {
1451       Node* n = b->_nodes[insidx];
1452       if( n->is_Mach() && n->as_Mach()->ideal_Opcode() == Op_CreateEx ) {
1453         ex_blocks.push(b);
1454         break;
1455       }
1456     }
1457   }
1458 }
1459 
1460 //------------------------------fixup_ex_blocks-------------------------------
1461 // Spills could be inserted before CreateEx node which should be first
1462 // instruction in an exception block after Phis. Move CreateEx node up.
1463 void PhaseChaitin::fixup_ex_blocks(Block_List& ex_blocks) {
1464   // For all exception blocks.
1465   for( uint i = 0; i < ex_blocks.size(); i++ ) {
1466     Block* b = ex_blocks[i];
1467     uint last_inst = b->end_idx();
1468     uint last_phi = 1;
1469     for( ; last_phi < last_inst; last_phi++ )
1470       if( !b->_nodes[last_phi]->is_Phi() )
1471         break;
1472 
1473     for( uint insidx = (last_phi+1); insidx < last_inst; insidx++ ) {
1474       Node* n = b->_nodes[insidx];
1475       if( n->is_Mach() && n->as_Mach()->ideal_Opcode() == Op_CreateEx ) {
1476         b->_nodes.remove(insidx);
1477         b->_nodes.insert(last_phi, n);
1478         break;
1479       }
1480     }
1481   }
1482 }
1483 
1484 
1485 //------------------------------find_base_for_derived--------------------------
1486 // Helper to stretch above; recursively discover the base Node for a
1487 // given derived Node.  Easy for AddP-related machine nodes, but needs
1488 // to be recursive for derived Phis.
1489 Node *PhaseChaitin::find_base_for_derived( Node **derived_base_map, Node *derived, uint &maxlrg ) {
1490   // See if already computed; if so return it
1491   if( derived_base_map[derived->_idx] )
1492     return derived_base_map[derived->_idx];
1493 
1494   // See if this happens to be a base.
1495   // NOTE: we use TypePtr instead of TypeOopPtr because we can have
1496   // pointers derived from NULL!  These are always along paths that
1497   // can't happen at run-time but the optimizer cannot deduce it so
1498   // we have to handle it gracefully.
1499   const TypePtr *tj = derived->bottom_type()->isa_ptr();
1500   // If its an OOP with a non-zero offset, then it is derived.
1501   if( tj->_offset == 0 ) {
1502     derived_base_map[derived->_idx] = derived;
1503     return derived;
1504   }
1505   // Derived is NULL+offset?  Base is NULL!
1506   if( derived->is_Con() ) {
1507     Node *base = new (C, 1) ConPNode( TypePtr::NULL_PTR );
1508     uint no_lidx = 0;  // an unmatched constant in debug info has no LRG
1509     _names.extend(base->_idx, no_lidx);
1510     derived_base_map[derived->_idx] = base;
1511     return base;
1512   }
1513 
1514   // Check for AddP-related opcodes
1515   if( !derived->is_Phi() ) {
1516     assert( derived->as_Mach()->ideal_Opcode() == Op_AddP, "" );
1517     Node *base = derived->in(AddPNode::Base);
1518     derived_base_map[derived->_idx] = base;
1519     return base;
1520   }
1521 
1522   // Recursively find bases for Phis.
1523   // First check to see if we can avoid a base Phi here.
1524   Node *base = find_base_for_derived( derived_base_map, derived->in(1),maxlrg);
1525   uint i;
1526   for( i = 2; i < derived->req(); i++ )
1527     if( base != find_base_for_derived( derived_base_map,derived->in(i),maxlrg))
1528       break;
1529   // Went to the end without finding any different bases?
1530   if( i == derived->req() ) {   // No need for a base Phi here
1531     derived_base_map[derived->_idx] = base;
1532     return base;
1533   }
1534 
1535   // Now we see we need a base-Phi here to merge the bases
1536   base = new (C, derived->req()) PhiNode( derived->in(0), base->bottom_type() );
1537   for( i = 1; i < derived->req(); i++ )
1538     base->init_req(i, find_base_for_derived(derived_base_map, derived->in(i), maxlrg));
1539 
1540   // Search the current block for an existing base-Phi
1541   Block *b = _cfg._bbs[derived->_idx];
1542   for( i = 1; i <= b->end_idx(); i++ ) {// Search for matching Phi
1543     Node *phi = b->_nodes[i];
1544     if( !phi->is_Phi() ) {      // Found end of Phis with no match?
1545       b->_nodes.insert( i, base ); // Must insert created Phi here as base
1546       _cfg._bbs.map( base->_idx, b );
1547       new_lrg(base,maxlrg++);
1548       break;
1549     }
1550     // See if Phi matches.
1551     uint j;
1552     for( j = 1; j < base->req(); j++ )
1553       if( phi->in(j) != base->in(j) &&
1554           !(phi->in(j)->is_Con() && base->in(j)->is_Con()) ) // allow different NULLs
1555         break;
1556     if( j == base->req() ) {    // All inputs match?
1557       base = phi;               // Then use existing 'phi' and drop 'base'
1558       break;
1559     }
1560   }
1561 
1562 
1563   // Cache info for later passes
1564   derived_base_map[derived->_idx] = base;
1565   return base;
1566 }
1567 
1568 
1569 //------------------------------stretch_base_pointer_live_ranges---------------
1570 // At each Safepoint, insert extra debug edges for each pair of derived value/
1571 // base pointer that is live across the Safepoint for oopmap building.  The
1572 // edge pairs get added in after sfpt->jvmtail()->oopoff(), but are in the
1573 // required edge set.
1574 bool PhaseChaitin::stretch_base_pointer_live_ranges( ResourceArea *a ) {
1575   int must_recompute_live = false;
1576   uint maxlrg = _maxlrg;
1577   Node **derived_base_map = (Node**)a->Amalloc(sizeof(Node*)*C->unique());
1578   memset( derived_base_map, 0, sizeof(Node*)*C->unique() );
1579 
1580   // For all blocks in RPO do...
1581   for( uint i=0; i<_cfg._num_blocks; i++ ) {
1582     Block *b = _cfg._blocks[i];
1583     // Note use of deep-copy constructor.  I cannot hammer the original
1584     // liveout bits, because they are needed by the following coalesce pass.
1585     IndexSet liveout(_live->live(b));
1586 
1587     for( uint j = b->end_idx() + 1; j > 1; j-- ) {
1588       Node *n = b->_nodes[j-1];
1589 
1590       // Pre-split compares of loop-phis.  Loop-phis form a cycle we would
1591       // like to see in the same register.  Compare uses the loop-phi and so
1592       // extends its live range BUT cannot be part of the cycle.  If this
1593       // extended live range overlaps with the update of the loop-phi value
1594       // we need both alive at the same time -- which requires at least 1
1595       // copy.  But because Intel has only 2-address registers we end up with
1596       // at least 2 copies, one before the loop-phi update instruction and
1597       // one after.  Instead we split the input to the compare just after the
1598       // phi.
1599       if( n->is_Mach() && n->as_Mach()->ideal_Opcode() == Op_CmpI ) {
1600         Node *phi = n->in(1);
1601         if( phi->is_Phi() && phi->as_Phi()->region()->is_Loop() ) {
1602           Block *phi_block = _cfg._bbs[phi->_idx];
1603           if( _cfg._bbs[phi_block->pred(2)->_idx] == b ) {
1604             const RegMask *mask = C->matcher()->idealreg2spillmask[Op_RegI];
1605             Node *spill = new (C) MachSpillCopyNode( phi, *mask, *mask );
1606             insert_proj( phi_block, 1, spill, maxlrg++ );
1607             n->set_req(1,spill);
1608             must_recompute_live = true;
1609           }
1610         }
1611       }
1612 
1613       // Get value being defined
1614       uint lidx = n2lidx(n);
1615       if( lidx && lidx < _maxlrg /* Ignore the occasional brand-new live range */) {
1616         // Remove from live-out set
1617         liveout.remove(lidx);
1618 
1619         // Copies do not define a new value and so do not interfere.
1620         // Remove the copies source from the liveout set before interfering.
1621         uint idx = n->is_Copy();
1622         if( idx ) liveout.remove( n2lidx(n->in(idx)) );
1623       }
1624 
1625       // Found a safepoint?
1626       JVMState *jvms = n->jvms();
1627       if( jvms ) {
1628         // Now scan for a live derived pointer
1629         IndexSetIterator elements(&liveout);
1630         uint neighbor;
1631         while ((neighbor = elements.next()) != 0) {
1632           // Find reaching DEF for base and derived values
1633           // This works because we are still in SSA during this call.
1634           Node *derived = lrgs(neighbor)._def;
1635           const TypePtr *tj = derived->bottom_type()->isa_ptr();
1636           // If its an OOP with a non-zero offset, then it is derived.
1637           if( tj && tj->_offset != 0 && tj->isa_oop_ptr() ) {
1638             Node *base = find_base_for_derived( derived_base_map, derived, maxlrg );
1639             assert( base->_idx < _names.Size(), "" );
1640             // Add reaching DEFs of derived pointer and base pointer as a
1641             // pair of inputs
1642             n->add_req( derived );
1643             n->add_req( base );
1644 
1645             // See if the base pointer is already live to this point.
1646             // Since I'm working on the SSA form, live-ness amounts to
1647             // reaching def's.  So if I find the base's live range then
1648             // I know the base's def reaches here.
1649             if( (n2lidx(base) >= _maxlrg ||// (Brand new base (hence not live) or
1650                  !liveout.member( n2lidx(base) ) ) && // not live) AND
1651                  (n2lidx(base) > 0)                && // not a constant
1652                  _cfg._bbs[base->_idx] != b ) {     //  base not def'd in blk)
1653               // Base pointer is not currently live.  Since I stretched
1654               // the base pointer to here and it crosses basic-block
1655               // boundaries, the global live info is now incorrect.
1656               // Recompute live.
1657               must_recompute_live = true;
1658             } // End of if base pointer is not live to debug info
1659           }
1660         } // End of scan all live data for derived ptrs crossing GC point
1661       } // End of if found a GC point
1662 
1663       // Make all inputs live
1664       if( !n->is_Phi() ) {      // Phi function uses come from prior block
1665         for( uint k = 1; k < n->req(); k++ ) {
1666           uint lidx = n2lidx(n->in(k));
1667           if( lidx < _maxlrg )
1668             liveout.insert( lidx );
1669         }
1670       }
1671 
1672     } // End of forall instructions in block
1673     liveout.clear();  // Free the memory used by liveout.
1674 
1675   } // End of forall blocks
1676   _maxlrg = maxlrg;
1677 
1678   // If I created a new live range I need to recompute live
1679   if( maxlrg != _ifg->_maxlrg )
1680     must_recompute_live = true;
1681 
1682   return must_recompute_live != 0;
1683 }
1684 
1685 
1686 //------------------------------add_reference----------------------------------
1687 // Extend the node to LRG mapping
1688 void PhaseChaitin::add_reference( const Node *node, const Node *old_node ) {
1689   _names.extend( node->_idx, n2lidx(old_node) );
1690 }
1691 
1692 //------------------------------dump-------------------------------------------
1693 #ifndef PRODUCT
1694 void PhaseChaitin::dump( const Node *n ) const {
1695   uint r = (n->_idx < _names.Size() ) ? Find_const(n) : 0;
1696   tty->print("L%d",r);
1697   if( r && n->Opcode() != Op_Phi ) {
1698     if( _node_regs ) {          // Got a post-allocation copy of allocation?
1699       tty->print("[");
1700       OptoReg::Name second = get_reg_second(n);
1701       if( OptoReg::is_valid(second) ) {
1702         if( OptoReg::is_reg(second) )
1703           tty->print("%s:",Matcher::regName[second]);
1704         else
1705           tty->print("%s+%d:",OptoReg::regname(OptoReg::c_frame_pointer), reg2offset_unchecked(second));
1706       }
1707       OptoReg::Name first = get_reg_first(n);
1708       if( OptoReg::is_reg(first) )
1709         tty->print("%s]",Matcher::regName[first]);
1710       else
1711          tty->print("%s+%d]",OptoReg::regname(OptoReg::c_frame_pointer), reg2offset_unchecked(first));
1712     } else
1713     n->out_RegMask().dump();
1714   }
1715   tty->print("/N%d\t",n->_idx);
1716   tty->print("%s === ", n->Name());
1717   uint k;
1718   for( k = 0; k < n->req(); k++) {
1719     Node *m = n->in(k);
1720     if( !m ) tty->print("_ ");
1721     else {
1722       uint r = (m->_idx < _names.Size() ) ? Find_const(m) : 0;
1723       tty->print("L%d",r);
1724       // Data MultiNode's can have projections with no real registers.
1725       // Don't die while dumping them.
1726       int op = n->Opcode();
1727       if( r && op != Op_Phi && op != Op_Proj && op != Op_SCMemProj) {
1728         if( _node_regs ) {
1729           tty->print("[");
1730           OptoReg::Name second = get_reg_second(n->in(k));
1731           if( OptoReg::is_valid(second) ) {
1732             if( OptoReg::is_reg(second) )
1733               tty->print("%s:",Matcher::regName[second]);
1734             else
1735               tty->print("%s+%d:",OptoReg::regname(OptoReg::c_frame_pointer),
1736                          reg2offset_unchecked(second));
1737           }
1738           OptoReg::Name first = get_reg_first(n->in(k));
1739           if( OptoReg::is_reg(first) )
1740             tty->print("%s]",Matcher::regName[first]);
1741           else
1742             tty->print("%s+%d]",OptoReg::regname(OptoReg::c_frame_pointer),
1743                        reg2offset_unchecked(first));
1744         } else
1745           n->in_RegMask(k).dump();
1746       }
1747       tty->print("/N%d ",m->_idx);
1748     }
1749   }
1750   if( k < n->len() && n->in(k) ) tty->print("| ");
1751   for( ; k < n->len(); k++ ) {
1752     Node *m = n->in(k);
1753     if( !m ) break;
1754     uint r = (m->_idx < _names.Size() ) ? Find_const(m) : 0;
1755     tty->print("L%d",r);
1756     tty->print("/N%d ",m->_idx);
1757   }
1758   if( n->is_Mach() ) n->as_Mach()->dump_spec(tty);
1759   else n->dump_spec(tty);
1760   if( _spilled_once.test(n->_idx ) ) {
1761     tty->print(" Spill_1");
1762     if( _spilled_twice.test(n->_idx ) )
1763       tty->print(" Spill_2");
1764   }
1765   tty->print("\n");
1766 }
1767 
1768 void PhaseChaitin::dump( const Block * b ) const {
1769   b->dump_head( &_cfg._bbs );
1770 
1771   // For all instructions
1772   for( uint j = 0; j < b->_nodes.size(); j++ )
1773     dump(b->_nodes[j]);
1774   // Print live-out info at end of block
1775   if( _live ) {
1776     tty->print("Liveout: ");
1777     IndexSet *live = _live->live(b);
1778     IndexSetIterator elements(live);
1779     tty->print("{");
1780     uint i;
1781     while ((i = elements.next()) != 0) {
1782       tty->print("L%d ", Find_const(i));
1783     }
1784     tty->print_cr("}");
1785   }
1786   tty->print("\n");
1787 }
1788 
1789 void PhaseChaitin::dump() const {
1790   tty->print( "--- Chaitin -- argsize: %d  framesize: %d ---\n",
1791               _matcher._new_SP, _framesize );
1792 
1793   // For all blocks
1794   for( uint i = 0; i < _cfg._num_blocks; i++ )
1795     dump(_cfg._blocks[i]);
1796   // End of per-block dump
1797   tty->print("\n");
1798 
1799   if (!_ifg) {
1800     tty->print("(No IFG.)\n");
1801     return;
1802   }
1803 
1804   // Dump LRG array
1805   tty->print("--- Live RanGe Array ---\n");
1806   for(uint i2 = 1; i2 < _maxlrg; i2++ ) {
1807     tty->print("L%d: ",i2);
1808     if( i2 < _ifg->_maxlrg ) lrgs(i2).dump( );
1809     else tty->print("new LRG");
1810   }
1811   tty->print_cr("");
1812 
1813   // Dump lo-degree list
1814   tty->print("Lo degree: ");
1815   for(uint i3 = _lo_degree; i3; i3 = lrgs(i3)._next )
1816     tty->print("L%d ",i3);
1817   tty->print_cr("");
1818 
1819   // Dump lo-stk-degree list
1820   tty->print("Lo stk degree: ");
1821   for(uint i4 = _lo_stk_degree; i4; i4 = lrgs(i4)._next )
1822     tty->print("L%d ",i4);
1823   tty->print_cr("");
1824 
1825   // Dump lo-degree list
1826   tty->print("Hi degree: ");
1827   for(uint i5 = _hi_degree; i5; i5 = lrgs(i5)._next )
1828     tty->print("L%d ",i5);
1829   tty->print_cr("");
1830 }
1831 
1832 //------------------------------dump_degree_lists------------------------------
1833 void PhaseChaitin::dump_degree_lists() const {
1834   // Dump lo-degree list
1835   tty->print("Lo degree: ");
1836   for( uint i = _lo_degree; i; i = lrgs(i)._next )
1837     tty->print("L%d ",i);
1838   tty->print_cr("");
1839 
1840   // Dump lo-stk-degree list
1841   tty->print("Lo stk degree: ");
1842   for(uint i2 = _lo_stk_degree; i2; i2 = lrgs(i2)._next )
1843     tty->print("L%d ",i2);
1844   tty->print_cr("");
1845 
1846   // Dump lo-degree list
1847   tty->print("Hi degree: ");
1848   for(uint i3 = _hi_degree; i3; i3 = lrgs(i3)._next )
1849     tty->print("L%d ",i3);
1850   tty->print_cr("");
1851 }
1852 
1853 //------------------------------dump_simplified--------------------------------
1854 void PhaseChaitin::dump_simplified() const {
1855   tty->print("Simplified: ");
1856   for( uint i = _simplified; i; i = lrgs(i)._next )
1857     tty->print("L%d ",i);
1858   tty->print_cr("");
1859 }
1860 
1861 static char *print_reg( OptoReg::Name reg, const PhaseChaitin *pc, char *buf ) {
1862   if ((int)reg < 0)
1863     sprintf(buf, "<OptoReg::%d>", (int)reg);
1864   else if (OptoReg::is_reg(reg))
1865     strcpy(buf, Matcher::regName[reg]);
1866   else
1867     sprintf(buf,"%s + #%d",OptoReg::regname(OptoReg::c_frame_pointer),
1868             pc->reg2offset(reg));
1869   return buf+strlen(buf);
1870 }
1871 
1872 //------------------------------dump_register----------------------------------
1873 // Dump a register name into a buffer.  Be intelligent if we get called
1874 // before allocation is complete.
1875 char *PhaseChaitin::dump_register( const Node *n, char *buf  ) const {
1876   if( !this ) {                 // Not got anything?
1877     sprintf(buf,"N%d",n->_idx); // Then use Node index
1878   } else if( _node_regs ) {
1879     // Post allocation, use direct mappings, no LRG info available
1880     print_reg( get_reg_first(n), this, buf );
1881   } else {
1882     uint lidx = Find_const(n); // Grab LRG number
1883     if( !_ifg ) {
1884       sprintf(buf,"L%d",lidx);  // No register binding yet
1885     } else if( !lidx ) {        // Special, not allocated value
1886       strcpy(buf,"Special");
1887     } else if( (lrgs(lidx).num_regs() == 1)
1888                 ? !lrgs(lidx).mask().is_bound1()
1889                 : !lrgs(lidx).mask().is_bound2() ) {
1890       sprintf(buf,"L%d",lidx); // No register binding yet
1891     } else {                    // Hah!  We have a bound machine register
1892       print_reg( lrgs(lidx).reg(), this, buf );
1893     }
1894   }
1895   return buf+strlen(buf);
1896 }
1897 
1898 //----------------------dump_for_spill_split_recycle--------------------------
1899 void PhaseChaitin::dump_for_spill_split_recycle() const {
1900   if( WizardMode && (PrintCompilation || PrintOpto) ) {
1901     // Display which live ranges need to be split and the allocator's state
1902     tty->print_cr("Graph-Coloring Iteration %d will split the following live ranges", _trip_cnt);
1903     for( uint bidx = 1; bidx < _maxlrg; bidx++ ) {
1904       if( lrgs(bidx).alive() && lrgs(bidx).reg() >= LRG::SPILL_REG ) {
1905         tty->print("L%d: ", bidx);
1906         lrgs(bidx).dump();
1907       }
1908     }
1909     tty->cr();
1910     dump();
1911   }
1912 }
1913 
1914 //------------------------------dump_frame------------------------------------
1915 void PhaseChaitin::dump_frame() const {
1916   const char *fp = OptoReg::regname(OptoReg::c_frame_pointer);
1917   const TypeTuple *domain = C->tf()->domain();
1918   const int        argcnt = domain->cnt() - TypeFunc::Parms;
1919 
1920   // Incoming arguments in registers dump
1921   for( int k = 0; k < argcnt; k++ ) {
1922     OptoReg::Name parmreg = _matcher._parm_regs[k].first();
1923     if( OptoReg::is_reg(parmreg))  {
1924       const char *reg_name = OptoReg::regname(parmreg);
1925       tty->print("#r%3.3d %s", parmreg, reg_name);
1926       parmreg = _matcher._parm_regs[k].second();
1927       if( OptoReg::is_reg(parmreg))  {
1928         tty->print(":%s", OptoReg::regname(parmreg));
1929       }
1930       tty->print("   : parm %d: ", k);
1931       domain->field_at(k + TypeFunc::Parms)->dump();
1932       tty->print_cr("");
1933     }
1934   }
1935 
1936   // Check for un-owned padding above incoming args
1937   OptoReg::Name reg = _matcher._new_SP;
1938   if( reg > _matcher._in_arg_limit ) {
1939     reg = OptoReg::add(reg, -1);
1940     tty->print_cr("#r%3.3d %s+%2d: pad0, owned by CALLER", reg, fp, reg2offset_unchecked(reg));
1941   }
1942 
1943   // Incoming argument area dump
1944   OptoReg::Name begin_in_arg = OptoReg::add(_matcher._old_SP,C->out_preserve_stack_slots());
1945   while( reg > begin_in_arg ) {
1946     reg = OptoReg::add(reg, -1);
1947     tty->print("#r%3.3d %s+%2d: ",reg,fp,reg2offset_unchecked(reg));
1948     int j;
1949     for( j = 0; j < argcnt; j++) {
1950       if( _matcher._parm_regs[j].first() == reg ||
1951           _matcher._parm_regs[j].second() == reg ) {
1952         tty->print("parm %d: ",j);
1953         domain->field_at(j + TypeFunc::Parms)->dump();
1954         tty->print_cr("");
1955         break;
1956       }
1957     }
1958     if( j >= argcnt )
1959       tty->print_cr("HOLE, owned by SELF");
1960   }
1961 
1962   // Old outgoing preserve area
1963   while( reg > _matcher._old_SP ) {
1964     reg = OptoReg::add(reg, -1);
1965     tty->print_cr("#r%3.3d %s+%2d: old out preserve",reg,fp,reg2offset_unchecked(reg));
1966   }
1967 
1968   // Old SP
1969   tty->print_cr("# -- Old %s -- Framesize: %d --",fp,
1970     reg2offset_unchecked(OptoReg::add(_matcher._old_SP,-1)) - reg2offset_unchecked(_matcher._new_SP)+jintSize);
1971 
1972   // Preserve area dump
1973   reg = OptoReg::add(reg, -1);
1974   while( OptoReg::is_stack(reg)) {
1975     tty->print("#r%3.3d %s+%2d: ",reg,fp,reg2offset_unchecked(reg));
1976     if( _matcher.return_addr() == reg )
1977       tty->print_cr("return address");
1978     else if( _matcher.return_addr() == OptoReg::add(reg,1) &&
1979              VerifyStackAtCalls )
1980       tty->print_cr("0xBADB100D   +VerifyStackAtCalls");
1981     else if ((int)OptoReg::reg2stack(reg) < C->fixed_slots())
1982       tty->print_cr("Fixed slot %d", OptoReg::reg2stack(reg));
1983     else
1984       tty->print_cr("pad2, in_preserve");
1985     reg = OptoReg::add(reg, -1);
1986   }
1987 
1988   // Spill area dump
1989   reg = OptoReg::add(_matcher._new_SP, _framesize );
1990   while( reg > _matcher._out_arg_limit ) {
1991     reg = OptoReg::add(reg, -1);
1992     tty->print_cr("#r%3.3d %s+%2d: spill",reg,fp,reg2offset_unchecked(reg));
1993   }
1994 
1995   // Outgoing argument area dump
1996   while( reg > OptoReg::add(_matcher._new_SP, C->out_preserve_stack_slots()) ) {
1997     reg = OptoReg::add(reg, -1);
1998     tty->print_cr("#r%3.3d %s+%2d: outgoing argument",reg,fp,reg2offset_unchecked(reg));
1999   }
2000 
2001   // Outgoing new preserve area
2002   while( reg > _matcher._new_SP ) {
2003     reg = OptoReg::add(reg, -1);
2004     tty->print_cr("#r%3.3d %s+%2d: new out preserve",reg,fp,reg2offset_unchecked(reg));
2005   }
2006   tty->print_cr("#");
2007 }
2008 
2009 //------------------------------dump_bb----------------------------------------
2010 void PhaseChaitin::dump_bb( uint pre_order ) const {
2011   tty->print_cr("---dump of B%d---",pre_order);
2012   for( uint i = 0; i < _cfg._num_blocks; i++ ) {
2013     Block *b = _cfg._blocks[i];
2014     if( b->_pre_order == pre_order )
2015       dump(b);
2016   }
2017 }
2018 
2019 //------------------------------dump_lrg---------------------------------------
2020 void PhaseChaitin::dump_lrg( uint lidx ) const {
2021   tty->print_cr("---dump of L%d---",lidx);
2022 
2023   if( _ifg ) {
2024     if( lidx >= _maxlrg ) {
2025       tty->print("Attempt to print live range index beyond max live range.\n");
2026       return;
2027     }
2028     tty->print("L%d: ",lidx);
2029     lrgs(lidx).dump( );
2030   }
2031   if( _ifg ) {    tty->print("Neighbors: %d - ", _ifg->neighbor_cnt(lidx));
2032     _ifg->neighbors(lidx)->dump();
2033     tty->cr();
2034   }
2035   // For all blocks
2036   for( uint i = 0; i < _cfg._num_blocks; i++ ) {
2037     Block *b = _cfg._blocks[i];
2038     int dump_once = 0;
2039 
2040     // For all instructions
2041     for( uint j = 0; j < b->_nodes.size(); j++ ) {
2042       Node *n = b->_nodes[j];
2043       if( Find_const(n) == lidx ) {
2044         if( !dump_once++ ) {
2045           tty->cr();
2046           b->dump_head( &_cfg._bbs );
2047         }
2048         dump(n);
2049         continue;
2050       }
2051       uint cnt = n->req();
2052       for( uint k = 1; k < cnt; k++ ) {
2053         Node *m = n->in(k);
2054         if (!m)  continue;  // be robust in the dumper
2055         if( Find_const(m) == lidx ) {
2056           if( !dump_once++ ) {
2057             tty->cr();
2058             b->dump_head( &_cfg._bbs );
2059           }
2060           dump(n);
2061         }
2062       }
2063     }
2064   } // End of per-block dump
2065   tty->cr();
2066 }
2067 #endif // not PRODUCT
2068 
2069 //------------------------------print_chaitin_statistics-------------------------------
2070 int PhaseChaitin::_final_loads  = 0;
2071 int PhaseChaitin::_final_stores = 0;
2072 int PhaseChaitin::_final_memoves= 0;
2073 int PhaseChaitin::_final_copies = 0;
2074 double PhaseChaitin::_final_load_cost  = 0;
2075 double PhaseChaitin::_final_store_cost = 0;
2076 double PhaseChaitin::_final_memove_cost= 0;
2077 double PhaseChaitin::_final_copy_cost  = 0;
2078 int PhaseChaitin::_conserv_coalesce = 0;
2079 int PhaseChaitin::_conserv_coalesce_pair = 0;
2080 int PhaseChaitin::_conserv_coalesce_trie = 0;
2081 int PhaseChaitin::_conserv_coalesce_quad = 0;
2082 int PhaseChaitin::_post_alloc = 0;
2083 int PhaseChaitin::_lost_opp_pp_coalesce = 0;
2084 int PhaseChaitin::_lost_opp_cflow_coalesce = 0;
2085 int PhaseChaitin::_used_cisc_instructions   = 0;
2086 int PhaseChaitin::_unused_cisc_instructions = 0;
2087 int PhaseChaitin::_allocator_attempts       = 0;
2088 int PhaseChaitin::_allocator_successes      = 0;
2089 
2090 #ifndef PRODUCT
2091 uint PhaseChaitin::_high_pressure           = 0;
2092 uint PhaseChaitin::_low_pressure            = 0;
2093 
2094 void PhaseChaitin::print_chaitin_statistics() {
2095   tty->print_cr("Inserted %d spill loads, %d spill stores, %d mem-mem moves and %d copies.", _final_loads, _final_stores, _final_memoves, _final_copies);
2096   tty->print_cr("Total load cost= %6.0f, store cost = %6.0f, mem-mem cost = %5.2f, copy cost = %5.0f.", _final_load_cost, _final_store_cost, _final_memove_cost, _final_copy_cost);
2097   tty->print_cr("Adjusted spill cost = %7.0f.",
2098                 _final_load_cost*4.0 + _final_store_cost  * 2.0 +
2099                 _final_copy_cost*1.0 + _final_memove_cost*12.0);
2100   tty->print("Conservatively coalesced %d copies, %d pairs",
2101                 _conserv_coalesce, _conserv_coalesce_pair);
2102   if( _conserv_coalesce_trie || _conserv_coalesce_quad )
2103     tty->print(", %d tries, %d quads", _conserv_coalesce_trie, _conserv_coalesce_quad);
2104   tty->print_cr(", %d post alloc.", _post_alloc);
2105   if( _lost_opp_pp_coalesce || _lost_opp_cflow_coalesce )
2106     tty->print_cr("Lost coalesce opportunity, %d private-private, and %d cflow interfered.",
2107                   _lost_opp_pp_coalesce, _lost_opp_cflow_coalesce );
2108   if( _used_cisc_instructions || _unused_cisc_instructions )
2109     tty->print_cr("Used cisc instruction  %d,  remained in register %d",
2110                    _used_cisc_instructions, _unused_cisc_instructions);
2111   if( _allocator_successes != 0 )
2112     tty->print_cr("Average allocation trips %f", (float)_allocator_attempts/(float)_allocator_successes);
2113   tty->print_cr("High Pressure Blocks = %d, Low Pressure Blocks = %d", _high_pressure, _low_pressure);
2114 }
2115 #endif // not PRODUCT