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