1 /* 2 * Copyright (c) 1998, 2025, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. 8 * 9 * This code is distributed in the hope that it will be useful, but WITHOUT 10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 12 * version 2 for more details (a copy is included in the LICENSE file that 13 * accompanied this code). 14 * 15 * You should have received a copy of the GNU General Public License version 16 * 2 along with this work; if not, write to the Free Software Foundation, 17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 18 * 19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 20 * or visit www.oracle.com if you need additional information or have any 21 * questions. 22 * 23 */ 24 25 #include "asm/macroAssembler.inline.hpp" 26 #include "gc/shared/gc_globals.hpp" 27 #include "memory/allocation.inline.hpp" 28 #include "oops/compressedOops.hpp" 29 #include "opto/ad.hpp" 30 #include "opto/block.hpp" 31 #include "opto/c2compiler.hpp" 32 #include "opto/callnode.hpp" 33 #include "opto/cfgnode.hpp" 34 #include "opto/chaitin.hpp" 35 #include "opto/machnode.hpp" 36 #include "opto/runtime.hpp" 37 #include "runtime/os.inline.hpp" 38 #include "runtime/sharedRuntime.hpp" 39 40 // Optimization - Graph Style 41 42 // Check whether val is not-null-decoded compressed oop, 43 // i.e. will grab into the base of the heap if it represents null. 44 static bool accesses_heap_base_zone(Node *val) { 45 if (CompressedOops::base() != nullptr) { // Implies UseCompressedOops. 46 if (val && val->is_Mach()) { 47 if (val->as_Mach()->ideal_Opcode() == Op_DecodeN) { 48 // This assumes all Decodes with TypePtr::NotNull are matched to nodes that 49 // decode null to point to the heap base (Decode_NN). 50 if (val->bottom_type()->is_oopptr()->ptr() == TypePtr::NotNull) { 51 return true; 52 } 53 } 54 // Must recognize load operation with Decode matched in memory operand. 55 // We should not reach here except for PPC/AIX, as os::zero_page_read_protected() 56 // returns true everywhere else. On PPC, no such memory operands 57 // exist, therefore we did not yet implement a check for such operands. 58 NOT_AIX(Unimplemented()); 59 } 60 } 61 return false; 62 } 63 64 static bool needs_explicit_null_check_for_read(Node *val) { 65 // On some OSes (AIX) the page at address 0 is only write protected. 66 // If so, only Store operations will trap. 67 if (os::zero_page_read_protected()) { 68 return false; // Implicit null check will work. 69 } 70 // Also a read accessing the base of a heap-based compressed heap will trap. 71 if (accesses_heap_base_zone(val) && // Hits the base zone page. 72 CompressedOops::use_implicit_null_checks()) { // Base zone page is protected. 73 return false; 74 } 75 76 return true; 77 } 78 79 void PhaseCFG::move_node_and_its_projections_to_block(Node* n, Block* b) { 80 assert(!is_CFG(n), "cannot move CFG node"); 81 Block* old = get_block_for_node(n); 82 old->find_remove(n); 83 b->add_inst(n); 84 map_node_to_block(n, b); 85 // Check for Mach projections that also need to be moved. 86 for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) { 87 Node* out = n->fast_out(i); 88 if (!out->is_MachProj()) { 89 continue; 90 } 91 assert(!n->is_MachProj(), "nested projections are not allowed"); 92 move_node_and_its_projections_to_block(out, b); 93 } 94 } 95 96 void PhaseCFG::ensure_node_is_at_block_or_above(Node* n, Block* b) { 97 assert(!is_CFG(n), "cannot move CFG node"); 98 Block* current = get_block_for_node(n); 99 if (current->dominates(b)) { 100 return; // n is already placed above b, do nothing. 101 } 102 // We only expect nodes without further inputs, like MachTemp or load Base. 103 assert(n->req() == 0 || (n->req() == 1 && n->in(0) == (Node*)C->root()), 104 "need for recursive hoisting not expected"); 105 assert(b->dominates(current), "precondition: can only move n to b if b dominates n"); 106 move_node_and_its_projections_to_block(n, b); 107 } 108 109 //------------------------------implicit_null_check---------------------------- 110 // Detect implicit-null-check opportunities. Basically, find null checks 111 // with suitable memory ops nearby. Use the memory op to do the null check. 112 // I can generate a memory op if there is not one nearby. 113 // The proj is the control projection for the not-null case. 114 // The val is the pointer being checked for nullness or 115 // decodeHeapOop_not_null node if it did not fold into address. 116 void PhaseCFG::implicit_null_check(Block* block, Node *proj, Node *val, int allowed_reasons) { 117 // Assume if null check need for 0 offset then always needed 118 // Intel solaris doesn't support any null checks yet and no 119 // mechanism exists (yet) to set the switches at an os_cpu level 120 if( !ImplicitNullChecks || MacroAssembler::needs_explicit_null_check(0)) return; 121 122 // Make sure the ptr-is-null path appears to be uncommon! 123 float f = block->end()->as_MachIf()->_prob; 124 if( proj->Opcode() == Op_IfTrue ) f = 1.0f - f; 125 if( f > PROB_UNLIKELY_MAG(4) ) return; 126 127 uint bidx = 0; // Capture index of value into memop 128 bool was_store; // Memory op is a store op 129 130 // Get the successor block for if the test ptr is non-null 131 Block* not_null_block; // this one goes with the proj 132 Block* null_block; 133 if (block->get_node(block->number_of_nodes()-1) == proj) { 134 null_block = block->_succs[0]; 135 not_null_block = block->_succs[1]; 136 } else { 137 assert(block->get_node(block->number_of_nodes()-2) == proj, "proj is one or the other"); 138 not_null_block = block->_succs[0]; 139 null_block = block->_succs[1]; 140 } 141 while (null_block->is_Empty() == Block::empty_with_goto) { 142 null_block = null_block->_succs[0]; 143 } 144 145 // Search the exception block for an uncommon trap. 146 // (See Parse::do_if and Parse::do_ifnull for the reason 147 // we need an uncommon trap. Briefly, we need a way to 148 // detect failure of this optimization, as in 6366351.) 149 { 150 bool found_trap = false; 151 for (uint i1 = 0; i1 < null_block->number_of_nodes(); i1++) { 152 Node* nn = null_block->get_node(i1); 153 if (nn->is_MachCall() && 154 nn->as_MachCall()->entry_point() == OptoRuntime::uncommon_trap_blob()->entry_point()) { 155 const Type* trtype = nn->in(TypeFunc::Parms)->bottom_type(); 156 if (trtype->isa_int() && trtype->is_int()->is_con()) { 157 jint tr_con = trtype->is_int()->get_con(); 158 Deoptimization::DeoptReason reason = Deoptimization::trap_request_reason(tr_con); 159 Deoptimization::DeoptAction action = Deoptimization::trap_request_action(tr_con); 160 assert((int)reason < (int)BitsPerInt, "recode bit map"); 161 if (is_set_nth_bit(allowed_reasons, (int) reason) 162 && action != Deoptimization::Action_none) { 163 // This uncommon trap is sure to recompile, eventually. 164 // When that happens, C->too_many_traps will prevent 165 // this transformation from happening again. 166 found_trap = true; 167 } 168 } 169 break; 170 } 171 } 172 if (!found_trap) { 173 // We did not find an uncommon trap. 174 return; 175 } 176 } 177 178 // Check for decodeHeapOop_not_null node which did not fold into address 179 bool is_decoden = ((intptr_t)val) & 1; 180 val = (Node*)(((intptr_t)val) & ~1); 181 182 assert(!is_decoden || 183 ((val->in(0) == nullptr) && val->is_Mach() && 184 (val->as_Mach()->ideal_Opcode() == Op_DecodeN)), "sanity"); 185 186 // Search the successor block for a load or store who's base value is also 187 // the tested value. There may be several. 188 MachNode *best = nullptr; // Best found so far 189 for (DUIterator i = val->outs(); val->has_out(i); i++) { 190 Node *m = val->out(i); 191 if( !m->is_Mach() ) continue; 192 MachNode *mach = m->as_Mach(); 193 if (mach->barrier_data() != 0 && 194 !mach->is_late_expanded_null_check_candidate()) { 195 // Using memory accesses with barriers to perform implicit null checks is 196 // only supported if these are explicit marked as emitting a candidate 197 // memory access instruction at their initial address. If not marked as 198 // such, barrier-tagged operations might expand into one or several memory 199 // access instructions located at arbitrary offsets from the initial 200 // address, which would invalidate the implicit null exception table. 201 continue; 202 } 203 was_store = false; 204 int iop = mach->ideal_Opcode(); 205 switch( iop ) { 206 case Op_LoadB: 207 case Op_LoadUB: 208 case Op_LoadUS: 209 case Op_LoadD: 210 case Op_LoadF: 211 case Op_LoadI: 212 case Op_LoadL: 213 case Op_LoadP: 214 case Op_LoadN: 215 case Op_LoadS: 216 case Op_LoadKlass: 217 case Op_LoadNKlass: 218 case Op_LoadRange: 219 case Op_LoadD_unaligned: 220 case Op_LoadL_unaligned: 221 assert(mach->in(2) == val, "should be address"); 222 break; 223 case Op_StoreB: 224 case Op_StoreC: 225 case Op_StoreD: 226 case Op_StoreF: 227 case Op_StoreI: 228 case Op_StoreL: 229 case Op_StoreP: 230 case Op_StoreN: 231 case Op_StoreNKlass: 232 was_store = true; // Memory op is a store op 233 // Stores will have their address in slot 2 (memory in slot 1). 234 // If the value being nul-checked is in another slot, it means we 235 // are storing the checked value, which does NOT check the value! 236 if( mach->in(2) != val ) continue; 237 break; // Found a memory op? 238 case Op_StrComp: 239 case Op_StrEquals: 240 case Op_StrIndexOf: 241 case Op_StrIndexOfChar: 242 case Op_AryEq: 243 case Op_VectorizedHashCode: 244 case Op_StrInflatedCopy: 245 case Op_StrCompressedCopy: 246 case Op_EncodeISOArray: 247 case Op_CountPositives: 248 // Not a legit memory op for implicit null check regardless of 249 // embedded loads 250 continue; 251 default: // Also check for embedded loads 252 if( !mach->needs_anti_dependence_check() ) 253 continue; // Not an memory op; skip it 254 if( must_clone[iop] ) { 255 // Do not move nodes which produce flags because 256 // RA will try to clone it to place near branch and 257 // it will cause recompilation, see clone_node(). 258 continue; 259 } 260 { 261 // Check that value is used in memory address in 262 // instructions with embedded load (CmpP val1,(val2+off)). 263 Node* base; 264 Node* index; 265 const MachOper* oper = mach->memory_inputs(base, index); 266 if (oper == nullptr || oper == (MachOper*)-1) { 267 continue; // Not an memory op; skip it 268 } 269 if (val == base || 270 (val == index && val->bottom_type()->isa_narrowoop())) { 271 break; // Found it 272 } else { 273 continue; // Skip it 274 } 275 } 276 break; 277 } 278 279 // On some OSes (AIX) the page at address 0 is only write protected. 280 // If so, only Store operations will trap. 281 // But a read accessing the base of a heap-based compressed heap will trap. 282 if (!was_store && needs_explicit_null_check_for_read(val)) { 283 continue; 284 } 285 286 // Check that node's control edge is not-null block's head or dominates it, 287 // otherwise we can't hoist it because there are other control dependencies. 288 Node* ctrl = mach->in(0); 289 if (ctrl != nullptr && !(ctrl == not_null_block->head() || 290 get_block_for_node(ctrl)->dominates(not_null_block))) { 291 continue; 292 } 293 294 // check if the offset is not too high for implicit exception 295 { 296 intptr_t offset = 0; 297 const TypePtr *adr_type = nullptr; // Do not need this return value here 298 const Node* base = mach->get_base_and_disp(offset, adr_type); 299 if (base == nullptr || base == NodeSentinel) { 300 // Narrow oop address doesn't have base, only index. 301 // Give up if offset is beyond page size or if heap base is not protected. 302 if (val->bottom_type()->isa_narrowoop() && 303 (MacroAssembler::needs_explicit_null_check(offset) || 304 !CompressedOops::use_implicit_null_checks())) 305 continue; 306 // cannot reason about it; is probably not implicit null exception 307 } else { 308 const TypePtr* tptr; 309 if ((UseCompressedOops && CompressedOops::shift() == 0) || 310 (UseCompressedClassPointers && CompressedKlassPointers::shift() == 0)) { 311 // 32-bits narrow oop can be the base of address expressions 312 tptr = base->get_ptr_type(); 313 } else { 314 // only regular oops are expected here 315 tptr = base->bottom_type()->is_ptr(); 316 } 317 // Give up if offset is not a compile-time constant. 318 if (offset == Type::OffsetBot || tptr->_offset == Type::OffsetBot) 319 continue; 320 offset += tptr->_offset; // correct if base is offsetted 321 // Give up if reference is beyond page size. 322 if (MacroAssembler::needs_explicit_null_check(offset)) 323 continue; 324 // Give up if base is a decode node and the heap base is not protected. 325 if (base->is_Mach() && base->as_Mach()->ideal_Opcode() == Op_DecodeN && 326 !CompressedOops::use_implicit_null_checks()) 327 continue; 328 } 329 } 330 331 // Check ctrl input to see if the null-check dominates the memory op 332 Block *cb = get_block_for_node(mach); 333 cb = cb->_idom; // Always hoist at least 1 block 334 if( !was_store ) { // Stores can be hoisted only one block 335 while( cb->_dom_depth > (block->_dom_depth + 1)) 336 cb = cb->_idom; // Hoist loads as far as we want 337 // The non-null-block should dominate the memory op, too. Live 338 // range spilling will insert a spill in the non-null-block if it is 339 // needs to spill the memory op for an implicit null check. 340 if (cb->_dom_depth == (block->_dom_depth + 1)) { 341 if (cb != not_null_block) continue; 342 cb = cb->_idom; 343 } 344 } 345 if( cb != block ) continue; 346 347 // Found a memory user; see if it can be hoisted to check-block 348 uint vidx = 0; // Capture index of value into memop 349 uint j; 350 for( j = mach->req()-1; j > 0; j-- ) { 351 if( mach->in(j) == val ) { 352 vidx = j; 353 // Ignore DecodeN val which could be hoisted to where needed. 354 if( is_decoden ) continue; 355 } 356 if (mach->in(j)->is_MachTemp()) { 357 assert(mach->in(j)->outcnt() == 1, "MachTemp nodes should not be shared"); 358 // Ignore MachTemp inputs, they can be safely hoisted with the candidate. 359 // MachTemp nodes have no inputs themselves and are only used to reserve 360 // a scratch register for the implementation of the node (e.g. in 361 // late-expanded GC barriers). 362 continue; 363 } 364 // Block of memory-op input 365 Block *inb = get_block_for_node(mach->in(j)); 366 Block *b = block; // Start from nul check 367 while( b != inb && b->_dom_depth > inb->_dom_depth ) 368 b = b->_idom; // search upwards for input 369 // See if input dominates null check 370 if( b != inb ) 371 break; 372 } 373 if( j > 0 ) 374 continue; 375 Block *mb = get_block_for_node(mach); 376 // Hoisting stores requires more checks for the anti-dependence case. 377 // Give up hoisting if we have to move the store past any load. 378 if (was_store) { 379 // Make sure control does not do a merge (would have to check allpaths) 380 if (mb->num_preds() != 2) { 381 continue; 382 } 383 // mach is a store, hence block is the immediate dominator of mb. 384 // Due to the null-check shape of block (where its successors cannot re-join), 385 // block must be the direct predecessor of mb. 386 assert(get_block_for_node(mb->pred(1)) == block, "Unexpected predecessor block"); 387 uint k; 388 uint num_nodes = mb->number_of_nodes(); 389 for (k = 1; k < num_nodes; k++) { 390 Node *n = mb->get_node(k); 391 if (n->needs_anti_dependence_check() && 392 n->in(LoadNode::Memory) == mach->in(StoreNode::Memory)) { 393 break; // Found anti-dependent load 394 } 395 } 396 if (k < num_nodes) { 397 continue; // Found anti-dependent load 398 } 399 } 400 401 // Make sure this memory op is not already being used for a NullCheck 402 Node *e = mb->end(); 403 if( e->is_MachNullCheck() && e->in(1) == mach ) 404 continue; // Already being used as a null check 405 406 // Found a candidate! Pick one with least dom depth - the highest 407 // in the dom tree should be closest to the null check. 408 if (best == nullptr || get_block_for_node(mach)->_dom_depth < get_block_for_node(best)->_dom_depth) { 409 best = mach; 410 bidx = vidx; 411 } 412 } 413 // No candidate! 414 if (best == nullptr) { 415 return; 416 } 417 418 // ---- Found an implicit null check 419 #ifndef PRODUCT 420 extern uint implicit_null_checks; 421 implicit_null_checks++; 422 #endif 423 424 if( is_decoden ) { 425 // Check if we need to hoist decodeHeapOop_not_null first. 426 Block *valb = get_block_for_node(val); 427 if( block != valb && block->_dom_depth < valb->_dom_depth ) { 428 // Hoist it up to the end of the test block together with its inputs if they exist. 429 for (uint i = 2; i < val->req(); i++) { 430 // DecodeN has 2 regular inputs + optional MachTemp or load Base inputs. 431 // Inputs of val may already be early enough, but if not move them together with val. 432 ensure_node_is_at_block_or_above(val->in(i), block); 433 } 434 move_node_and_its_projections_to_block(val, block); 435 } 436 } 437 438 // Move any MachTemp inputs to the end of the test block. 439 for (uint i = 0; i < best->req(); i++) { 440 Node* n = best->in(i); 441 if (n == nullptr || !n->is_MachTemp()) { 442 continue; 443 } 444 ensure_node_is_at_block_or_above(n, block); 445 } 446 447 // Hoist the memory candidate up to the end of the test block. 448 move_node_and_its_projections_to_block(best, block); 449 450 // Move the control dependence if it is pinned to not-null block. 451 // Don't change it in other cases: null or dominating control. 452 Node* ctrl = best->in(0); 453 if (ctrl != nullptr && get_block_for_node(ctrl) == not_null_block) { 454 // Set it to control edge of null check. 455 best->set_req(0, proj->in(0)->in(0)); 456 } 457 458 // proj==Op_True --> ne test; proj==Op_False --> eq test. 459 // One of two graph shapes got matched: 460 // (IfTrue (If (Bool NE (CmpP ptr null)))) 461 // (IfFalse (If (Bool EQ (CmpP ptr null)))) 462 // null checks are always branch-if-eq. If we see a IfTrue projection 463 // then we are replacing a 'ne' test with a 'eq' null check test. 464 // We need to flip the projections to keep the same semantics. 465 if( proj->Opcode() == Op_IfTrue ) { 466 // Swap order of projections in basic block to swap branch targets 467 Node *tmp1 = block->get_node(block->end_idx()+1); 468 Node *tmp2 = block->get_node(block->end_idx()+2); 469 block->map_node(tmp2, block->end_idx()+1); 470 block->map_node(tmp1, block->end_idx()+2); 471 Node *tmp = new Node(C->top()); // Use not null input 472 tmp1->replace_by(tmp); 473 tmp2->replace_by(tmp1); 474 tmp->replace_by(tmp2); 475 tmp->destruct(nullptr); 476 } 477 478 // Remove the existing null check; use a new implicit null check instead. 479 // Since schedule-local needs precise def-use info, we need to correct 480 // it as well. 481 Node *old_tst = proj->in(0); 482 MachNode *nul_chk = new MachNullCheckNode(old_tst->in(0),best,bidx); 483 block->map_node(nul_chk, block->end_idx()); 484 map_node_to_block(nul_chk, block); 485 // Redirect users of old_test to nul_chk 486 for (DUIterator_Last i2min, i2 = old_tst->last_outs(i2min); i2 >= i2min; --i2) 487 old_tst->last_out(i2)->set_req(0, nul_chk); 488 // Clean-up any dead code 489 for (uint i3 = 0; i3 < old_tst->req(); i3++) { 490 Node* in = old_tst->in(i3); 491 old_tst->set_req(i3, nullptr); 492 if (in->outcnt() == 0) { 493 // Remove dead input node 494 in->disconnect_inputs(C); 495 block->find_remove(in); 496 } 497 } 498 499 latency_from_uses(nul_chk); 500 latency_from_uses(best); 501 502 // insert anti-dependences to defs in this block 503 if (! best->needs_anti_dependence_check()) { 504 for (uint k = 1; k < block->number_of_nodes(); k++) { 505 Node *n = block->get_node(k); 506 if (n->needs_anti_dependence_check() && 507 n->in(LoadNode::Memory) == best->in(StoreNode::Memory)) { 508 // Found anti-dependent load 509 raise_above_anti_dependences(block, n); 510 if (C->failing()) { 511 return; 512 } 513 } 514 } 515 } 516 } 517 518 519 //------------------------------select----------------------------------------- 520 // Select a nice fellow from the worklist to schedule next. If there is only one 521 // choice, then use it. CreateEx nodes that are initially ready must start their 522 // blocks and are given the highest priority, by being placed at the beginning 523 // of the worklist. Next after initially-ready CreateEx nodes are projections, 524 // which must follow their parents, and CreateEx nodes with local input 525 // dependencies. Next are constants and CheckCastPP nodes. There are a number of 526 // other special cases, for instructions that consume condition codes, et al. 527 // These are chosen immediately. Some instructions are required to immediately 528 // precede the last instruction in the block, and these are taken last. Of the 529 // remaining cases (most), choose the instruction with the greatest latency 530 // (that is, the most number of pseudo-cycles required to the end of the 531 // routine). If there is a tie, choose the instruction with the most inputs. 532 Node* PhaseCFG::select( 533 Block* block, 534 Node_List &worklist, 535 GrowableArray<int> &ready_cnt, 536 VectorSet &next_call, 537 uint sched_slot, 538 intptr_t* recalc_pressure_nodes) { 539 540 // If only a single entry on the stack, use it 541 uint cnt = worklist.size(); 542 if (cnt == 1) { 543 Node *n = worklist[0]; 544 worklist.map(0,worklist.pop()); 545 return n; 546 } 547 548 uint choice = 0; // Bigger is most important 549 uint latency = 0; // Bigger is scheduled first 550 uint score = 0; // Bigger is better 551 int idx = -1; // Index in worklist 552 int cand_cnt = 0; // Candidate count 553 bool block_size_threshold_ok = (recalc_pressure_nodes != nullptr) && (block->number_of_nodes() > 10); 554 555 for( uint i=0; i<cnt; i++ ) { // Inspect entire worklist 556 // Order in worklist is used to break ties. 557 // See caller for how this is used to delay scheduling 558 // of induction variable increments to after the other 559 // uses of the phi are scheduled. 560 Node *n = worklist[i]; // Get Node on worklist 561 562 int iop = n->is_Mach() ? n->as_Mach()->ideal_Opcode() : 0; 563 if (iop == Op_CreateEx || n->is_Proj()) { 564 // CreateEx nodes that are initially ready must start the block (after Phi 565 // and Parm nodes which are pre-scheduled) and get top priority. This is 566 // currently enforced by placing them at the beginning of the initial 567 // worklist and selecting them eagerly here. After these, projections and 568 // other CreateEx nodes are selected with equal priority. 569 worklist.map(i,worklist.pop()); 570 return n; 571 } 572 573 if (n->Opcode() == Op_Con || iop == Op_CheckCastPP) { 574 // Constants and CheckCastPP nodes have higher priority than the rest of 575 // the nodes tested below. Record as current winner, but keep looking for 576 // higher-priority nodes in the worklist. 577 choice = 4; 578 // Latency and score are only used to break ties among low-priority nodes. 579 latency = 0; 580 score = 0; 581 idx = i; 582 continue; 583 } 584 585 // Final call in a block must be adjacent to 'catch' 586 Node *e = block->end(); 587 if( e->is_Catch() && e->in(0)->in(0) == n ) 588 continue; 589 590 // Memory op for an implicit null check has to be at the end of the block 591 if( e->is_MachNullCheck() && e->in(1) == n ) 592 continue; 593 594 // Schedule IV increment last. 595 if (e->is_Mach() && e->as_Mach()->ideal_Opcode() == Op_CountedLoopEnd) { 596 // Cmp might be matched into CountedLoopEnd node. 597 Node *cmp = (e->in(1)->ideal_reg() == Op_RegFlags) ? e->in(1) : e; 598 if (cmp->req() > 1 && cmp->in(1) == n && n->is_iteratively_computed()) { 599 continue; 600 } 601 } 602 603 uint n_choice = 2; 604 605 // See if this instruction is consumed by a branch. If so, then (as the 606 // branch is the last instruction in the basic block) force it to the 607 // end of the basic block 608 if ( must_clone[iop] ) { 609 // See if any use is a branch 610 bool found_machif = false; 611 612 for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++) { 613 Node* use = n->fast_out(j); 614 615 // The use is a conditional branch, make them adjacent 616 if (use->is_MachIf() && get_block_for_node(use) == block) { 617 found_machif = true; 618 break; 619 } 620 621 // More than this instruction pending for successor to be ready, 622 // don't choose this if other opportunities are ready 623 if (ready_cnt.at(use->_idx) > 1) 624 n_choice = 1; 625 } 626 627 // loop terminated, prefer not to use this instruction 628 if (found_machif) 629 continue; 630 } 631 632 // See if this has a predecessor that is "must_clone", i.e. sets the 633 // condition code. If so, choose this first 634 for (uint j = 0; j < n->req() ; j++) { 635 Node *inn = n->in(j); 636 if (inn) { 637 if (inn->is_Mach() && must_clone[inn->as_Mach()->ideal_Opcode()] ) { 638 n_choice = 3; 639 break; 640 } 641 } 642 } 643 644 // MachTemps should be scheduled last so they are near their uses 645 if (n->is_MachTemp()) { 646 n_choice = 1; 647 } 648 649 uint n_latency = get_latency_for_node(n); 650 uint n_score = n->req(); // Many inputs get high score to break ties 651 652 if (OptoRegScheduling && block_size_threshold_ok) { 653 if (recalc_pressure_nodes[n->_idx] == 0x7fff7fff) { 654 _regalloc->_scratch_int_pressure.init(_regalloc->_sched_int_pressure.high_pressure_limit()); 655 _regalloc->_scratch_float_pressure.init(_regalloc->_sched_float_pressure.high_pressure_limit()); 656 // simulate the notion that we just picked this node to schedule 657 n->add_flag(Node::Flag_is_scheduled); 658 // now calculate its effect upon the graph if we did 659 adjust_register_pressure(n, block, recalc_pressure_nodes, false); 660 // return its state for finalize in case somebody else wins 661 n->remove_flag(Node::Flag_is_scheduled); 662 // now save the two final pressure components of register pressure, limiting pressure calcs to short size 663 short int_pressure = (short)_regalloc->_scratch_int_pressure.current_pressure(); 664 short float_pressure = (short)_regalloc->_scratch_float_pressure.current_pressure(); 665 recalc_pressure_nodes[n->_idx] = int_pressure; 666 recalc_pressure_nodes[n->_idx] |= (float_pressure << 16); 667 } 668 669 if (_scheduling_for_pressure) { 670 latency = n_latency; 671 if (n_choice != 3) { 672 // Now evaluate each register pressure component based on threshold in the score. 673 // In general the defining register type will dominate the score, ergo we will not see register pressure grow on both banks 674 // on a single instruction, but we might see it shrink on both banks. 675 // For each use of register that has a register class that is over the high pressure limit, we build n_score up for 676 // live ranges that terminate on this instruction. 677 if (_regalloc->_sched_int_pressure.current_pressure() > _regalloc->_sched_int_pressure.high_pressure_limit()) { 678 short int_pressure = (short)recalc_pressure_nodes[n->_idx]; 679 n_score = (int_pressure < 0) ? ((score + n_score) - int_pressure) : (int_pressure > 0) ? 1 : n_score; 680 } 681 if (_regalloc->_sched_float_pressure.current_pressure() > _regalloc->_sched_float_pressure.high_pressure_limit()) { 682 short float_pressure = (short)(recalc_pressure_nodes[n->_idx] >> 16); 683 n_score = (float_pressure < 0) ? ((score + n_score) - float_pressure) : (float_pressure > 0) ? 1 : n_score; 684 } 685 } else { 686 // make sure we choose these candidates 687 score = 0; 688 } 689 } 690 } 691 692 // Keep best latency found 693 cand_cnt++; 694 if (choice < n_choice || 695 (choice == n_choice && 696 ((StressLCM && C->randomized_select(cand_cnt)) || 697 (!StressLCM && 698 (latency < n_latency || 699 (latency == n_latency && 700 (score < n_score))))))) { 701 choice = n_choice; 702 latency = n_latency; 703 score = n_score; 704 idx = i; // Also keep index in worklist 705 } 706 } // End of for all ready nodes in worklist 707 708 guarantee(idx >= 0, "index should be set"); 709 Node *n = worklist[(uint)idx]; // Get the winner 710 711 worklist.map((uint)idx, worklist.pop()); // Compress worklist 712 return n; 713 } 714 715 //-------------------------adjust_register_pressure---------------------------- 716 void PhaseCFG::adjust_register_pressure(Node* n, Block* block, intptr_t* recalc_pressure_nodes, bool finalize_mode) { 717 PhaseLive* liveinfo = _regalloc->get_live(); 718 IndexSet* liveout = liveinfo->live(block); 719 // first adjust the register pressure for the sources 720 for (uint i = 1; i < n->req(); i++) { 721 bool lrg_ends = false; 722 Node *src_n = n->in(i); 723 if (src_n == nullptr) continue; 724 if (!src_n->is_Mach()) continue; 725 uint src = _regalloc->_lrg_map.find(src_n); 726 if (src == 0) continue; 727 LRG& lrg_src = _regalloc->lrgs(src); 728 // detect if the live range ends or not 729 if (liveout->member(src) == false) { 730 lrg_ends = true; 731 for (DUIterator_Fast jmax, j = src_n->fast_outs(jmax); j < jmax; j++) { 732 Node* m = src_n->fast_out(j); // Get user 733 if (m == n) continue; 734 if (!m->is_Mach()) continue; 735 MachNode *mach = m->as_Mach(); 736 bool src_matches = false; 737 int iop = mach->ideal_Opcode(); 738 739 switch (iop) { 740 case Op_StoreB: 741 case Op_StoreC: 742 case Op_StoreD: 743 case Op_StoreF: 744 case Op_StoreI: 745 case Op_StoreL: 746 case Op_StoreP: 747 case Op_StoreN: 748 case Op_StoreVector: 749 case Op_StoreVectorMasked: 750 case Op_StoreVectorScatter: 751 case Op_StoreVectorScatterMasked: 752 case Op_StoreNKlass: 753 for (uint k = 1; k < m->req(); k++) { 754 Node *in = m->in(k); 755 if (in == src_n) { 756 src_matches = true; 757 break; 758 } 759 } 760 break; 761 762 default: 763 src_matches = true; 764 break; 765 } 766 767 // If we have a store as our use, ignore the non source operands 768 if (src_matches == false) continue; 769 770 // Mark every unscheduled use which is not n with a recalculation 771 if ((get_block_for_node(m) == block) && (!m->is_scheduled())) { 772 if (finalize_mode && !m->is_Phi()) { 773 recalc_pressure_nodes[m->_idx] = 0x7fff7fff; 774 } 775 lrg_ends = false; 776 } 777 } 778 } 779 // if none, this live range ends and we can adjust register pressure 780 if (lrg_ends) { 781 if (finalize_mode) { 782 _regalloc->lower_pressure(block, 0, lrg_src, nullptr, _regalloc->_sched_int_pressure, _regalloc->_sched_float_pressure); 783 } else { 784 _regalloc->lower_pressure(block, 0, lrg_src, nullptr, _regalloc->_scratch_int_pressure, _regalloc->_scratch_float_pressure); 785 } 786 } 787 } 788 789 // now add the register pressure from the dest and evaluate which heuristic we should use: 790 // 1.) The default, latency scheduling 791 // 2.) Register pressure scheduling based on the high pressure limit threshold for int or float register stacks 792 uint dst = _regalloc->_lrg_map.find(n); 793 if (dst != 0) { 794 LRG& lrg_dst = _regalloc->lrgs(dst); 795 if (finalize_mode) { 796 _regalloc->raise_pressure(block, lrg_dst, _regalloc->_sched_int_pressure, _regalloc->_sched_float_pressure); 797 // check to see if we fall over the register pressure cliff here 798 if (_regalloc->_sched_int_pressure.current_pressure() > _regalloc->_sched_int_pressure.high_pressure_limit()) { 799 _scheduling_for_pressure = true; 800 } else if (_regalloc->_sched_float_pressure.current_pressure() > _regalloc->_sched_float_pressure.high_pressure_limit()) { 801 _scheduling_for_pressure = true; 802 } else { 803 // restore latency scheduling mode 804 _scheduling_for_pressure = false; 805 } 806 } else { 807 _regalloc->raise_pressure(block, lrg_dst, _regalloc->_scratch_int_pressure, _regalloc->_scratch_float_pressure); 808 } 809 } 810 } 811 812 //------------------------------set_next_call---------------------------------- 813 void PhaseCFG::set_next_call(const Block* block, Node* init, VectorSet& next_call) const { 814 Node_List worklist; 815 worklist.push(init); 816 817 while (worklist.size() > 0) { 818 Node* n = worklist.pop(); 819 if (next_call.test_set(n->_idx)) continue; 820 for (uint i = 0; i < n->len(); i++) { 821 Node* m = n->in(i); 822 if (m == nullptr) continue; // must see all nodes in block that precede call 823 if (get_block_for_node(m) == block) { 824 worklist.push(m); 825 } 826 } 827 } 828 } 829 830 //------------------------------needed_for_next_call--------------------------- 831 // Set the flag 'next_call' for each Node that is needed for the next call to 832 // be scheduled. This flag lets me bias scheduling so Nodes needed for the 833 // next subroutine call get priority - basically it moves things NOT needed 834 // for the next call till after the call. This prevents me from trying to 835 // carry lots of stuff live across a call. 836 void PhaseCFG::needed_for_next_call(Block* block, Node* this_call, VectorSet& next_call) { 837 // Find the next control-defining Node in this block 838 Node* call = nullptr; 839 for (DUIterator_Fast imax, i = this_call->fast_outs(imax); i < imax; i++) { 840 Node* m = this_call->fast_out(i); 841 if (get_block_for_node(m) == block && // Local-block user 842 m != this_call && // Not self-start node 843 m->is_MachCall()) { 844 call = m; 845 break; 846 } 847 } 848 if (call == nullptr) return; // No next call (e.g., block end is near) 849 // Set next-call for all inputs to this call 850 set_next_call(block, call, next_call); 851 } 852 853 //------------------------------add_call_kills------------------------------------- 854 // helper function that adds caller save registers to MachProjNode 855 static void add_call_kills(MachProjNode *proj, RegMask& regs, const char* save_policy, bool exclude_soe) { 856 // Fill in the kill mask for the call 857 for( OptoReg::Name r = OptoReg::Name(0); r < _last_Mach_Reg; r=OptoReg::add(r,1) ) { 858 if( !regs.Member(r) ) { // Not already defined by the call 859 // Save-on-call register? 860 if ((save_policy[r] == 'C') || 861 (save_policy[r] == 'A') || 862 ((save_policy[r] == 'E') && exclude_soe)) { 863 proj->_rout.Insert(r); 864 } 865 } 866 } 867 } 868 869 870 //------------------------------sched_call------------------------------------- 871 uint PhaseCFG::sched_call(Block* block, uint node_cnt, Node_List& worklist, GrowableArray<int>& ready_cnt, MachCallNode* mcall, VectorSet& next_call) { 872 RegMask regs; 873 874 // Schedule all the users of the call right now. All the users are 875 // projection Nodes, so they must be scheduled next to the call. 876 // Collect all the defined registers. 877 for (DUIterator_Fast imax, i = mcall->fast_outs(imax); i < imax; i++) { 878 Node* n = mcall->fast_out(i); 879 assert( n->is_MachProj(), "" ); 880 int n_cnt = ready_cnt.at(n->_idx)-1; 881 ready_cnt.at_put(n->_idx, n_cnt); 882 assert( n_cnt == 0, "" ); 883 // Schedule next to call 884 block->map_node(n, node_cnt++); 885 // Collect defined registers 886 regs.OR(n->out_RegMask()); 887 // Check for scheduling the next control-definer 888 if( n->bottom_type() == Type::CONTROL ) 889 // Warm up next pile of heuristic bits 890 needed_for_next_call(block, n, next_call); 891 892 // Children of projections are now all ready 893 for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++) { 894 Node* m = n->fast_out(j); // Get user 895 if(get_block_for_node(m) != block) { 896 continue; 897 } 898 if( m->is_Phi() ) continue; 899 int m_cnt = ready_cnt.at(m->_idx) - 1; 900 ready_cnt.at_put(m->_idx, m_cnt); 901 if( m_cnt == 0 ) 902 worklist.push(m); 903 } 904 905 } 906 907 // Act as if the call defines the Frame Pointer. 908 // Certainly the FP is alive and well after the call. 909 regs.Insert(_matcher.c_frame_pointer()); 910 911 // Set all registers killed and not already defined by the call. 912 uint r_cnt = mcall->tf()->range()->cnt(); 913 int op = mcall->ideal_Opcode(); 914 MachProjNode *proj = new MachProjNode( mcall, r_cnt+1, RegMask::Empty, MachProjNode::fat_proj ); 915 map_node_to_block(proj, block); 916 block->insert_node(proj, node_cnt++); 917 918 // Select the right register save policy. 919 const char *save_policy = nullptr; 920 switch (op) { 921 case Op_CallRuntime: 922 case Op_CallLeaf: 923 case Op_CallLeafNoFP: 924 case Op_CallLeafVector: 925 // Calling C code so use C calling convention 926 save_policy = _matcher._c_reg_save_policy; 927 break; 928 929 case Op_CallStaticJava: 930 case Op_CallDynamicJava: 931 // Calling Java code so use Java calling convention 932 save_policy = _matcher._register_save_policy; 933 break; 934 935 default: 936 ShouldNotReachHere(); 937 } 938 939 // When using CallRuntime mark SOE registers as killed by the call 940 // so values that could show up in the RegisterMap aren't live in a 941 // callee saved register since the register wouldn't know where to 942 // find them. CallLeaf and CallLeafNoFP are ok because they can't 943 // have debug info on them. Strictly speaking this only needs to be 944 // done for oops since idealreg2debugmask takes care of debug info 945 // references but there no way to handle oops differently than other 946 // pointers as far as the kill mask goes. 947 bool exclude_soe = op == Op_CallRuntime; 948 949 // If the call is a MethodHandle invoke, we need to exclude the 950 // register which is used to save the SP value over MH invokes from 951 // the mask. Otherwise this register could be used for 952 // deoptimization information. 953 if (op == Op_CallStaticJava) { 954 MachCallStaticJavaNode* mcallstaticjava = (MachCallStaticJavaNode*) mcall; 955 if (mcallstaticjava->_method_handle_invoke) 956 proj->_rout.OR(Matcher::method_handle_invoke_SP_save_mask()); 957 } 958 959 add_call_kills(proj, regs, save_policy, exclude_soe); 960 961 return node_cnt; 962 } 963 964 965 //------------------------------schedule_local--------------------------------- 966 // Topological sort within a block. Someday become a real scheduler. 967 bool PhaseCFG::schedule_local(Block* block, GrowableArray<int>& ready_cnt, VectorSet& next_call, intptr_t *recalc_pressure_nodes) { 968 // Already "sorted" are the block start Node (as the first entry), and 969 // the block-ending Node and any trailing control projections. We leave 970 // these alone. PhiNodes and ParmNodes are made to follow the block start 971 // Node. Everything else gets topo-sorted. 972 973 #ifndef PRODUCT 974 if (trace_opto_pipelining()) { 975 tty->print_cr("# --- schedule_local B%d, before: ---", block->_pre_order); 976 for (uint i = 0;i < block->number_of_nodes(); i++) { 977 tty->print("# "); 978 block->get_node(i)->dump(); 979 } 980 tty->print_cr("#"); 981 } 982 #endif 983 984 // RootNode is already sorted 985 if (block->number_of_nodes() == 1) { 986 return true; 987 } 988 989 bool block_size_threshold_ok = (recalc_pressure_nodes != nullptr) && (block->number_of_nodes() > 10); 990 991 // We track the uses of local definitions as input dependences so that 992 // we know when a given instruction is available to be scheduled. 993 uint i; 994 if (OptoRegScheduling && block_size_threshold_ok) { 995 for (i = 1; i < block->number_of_nodes(); i++) { // setup nodes for pressure calc 996 Node *n = block->get_node(i); 997 n->remove_flag(Node::Flag_is_scheduled); 998 if (!n->is_Phi()) { 999 recalc_pressure_nodes[n->_idx] = 0x7fff7fff; 1000 } 1001 } 1002 } 1003 1004 // Move PhiNodes and ParmNodes from 1 to cnt up to the start 1005 uint node_cnt = block->end_idx(); 1006 uint phi_cnt = 1; 1007 for( i = 1; i<node_cnt; i++ ) { // Scan for Phi 1008 Node *n = block->get_node(i); 1009 if( n->is_Phi() || // Found a PhiNode or ParmNode 1010 (n->is_Proj() && n->in(0) == block->head()) ) { 1011 // Move guy at 'phi_cnt' to the end; makes a hole at phi_cnt 1012 block->map_node(block->get_node(phi_cnt), i); 1013 block->map_node(n, phi_cnt++); // swap Phi/Parm up front 1014 if (OptoRegScheduling && block_size_threshold_ok) { 1015 // mark n as scheduled 1016 n->add_flag(Node::Flag_is_scheduled); 1017 } 1018 } else { // All others 1019 // Count block-local inputs to 'n' 1020 uint cnt = n->len(); // Input count 1021 uint local = 0; 1022 for( uint j=0; j<cnt; j++ ) { 1023 Node *m = n->in(j); 1024 if( m && get_block_for_node(m) == block && !m->is_top() ) 1025 local++; // One more block-local input 1026 } 1027 ready_cnt.at_put(n->_idx, local); // Count em up 1028 // A few node types require changing a required edge to a precedence edge 1029 // before allocation. 1030 if( n->is_Mach() && n->req() > TypeFunc::Parms && 1031 (n->as_Mach()->ideal_Opcode() == Op_MemBarAcquire || 1032 n->as_Mach()->ideal_Opcode() == Op_MemBarVolatile) ) { 1033 // MemBarAcquire could be created without Precedent edge. 1034 // del_req() replaces the specified edge with the last input edge 1035 // and then removes the last edge. If the specified edge > number of 1036 // edges the last edge will be moved outside of the input edges array 1037 // and the edge will be lost. This is why this code should be 1038 // executed only when Precedent (== TypeFunc::Parms) edge is present. 1039 Node *x = n->in(TypeFunc::Parms); 1040 if (x != nullptr && get_block_for_node(x) == block && n->find_prec_edge(x) != -1) { 1041 // Old edge to node within same block will get removed, but no precedence 1042 // edge will get added because it already exists. Update ready count. 1043 int cnt = ready_cnt.at(n->_idx); 1044 assert(cnt > 1, "MemBar node %d must not get ready here", n->_idx); 1045 ready_cnt.at_put(n->_idx, cnt-1); 1046 } 1047 n->del_req(TypeFunc::Parms); 1048 n->add_prec(x); 1049 } 1050 } 1051 } 1052 for(uint i2=i; i2< block->number_of_nodes(); i2++ ) // Trailing guys get zapped count 1053 ready_cnt.at_put(block->get_node(i2)->_idx, 0); 1054 1055 // All the prescheduled guys do not hold back internal nodes 1056 uint i3; 1057 for (i3 = 0; i3 < phi_cnt; i3++) { // For all pre-scheduled 1058 Node *n = block->get_node(i3); // Get pre-scheduled 1059 for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++) { 1060 Node* m = n->fast_out(j); 1061 if (get_block_for_node(m) == block) { // Local-block user 1062 int m_cnt = ready_cnt.at(m->_idx)-1; 1063 if (OptoRegScheduling && block_size_threshold_ok) { 1064 // mark m as scheduled 1065 if (m_cnt < 0) { 1066 m->add_flag(Node::Flag_is_scheduled); 1067 } 1068 } 1069 ready_cnt.at_put(m->_idx, m_cnt); // Fix ready count 1070 } 1071 } 1072 } 1073 1074 Node_List delay; 1075 // Make a worklist 1076 Node_List worklist; 1077 for(uint i4=i3; i4<node_cnt; i4++ ) { // Put ready guys on worklist 1078 Node *m = block->get_node(i4); 1079 if( !ready_cnt.at(m->_idx) ) { // Zero ready count? 1080 if (m->is_iteratively_computed()) { 1081 // Push induction variable increments last to allow other uses 1082 // of the phi to be scheduled first. The select() method breaks 1083 // ties in scheduling by worklist order. 1084 delay.push(m); 1085 } else if (m->is_Mach() && m->as_Mach()->ideal_Opcode() == Op_CreateEx) { 1086 // Place CreateEx nodes that are initially ready at the beginning of the 1087 // worklist so they are selected first and scheduled at the block start. 1088 worklist.insert(0, m); 1089 } else { 1090 worklist.push(m); // Then on to worklist! 1091 } 1092 } 1093 } 1094 while (delay.size()) { 1095 Node* d = delay.pop(); 1096 worklist.push(d); 1097 } 1098 1099 if (OptoRegScheduling && block_size_threshold_ok) { 1100 // To stage register pressure calculations we need to examine the live set variables 1101 // breaking them up by register class to compartmentalize the calculations. 1102 _regalloc->_sched_int_pressure.init(Matcher::int_pressure_limit()); 1103 _regalloc->_sched_float_pressure.init(Matcher::float_pressure_limit()); 1104 _regalloc->_scratch_int_pressure.init(Matcher::int_pressure_limit()); 1105 _regalloc->_scratch_float_pressure.init(Matcher::float_pressure_limit()); 1106 1107 _regalloc->compute_entry_block_pressure(block); 1108 } 1109 1110 // Warm up the 'next_call' heuristic bits 1111 needed_for_next_call(block, block->head(), next_call); 1112 1113 #ifndef PRODUCT 1114 if (trace_opto_pipelining()) { 1115 for (uint j=0; j< block->number_of_nodes(); j++) { 1116 Node *n = block->get_node(j); 1117 int idx = n->_idx; 1118 tty->print("# ready cnt:%3d ", ready_cnt.at(idx)); 1119 tty->print("latency:%3d ", get_latency_for_node(n)); 1120 tty->print("%4d: %s\n", idx, n->Name()); 1121 } 1122 } 1123 #endif 1124 1125 uint max_idx = (uint)ready_cnt.length(); 1126 // Pull from worklist and schedule 1127 while( worklist.size() ) { // Worklist is not ready 1128 1129 #ifndef PRODUCT 1130 if (trace_opto_pipelining()) { 1131 tty->print("# ready list:"); 1132 for( uint i=0; i<worklist.size(); i++ ) { // Inspect entire worklist 1133 Node *n = worklist[i]; // Get Node on worklist 1134 tty->print(" %d", n->_idx); 1135 } 1136 tty->cr(); 1137 } 1138 #endif 1139 1140 // Select and pop a ready guy from worklist 1141 Node* n = select(block, worklist, ready_cnt, next_call, phi_cnt, recalc_pressure_nodes); 1142 block->map_node(n, phi_cnt++); // Schedule him next 1143 1144 if (OptoRegScheduling && block_size_threshold_ok) { 1145 n->add_flag(Node::Flag_is_scheduled); 1146 1147 // Now adjust the resister pressure with the node we selected 1148 if (!n->is_Phi()) { 1149 adjust_register_pressure(n, block, recalc_pressure_nodes, true); 1150 } 1151 } 1152 1153 #ifndef PRODUCT 1154 if (trace_opto_pipelining()) { 1155 tty->print("# select %d: %s", n->_idx, n->Name()); 1156 tty->print(", latency:%d", get_latency_for_node(n)); 1157 n->dump(); 1158 if (Verbose) { 1159 tty->print("# ready list:"); 1160 for( uint i=0; i<worklist.size(); i++ ) { // Inspect entire worklist 1161 Node *n = worklist[i]; // Get Node on worklist 1162 tty->print(" %d", n->_idx); 1163 } 1164 tty->cr(); 1165 } 1166 } 1167 1168 #endif 1169 if( n->is_MachCall() ) { 1170 MachCallNode *mcall = n->as_MachCall(); 1171 phi_cnt = sched_call(block, phi_cnt, worklist, ready_cnt, mcall, next_call); 1172 continue; 1173 } 1174 1175 if (n->is_Mach() && n->as_Mach()->has_call()) { 1176 RegMask regs; 1177 regs.Insert(_matcher.c_frame_pointer()); 1178 regs.OR(n->out_RegMask()); 1179 1180 MachProjNode *proj = new MachProjNode( n, 1, RegMask::Empty, MachProjNode::fat_proj ); 1181 map_node_to_block(proj, block); 1182 block->insert_node(proj, phi_cnt++); 1183 1184 add_call_kills(proj, regs, _matcher._c_reg_save_policy, false); 1185 } 1186 1187 // Children are now all ready 1188 for (DUIterator_Fast i5max, i5 = n->fast_outs(i5max); i5 < i5max; i5++) { 1189 Node* m = n->fast_out(i5); // Get user 1190 if (get_block_for_node(m) != block) { 1191 continue; 1192 } 1193 if( m->is_Phi() ) continue; 1194 if (m->_idx >= max_idx) { // new node, skip it 1195 assert(m->is_MachProj() && n->is_Mach() && n->as_Mach()->has_call(), "unexpected node types"); 1196 continue; 1197 } 1198 int m_cnt = ready_cnt.at(m->_idx) - 1; 1199 ready_cnt.at_put(m->_idx, m_cnt); 1200 if( m_cnt == 0 ) 1201 worklist.push(m); 1202 } 1203 } 1204 1205 if( phi_cnt != block->end_idx() ) { 1206 // did not schedule all. Retry, Bailout, or Die 1207 if (C->subsume_loads() == true && !C->failing()) { 1208 // Retry with subsume_loads == false 1209 // If this is the first failure, the sentinel string will "stick" 1210 // to the Compile object, and the C2Compiler will see it and retry. 1211 C->record_failure(C2Compiler::retry_no_subsuming_loads()); 1212 } else { 1213 assert(C->failure_is_artificial(), "graph should be schedulable"); 1214 } 1215 // assert( phi_cnt == end_idx(), "did not schedule all" ); 1216 return false; 1217 } 1218 1219 if (OptoRegScheduling && block_size_threshold_ok) { 1220 _regalloc->compute_exit_block_pressure(block); 1221 block->_reg_pressure = _regalloc->_sched_int_pressure.final_pressure(); 1222 block->_freg_pressure = _regalloc->_sched_float_pressure.final_pressure(); 1223 } 1224 1225 #ifndef PRODUCT 1226 if (trace_opto_pipelining()) { 1227 tty->print_cr("#"); 1228 tty->print_cr("# after schedule_local"); 1229 for (uint i = 0;i < block->number_of_nodes();i++) { 1230 tty->print("# "); 1231 block->get_node(i)->dump(); 1232 } 1233 tty->print_cr("# "); 1234 1235 if (OptoRegScheduling && block_size_threshold_ok) { 1236 tty->print_cr("# pressure info : %d", block->_pre_order); 1237 _regalloc->print_pressure_info(_regalloc->_sched_int_pressure, "int register info"); 1238 _regalloc->print_pressure_info(_regalloc->_sched_float_pressure, "float register info"); 1239 } 1240 tty->cr(); 1241 } 1242 #endif 1243 1244 return true; 1245 } 1246 1247 //--------------------------catch_cleanup_fix_all_inputs----------------------- 1248 static void catch_cleanup_fix_all_inputs(Node *use, Node *old_def, Node *new_def) { 1249 for (uint l = 0; l < use->len(); l++) { 1250 if (use->in(l) == old_def) { 1251 if (l < use->req()) { 1252 use->set_req(l, new_def); 1253 } else { 1254 use->rm_prec(l); 1255 use->add_prec(new_def); 1256 l--; 1257 } 1258 } 1259 } 1260 } 1261 1262 //------------------------------catch_cleanup_find_cloned_def------------------ 1263 Node* PhaseCFG::catch_cleanup_find_cloned_def(Block *use_blk, Node *def, Block *def_blk, int n_clone_idx) { 1264 assert( use_blk != def_blk, "Inter-block cleanup only"); 1265 1266 // The use is some block below the Catch. Find and return the clone of the def 1267 // that dominates the use. If there is no clone in a dominating block, then 1268 // create a phi for the def in a dominating block. 1269 1270 // Find which successor block dominates this use. The successor 1271 // blocks must all be single-entry (from the Catch only; I will have 1272 // split blocks to make this so), hence they all dominate. 1273 while( use_blk->_dom_depth > def_blk->_dom_depth+1 ) 1274 use_blk = use_blk->_idom; 1275 1276 // Find the successor 1277 Node *fixup = nullptr; 1278 1279 uint j; 1280 for( j = 0; j < def_blk->_num_succs; j++ ) 1281 if( use_blk == def_blk->_succs[j] ) 1282 break; 1283 1284 if( j == def_blk->_num_succs ) { 1285 // Block at same level in dom-tree is not a successor. It needs a 1286 // PhiNode, the PhiNode uses from the def and IT's uses need fixup. 1287 Node_Array inputs; 1288 for(uint k = 1; k < use_blk->num_preds(); k++) { 1289 Block* block = get_block_for_node(use_blk->pred(k)); 1290 inputs.map(k, catch_cleanup_find_cloned_def(block, def, def_blk, n_clone_idx)); 1291 } 1292 1293 // Check to see if the use_blk already has an identical phi inserted. 1294 // If it exists, it will be at the first position since all uses of a 1295 // def are processed together. 1296 Node *phi = use_blk->get_node(1); 1297 if( phi->is_Phi() ) { 1298 fixup = phi; 1299 for (uint k = 1; k < use_blk->num_preds(); k++) { 1300 if (phi->in(k) != inputs[k]) { 1301 // Not a match 1302 fixup = nullptr; 1303 break; 1304 } 1305 } 1306 } 1307 1308 // If an existing PhiNode was not found, make a new one. 1309 if (fixup == nullptr) { 1310 Node *new_phi = PhiNode::make(use_blk->head(), def); 1311 use_blk->insert_node(new_phi, 1); 1312 map_node_to_block(new_phi, use_blk); 1313 for (uint k = 1; k < use_blk->num_preds(); k++) { 1314 new_phi->set_req(k, inputs[k]); 1315 } 1316 fixup = new_phi; 1317 } 1318 1319 } else { 1320 // Found the use just below the Catch. Make it use the clone. 1321 fixup = use_blk->get_node(n_clone_idx); 1322 } 1323 1324 return fixup; 1325 } 1326 1327 //--------------------------catch_cleanup_intra_block-------------------------- 1328 // Fix all input edges in use that reference "def". The use is in the same 1329 // block as the def and both have been cloned in each successor block. 1330 static void catch_cleanup_intra_block(Node *use, Node *def, Block *blk, int beg, int n_clone_idx) { 1331 1332 // Both the use and def have been cloned. For each successor block, 1333 // get the clone of the use, and make its input the clone of the def 1334 // found in that block. 1335 1336 uint use_idx = blk->find_node(use); 1337 uint offset_idx = use_idx - beg; 1338 for( uint k = 0; k < blk->_num_succs; k++ ) { 1339 // Get clone in each successor block 1340 Block *sb = blk->_succs[k]; 1341 Node *clone = sb->get_node(offset_idx+1); 1342 assert( clone->Opcode() == use->Opcode(), "" ); 1343 1344 // Make use-clone reference the def-clone 1345 catch_cleanup_fix_all_inputs(clone, def, sb->get_node(n_clone_idx)); 1346 } 1347 } 1348 1349 //------------------------------catch_cleanup_inter_block--------------------- 1350 // Fix all input edges in use that reference "def". The use is in a different 1351 // block than the def. 1352 void PhaseCFG::catch_cleanup_inter_block(Node *use, Block *use_blk, Node *def, Block *def_blk, int n_clone_idx) { 1353 if( !use_blk ) return; // Can happen if the use is a precedence edge 1354 1355 Node *new_def = catch_cleanup_find_cloned_def(use_blk, def, def_blk, n_clone_idx); 1356 catch_cleanup_fix_all_inputs(use, def, new_def); 1357 } 1358 1359 //------------------------------call_catch_cleanup----------------------------- 1360 // If we inserted any instructions between a Call and his CatchNode, 1361 // clone the instructions on all paths below the Catch. 1362 void PhaseCFG::call_catch_cleanup(Block* block) { 1363 1364 // End of region to clone 1365 uint end = block->end_idx(); 1366 if( !block->get_node(end)->is_Catch() ) return; 1367 // Start of region to clone 1368 uint beg = end; 1369 while(!block->get_node(beg-1)->is_MachProj() || 1370 !block->get_node(beg-1)->in(0)->is_MachCall() ) { 1371 beg--; 1372 assert(beg > 0,"Catch cleanup walking beyond block boundary"); 1373 } 1374 // Range of inserted instructions is [beg, end) 1375 if( beg == end ) return; 1376 1377 // Clone along all Catch output paths. Clone area between the 'beg' and 1378 // 'end' indices. 1379 for( uint i = 0; i < block->_num_succs; i++ ) { 1380 Block *sb = block->_succs[i]; 1381 // Clone the entire area; ignoring the edge fixup for now. 1382 for( uint j = end; j > beg; j-- ) { 1383 Node *clone = block->get_node(j-1)->clone(); 1384 sb->insert_node(clone, 1); 1385 map_node_to_block(clone, sb); 1386 if (clone->needs_anti_dependence_check()) { 1387 raise_above_anti_dependences(sb, clone); 1388 if (C->failing()) { 1389 return; 1390 } 1391 } 1392 } 1393 } 1394 1395 1396 // Fixup edges. Check the def-use info per cloned Node 1397 for(uint i2 = beg; i2 < end; i2++ ) { 1398 uint n_clone_idx = i2-beg+1; // Index of clone of n in each successor block 1399 Node *n = block->get_node(i2); // Node that got cloned 1400 // Need DU safe iterator because of edge manipulation in calls. 1401 Unique_Node_List* out = new Unique_Node_List(); 1402 for (DUIterator_Fast j1max, j1 = n->fast_outs(j1max); j1 < j1max; j1++) { 1403 out->push(n->fast_out(j1)); 1404 } 1405 uint max = out->size(); 1406 for (uint j = 0; j < max; j++) {// For all users 1407 Node *use = out->pop(); 1408 Block *buse = get_block_for_node(use); 1409 if( use->is_Phi() ) { 1410 for( uint k = 1; k < use->req(); k++ ) 1411 if( use->in(k) == n ) { 1412 Block* b = get_block_for_node(buse->pred(k)); 1413 Node *fixup = catch_cleanup_find_cloned_def(b, n, block, n_clone_idx); 1414 use->set_req(k, fixup); 1415 } 1416 } else { 1417 if (block == buse) { 1418 catch_cleanup_intra_block(use, n, block, beg, n_clone_idx); 1419 } else { 1420 catch_cleanup_inter_block(use, buse, n, block, n_clone_idx); 1421 } 1422 } 1423 } // End for all users 1424 1425 } // End of for all Nodes in cloned area 1426 1427 // Remove the now-dead cloned ops 1428 for(uint i3 = beg; i3 < end; i3++ ) { 1429 block->get_node(beg)->disconnect_inputs(C); 1430 block->remove_node(beg); 1431 } 1432 1433 // If the successor blocks have a CreateEx node, move it back to the top 1434 for (uint i4 = 0; i4 < block->_num_succs; i4++) { 1435 Block *sb = block->_succs[i4]; 1436 uint new_cnt = end - beg; 1437 // Remove any newly created, but dead, nodes by traversing their schedule 1438 // backwards. Here, a dead node is a node whose only outputs (if any) are 1439 // unused projections. 1440 for (uint j = new_cnt; j > 0; j--) { 1441 Node *n = sb->get_node(j); 1442 // Individual projections are examined together with all siblings when 1443 // their parent is visited. 1444 if (n->is_Proj()) { 1445 continue; 1446 } 1447 bool dead = true; 1448 for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) { 1449 Node* out = n->fast_out(i); 1450 // n is live if it has a non-projection output or a used projection. 1451 if (!out->is_Proj() || out->outcnt() > 0) { 1452 dead = false; 1453 break; 1454 } 1455 } 1456 if (dead) { 1457 // n's only outputs (if any) are unused projections scheduled next to n 1458 // (see PhaseCFG::select()). Remove these projections backwards. 1459 for (uint k = j + n->outcnt(); k > j; k--) { 1460 Node* proj = sb->get_node(k); 1461 assert(proj->is_Proj() && proj->in(0) == n, 1462 "projection should correspond to dead node"); 1463 proj->disconnect_inputs(C); 1464 sb->remove_node(k); 1465 new_cnt--; 1466 } 1467 // Now remove the node itself. 1468 n->disconnect_inputs(C); 1469 sb->remove_node(j); 1470 new_cnt--; 1471 } 1472 } 1473 // If any newly created nodes remain, move the CreateEx node to the top 1474 if (new_cnt > 0) { 1475 Node *cex = sb->get_node(1+new_cnt); 1476 if( cex->is_Mach() && cex->as_Mach()->ideal_Opcode() == Op_CreateEx ) { 1477 sb->remove_node(1+new_cnt); 1478 sb->insert_node(cex, 1); 1479 } 1480 } 1481 } 1482 }