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