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