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