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