1 /* 2 * Copyright (c) 1998, 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 "asm/assembler.inline.hpp" 27 #include "asm/macroAssembler.inline.hpp" 28 #include "code/compiledIC.hpp" 29 #include "code/debugInfo.hpp" 30 #include "code/debugInfoRec.hpp" 31 #include "compiler/compileBroker.hpp" 32 #include "compiler/compilerDirectives.hpp" 33 #include "compiler/disassembler.hpp" 34 #include "compiler/oopMap.hpp" 35 #include "gc/shared/barrierSet.hpp" 36 #include "gc/shared/c2/barrierSetC2.hpp" 37 #include "memory/allocation.inline.hpp" 38 #include "memory/allocation.hpp" 39 #include "opto/ad.hpp" 40 #include "opto/block.hpp" 41 #include "opto/c2compiler.hpp" 42 #include "opto/c2_MacroAssembler.hpp" 43 #include "opto/callnode.hpp" 44 #include "opto/cfgnode.hpp" 45 #include "opto/locknode.hpp" 46 #include "opto/machnode.hpp" 47 #include "opto/node.hpp" 48 #include "opto/optoreg.hpp" 49 #include "opto/output.hpp" 50 #include "opto/regalloc.hpp" 51 #include "opto/runtime.hpp" 52 #include "opto/subnode.hpp" 53 #include "opto/type.hpp" 54 #include "runtime/handles.inline.hpp" 55 #include "runtime/sharedRuntime.hpp" 56 #include "utilities/macros.hpp" 57 #include "utilities/powerOfTwo.hpp" 58 #include "utilities/xmlstream.hpp" 59 60 #ifndef PRODUCT 61 #define DEBUG_ARG(x) , x 62 #else 63 #define DEBUG_ARG(x) 64 #endif 65 66 //------------------------------Scheduling---------------------------------- 67 // This class contains all the information necessary to implement instruction 68 // scheduling and bundling. 69 class Scheduling { 70 71 private: 72 // Arena to use 73 Arena *_arena; 74 75 // Control-Flow Graph info 76 PhaseCFG *_cfg; 77 78 // Register Allocation info 79 PhaseRegAlloc *_regalloc; 80 81 // Number of nodes in the method 82 uint _node_bundling_limit; 83 84 // List of scheduled nodes. Generated in reverse order 85 Node_List _scheduled; 86 87 // List of nodes currently available for choosing for scheduling 88 Node_List _available; 89 90 // For each instruction beginning a bundle, the number of following 91 // nodes to be bundled with it. 92 Bundle *_node_bundling_base; 93 94 // Mapping from register to Node 95 Node_List _reg_node; 96 97 // Free list for pinch nodes. 98 Node_List _pinch_free_list; 99 100 // Number of uses of this node within the containing basic block. 101 short *_uses; 102 103 // Schedulable portion of current block. Skips Region/Phi/CreateEx up 104 // front, branch+proj at end. Also skips Catch/CProj (same as 105 // branch-at-end), plus just-prior exception-throwing call. 106 uint _bb_start, _bb_end; 107 108 // Latency from the end of the basic block as scheduled 109 unsigned short *_current_latency; 110 111 // Remember the next node 112 Node *_next_node; 113 114 // Use this for an unconditional branch delay slot 115 Node *_unconditional_delay_slot; 116 117 // Pointer to a Nop 118 MachNopNode *_nop; 119 120 // Length of the current bundle, in instructions 121 uint _bundle_instr_count; 122 123 // Current Cycle number, for computing latencies and bundling 124 uint _bundle_cycle_number; 125 126 // Bundle information 127 Pipeline_Use_Element _bundle_use_elements[resource_count]; 128 Pipeline_Use _bundle_use; 129 130 // Dump the available list 131 void dump_available() const; 132 133 public: 134 Scheduling(Arena *arena, Compile &compile); 135 136 // Destructor 137 NOT_PRODUCT( ~Scheduling(); ) 138 139 // Step ahead "i" cycles 140 void step(uint i); 141 142 // Step ahead 1 cycle, and clear the bundle state (for example, 143 // at a branch target) 144 void step_and_clear(); 145 146 Bundle* node_bundling(const Node *n) { 147 assert(valid_bundle_info(n), "oob"); 148 return (&_node_bundling_base[n->_idx]); 149 } 150 151 bool valid_bundle_info(const Node *n) const { 152 return (_node_bundling_limit > n->_idx); 153 } 154 155 bool starts_bundle(const Node *n) const { 156 return (_node_bundling_limit > n->_idx && _node_bundling_base[n->_idx].starts_bundle()); 157 } 158 159 // Do the scheduling 160 void DoScheduling(); 161 162 // Compute the register antidependencies within a basic block 163 void ComputeRegisterAntidependencies(Block *bb); 164 void verify_do_def( Node *n, OptoReg::Name def, const char *msg ); 165 void verify_good_schedule( Block *b, const char *msg ); 166 void anti_do_def( Block *b, Node *def, OptoReg::Name def_reg, int is_def ); 167 void anti_do_use( Block *b, Node *use, OptoReg::Name use_reg ); 168 169 // Add a node to the current bundle 170 void AddNodeToBundle(Node *n, const Block *bb); 171 172 // Return an integer less than, equal to, or greater than zero 173 // if the stack offset of the first argument is respectively 174 // less than, equal to, or greater than the second. 175 int compare_two_spill_nodes(Node* first, Node* second); 176 177 // Add a node to the list of available nodes 178 void AddNodeToAvailableList(Node *n); 179 180 // Compute the local use count for the nodes in a block, and compute 181 // the list of instructions with no uses in the block as available 182 void ComputeUseCount(const Block *bb); 183 184 // Choose an instruction from the available list to add to the bundle 185 Node * ChooseNodeToBundle(); 186 187 // See if this Node fits into the currently accumulating bundle 188 bool NodeFitsInBundle(Node *n); 189 190 // Decrement the use count for a node 191 void DecrementUseCounts(Node *n, const Block *bb); 192 193 // Garbage collect pinch nodes for reuse by other blocks. 194 void garbage_collect_pinch_nodes(); 195 // Clean up a pinch node for reuse (helper for above). 196 void cleanup_pinch( Node *pinch ); 197 198 // Information for statistics gathering 199 #ifndef PRODUCT 200 private: 201 // Gather information on size of nops relative to total 202 uint _branches, _unconditional_delays; 203 204 static uint _total_nop_size, _total_method_size; 205 static uint _total_branches, _total_unconditional_delays; 206 static uint _total_instructions_per_bundle[Pipeline::_max_instrs_per_cycle+1]; 207 208 public: 209 static void print_statistics(); 210 211 static void increment_instructions_per_bundle(uint i) { 212 _total_instructions_per_bundle[i]++; 213 } 214 215 static void increment_nop_size(uint s) { 216 _total_nop_size += s; 217 } 218 219 static void increment_method_size(uint s) { 220 _total_method_size += s; 221 } 222 #endif 223 224 }; 225 226 PhaseOutput::PhaseOutput() 227 : Phase(Phase::Output), 228 _code_buffer("Compile::Fill_buffer"), 229 _first_block_size(0), 230 _handler_table(), 231 _inc_table(), 232 _stub_list(), 233 _oop_map_set(nullptr), 234 _scratch_buffer_blob(nullptr), 235 _scratch_locs_memory(nullptr), 236 _scratch_const_size(-1), 237 _in_scratch_emit_size(false), 238 _frame_slots(0), 239 _code_offsets(), 240 _node_bundling_limit(0), 241 _node_bundling_base(nullptr), 242 _orig_pc_slot(0), 243 _orig_pc_slot_offset_in_bytes(0), 244 _buf_sizes(), 245 _block(nullptr), 246 _index(0) { 247 C->set_output(this); 248 if (C->stub_name() == nullptr) { 249 _orig_pc_slot = C->fixed_slots() - (sizeof(address) / VMRegImpl::stack_slot_size); 250 } 251 } 252 253 PhaseOutput::~PhaseOutput() { 254 C->set_output(nullptr); 255 if (_scratch_buffer_blob != nullptr) { 256 BufferBlob::free(_scratch_buffer_blob); 257 } 258 } 259 260 void PhaseOutput::perform_mach_node_analysis() { 261 // Late barrier analysis must be done after schedule and bundle 262 // Otherwise liveness based spilling will fail 263 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2(); 264 bs->late_barrier_analysis(); 265 266 pd_perform_mach_node_analysis(); 267 268 C->print_method(CompilerPhaseType::PHASE_MACH_ANALYSIS, 3); 269 } 270 271 // Convert Nodes to instruction bits and pass off to the VM 272 void PhaseOutput::Output() { 273 // RootNode goes 274 assert( C->cfg()->get_root_block()->number_of_nodes() == 0, "" ); 275 276 // The number of new nodes (mostly MachNop) is proportional to 277 // the number of java calls and inner loops which are aligned. 278 if ( C->check_node_count((NodeLimitFudgeFactor + C->java_calls()*3 + 279 C->inner_loops()*(OptoLoopAlignment-1)), 280 "out of nodes before code generation" ) ) { 281 return; 282 } 283 // Make sure I can find the Start Node 284 Block *entry = C->cfg()->get_block(1); 285 Block *broot = C->cfg()->get_root_block(); 286 287 const StartNode *start = entry->head()->as_Start(); 288 289 // Replace StartNode with prolog 290 MachPrologNode *prolog = new MachPrologNode(); 291 entry->map_node(prolog, 0); 292 C->cfg()->map_node_to_block(prolog, entry); 293 C->cfg()->unmap_node_from_block(start); // start is no longer in any block 294 295 // Virtual methods need an unverified entry point 296 297 if( C->is_osr_compilation() ) { 298 if( PoisonOSREntry ) { 299 // TODO: Should use a ShouldNotReachHereNode... 300 C->cfg()->insert( broot, 0, new MachBreakpointNode() ); 301 } 302 } else { 303 if( C->method() && !C->method()->flags().is_static() ) { 304 // Insert unvalidated entry point 305 C->cfg()->insert( broot, 0, new MachUEPNode() ); 306 } 307 308 } 309 310 // Break before main entry point 311 if ((C->method() && C->directive()->BreakAtExecuteOption) || 312 (OptoBreakpoint && C->is_method_compilation()) || 313 (OptoBreakpointOSR && C->is_osr_compilation()) || 314 (OptoBreakpointC2R && !C->method()) ) { 315 // checking for C->method() means that OptoBreakpoint does not apply to 316 // runtime stubs or frame converters 317 C->cfg()->insert( entry, 1, new MachBreakpointNode() ); 318 } 319 320 // Insert epilogs before every return 321 for (uint i = 0; i < C->cfg()->number_of_blocks(); i++) { 322 Block* block = C->cfg()->get_block(i); 323 if (!block->is_connector() && block->non_connector_successor(0) == C->cfg()->get_root_block()) { // Found a program exit point? 324 Node* m = block->end(); 325 if (m->is_Mach() && m->as_Mach()->ideal_Opcode() != Op_Halt) { 326 MachEpilogNode* epilog = new MachEpilogNode(m->as_Mach()->ideal_Opcode() == Op_Return); 327 block->add_inst(epilog); 328 C->cfg()->map_node_to_block(epilog, block); 329 } 330 } 331 } 332 333 // Keeper of sizing aspects 334 _buf_sizes = BufferSizingData(); 335 336 // Initialize code buffer 337 estimate_buffer_size(_buf_sizes._const); 338 if (C->failing()) return; 339 340 // Pre-compute the length of blocks and replace 341 // long branches with short if machine supports it. 342 // Must be done before ScheduleAndBundle due to SPARC delay slots 343 uint* blk_starts = NEW_RESOURCE_ARRAY(uint, C->cfg()->number_of_blocks() + 1); 344 blk_starts[0] = 0; 345 shorten_branches(blk_starts); 346 347 ScheduleAndBundle(); 348 if (C->failing()) { 349 return; 350 } 351 352 perform_mach_node_analysis(); 353 354 // Complete sizing of codebuffer 355 CodeBuffer* cb = init_buffer(); 356 if (cb == nullptr || C->failing()) { 357 return; 358 } 359 360 BuildOopMaps(); 361 362 if (C->failing()) { 363 return; 364 } 365 366 C2_MacroAssembler masm(cb); 367 fill_buffer(&masm, blk_starts); 368 } 369 370 bool PhaseOutput::need_stack_bang(int frame_size_in_bytes) const { 371 // Determine if we need to generate a stack overflow check. 372 // Do it if the method is not a stub function and 373 // has java calls or has frame size > vm_page_size/8. 374 // The debug VM checks that deoptimization doesn't trigger an 375 // unexpected stack overflow (compiled method stack banging should 376 // guarantee it doesn't happen) so we always need the stack bang in 377 // a debug VM. 378 return (C->stub_function() == nullptr && 379 (C->has_java_calls() || frame_size_in_bytes > (int)(os::vm_page_size())>>3 380 DEBUG_ONLY(|| true))); 381 } 382 383 bool PhaseOutput::need_register_stack_bang() const { 384 // Determine if we need to generate a register stack overflow check. 385 // This is only used on architectures which have split register 386 // and memory stacks (ie. IA64). 387 // Bang if the method is not a stub function and has java calls 388 return (C->stub_function() == nullptr && C->has_java_calls()); 389 } 390 391 392 // Compute the size of first NumberOfLoopInstrToAlign instructions at the top 393 // of a loop. When aligning a loop we need to provide enough instructions 394 // in cpu's fetch buffer to feed decoders. The loop alignment could be 395 // avoided if we have enough instructions in fetch buffer at the head of a loop. 396 // By default, the size is set to 999999 by Block's constructor so that 397 // a loop will be aligned if the size is not reset here. 398 // 399 // Note: Mach instructions could contain several HW instructions 400 // so the size is estimated only. 401 // 402 void PhaseOutput::compute_loop_first_inst_sizes() { 403 // The next condition is used to gate the loop alignment optimization. 404 // Don't aligned a loop if there are enough instructions at the head of a loop 405 // or alignment padding is larger then MaxLoopPad. By default, MaxLoopPad 406 // is equal to OptoLoopAlignment-1 except on new Intel cpus, where it is 407 // equal to 11 bytes which is the largest address NOP instruction. 408 if (MaxLoopPad < OptoLoopAlignment - 1) { 409 uint last_block = C->cfg()->number_of_blocks() - 1; 410 for (uint i = 1; i <= last_block; i++) { 411 Block* block = C->cfg()->get_block(i); 412 // Check the first loop's block which requires an alignment. 413 if (block->loop_alignment() > (uint)relocInfo::addr_unit()) { 414 uint sum_size = 0; 415 uint inst_cnt = NumberOfLoopInstrToAlign; 416 inst_cnt = block->compute_first_inst_size(sum_size, inst_cnt, C->regalloc()); 417 418 // Check subsequent fallthrough blocks if the loop's first 419 // block(s) does not have enough instructions. 420 Block *nb = block; 421 while(inst_cnt > 0 && 422 i < last_block && 423 !C->cfg()->get_block(i + 1)->has_loop_alignment() && 424 !nb->has_successor(block)) { 425 i++; 426 nb = C->cfg()->get_block(i); 427 inst_cnt = nb->compute_first_inst_size(sum_size, inst_cnt, C->regalloc()); 428 } // while( inst_cnt > 0 && i < last_block ) 429 430 block->set_first_inst_size(sum_size); 431 } // f( b->head()->is_Loop() ) 432 } // for( i <= last_block ) 433 } // if( MaxLoopPad < OptoLoopAlignment-1 ) 434 } 435 436 // The architecture description provides short branch variants for some long 437 // branch instructions. Replace eligible long branches with short branches. 438 void PhaseOutput::shorten_branches(uint* blk_starts) { 439 440 Compile::TracePhase tp(_t_shortenBranches); 441 442 // Compute size of each block, method size, and relocation information size 443 uint nblocks = C->cfg()->number_of_blocks(); 444 445 uint* jmp_offset = NEW_RESOURCE_ARRAY(uint,nblocks); 446 uint* jmp_size = NEW_RESOURCE_ARRAY(uint,nblocks); 447 int* jmp_nidx = NEW_RESOURCE_ARRAY(int ,nblocks); 448 449 // Collect worst case block paddings 450 int* block_worst_case_pad = NEW_RESOURCE_ARRAY(int, nblocks); 451 memset(block_worst_case_pad, 0, nblocks * sizeof(int)); 452 453 DEBUG_ONLY( uint *jmp_target = NEW_RESOURCE_ARRAY(uint,nblocks); ) 454 DEBUG_ONLY( uint *jmp_rule = NEW_RESOURCE_ARRAY(uint,nblocks); ) 455 456 bool has_short_branch_candidate = false; 457 458 // Initialize the sizes to 0 459 int code_size = 0; // Size in bytes of generated code 460 int stub_size = 0; // Size in bytes of all stub entries 461 // Size in bytes of all relocation entries, including those in local stubs. 462 // Start with 2-bytes of reloc info for the unvalidated entry point 463 int reloc_size = 1; // Number of relocation entries 464 465 // Make three passes. The first computes pessimistic blk_starts, 466 // relative jmp_offset and reloc_size information. The second performs 467 // short branch substitution using the pessimistic sizing. The 468 // third inserts nops where needed. 469 470 // Step one, perform a pessimistic sizing pass. 471 uint last_call_adr = max_juint; 472 uint last_avoid_back_to_back_adr = max_juint; 473 uint nop_size = (new MachNopNode())->size(C->regalloc()); 474 for (uint i = 0; i < nblocks; i++) { // For all blocks 475 Block* block = C->cfg()->get_block(i); 476 _block = block; 477 478 // During short branch replacement, we store the relative (to blk_starts) 479 // offset of jump in jmp_offset, rather than the absolute offset of jump. 480 // This is so that we do not need to recompute sizes of all nodes when 481 // we compute correct blk_starts in our next sizing pass. 482 jmp_offset[i] = 0; 483 jmp_size[i] = 0; 484 jmp_nidx[i] = -1; 485 DEBUG_ONLY( jmp_target[i] = 0; ) 486 DEBUG_ONLY( jmp_rule[i] = 0; ) 487 488 // Sum all instruction sizes to compute block size 489 uint last_inst = block->number_of_nodes(); 490 uint blk_size = 0; 491 for (uint j = 0; j < last_inst; j++) { 492 _index = j; 493 Node* nj = block->get_node(_index); 494 // Handle machine instruction nodes 495 if (nj->is_Mach()) { 496 MachNode* mach = nj->as_Mach(); 497 blk_size += (mach->alignment_required() - 1) * relocInfo::addr_unit(); // assume worst case padding 498 reloc_size += mach->reloc(); 499 if (mach->is_MachCall()) { 500 // add size information for trampoline stub 501 // class CallStubImpl is platform-specific and defined in the *.ad files. 502 stub_size += CallStubImpl::size_call_trampoline(); 503 reloc_size += CallStubImpl::reloc_call_trampoline(); 504 505 MachCallNode *mcall = mach->as_MachCall(); 506 // This destination address is NOT PC-relative 507 508 mcall->method_set((intptr_t)mcall->entry_point()); 509 510 if (mcall->is_MachCallJava() && mcall->as_MachCallJava()->_method) { 511 stub_size += CompiledDirectCall::to_interp_stub_size(); 512 reloc_size += CompiledDirectCall::reloc_to_interp_stub(); 513 } 514 } else if (mach->is_MachSafePoint()) { 515 // If call/safepoint are adjacent, account for possible 516 // nop to disambiguate the two safepoints. 517 // ScheduleAndBundle() can rearrange nodes in a block, 518 // check for all offsets inside this block. 519 if (last_call_adr >= blk_starts[i]) { 520 blk_size += nop_size; 521 } 522 } 523 if (mach->avoid_back_to_back(MachNode::AVOID_BEFORE)) { 524 // Nop is inserted between "avoid back to back" instructions. 525 // ScheduleAndBundle() can rearrange nodes in a block, 526 // check for all offsets inside this block. 527 if (last_avoid_back_to_back_adr >= blk_starts[i]) { 528 blk_size += nop_size; 529 } 530 } 531 if (mach->may_be_short_branch()) { 532 if (!nj->is_MachBranch()) { 533 #ifndef PRODUCT 534 nj->dump(3); 535 #endif 536 Unimplemented(); 537 } 538 assert(jmp_nidx[i] == -1, "block should have only one branch"); 539 jmp_offset[i] = blk_size; 540 jmp_size[i] = nj->size(C->regalloc()); 541 jmp_nidx[i] = j; 542 has_short_branch_candidate = true; 543 } 544 } 545 blk_size += nj->size(C->regalloc()); 546 // Remember end of call offset 547 if (nj->is_MachCall() && !nj->is_MachCallLeaf()) { 548 last_call_adr = blk_starts[i]+blk_size; 549 } 550 // Remember end of avoid_back_to_back offset 551 if (nj->is_Mach() && nj->as_Mach()->avoid_back_to_back(MachNode::AVOID_AFTER)) { 552 last_avoid_back_to_back_adr = blk_starts[i]+blk_size; 553 } 554 } 555 556 // When the next block starts a loop, we may insert pad NOP 557 // instructions. Since we cannot know our future alignment, 558 // assume the worst. 559 if (i < nblocks - 1) { 560 Block* nb = C->cfg()->get_block(i + 1); 561 int max_loop_pad = nb->code_alignment()-relocInfo::addr_unit(); 562 if (max_loop_pad > 0) { 563 assert(is_power_of_2(max_loop_pad+relocInfo::addr_unit()), ""); 564 // Adjust last_call_adr and/or last_avoid_back_to_back_adr. 565 // If either is the last instruction in this block, bump by 566 // max_loop_pad in lock-step with blk_size, so sizing 567 // calculations in subsequent blocks still can conservatively 568 // detect that it may the last instruction in this block. 569 if (last_call_adr == blk_starts[i]+blk_size) { 570 last_call_adr += max_loop_pad; 571 } 572 if (last_avoid_back_to_back_adr == blk_starts[i]+blk_size) { 573 last_avoid_back_to_back_adr += max_loop_pad; 574 } 575 blk_size += max_loop_pad; 576 block_worst_case_pad[i + 1] = max_loop_pad; 577 } 578 } 579 580 // Save block size; update total method size 581 blk_starts[i+1] = blk_starts[i]+blk_size; 582 } 583 584 // Step two, replace eligible long jumps. 585 bool progress = true; 586 uint last_may_be_short_branch_adr = max_juint; 587 while (has_short_branch_candidate && progress) { 588 progress = false; 589 has_short_branch_candidate = false; 590 int adjust_block_start = 0; 591 for (uint i = 0; i < nblocks; i++) { 592 Block* block = C->cfg()->get_block(i); 593 int idx = jmp_nidx[i]; 594 MachNode* mach = (idx == -1) ? nullptr: block->get_node(idx)->as_Mach(); 595 if (mach != nullptr && mach->may_be_short_branch()) { 596 #ifdef ASSERT 597 assert(jmp_size[i] > 0 && mach->is_MachBranch(), "sanity"); 598 int j; 599 // Find the branch; ignore trailing NOPs. 600 for (j = block->number_of_nodes()-1; j>=0; j--) { 601 Node* n = block->get_node(j); 602 if (!n->is_Mach() || n->as_Mach()->ideal_Opcode() != Op_Con) 603 break; 604 } 605 assert(j >= 0 && j == idx && block->get_node(j) == (Node*)mach, "sanity"); 606 #endif 607 int br_size = jmp_size[i]; 608 int br_offs = blk_starts[i] + jmp_offset[i]; 609 610 // This requires the TRUE branch target be in succs[0] 611 uint bnum = block->non_connector_successor(0)->_pre_order; 612 int offset = blk_starts[bnum] - br_offs; 613 if (bnum > i) { // adjust following block's offset 614 offset -= adjust_block_start; 615 } 616 617 // This block can be a loop header, account for the padding 618 // in the previous block. 619 int block_padding = block_worst_case_pad[i]; 620 assert(i == 0 || block_padding == 0 || br_offs >= block_padding, "Should have at least a padding on top"); 621 // In the following code a nop could be inserted before 622 // the branch which will increase the backward distance. 623 bool needs_padding = ((uint)(br_offs - block_padding) == last_may_be_short_branch_adr); 624 assert(!needs_padding || jmp_offset[i] == 0, "padding only branches at the beginning of block"); 625 626 if (needs_padding && offset <= 0) 627 offset -= nop_size; 628 629 if (C->matcher()->is_short_branch_offset(mach->rule(), br_size, offset)) { 630 // We've got a winner. Replace this branch. 631 MachNode* replacement = mach->as_MachBranch()->short_branch_version(); 632 633 // Update the jmp_size. 634 int new_size = replacement->size(C->regalloc()); 635 int diff = br_size - new_size; 636 assert(diff >= (int)nop_size, "short_branch size should be smaller"); 637 // Conservatively take into account padding between 638 // avoid_back_to_back branches. Previous branch could be 639 // converted into avoid_back_to_back branch during next 640 // rounds. 641 if (needs_padding && replacement->avoid_back_to_back(MachNode::AVOID_BEFORE)) { 642 jmp_offset[i] += nop_size; 643 diff -= nop_size; 644 } 645 adjust_block_start += diff; 646 block->map_node(replacement, idx); 647 mach->subsume_by(replacement, C); 648 mach = replacement; 649 progress = true; 650 651 jmp_size[i] = new_size; 652 DEBUG_ONLY( jmp_target[i] = bnum; ); 653 DEBUG_ONLY( jmp_rule[i] = mach->rule(); ); 654 } else { 655 // The jump distance is not short, try again during next iteration. 656 has_short_branch_candidate = true; 657 } 658 } // (mach->may_be_short_branch()) 659 if (mach != nullptr && (mach->may_be_short_branch() || 660 mach->avoid_back_to_back(MachNode::AVOID_AFTER))) { 661 last_may_be_short_branch_adr = blk_starts[i] + jmp_offset[i] + jmp_size[i]; 662 } 663 blk_starts[i+1] -= adjust_block_start; 664 } 665 } 666 667 #ifdef ASSERT 668 for (uint i = 0; i < nblocks; i++) { // For all blocks 669 if (jmp_target[i] != 0) { 670 int br_size = jmp_size[i]; 671 int offset = blk_starts[jmp_target[i]]-(blk_starts[i] + jmp_offset[i]); 672 if (!C->matcher()->is_short_branch_offset(jmp_rule[i], br_size, offset)) { 673 tty->print_cr("target (%d) - jmp_offset(%d) = offset (%d), jump_size(%d), jmp_block B%d, target_block B%d", blk_starts[jmp_target[i]], blk_starts[i] + jmp_offset[i], offset, br_size, i, jmp_target[i]); 674 } 675 assert(C->matcher()->is_short_branch_offset(jmp_rule[i], br_size, offset), "Displacement too large for short jmp"); 676 } 677 } 678 #endif 679 680 // Step 3, compute the offsets of all blocks, will be done in fill_buffer() 681 // after ScheduleAndBundle(). 682 683 // ------------------ 684 // Compute size for code buffer 685 code_size = blk_starts[nblocks]; 686 687 // Relocation records 688 reloc_size += 1; // Relo entry for exception handler 689 690 // Adjust reloc_size to number of record of relocation info 691 // Min is 2 bytes, max is probably 6 or 8, with a tax up to 25% for 692 // a relocation index. 693 // The CodeBuffer will expand the locs array if this estimate is too low. 694 reloc_size *= 10 / sizeof(relocInfo); 695 696 _buf_sizes._reloc = reloc_size; 697 _buf_sizes._code = code_size; 698 _buf_sizes._stub = stub_size; 699 } 700 701 //------------------------------FillLocArray----------------------------------- 702 // Create a bit of debug info and append it to the array. The mapping is from 703 // Java local or expression stack to constant, register or stack-slot. For 704 // doubles, insert 2 mappings and return 1 (to tell the caller that the next 705 // entry has been taken care of and caller should skip it). 706 static LocationValue *new_loc_value( PhaseRegAlloc *ra, OptoReg::Name regnum, Location::Type l_type ) { 707 // This should never have accepted Bad before 708 assert(OptoReg::is_valid(regnum), "location must be valid"); 709 return (OptoReg::is_reg(regnum)) 710 ? new LocationValue(Location::new_reg_loc(l_type, OptoReg::as_VMReg(regnum)) ) 711 : new LocationValue(Location::new_stk_loc(l_type, ra->reg2offset(regnum))); 712 } 713 714 715 ObjectValue* 716 PhaseOutput::sv_for_node_id(GrowableArray<ScopeValue*> *objs, int id) { 717 for (int i = 0; i < objs->length(); i++) { 718 assert(objs->at(i)->is_object(), "corrupt object cache"); 719 ObjectValue* sv = objs->at(i)->as_ObjectValue(); 720 if (sv->id() == id) { 721 return sv; 722 } 723 } 724 // Otherwise.. 725 return nullptr; 726 } 727 728 void PhaseOutput::set_sv_for_object_node(GrowableArray<ScopeValue*> *objs, 729 ObjectValue* sv ) { 730 assert(sv_for_node_id(objs, sv->id()) == nullptr, "Precondition"); 731 objs->append(sv); 732 } 733 734 735 void PhaseOutput::FillLocArray( int idx, MachSafePointNode* sfpt, Node *local, 736 GrowableArray<ScopeValue*> *array, 737 GrowableArray<ScopeValue*> *objs ) { 738 assert( local, "use _top instead of null" ); 739 if (array->length() != idx) { 740 assert(array->length() == idx + 1, "Unexpected array count"); 741 // Old functionality: 742 // return 743 // New functionality: 744 // Assert if the local is not top. In product mode let the new node 745 // override the old entry. 746 assert(local == C->top(), "LocArray collision"); 747 if (local == C->top()) { 748 return; 749 } 750 array->pop(); 751 } 752 const Type *t = local->bottom_type(); 753 754 // Is it a safepoint scalar object node? 755 if (local->is_SafePointScalarObject()) { 756 SafePointScalarObjectNode* spobj = local->as_SafePointScalarObject(); 757 758 ObjectValue* sv = sv_for_node_id(objs, spobj->_idx); 759 if (sv == nullptr) { 760 ciKlass* cik = t->is_oopptr()->exact_klass(); 761 assert(cik->is_instance_klass() || 762 cik->is_array_klass(), "Not supported allocation."); 763 sv = new ObjectValue(spobj->_idx, 764 new ConstantOopWriteValue(cik->java_mirror()->constant_encoding())); 765 set_sv_for_object_node(objs, sv); 766 767 uint first_ind = spobj->first_index(sfpt->jvms()); 768 for (uint i = 0; i < spobj->n_fields(); i++) { 769 Node* fld_node = sfpt->in(first_ind+i); 770 (void)FillLocArray(sv->field_values()->length(), sfpt, fld_node, sv->field_values(), objs); 771 } 772 } 773 array->append(sv); 774 return; 775 } else if (local->is_SafePointScalarMerge()) { 776 SafePointScalarMergeNode* smerge = local->as_SafePointScalarMerge(); 777 ObjectMergeValue* mv = (ObjectMergeValue*) sv_for_node_id(objs, smerge->_idx); 778 779 if (mv == nullptr) { 780 GrowableArray<ScopeValue*> deps; 781 782 int merge_pointer_idx = smerge->merge_pointer_idx(sfpt->jvms()); 783 (void)FillLocArray(0, sfpt, sfpt->in(merge_pointer_idx), &deps, objs); 784 assert(deps.length() == 1, "missing value"); 785 786 int selector_idx = smerge->selector_idx(sfpt->jvms()); 787 (void)FillLocArray(1, nullptr, sfpt->in(selector_idx), &deps, nullptr); 788 assert(deps.length() == 2, "missing value"); 789 790 mv = new ObjectMergeValue(smerge->_idx, deps.at(0), deps.at(1)); 791 set_sv_for_object_node(objs, mv); 792 793 for (uint i = 1; i < smerge->req(); i++) { 794 Node* obj_node = smerge->in(i); 795 int idx = mv->possible_objects()->length(); 796 (void)FillLocArray(idx, sfpt, obj_node, mv->possible_objects(), objs); 797 798 // By default ObjectValues that are in 'possible_objects' are not root objects. 799 // They will be marked as root later if they are directly referenced in a JVMS. 800 assert(mv->possible_objects()->length() > idx, "Didn't add entry to possible_objects?!"); 801 assert(mv->possible_objects()->at(idx)->is_object(), "Entries in possible_objects should be ObjectValue."); 802 mv->possible_objects()->at(idx)->as_ObjectValue()->set_root(false); 803 } 804 } 805 array->append(mv); 806 return; 807 } 808 809 // Grab the register number for the local 810 OptoReg::Name regnum = C->regalloc()->get_reg_first(local); 811 if( OptoReg::is_valid(regnum) ) {// Got a register/stack? 812 // Record the double as two float registers. 813 // The register mask for such a value always specifies two adjacent 814 // float registers, with the lower register number even. 815 // Normally, the allocation of high and low words to these registers 816 // is irrelevant, because nearly all operations on register pairs 817 // (e.g., StoreD) treat them as a single unit. 818 // Here, we assume in addition that the words in these two registers 819 // stored "naturally" (by operations like StoreD and double stores 820 // within the interpreter) such that the lower-numbered register 821 // is written to the lower memory address. This may seem like 822 // a machine dependency, but it is not--it is a requirement on 823 // the author of the <arch>.ad file to ensure that, for every 824 // even/odd double-register pair to which a double may be allocated, 825 // the word in the even single-register is stored to the first 826 // memory word. (Note that register numbers are completely 827 // arbitrary, and are not tied to any machine-level encodings.) 828 #ifdef _LP64 829 if( t->base() == Type::DoubleBot || t->base() == Type::DoubleCon ) { 830 array->append(new ConstantIntValue((jint)0)); 831 array->append(new_loc_value( C->regalloc(), regnum, Location::dbl )); 832 } else if ( t->base() == Type::Long ) { 833 array->append(new ConstantIntValue((jint)0)); 834 array->append(new_loc_value( C->regalloc(), regnum, Location::lng )); 835 } else if ( t->base() == Type::RawPtr ) { 836 // jsr/ret return address which must be restored into the full 837 // width 64-bit stack slot. 838 array->append(new_loc_value( C->regalloc(), regnum, Location::lng )); 839 } 840 #else //_LP64 841 if( t->base() == Type::DoubleBot || t->base() == Type::DoubleCon || t->base() == Type::Long ) { 842 // Repack the double/long as two jints. 843 // The convention the interpreter uses is that the second local 844 // holds the first raw word of the native double representation. 845 // This is actually reasonable, since locals and stack arrays 846 // grow downwards in all implementations. 847 // (If, on some machine, the interpreter's Java locals or stack 848 // were to grow upwards, the embedded doubles would be word-swapped.) 849 array->append(new_loc_value( C->regalloc(), OptoReg::add(regnum,1), Location::normal )); 850 array->append(new_loc_value( C->regalloc(), regnum , Location::normal )); 851 } 852 #endif //_LP64 853 else if( (t->base() == Type::FloatBot || t->base() == Type::FloatCon) && 854 OptoReg::is_reg(regnum) ) { 855 array->append(new_loc_value( C->regalloc(), regnum, Matcher::float_in_double() 856 ? Location::float_in_dbl : Location::normal )); 857 } else if( t->base() == Type::Int && OptoReg::is_reg(regnum) ) { 858 array->append(new_loc_value( C->regalloc(), regnum, Matcher::int_in_long 859 ? Location::int_in_long : Location::normal )); 860 } else if( t->base() == Type::NarrowOop ) { 861 array->append(new_loc_value( C->regalloc(), regnum, Location::narrowoop )); 862 } else if (t->base() == Type::VectorA || t->base() == Type::VectorS || 863 t->base() == Type::VectorD || t->base() == Type::VectorX || 864 t->base() == Type::VectorY || t->base() == Type::VectorZ) { 865 array->append(new_loc_value( C->regalloc(), regnum, Location::vector )); 866 } else if (C->regalloc()->is_oop(local)) { 867 assert(t->base() == Type::OopPtr || t->base() == Type::InstPtr || 868 t->base() == Type::AryPtr, 869 "Unexpected type: %s", t->msg()); 870 array->append(new_loc_value( C->regalloc(), regnum, Location::oop )); 871 } else { 872 assert(t->base() == Type::Int || t->base() == Type::Half || 873 t->base() == Type::FloatCon || t->base() == Type::FloatBot, 874 "Unexpected type: %s", t->msg()); 875 array->append(new_loc_value( C->regalloc(), regnum, Location::normal )); 876 } 877 return; 878 } 879 880 // No register. It must be constant data. 881 switch (t->base()) { 882 case Type::Half: // Second half of a double 883 ShouldNotReachHere(); // Caller should skip 2nd halves 884 break; 885 case Type::AnyPtr: 886 array->append(new ConstantOopWriteValue(nullptr)); 887 break; 888 case Type::AryPtr: 889 case Type::InstPtr: // fall through 890 array->append(new ConstantOopWriteValue(t->isa_oopptr()->const_oop()->constant_encoding())); 891 break; 892 case Type::NarrowOop: 893 if (t == TypeNarrowOop::NULL_PTR) { 894 array->append(new ConstantOopWriteValue(nullptr)); 895 } else { 896 array->append(new ConstantOopWriteValue(t->make_ptr()->isa_oopptr()->const_oop()->constant_encoding())); 897 } 898 break; 899 case Type::Int: 900 array->append(new ConstantIntValue(t->is_int()->get_con())); 901 break; 902 case Type::RawPtr: 903 // A return address (T_ADDRESS). 904 assert((intptr_t)t->is_ptr()->get_con() < (intptr_t)0x10000, "must be a valid BCI"); 905 #ifdef _LP64 906 // Must be restored to the full-width 64-bit stack slot. 907 array->append(new ConstantLongValue(t->is_ptr()->get_con())); 908 #else 909 array->append(new ConstantIntValue(t->is_ptr()->get_con())); 910 #endif 911 break; 912 case Type::FloatCon: { 913 float f = t->is_float_constant()->getf(); 914 array->append(new ConstantIntValue(jint_cast(f))); 915 break; 916 } 917 case Type::DoubleCon: { 918 jdouble d = t->is_double_constant()->getd(); 919 #ifdef _LP64 920 array->append(new ConstantIntValue((jint)0)); 921 array->append(new ConstantDoubleValue(d)); 922 #else 923 // Repack the double as two jints. 924 // The convention the interpreter uses is that the second local 925 // holds the first raw word of the native double representation. 926 // This is actually reasonable, since locals and stack arrays 927 // grow downwards in all implementations. 928 // (If, on some machine, the interpreter's Java locals or stack 929 // were to grow upwards, the embedded doubles would be word-swapped.) 930 jlong_accessor acc; 931 acc.long_value = jlong_cast(d); 932 array->append(new ConstantIntValue(acc.words[1])); 933 array->append(new ConstantIntValue(acc.words[0])); 934 #endif 935 break; 936 } 937 case Type::Long: { 938 jlong d = t->is_long()->get_con(); 939 #ifdef _LP64 940 array->append(new ConstantIntValue((jint)0)); 941 array->append(new ConstantLongValue(d)); 942 #else 943 // Repack the long as two jints. 944 // The convention the interpreter uses is that the second local 945 // holds the first raw word of the native double representation. 946 // This is actually reasonable, since locals and stack arrays 947 // grow downwards in all implementations. 948 // (If, on some machine, the interpreter's Java locals or stack 949 // were to grow upwards, the embedded doubles would be word-swapped.) 950 jlong_accessor acc; 951 acc.long_value = d; 952 array->append(new ConstantIntValue(acc.words[1])); 953 array->append(new ConstantIntValue(acc.words[0])); 954 #endif 955 break; 956 } 957 case Type::Top: // Add an illegal value here 958 array->append(new LocationValue(Location())); 959 break; 960 default: 961 ShouldNotReachHere(); 962 break; 963 } 964 } 965 966 // Determine if this node starts a bundle 967 bool PhaseOutput::starts_bundle(const Node *n) const { 968 return (_node_bundling_limit > n->_idx && 969 _node_bundling_base[n->_idx].starts_bundle()); 970 } 971 972 // Determine if there is a monitor that has 'ov' as its owner. 973 bool PhaseOutput::contains_as_owner(GrowableArray<MonitorValue*> *monarray, ObjectValue *ov) const { 974 for (int k = 0; k < monarray->length(); k++) { 975 MonitorValue* mv = monarray->at(k); 976 if (mv->owner() == ov) { 977 return true; 978 } 979 } 980 981 return false; 982 } 983 984 // Determine if there is a scalar replaced object description represented by 'ov'. 985 bool PhaseOutput::contains_as_scalarized_obj(JVMState* jvms, MachSafePointNode* sfn, 986 GrowableArray<ScopeValue*>* objs, 987 ObjectValue* ov) const { 988 for (int i = 0; i < jvms->scl_size(); i++) { 989 Node* n = sfn->scalarized_obj(jvms, i); 990 // Other kinds of nodes that we may encounter here, for instance constants 991 // representing values of fields of objects scalarized, aren't relevant for 992 // us, since they don't map to ObjectValue. 993 if (!n->is_SafePointScalarObject()) { 994 continue; 995 } 996 997 ObjectValue* other = sv_for_node_id(objs, n->_idx); 998 if (ov == other) { 999 return true; 1000 } 1001 } 1002 return false; 1003 } 1004 1005 //--------------------------Process_OopMap_Node-------------------------------- 1006 void PhaseOutput::Process_OopMap_Node(MachNode *mach, int current_offset) { 1007 // Handle special safepoint nodes for synchronization 1008 MachSafePointNode *sfn = mach->as_MachSafePoint(); 1009 MachCallNode *mcall; 1010 1011 int safepoint_pc_offset = current_offset; 1012 bool is_method_handle_invoke = false; 1013 bool return_oop = false; 1014 bool has_ea_local_in_scope = sfn->_has_ea_local_in_scope; 1015 bool arg_escape = false; 1016 1017 // Add the safepoint in the DebugInfoRecorder 1018 if( !mach->is_MachCall() ) { 1019 mcall = nullptr; 1020 C->debug_info()->add_safepoint(safepoint_pc_offset, sfn->_oop_map); 1021 } else { 1022 mcall = mach->as_MachCall(); 1023 1024 // Is the call a MethodHandle call? 1025 if (mcall->is_MachCallJava()) { 1026 if (mcall->as_MachCallJava()->_method_handle_invoke) { 1027 assert(C->has_method_handle_invokes(), "must have been set during call generation"); 1028 is_method_handle_invoke = true; 1029 } 1030 arg_escape = mcall->as_MachCallJava()->_arg_escape; 1031 } 1032 1033 // Check if a call returns an object. 1034 if (mcall->returns_pointer()) { 1035 return_oop = true; 1036 } 1037 safepoint_pc_offset += mcall->ret_addr_offset(); 1038 C->debug_info()->add_safepoint(safepoint_pc_offset, mcall->_oop_map); 1039 } 1040 1041 // Loop over the JVMState list to add scope information 1042 // Do not skip safepoints with a null method, they need monitor info 1043 JVMState* youngest_jvms = sfn->jvms(); 1044 int max_depth = youngest_jvms->depth(); 1045 1046 // Allocate the object pool for scalar-replaced objects -- the map from 1047 // small-integer keys (which can be recorded in the local and ostack 1048 // arrays) to descriptions of the object state. 1049 GrowableArray<ScopeValue*> *objs = new GrowableArray<ScopeValue*>(); 1050 1051 // Visit scopes from oldest to youngest. 1052 for (int depth = 1; depth <= max_depth; depth++) { 1053 JVMState* jvms = youngest_jvms->of_depth(depth); 1054 int idx; 1055 ciMethod* method = jvms->has_method() ? jvms->method() : nullptr; 1056 // Safepoints that do not have method() set only provide oop-map and monitor info 1057 // to support GC; these do not support deoptimization. 1058 int num_locs = (method == nullptr) ? 0 : jvms->loc_size(); 1059 int num_exps = (method == nullptr) ? 0 : jvms->stk_size(); 1060 int num_mon = jvms->nof_monitors(); 1061 assert(method == nullptr || jvms->bci() < 0 || num_locs == method->max_locals(), 1062 "JVMS local count must match that of the method"); 1063 1064 // Add Local and Expression Stack Information 1065 1066 // Insert locals into the locarray 1067 GrowableArray<ScopeValue*> *locarray = new GrowableArray<ScopeValue*>(num_locs); 1068 for( idx = 0; idx < num_locs; idx++ ) { 1069 FillLocArray( idx, sfn, sfn->local(jvms, idx), locarray, objs ); 1070 } 1071 1072 // Insert expression stack entries into the exparray 1073 GrowableArray<ScopeValue*> *exparray = new GrowableArray<ScopeValue*>(num_exps); 1074 for( idx = 0; idx < num_exps; idx++ ) { 1075 FillLocArray( idx, sfn, sfn->stack(jvms, idx), exparray, objs ); 1076 } 1077 1078 // Add in mappings of the monitors 1079 assert( !method || 1080 !method->is_synchronized() || 1081 method->is_native() || 1082 num_mon > 0 || 1083 !GenerateSynchronizationCode, 1084 "monitors must always exist for synchronized methods"); 1085 1086 // Build the growable array of ScopeValues for exp stack 1087 GrowableArray<MonitorValue*> *monarray = new GrowableArray<MonitorValue*>(num_mon); 1088 1089 // Loop over monitors and insert into array 1090 for (idx = 0; idx < num_mon; idx++) { 1091 // Grab the node that defines this monitor 1092 Node* box_node = sfn->monitor_box(jvms, idx); 1093 Node* obj_node = sfn->monitor_obj(jvms, idx); 1094 1095 // Create ScopeValue for object 1096 ScopeValue *scval = nullptr; 1097 1098 if (obj_node->is_SafePointScalarObject()) { 1099 SafePointScalarObjectNode* spobj = obj_node->as_SafePointScalarObject(); 1100 scval = PhaseOutput::sv_for_node_id(objs, spobj->_idx); 1101 if (scval == nullptr) { 1102 const Type *t = spobj->bottom_type(); 1103 ciKlass* cik = t->is_oopptr()->exact_klass(); 1104 assert(cik->is_instance_klass() || 1105 cik->is_array_klass(), "Not supported allocation."); 1106 ObjectValue* sv = new ObjectValue(spobj->_idx, 1107 new ConstantOopWriteValue(cik->java_mirror()->constant_encoding())); 1108 PhaseOutput::set_sv_for_object_node(objs, sv); 1109 1110 uint first_ind = spobj->first_index(youngest_jvms); 1111 for (uint i = 0; i < spobj->n_fields(); i++) { 1112 Node* fld_node = sfn->in(first_ind+i); 1113 (void)FillLocArray(sv->field_values()->length(), sfn, fld_node, sv->field_values(), objs); 1114 } 1115 scval = sv; 1116 } 1117 } else if (obj_node->is_SafePointScalarMerge()) { 1118 SafePointScalarMergeNode* smerge = obj_node->as_SafePointScalarMerge(); 1119 ObjectMergeValue* mv = (ObjectMergeValue*) sv_for_node_id(objs, smerge->_idx); 1120 1121 if (mv == nullptr) { 1122 GrowableArray<ScopeValue*> deps; 1123 1124 int merge_pointer_idx = smerge->merge_pointer_idx(youngest_jvms); 1125 FillLocArray(0, sfn, sfn->in(merge_pointer_idx), &deps, objs); 1126 assert(deps.length() == 1, "missing value"); 1127 1128 int selector_idx = smerge->selector_idx(youngest_jvms); 1129 FillLocArray(1, nullptr, sfn->in(selector_idx), &deps, nullptr); 1130 assert(deps.length() == 2, "missing value"); 1131 1132 mv = new ObjectMergeValue(smerge->_idx, deps.at(0), deps.at(1)); 1133 set_sv_for_object_node(objs, mv); 1134 1135 for (uint i = 1; i < smerge->req(); i++) { 1136 Node* obj_node = smerge->in(i); 1137 int idx = mv->possible_objects()->length(); 1138 (void)FillLocArray(idx, sfn, obj_node, mv->possible_objects(), objs); 1139 1140 // By default ObjectValues that are in 'possible_objects' are not root objects. 1141 // They will be marked as root later if they are directly referenced in a JVMS. 1142 assert(mv->possible_objects()->length() > idx, "Didn't add entry to possible_objects?!"); 1143 assert(mv->possible_objects()->at(idx)->is_object(), "Entries in possible_objects should be ObjectValue."); 1144 mv->possible_objects()->at(idx)->as_ObjectValue()->set_root(false); 1145 } 1146 } 1147 scval = mv; 1148 } else if (!obj_node->is_Con()) { 1149 OptoReg::Name obj_reg = C->regalloc()->get_reg_first(obj_node); 1150 if( obj_node->bottom_type()->base() == Type::NarrowOop ) { 1151 scval = new_loc_value( C->regalloc(), obj_reg, Location::narrowoop ); 1152 } else { 1153 scval = new_loc_value( C->regalloc(), obj_reg, Location::oop ); 1154 } 1155 } else { 1156 const TypePtr *tp = obj_node->get_ptr_type(); 1157 scval = new ConstantOopWriteValue(tp->is_oopptr()->const_oop()->constant_encoding()); 1158 } 1159 1160 OptoReg::Name box_reg = BoxLockNode::reg(box_node); 1161 Location basic_lock = Location::new_stk_loc(Location::normal,C->regalloc()->reg2offset(box_reg)); 1162 bool eliminated = (box_node->is_BoxLock() && box_node->as_BoxLock()->is_eliminated()); 1163 monarray->append(new MonitorValue(scval, basic_lock, eliminated)); 1164 } 1165 1166 // Mark ObjectValue nodes as root nodes if they are directly 1167 // referenced in the JVMS. 1168 for (int i = 0; i < objs->length(); i++) { 1169 ScopeValue* sv = objs->at(i); 1170 if (sv->is_object_merge()) { 1171 ObjectMergeValue* merge = sv->as_ObjectMergeValue(); 1172 1173 for (int j = 0; j< merge->possible_objects()->length(); j++) { 1174 ObjectValue* ov = merge->possible_objects()->at(j)->as_ObjectValue(); 1175 if (ov->is_root()) { 1176 // Already flagged as 'root' by something else. We shouldn't change it 1177 // to non-root in a younger JVMS because it may need to be alive in 1178 // a younger JVMS. 1179 } else { 1180 bool is_root = locarray->contains(ov) || 1181 exparray->contains(ov) || 1182 contains_as_owner(monarray, ov) || 1183 contains_as_scalarized_obj(jvms, sfn, objs, ov); 1184 ov->set_root(is_root); 1185 } 1186 } 1187 } 1188 } 1189 1190 // We dump the object pool first, since deoptimization reads it in first. 1191 C->debug_info()->dump_object_pool(objs); 1192 1193 // Build first class objects to pass to scope 1194 DebugToken *locvals = C->debug_info()->create_scope_values(locarray); 1195 DebugToken *expvals = C->debug_info()->create_scope_values(exparray); 1196 DebugToken *monvals = C->debug_info()->create_monitor_values(monarray); 1197 1198 // Make method available for all Safepoints 1199 ciMethod* scope_method = method ? method : C->method(); 1200 // Describe the scope here 1201 assert(jvms->bci() >= InvocationEntryBci && jvms->bci() <= 0x10000, "must be a valid or entry BCI"); 1202 assert(!jvms->should_reexecute() || depth == max_depth, "reexecute allowed only for the youngest"); 1203 // Now we can describe the scope. 1204 methodHandle null_mh; 1205 bool rethrow_exception = false; 1206 C->debug_info()->describe_scope( 1207 safepoint_pc_offset, 1208 null_mh, 1209 scope_method, 1210 jvms->bci(), 1211 jvms->should_reexecute(), 1212 rethrow_exception, 1213 is_method_handle_invoke, 1214 return_oop, 1215 has_ea_local_in_scope, 1216 arg_escape, 1217 locvals, 1218 expvals, 1219 monvals 1220 ); 1221 } // End jvms loop 1222 1223 // Mark the end of the scope set. 1224 C->debug_info()->end_safepoint(safepoint_pc_offset); 1225 } 1226 1227 1228 1229 // A simplified version of Process_OopMap_Node, to handle non-safepoints. 1230 class NonSafepointEmitter { 1231 Compile* C; 1232 JVMState* _pending_jvms; 1233 int _pending_offset; 1234 1235 void emit_non_safepoint(); 1236 1237 public: 1238 NonSafepointEmitter(Compile* compile) { 1239 this->C = compile; 1240 _pending_jvms = nullptr; 1241 _pending_offset = 0; 1242 } 1243 1244 void observe_instruction(Node* n, int pc_offset) { 1245 if (!C->debug_info()->recording_non_safepoints()) return; 1246 1247 Node_Notes* nn = C->node_notes_at(n->_idx); 1248 if (nn == nullptr || nn->jvms() == nullptr) return; 1249 if (_pending_jvms != nullptr && 1250 _pending_jvms->same_calls_as(nn->jvms())) { 1251 // Repeated JVMS? Stretch it up here. 1252 _pending_offset = pc_offset; 1253 } else { 1254 if (_pending_jvms != nullptr && 1255 _pending_offset < pc_offset) { 1256 emit_non_safepoint(); 1257 } 1258 _pending_jvms = nullptr; 1259 if (pc_offset > C->debug_info()->last_pc_offset()) { 1260 // This is the only way _pending_jvms can become non-null: 1261 _pending_jvms = nn->jvms(); 1262 _pending_offset = pc_offset; 1263 } 1264 } 1265 } 1266 1267 // Stay out of the way of real safepoints: 1268 void observe_safepoint(JVMState* jvms, int pc_offset) { 1269 if (_pending_jvms != nullptr && 1270 !_pending_jvms->same_calls_as(jvms) && 1271 _pending_offset < pc_offset) { 1272 emit_non_safepoint(); 1273 } 1274 _pending_jvms = nullptr; 1275 } 1276 1277 void flush_at_end() { 1278 if (_pending_jvms != nullptr) { 1279 emit_non_safepoint(); 1280 } 1281 _pending_jvms = nullptr; 1282 } 1283 }; 1284 1285 void NonSafepointEmitter::emit_non_safepoint() { 1286 JVMState* youngest_jvms = _pending_jvms; 1287 int pc_offset = _pending_offset; 1288 1289 // Clear it now: 1290 _pending_jvms = nullptr; 1291 1292 DebugInformationRecorder* debug_info = C->debug_info(); 1293 assert(debug_info->recording_non_safepoints(), "sanity"); 1294 1295 debug_info->add_non_safepoint(pc_offset); 1296 int max_depth = youngest_jvms->depth(); 1297 1298 // Visit scopes from oldest to youngest. 1299 for (int depth = 1; depth <= max_depth; depth++) { 1300 JVMState* jvms = youngest_jvms->of_depth(depth); 1301 ciMethod* method = jvms->has_method() ? jvms->method() : nullptr; 1302 assert(!jvms->should_reexecute() || depth==max_depth, "reexecute allowed only for the youngest"); 1303 methodHandle null_mh; 1304 debug_info->describe_scope(pc_offset, null_mh, method, jvms->bci(), jvms->should_reexecute()); 1305 } 1306 1307 // Mark the end of the scope set. 1308 debug_info->end_non_safepoint(pc_offset); 1309 } 1310 1311 //------------------------------init_buffer------------------------------------ 1312 void PhaseOutput::estimate_buffer_size(int& const_req) { 1313 1314 // Set the initially allocated size 1315 const_req = initial_const_capacity; 1316 1317 // The extra spacing after the code is necessary on some platforms. 1318 // Sometimes we need to patch in a jump after the last instruction, 1319 // if the nmethod has been deoptimized. (See 4932387, 4894843.) 1320 1321 // Compute the byte offset where we can store the deopt pc. 1322 if (C->fixed_slots() != 0) { 1323 _orig_pc_slot_offset_in_bytes = C->regalloc()->reg2offset(OptoReg::stack2reg(_orig_pc_slot)); 1324 } 1325 1326 // Compute prolog code size 1327 _frame_slots = OptoReg::reg2stack(C->matcher()->_old_SP) + C->regalloc()->_framesize; 1328 assert(_frame_slots >= 0 && _frame_slots < 1000000, "sanity check"); 1329 1330 if (C->has_mach_constant_base_node()) { 1331 uint add_size = 0; 1332 // Fill the constant table. 1333 // Note: This must happen before shorten_branches. 1334 for (uint i = 0; i < C->cfg()->number_of_blocks(); i++) { 1335 Block* b = C->cfg()->get_block(i); 1336 1337 for (uint j = 0; j < b->number_of_nodes(); j++) { 1338 Node* n = b->get_node(j); 1339 1340 // If the node is a MachConstantNode evaluate the constant 1341 // value section. 1342 if (n->is_MachConstant()) { 1343 MachConstantNode* machcon = n->as_MachConstant(); 1344 machcon->eval_constant(C); 1345 } else if (n->is_Mach()) { 1346 // On Power there are more nodes that issue constants. 1347 add_size += (n->as_Mach()->ins_num_consts() * 8); 1348 } 1349 } 1350 } 1351 1352 // Calculate the offsets of the constants and the size of the 1353 // constant table (including the padding to the next section). 1354 constant_table().calculate_offsets_and_size(); 1355 const_req = constant_table().size() + add_size; 1356 } 1357 1358 // Initialize the space for the BufferBlob used to find and verify 1359 // instruction size in MachNode::emit_size() 1360 init_scratch_buffer_blob(const_req); 1361 } 1362 1363 CodeBuffer* PhaseOutput::init_buffer() { 1364 int stub_req = _buf_sizes._stub; 1365 int code_req = _buf_sizes._code; 1366 int const_req = _buf_sizes._const; 1367 1368 int pad_req = NativeCall::byte_size(); 1369 1370 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2(); 1371 stub_req += bs->estimate_stub_size(); 1372 1373 // nmethod and CodeBuffer count stubs & constants as part of method's code. 1374 // class HandlerImpl is platform-specific and defined in the *.ad files. 1375 int exception_handler_req = HandlerImpl::size_exception_handler() + MAX_stubs_size; // add marginal slop for handler 1376 int deopt_handler_req = HandlerImpl::size_deopt_handler() + MAX_stubs_size; // add marginal slop for handler 1377 stub_req += MAX_stubs_size; // ensure per-stub margin 1378 code_req += MAX_inst_size; // ensure per-instruction margin 1379 1380 if (StressCodeBuffers) 1381 code_req = const_req = stub_req = exception_handler_req = deopt_handler_req = 0x10; // force expansion 1382 1383 int total_req = 1384 const_req + 1385 code_req + 1386 pad_req + 1387 stub_req + 1388 exception_handler_req + 1389 deopt_handler_req; // deopt handler 1390 1391 if (C->has_method_handle_invokes()) 1392 total_req += deopt_handler_req; // deopt MH handler 1393 1394 CodeBuffer* cb = code_buffer(); 1395 cb->initialize(total_req, _buf_sizes._reloc); 1396 1397 // Have we run out of code space? 1398 if ((cb->blob() == nullptr) || (!CompileBroker::should_compile_new_jobs())) { 1399 C->record_failure("CodeCache is full"); 1400 return nullptr; 1401 } 1402 // Configure the code buffer. 1403 cb->initialize_consts_size(const_req); 1404 cb->initialize_stubs_size(stub_req); 1405 cb->initialize_oop_recorder(C->env()->oop_recorder()); 1406 1407 // fill in the nop array for bundling computations 1408 MachNode *_nop_list[Bundle::_nop_count]; 1409 Bundle::initialize_nops(_nop_list); 1410 1411 return cb; 1412 } 1413 1414 //------------------------------fill_buffer------------------------------------ 1415 void PhaseOutput::fill_buffer(C2_MacroAssembler* masm, uint* blk_starts) { 1416 // blk_starts[] contains offsets calculated during short branches processing, 1417 // offsets should not be increased during following steps. 1418 1419 // Compute the size of first NumberOfLoopInstrToAlign instructions at head 1420 // of a loop. It is used to determine the padding for loop alignment. 1421 Compile::TracePhase tp(_t_fillBuffer); 1422 1423 compute_loop_first_inst_sizes(); 1424 1425 // Create oopmap set. 1426 _oop_map_set = new OopMapSet(); 1427 1428 // !!!!! This preserves old handling of oopmaps for now 1429 C->debug_info()->set_oopmaps(_oop_map_set); 1430 1431 uint nblocks = C->cfg()->number_of_blocks(); 1432 // Count and start of implicit null check instructions 1433 uint inct_cnt = 0; 1434 uint* inct_starts = NEW_RESOURCE_ARRAY(uint, nblocks+1); 1435 1436 // Count and start of calls 1437 uint* call_returns = NEW_RESOURCE_ARRAY(uint, nblocks+1); 1438 1439 uint return_offset = 0; 1440 int nop_size = (new MachNopNode())->size(C->regalloc()); 1441 1442 int previous_offset = 0; 1443 int current_offset = 0; 1444 int last_call_offset = -1; 1445 int last_avoid_back_to_back_offset = -1; 1446 #ifdef ASSERT 1447 uint* jmp_target = NEW_RESOURCE_ARRAY(uint,nblocks); 1448 uint* jmp_offset = NEW_RESOURCE_ARRAY(uint,nblocks); 1449 uint* jmp_size = NEW_RESOURCE_ARRAY(uint,nblocks); 1450 uint* jmp_rule = NEW_RESOURCE_ARRAY(uint,nblocks); 1451 #endif 1452 1453 // Create an array of unused labels, one for each basic block, if printing is enabled 1454 #if defined(SUPPORT_OPTO_ASSEMBLY) 1455 int* node_offsets = nullptr; 1456 uint node_offset_limit = C->unique(); 1457 1458 if (C->print_assembly()) { 1459 node_offsets = NEW_RESOURCE_ARRAY(int, node_offset_limit); 1460 } 1461 if (node_offsets != nullptr) { 1462 // We need to initialize. Unused array elements may contain garbage and mess up PrintOptoAssembly. 1463 memset(node_offsets, 0, node_offset_limit*sizeof(int)); 1464 } 1465 #endif 1466 1467 NonSafepointEmitter non_safepoints(C); // emit non-safepoints lazily 1468 1469 // Emit the constant table. 1470 if (C->has_mach_constant_base_node()) { 1471 if (!constant_table().emit(masm)) { 1472 C->record_failure("consts section overflow"); 1473 return; 1474 } 1475 } 1476 1477 // Create an array of labels, one for each basic block 1478 Label* blk_labels = NEW_RESOURCE_ARRAY(Label, nblocks+1); 1479 for (uint i = 0; i <= nblocks; i++) { 1480 blk_labels[i].init(); 1481 } 1482 1483 // Now fill in the code buffer 1484 Node* delay_slot = nullptr; 1485 for (uint i = 0; i < nblocks; i++) { 1486 Block* block = C->cfg()->get_block(i); 1487 _block = block; 1488 Node* head = block->head(); 1489 1490 // If this block needs to start aligned (i.e, can be reached other 1491 // than by falling-thru from the previous block), then force the 1492 // start of a new bundle. 1493 if (Pipeline::requires_bundling() && starts_bundle(head)) { 1494 masm->code()->flush_bundle(true); 1495 } 1496 1497 #ifdef ASSERT 1498 if (!block->is_connector()) { 1499 stringStream st; 1500 block->dump_head(C->cfg(), &st); 1501 masm->block_comment(st.freeze()); 1502 } 1503 jmp_target[i] = 0; 1504 jmp_offset[i] = 0; 1505 jmp_size[i] = 0; 1506 jmp_rule[i] = 0; 1507 #endif 1508 int blk_offset = current_offset; 1509 1510 // Define the label at the beginning of the basic block 1511 masm->bind(blk_labels[block->_pre_order]); 1512 1513 uint last_inst = block->number_of_nodes(); 1514 1515 // Emit block normally, except for last instruction. 1516 // Emit means "dump code bits into code buffer". 1517 for (uint j = 0; j<last_inst; j++) { 1518 _index = j; 1519 1520 // Get the node 1521 Node* n = block->get_node(j); 1522 1523 // See if delay slots are supported 1524 if (valid_bundle_info(n) && node_bundling(n)->used_in_unconditional_delay()) { 1525 assert(delay_slot == nullptr, "no use of delay slot node"); 1526 assert(n->size(C->regalloc()) == Pipeline::instr_unit_size(), "delay slot instruction wrong size"); 1527 1528 delay_slot = n; 1529 continue; 1530 } 1531 1532 // If this starts a new instruction group, then flush the current one 1533 // (but allow split bundles) 1534 if (Pipeline::requires_bundling() && starts_bundle(n)) 1535 masm->code()->flush_bundle(false); 1536 1537 // Special handling for SafePoint/Call Nodes 1538 bool is_mcall = false; 1539 if (n->is_Mach()) { 1540 MachNode *mach = n->as_Mach(); 1541 is_mcall = n->is_MachCall(); 1542 bool is_sfn = n->is_MachSafePoint(); 1543 1544 // If this requires all previous instructions be flushed, then do so 1545 if (is_sfn || is_mcall || mach->alignment_required() != 1) { 1546 masm->code()->flush_bundle(true); 1547 current_offset = masm->offset(); 1548 } 1549 1550 // A padding may be needed again since a previous instruction 1551 // could be moved to delay slot. 1552 1553 // align the instruction if necessary 1554 int padding = mach->compute_padding(current_offset); 1555 // Make sure safepoint node for polling is distinct from a call's 1556 // return by adding a nop if needed. 1557 if (is_sfn && !is_mcall && padding == 0 && current_offset == last_call_offset) { 1558 padding = nop_size; 1559 } 1560 if (padding == 0 && mach->avoid_back_to_back(MachNode::AVOID_BEFORE) && 1561 current_offset == last_avoid_back_to_back_offset) { 1562 // Avoid back to back some instructions. 1563 padding = nop_size; 1564 } 1565 1566 if (padding > 0) { 1567 assert((padding % nop_size) == 0, "padding is not a multiple of NOP size"); 1568 int nops_cnt = padding / nop_size; 1569 MachNode *nop = new MachNopNode(nops_cnt); 1570 block->insert_node(nop, j++); 1571 last_inst++; 1572 C->cfg()->map_node_to_block(nop, block); 1573 // Ensure enough space. 1574 masm->code()->insts()->maybe_expand_to_ensure_remaining(MAX_inst_size); 1575 if ((masm->code()->blob() == nullptr) || (!CompileBroker::should_compile_new_jobs())) { 1576 C->record_failure("CodeCache is full"); 1577 return; 1578 } 1579 nop->emit(masm, C->regalloc()); 1580 masm->code()->flush_bundle(true); 1581 current_offset = masm->offset(); 1582 } 1583 1584 bool observe_safepoint = is_sfn; 1585 // Remember the start of the last call in a basic block 1586 if (is_mcall) { 1587 MachCallNode *mcall = mach->as_MachCall(); 1588 1589 // This destination address is NOT PC-relative 1590 mcall->method_set((intptr_t)mcall->entry_point()); 1591 1592 // Save the return address 1593 call_returns[block->_pre_order] = current_offset + mcall->ret_addr_offset(); 1594 1595 observe_safepoint = mcall->guaranteed_safepoint(); 1596 } 1597 1598 // sfn will be valid whenever mcall is valid now because of inheritance 1599 if (observe_safepoint) { 1600 // Handle special safepoint nodes for synchronization 1601 if (!is_mcall) { 1602 MachSafePointNode *sfn = mach->as_MachSafePoint(); 1603 // !!!!! Stubs only need an oopmap right now, so bail out 1604 if (sfn->jvms()->method() == nullptr) { 1605 // Write the oopmap directly to the code blob??!! 1606 continue; 1607 } 1608 } // End synchronization 1609 1610 non_safepoints.observe_safepoint(mach->as_MachSafePoint()->jvms(), 1611 current_offset); 1612 Process_OopMap_Node(mach, current_offset); 1613 } // End if safepoint 1614 1615 // If this is a null check, then add the start of the previous instruction to the list 1616 else if( mach->is_MachNullCheck() ) { 1617 inct_starts[inct_cnt++] = previous_offset; 1618 } 1619 1620 // If this is a branch, then fill in the label with the target BB's label 1621 else if (mach->is_MachBranch()) { 1622 // This requires the TRUE branch target be in succs[0] 1623 uint block_num = block->non_connector_successor(0)->_pre_order; 1624 1625 // Try to replace long branch if delay slot is not used, 1626 // it is mostly for back branches since forward branch's 1627 // distance is not updated yet. 1628 bool delay_slot_is_used = valid_bundle_info(n) && 1629 C->output()->node_bundling(n)->use_unconditional_delay(); 1630 if (!delay_slot_is_used && mach->may_be_short_branch()) { 1631 assert(delay_slot == nullptr, "not expecting delay slot node"); 1632 int br_size = n->size(C->regalloc()); 1633 int offset = blk_starts[block_num] - current_offset; 1634 if (block_num >= i) { 1635 // Current and following block's offset are not 1636 // finalized yet, adjust distance by the difference 1637 // between calculated and final offsets of current block. 1638 offset -= (blk_starts[i] - blk_offset); 1639 } 1640 // In the following code a nop could be inserted before 1641 // the branch which will increase the backward distance. 1642 bool needs_padding = (current_offset == last_avoid_back_to_back_offset); 1643 if (needs_padding && offset <= 0) 1644 offset -= nop_size; 1645 1646 if (C->matcher()->is_short_branch_offset(mach->rule(), br_size, offset)) { 1647 // We've got a winner. Replace this branch. 1648 MachNode* replacement = mach->as_MachBranch()->short_branch_version(); 1649 1650 // Update the jmp_size. 1651 int new_size = replacement->size(C->regalloc()); 1652 assert((br_size - new_size) >= (int)nop_size, "short_branch size should be smaller"); 1653 // Insert padding between avoid_back_to_back branches. 1654 if (needs_padding && replacement->avoid_back_to_back(MachNode::AVOID_BEFORE)) { 1655 MachNode *nop = new MachNopNode(); 1656 block->insert_node(nop, j++); 1657 C->cfg()->map_node_to_block(nop, block); 1658 last_inst++; 1659 nop->emit(masm, C->regalloc()); 1660 masm->code()->flush_bundle(true); 1661 current_offset = masm->offset(); 1662 } 1663 #ifdef ASSERT 1664 jmp_target[i] = block_num; 1665 jmp_offset[i] = current_offset - blk_offset; 1666 jmp_size[i] = new_size; 1667 jmp_rule[i] = mach->rule(); 1668 #endif 1669 block->map_node(replacement, j); 1670 mach->subsume_by(replacement, C); 1671 n = replacement; 1672 mach = replacement; 1673 } 1674 } 1675 mach->as_MachBranch()->label_set( &blk_labels[block_num], block_num ); 1676 } else if (mach->ideal_Opcode() == Op_Jump) { 1677 for (uint h = 0; h < block->_num_succs; h++) { 1678 Block* succs_block = block->_succs[h]; 1679 for (uint j = 1; j < succs_block->num_preds(); j++) { 1680 Node* jpn = succs_block->pred(j); 1681 if (jpn->is_JumpProj() && jpn->in(0) == mach) { 1682 uint block_num = succs_block->non_connector()->_pre_order; 1683 Label *blkLabel = &blk_labels[block_num]; 1684 mach->add_case_label(jpn->as_JumpProj()->proj_no(), blkLabel); 1685 } 1686 } 1687 } 1688 } else if (!n->is_Proj()) { 1689 // Remember the beginning of the previous instruction, in case 1690 // it's followed by a flag-kill and a null-check. Happens on 1691 // Intel all the time, with add-to-memory kind of opcodes. 1692 previous_offset = current_offset; 1693 } 1694 1695 // Not an else-if! 1696 // If this is a trap based cmp then add its offset to the list. 1697 if (mach->is_TrapBasedCheckNode()) { 1698 inct_starts[inct_cnt++] = current_offset; 1699 } 1700 } 1701 1702 // Verify that there is sufficient space remaining 1703 masm->code()->insts()->maybe_expand_to_ensure_remaining(MAX_inst_size); 1704 if ((masm->code()->blob() == nullptr) || (!CompileBroker::should_compile_new_jobs())) { 1705 C->record_failure("CodeCache is full"); 1706 return; 1707 } 1708 1709 // Save the offset for the listing 1710 #if defined(SUPPORT_OPTO_ASSEMBLY) 1711 if ((node_offsets != nullptr) && (n->_idx < node_offset_limit)) { 1712 node_offsets[n->_idx] = masm->offset(); 1713 } 1714 #endif 1715 assert(!C->failing_internal() || C->failure_is_artificial(), "Should not reach here if failing."); 1716 1717 // "Normal" instruction case 1718 DEBUG_ONLY(uint instr_offset = masm->offset()); 1719 n->emit(masm, C->regalloc()); 1720 current_offset = masm->offset(); 1721 1722 // Above we only verified that there is enough space in the instruction section. 1723 // However, the instruction may emit stubs that cause code buffer expansion. 1724 // Bail out here if expansion failed due to a lack of code cache space. 1725 if (C->failing()) { 1726 return; 1727 } 1728 1729 assert(!is_mcall || (call_returns[block->_pre_order] <= (uint)current_offset), 1730 "ret_addr_offset() not within emitted code"); 1731 1732 #ifdef ASSERT 1733 uint n_size = n->size(C->regalloc()); 1734 if (n_size < (current_offset-instr_offset)) { 1735 MachNode* mach = n->as_Mach(); 1736 n->dump(); 1737 mach->dump_format(C->regalloc(), tty); 1738 tty->print_cr(" n_size (%d), current_offset (%d), instr_offset (%d)", n_size, current_offset, instr_offset); 1739 Disassembler::decode(masm->code()->insts_begin() + instr_offset, masm->code()->insts_begin() + current_offset + 1, tty); 1740 tty->print_cr(" ------------------- "); 1741 BufferBlob* blob = this->scratch_buffer_blob(); 1742 address blob_begin = blob->content_begin(); 1743 Disassembler::decode(blob_begin, blob_begin + n_size + 1, tty); 1744 assert(false, "wrong size of mach node"); 1745 } 1746 #endif 1747 non_safepoints.observe_instruction(n, current_offset); 1748 1749 // mcall is last "call" that can be a safepoint 1750 // record it so we can see if a poll will directly follow it 1751 // in which case we'll need a pad to make the PcDesc sites unique 1752 // see 5010568. This can be slightly inaccurate but conservative 1753 // in the case that return address is not actually at current_offset. 1754 // This is a small price to pay. 1755 1756 if (is_mcall) { 1757 last_call_offset = current_offset; 1758 } 1759 1760 if (n->is_Mach() && n->as_Mach()->avoid_back_to_back(MachNode::AVOID_AFTER)) { 1761 // Avoid back to back some instructions. 1762 last_avoid_back_to_back_offset = current_offset; 1763 } 1764 1765 // See if this instruction has a delay slot 1766 if (valid_bundle_info(n) && node_bundling(n)->use_unconditional_delay()) { 1767 guarantee(delay_slot != nullptr, "expecting delay slot node"); 1768 1769 // Back up 1 instruction 1770 masm->code()->set_insts_end(masm->code()->insts_end() - Pipeline::instr_unit_size()); 1771 1772 // Save the offset for the listing 1773 #if defined(SUPPORT_OPTO_ASSEMBLY) 1774 if ((node_offsets != nullptr) && (delay_slot->_idx < node_offset_limit)) { 1775 node_offsets[delay_slot->_idx] = masm->offset(); 1776 } 1777 #endif 1778 1779 // Support a SafePoint in the delay slot 1780 if (delay_slot->is_MachSafePoint()) { 1781 MachNode *mach = delay_slot->as_Mach(); 1782 // !!!!! Stubs only need an oopmap right now, so bail out 1783 if (!mach->is_MachCall() && mach->as_MachSafePoint()->jvms()->method() == nullptr) { 1784 // Write the oopmap directly to the code blob??!! 1785 delay_slot = nullptr; 1786 continue; 1787 } 1788 1789 int adjusted_offset = current_offset - Pipeline::instr_unit_size(); 1790 non_safepoints.observe_safepoint(mach->as_MachSafePoint()->jvms(), 1791 adjusted_offset); 1792 // Generate an OopMap entry 1793 Process_OopMap_Node(mach, adjusted_offset); 1794 } 1795 1796 // Insert the delay slot instruction 1797 delay_slot->emit(masm, C->regalloc()); 1798 1799 // Don't reuse it 1800 delay_slot = nullptr; 1801 } 1802 1803 } // End for all instructions in block 1804 1805 // If the next block is the top of a loop, pad this block out to align 1806 // the loop top a little. Helps prevent pipe stalls at loop back branches. 1807 if (i < nblocks-1) { 1808 Block *nb = C->cfg()->get_block(i + 1); 1809 int padding = nb->alignment_padding(current_offset); 1810 if( padding > 0 ) { 1811 MachNode *nop = new MachNopNode(padding / nop_size); 1812 block->insert_node(nop, block->number_of_nodes()); 1813 C->cfg()->map_node_to_block(nop, block); 1814 nop->emit(masm, C->regalloc()); 1815 current_offset = masm->offset(); 1816 } 1817 } 1818 // Verify that the distance for generated before forward 1819 // short branches is still valid. 1820 guarantee((int)(blk_starts[i+1] - blk_starts[i]) >= (current_offset - blk_offset), "shouldn't increase block size"); 1821 1822 // Save new block start offset 1823 blk_starts[i] = blk_offset; 1824 } // End of for all blocks 1825 blk_starts[nblocks] = current_offset; 1826 1827 non_safepoints.flush_at_end(); 1828 1829 // Offset too large? 1830 if (C->failing()) return; 1831 1832 // Define a pseudo-label at the end of the code 1833 masm->bind( blk_labels[nblocks] ); 1834 1835 // Compute the size of the first block 1836 _first_block_size = blk_labels[1].loc_pos() - blk_labels[0].loc_pos(); 1837 1838 #ifdef ASSERT 1839 for (uint i = 0; i < nblocks; i++) { // For all blocks 1840 if (jmp_target[i] != 0) { 1841 int br_size = jmp_size[i]; 1842 int offset = blk_starts[jmp_target[i]]-(blk_starts[i] + jmp_offset[i]); 1843 if (!C->matcher()->is_short_branch_offset(jmp_rule[i], br_size, offset)) { 1844 tty->print_cr("target (%d) - jmp_offset(%d) = offset (%d), jump_size(%d), jmp_block B%d, target_block B%d", blk_starts[jmp_target[i]], blk_starts[i] + jmp_offset[i], offset, br_size, i, jmp_target[i]); 1845 assert(false, "Displacement too large for short jmp"); 1846 } 1847 } 1848 } 1849 #endif 1850 1851 if (!masm->code()->finalize_stubs()) { 1852 C->record_failure("CodeCache is full"); 1853 return; 1854 } 1855 1856 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2(); 1857 bs->emit_stubs(*masm->code()); 1858 if (C->failing()) return; 1859 1860 // Fill in stubs. 1861 assert(masm->inst_mark() == nullptr, "should be."); 1862 _stub_list.emit(*masm); 1863 if (C->failing()) return; 1864 1865 #ifndef PRODUCT 1866 // Information on the size of the method, without the extraneous code 1867 Scheduling::increment_method_size(masm->offset()); 1868 #endif 1869 1870 // ------------------ 1871 // Fill in exception table entries. 1872 FillExceptionTables(inct_cnt, call_returns, inct_starts, blk_labels); 1873 1874 // Only java methods have exception handlers and deopt handlers 1875 // class HandlerImpl is platform-specific and defined in the *.ad files. 1876 if (C->method()) { 1877 // Emit the exception handler code. 1878 _code_offsets.set_value(CodeOffsets::Exceptions, HandlerImpl::emit_exception_handler(masm)); 1879 if (C->failing()) { 1880 return; // CodeBuffer::expand failed 1881 } 1882 // Emit the deopt handler code. 1883 _code_offsets.set_value(CodeOffsets::Deopt, HandlerImpl::emit_deopt_handler(masm)); 1884 1885 // Emit the MethodHandle deopt handler code (if required). 1886 if (C->has_method_handle_invokes() && !C->failing()) { 1887 // We can use the same code as for the normal deopt handler, we 1888 // just need a different entry point address. 1889 _code_offsets.set_value(CodeOffsets::DeoptMH, HandlerImpl::emit_deopt_handler(masm)); 1890 } 1891 } 1892 1893 // One last check for failed CodeBuffer::expand: 1894 if ((masm->code()->blob() == nullptr) || (!CompileBroker::should_compile_new_jobs())) { 1895 C->record_failure("CodeCache is full"); 1896 return; 1897 } 1898 1899 #if defined(SUPPORT_ABSTRACT_ASSEMBLY) || defined(SUPPORT_ASSEMBLY) || defined(SUPPORT_OPTO_ASSEMBLY) 1900 if (C->print_assembly()) { 1901 tty->cr(); 1902 tty->print_cr("============================= C2-compiled nmethod =============================="); 1903 } 1904 #endif 1905 1906 #if defined(SUPPORT_OPTO_ASSEMBLY) 1907 // Dump the assembly code, including basic-block numbers 1908 if (C->print_assembly()) { 1909 ttyLocker ttyl; // keep the following output all in one block 1910 if (!VMThread::should_terminate()) { // test this under the tty lock 1911 // print_metadata and dump_asm may safepoint which makes us loose the ttylock. 1912 // We call them first and write to a stringStream, then we retake the lock to 1913 // make sure the end tag is coherent, and that xmlStream->pop_tag is done thread safe. 1914 ResourceMark rm; 1915 stringStream method_metadata_str; 1916 if (C->method() != nullptr) { 1917 C->method()->print_metadata(&method_metadata_str); 1918 } 1919 stringStream dump_asm_str; 1920 dump_asm_on(&dump_asm_str, node_offsets, node_offset_limit); 1921 1922 NoSafepointVerifier nsv; 1923 ttyLocker ttyl2; 1924 // This output goes directly to the tty, not the compiler log. 1925 // To enable tools to match it up with the compilation activity, 1926 // be sure to tag this tty output with the compile ID. 1927 if (xtty != nullptr) { 1928 xtty->head("opto_assembly compile_id='%d'%s", C->compile_id(), 1929 C->is_osr_compilation() ? " compile_kind='osr'" : ""); 1930 } 1931 if (C->method() != nullptr) { 1932 tty->print_cr("----------------------- MetaData before Compile_id = %d ------------------------", C->compile_id()); 1933 tty->print_raw(method_metadata_str.freeze()); 1934 } else if (C->stub_name() != nullptr) { 1935 tty->print_cr("----------------------------- RuntimeStub %s -------------------------------", C->stub_name()); 1936 } 1937 tty->cr(); 1938 tty->print_cr("------------------------ OptoAssembly for Compile_id = %d -----------------------", C->compile_id()); 1939 tty->print_raw(dump_asm_str.freeze()); 1940 tty->print_cr("--------------------------------------------------------------------------------"); 1941 if (xtty != nullptr) { 1942 xtty->tail("opto_assembly"); 1943 } 1944 } 1945 } 1946 #endif 1947 } 1948 1949 void PhaseOutput::FillExceptionTables(uint cnt, uint *call_returns, uint *inct_starts, Label *blk_labels) { 1950 _inc_table.set_size(cnt); 1951 1952 uint inct_cnt = 0; 1953 for (uint i = 0; i < C->cfg()->number_of_blocks(); i++) { 1954 Block* block = C->cfg()->get_block(i); 1955 Node *n = nullptr; 1956 int j; 1957 1958 // Find the branch; ignore trailing NOPs. 1959 for (j = block->number_of_nodes() - 1; j >= 0; j--) { 1960 n = block->get_node(j); 1961 if (!n->is_Mach() || n->as_Mach()->ideal_Opcode() != Op_Con) { 1962 break; 1963 } 1964 } 1965 1966 // If we didn't find anything, continue 1967 if (j < 0) { 1968 continue; 1969 } 1970 1971 // Compute ExceptionHandlerTable subtable entry and add it 1972 // (skip empty blocks) 1973 if (n->is_Catch()) { 1974 1975 // Get the offset of the return from the call 1976 uint call_return = call_returns[block->_pre_order]; 1977 #ifdef ASSERT 1978 assert( call_return > 0, "no call seen for this basic block" ); 1979 while (block->get_node(--j)->is_MachProj()) ; 1980 assert(block->get_node(j)->is_MachCall(), "CatchProj must follow call"); 1981 #endif 1982 // last instruction is a CatchNode, find it's CatchProjNodes 1983 int nof_succs = block->_num_succs; 1984 // allocate space 1985 GrowableArray<intptr_t> handler_bcis(nof_succs); 1986 GrowableArray<intptr_t> handler_pcos(nof_succs); 1987 // iterate through all successors 1988 for (int j = 0; j < nof_succs; j++) { 1989 Block* s = block->_succs[j]; 1990 bool found_p = false; 1991 for (uint k = 1; k < s->num_preds(); k++) { 1992 Node* pk = s->pred(k); 1993 if (pk->is_CatchProj() && pk->in(0) == n) { 1994 const CatchProjNode* p = pk->as_CatchProj(); 1995 found_p = true; 1996 // add the corresponding handler bci & pco information 1997 if (p->_con != CatchProjNode::fall_through_index) { 1998 // p leads to an exception handler (and is not fall through) 1999 assert(s == C->cfg()->get_block(s->_pre_order), "bad numbering"); 2000 // no duplicates, please 2001 if (!handler_bcis.contains(p->handler_bci())) { 2002 uint block_num = s->non_connector()->_pre_order; 2003 handler_bcis.append(p->handler_bci()); 2004 handler_pcos.append(blk_labels[block_num].loc_pos()); 2005 } 2006 } 2007 } 2008 } 2009 assert(found_p, "no matching predecessor found"); 2010 // Note: Due to empty block removal, one block may have 2011 // several CatchProj inputs, from the same Catch. 2012 } 2013 2014 // Set the offset of the return from the call 2015 assert(handler_bcis.find(-1) != -1, "must have default handler"); 2016 _handler_table.add_subtable(call_return, &handler_bcis, nullptr, &handler_pcos); 2017 continue; 2018 } 2019 2020 // Handle implicit null exception table updates 2021 if (n->is_MachNullCheck()) { 2022 assert(n->in(1)->as_Mach()->barrier_data() == 0, 2023 "Implicit null checks on memory accesses with barriers are not yet supported"); 2024 uint block_num = block->non_connector_successor(0)->_pre_order; 2025 _inc_table.append(inct_starts[inct_cnt++], blk_labels[block_num].loc_pos()); 2026 continue; 2027 } 2028 // Handle implicit exception table updates: trap instructions. 2029 if (n->is_Mach() && n->as_Mach()->is_TrapBasedCheckNode()) { 2030 uint block_num = block->non_connector_successor(0)->_pre_order; 2031 _inc_table.append(inct_starts[inct_cnt++], blk_labels[block_num].loc_pos()); 2032 continue; 2033 } 2034 } // End of for all blocks fill in exception table entries 2035 } 2036 2037 // Static Variables 2038 #ifndef PRODUCT 2039 uint Scheduling::_total_nop_size = 0; 2040 uint Scheduling::_total_method_size = 0; 2041 uint Scheduling::_total_branches = 0; 2042 uint Scheduling::_total_unconditional_delays = 0; 2043 uint Scheduling::_total_instructions_per_bundle[Pipeline::_max_instrs_per_cycle+1]; 2044 #endif 2045 2046 // Initializer for class Scheduling 2047 2048 Scheduling::Scheduling(Arena *arena, Compile &compile) 2049 : _arena(arena), 2050 _cfg(compile.cfg()), 2051 _regalloc(compile.regalloc()), 2052 _scheduled(arena), 2053 _available(arena), 2054 _reg_node(arena), 2055 _pinch_free_list(arena), 2056 _next_node(nullptr), 2057 _bundle_instr_count(0), 2058 _bundle_cycle_number(0), 2059 _bundle_use(0, 0, resource_count, &_bundle_use_elements[0]) 2060 #ifndef PRODUCT 2061 , _branches(0) 2062 , _unconditional_delays(0) 2063 #endif 2064 { 2065 // Create a MachNopNode 2066 _nop = new MachNopNode(); 2067 2068 // Now that the nops are in the array, save the count 2069 // (but allow entries for the nops) 2070 _node_bundling_limit = compile.unique(); 2071 uint node_max = _regalloc->node_regs_max_index(); 2072 2073 compile.output()->set_node_bundling_limit(_node_bundling_limit); 2074 2075 // This one is persistent within the Compile class 2076 _node_bundling_base = NEW_ARENA_ARRAY(compile.comp_arena(), Bundle, node_max); 2077 2078 // Allocate space for fixed-size arrays 2079 _uses = NEW_ARENA_ARRAY(arena, short, node_max); 2080 _current_latency = NEW_ARENA_ARRAY(arena, unsigned short, node_max); 2081 2082 // Clear the arrays 2083 for (uint i = 0; i < node_max; i++) { 2084 ::new (&_node_bundling_base[i]) Bundle(); 2085 } 2086 memset(_uses, 0, node_max * sizeof(short)); 2087 memset(_current_latency, 0, node_max * sizeof(unsigned short)); 2088 2089 // Clear the bundling information 2090 memcpy(_bundle_use_elements, Pipeline_Use::elaborated_elements, sizeof(Pipeline_Use::elaborated_elements)); 2091 2092 // Get the last node 2093 Block* block = _cfg->get_block(_cfg->number_of_blocks() - 1); 2094 2095 _next_node = block->get_node(block->number_of_nodes() - 1); 2096 } 2097 2098 #ifndef PRODUCT 2099 // Scheduling destructor 2100 Scheduling::~Scheduling() { 2101 _total_branches += _branches; 2102 _total_unconditional_delays += _unconditional_delays; 2103 } 2104 #endif 2105 2106 // Step ahead "i" cycles 2107 void Scheduling::step(uint i) { 2108 2109 Bundle *bundle = node_bundling(_next_node); 2110 bundle->set_starts_bundle(); 2111 2112 // Update the bundle record, but leave the flags information alone 2113 if (_bundle_instr_count > 0) { 2114 bundle->set_instr_count(_bundle_instr_count); 2115 bundle->set_resources_used(_bundle_use.resourcesUsed()); 2116 } 2117 2118 // Update the state information 2119 _bundle_instr_count = 0; 2120 _bundle_cycle_number += i; 2121 _bundle_use.step(i); 2122 } 2123 2124 void Scheduling::step_and_clear() { 2125 Bundle *bundle = node_bundling(_next_node); 2126 bundle->set_starts_bundle(); 2127 2128 // Update the bundle record 2129 if (_bundle_instr_count > 0) { 2130 bundle->set_instr_count(_bundle_instr_count); 2131 bundle->set_resources_used(_bundle_use.resourcesUsed()); 2132 2133 _bundle_cycle_number += 1; 2134 } 2135 2136 // Clear the bundling information 2137 _bundle_instr_count = 0; 2138 _bundle_use.reset(); 2139 2140 memcpy(_bundle_use_elements, 2141 Pipeline_Use::elaborated_elements, 2142 sizeof(Pipeline_Use::elaborated_elements)); 2143 } 2144 2145 // Perform instruction scheduling and bundling over the sequence of 2146 // instructions in backwards order. 2147 void PhaseOutput::ScheduleAndBundle() { 2148 2149 // Don't optimize this if it isn't a method 2150 if (!C->method()) 2151 return; 2152 2153 // Don't optimize this if scheduling is disabled 2154 if (!C->do_scheduling()) 2155 return; 2156 2157 // Scheduling code works only with pairs (8 bytes) maximum. 2158 // And when the scalable vector register is used, we may spill/unspill 2159 // the whole reg regardless of the max vector size. 2160 if (C->max_vector_size() > 8 || 2161 (C->max_vector_size() > 0 && Matcher::supports_scalable_vector())) { 2162 return; 2163 } 2164 2165 Compile::TracePhase tp(_t_instrSched); 2166 2167 // Create a data structure for all the scheduling information 2168 Scheduling scheduling(Thread::current()->resource_area(), *C); 2169 2170 // Walk backwards over each basic block, computing the needed alignment 2171 // Walk over all the basic blocks 2172 scheduling.DoScheduling(); 2173 2174 #ifndef PRODUCT 2175 if (C->trace_opto_output()) { 2176 // Buffer and print all at once 2177 ResourceMark rm; 2178 stringStream ss; 2179 ss.print("\n---- After ScheduleAndBundle ----\n"); 2180 print_scheduling(&ss); 2181 tty->print("%s", ss.as_string()); 2182 } 2183 #endif 2184 } 2185 2186 #ifndef PRODUCT 2187 // Separated out so that it can be called directly from debugger 2188 void PhaseOutput::print_scheduling() { 2189 print_scheduling(tty); 2190 } 2191 2192 void PhaseOutput::print_scheduling(outputStream* output_stream) { 2193 for (uint i = 0; i < C->cfg()->number_of_blocks(); i++) { 2194 output_stream->print("\nBB#%03d:\n", i); 2195 Block* block = C->cfg()->get_block(i); 2196 for (uint j = 0; j < block->number_of_nodes(); j++) { 2197 Node* n = block->get_node(j); 2198 OptoReg::Name reg = C->regalloc()->get_reg_first(n); 2199 output_stream->print(" %-6s ", reg >= 0 && reg < REG_COUNT ? Matcher::regName[reg] : ""); 2200 n->dump("\n", false, output_stream); 2201 } 2202 } 2203 } 2204 #endif 2205 2206 // See if this node fits into the present instruction bundle 2207 bool Scheduling::NodeFitsInBundle(Node *n) { 2208 uint n_idx = n->_idx; 2209 2210 // If this is the unconditional delay instruction, then it fits 2211 if (n == _unconditional_delay_slot) { 2212 #ifndef PRODUCT 2213 if (_cfg->C->trace_opto_output()) 2214 tty->print("# NodeFitsInBundle [%4d]: TRUE; is in unconditional delay slot\n", n->_idx); 2215 #endif 2216 return (true); 2217 } 2218 2219 // If the node cannot be scheduled this cycle, skip it 2220 if (_current_latency[n_idx] > _bundle_cycle_number) { 2221 #ifndef PRODUCT 2222 if (_cfg->C->trace_opto_output()) 2223 tty->print("# NodeFitsInBundle [%4d]: FALSE; latency %4d > %d\n", 2224 n->_idx, _current_latency[n_idx], _bundle_cycle_number); 2225 #endif 2226 return (false); 2227 } 2228 2229 const Pipeline *node_pipeline = n->pipeline(); 2230 2231 uint instruction_count = node_pipeline->instructionCount(); 2232 if (node_pipeline->mayHaveNoCode() && n->size(_regalloc) == 0) 2233 instruction_count = 0; 2234 else if (node_pipeline->hasBranchDelay() && !_unconditional_delay_slot) 2235 instruction_count++; 2236 2237 if (_bundle_instr_count + instruction_count > Pipeline::_max_instrs_per_cycle) { 2238 #ifndef PRODUCT 2239 if (_cfg->C->trace_opto_output()) 2240 tty->print("# NodeFitsInBundle [%4d]: FALSE; too many instructions: %d > %d\n", 2241 n->_idx, _bundle_instr_count + instruction_count, Pipeline::_max_instrs_per_cycle); 2242 #endif 2243 return (false); 2244 } 2245 2246 // Don't allow non-machine nodes to be handled this way 2247 if (!n->is_Mach() && instruction_count == 0) 2248 return (false); 2249 2250 // See if there is any overlap 2251 uint delay = _bundle_use.full_latency(0, node_pipeline->resourceUse()); 2252 2253 if (delay > 0) { 2254 #ifndef PRODUCT 2255 if (_cfg->C->trace_opto_output()) 2256 tty->print("# NodeFitsInBundle [%4d]: FALSE; functional units overlap\n", n_idx); 2257 #endif 2258 return false; 2259 } 2260 2261 #ifndef PRODUCT 2262 if (_cfg->C->trace_opto_output()) 2263 tty->print("# NodeFitsInBundle [%4d]: TRUE\n", n_idx); 2264 #endif 2265 2266 return true; 2267 } 2268 2269 Node * Scheduling::ChooseNodeToBundle() { 2270 uint siz = _available.size(); 2271 2272 if (siz == 0) { 2273 2274 #ifndef PRODUCT 2275 if (_cfg->C->trace_opto_output()) 2276 tty->print("# ChooseNodeToBundle: null\n"); 2277 #endif 2278 return (nullptr); 2279 } 2280 2281 // Fast path, if only 1 instruction in the bundle 2282 if (siz == 1) { 2283 #ifndef PRODUCT 2284 if (_cfg->C->trace_opto_output()) { 2285 tty->print("# ChooseNodeToBundle (only 1): "); 2286 _available[0]->dump(); 2287 } 2288 #endif 2289 return (_available[0]); 2290 } 2291 2292 // Don't bother, if the bundle is already full 2293 if (_bundle_instr_count < Pipeline::_max_instrs_per_cycle) { 2294 for ( uint i = 0; i < siz; i++ ) { 2295 Node *n = _available[i]; 2296 2297 // Skip projections, we'll handle them another way 2298 if (n->is_Proj()) 2299 continue; 2300 2301 // This presupposed that instructions are inserted into the 2302 // available list in a legality order; i.e. instructions that 2303 // must be inserted first are at the head of the list 2304 if (NodeFitsInBundle(n)) { 2305 #ifndef PRODUCT 2306 if (_cfg->C->trace_opto_output()) { 2307 tty->print("# ChooseNodeToBundle: "); 2308 n->dump(); 2309 } 2310 #endif 2311 return (n); 2312 } 2313 } 2314 } 2315 2316 // Nothing fits in this bundle, choose the highest priority 2317 #ifndef PRODUCT 2318 if (_cfg->C->trace_opto_output()) { 2319 tty->print("# ChooseNodeToBundle: "); 2320 _available[0]->dump(); 2321 } 2322 #endif 2323 2324 return _available[0]; 2325 } 2326 2327 int Scheduling::compare_two_spill_nodes(Node* first, Node* second) { 2328 assert(first->is_MachSpillCopy() && second->is_MachSpillCopy(), ""); 2329 2330 OptoReg::Name first_src_lo = _regalloc->get_reg_first(first->in(1)); 2331 OptoReg::Name first_dst_lo = _regalloc->get_reg_first(first); 2332 OptoReg::Name second_src_lo = _regalloc->get_reg_first(second->in(1)); 2333 OptoReg::Name second_dst_lo = _regalloc->get_reg_first(second); 2334 2335 // Comparison between stack -> reg and stack -> reg 2336 if (OptoReg::is_stack(first_src_lo) && OptoReg::is_stack(second_src_lo) && 2337 OptoReg::is_reg(first_dst_lo) && OptoReg::is_reg(second_dst_lo)) { 2338 return _regalloc->reg2offset(first_src_lo) - _regalloc->reg2offset(second_src_lo); 2339 } 2340 2341 // Comparison between reg -> stack and reg -> stack 2342 if (OptoReg::is_stack(first_dst_lo) && OptoReg::is_stack(second_dst_lo) && 2343 OptoReg::is_reg(first_src_lo) && OptoReg::is_reg(second_src_lo)) { 2344 return _regalloc->reg2offset(first_dst_lo) - _regalloc->reg2offset(second_dst_lo); 2345 } 2346 2347 return 0; // Not comparable 2348 } 2349 2350 void Scheduling::AddNodeToAvailableList(Node *n) { 2351 assert( !n->is_Proj(), "projections never directly made available" ); 2352 #ifndef PRODUCT 2353 if (_cfg->C->trace_opto_output()) { 2354 tty->print("# AddNodeToAvailableList: "); 2355 n->dump(); 2356 } 2357 #endif 2358 2359 int latency = _current_latency[n->_idx]; 2360 2361 // Insert in latency order (insertion sort). If two MachSpillCopyNodes 2362 // for stack spilling or unspilling have the same latency, we sort 2363 // them in the order of stack offset. Some ports (e.g. aarch64) may also 2364 // have more opportunities to do ld/st merging 2365 uint i; 2366 for (i = 0; i < _available.size(); i++) { 2367 if (_current_latency[_available[i]->_idx] > latency) { 2368 break; 2369 } else if (_current_latency[_available[i]->_idx] == latency && 2370 n->is_MachSpillCopy() && _available[i]->is_MachSpillCopy() && 2371 compare_two_spill_nodes(n, _available[i]) > 0) { 2372 break; 2373 } 2374 } 2375 2376 // Special Check for compares following branches 2377 if( n->is_Mach() && _scheduled.size() > 0 ) { 2378 int op = n->as_Mach()->ideal_Opcode(); 2379 Node *last = _scheduled[0]; 2380 if( last->is_MachIf() && last->in(1) == n && 2381 ( op == Op_CmpI || 2382 op == Op_CmpU || 2383 op == Op_CmpUL || 2384 op == Op_CmpP || 2385 op == Op_CmpF || 2386 op == Op_CmpD || 2387 op == Op_CmpL ) ) { 2388 2389 // Recalculate position, moving to front of same latency 2390 for ( i=0 ; i < _available.size(); i++ ) 2391 if (_current_latency[_available[i]->_idx] >= latency) 2392 break; 2393 } 2394 } 2395 2396 // Insert the node in the available list 2397 _available.insert(i, n); 2398 2399 #ifndef PRODUCT 2400 if (_cfg->C->trace_opto_output()) 2401 dump_available(); 2402 #endif 2403 } 2404 2405 void Scheduling::DecrementUseCounts(Node *n, const Block *bb) { 2406 for ( uint i=0; i < n->len(); i++ ) { 2407 Node *def = n->in(i); 2408 if (!def) continue; 2409 if( def->is_Proj() ) // If this is a machine projection, then 2410 def = def->in(0); // propagate usage thru to the base instruction 2411 2412 if(_cfg->get_block_for_node(def) != bb) { // Ignore if not block-local 2413 continue; 2414 } 2415 2416 // Compute the latency 2417 uint l = _bundle_cycle_number + n->latency(i); 2418 if (_current_latency[def->_idx] < l) 2419 _current_latency[def->_idx] = l; 2420 2421 // If this does not have uses then schedule it 2422 if ((--_uses[def->_idx]) == 0) 2423 AddNodeToAvailableList(def); 2424 } 2425 } 2426 2427 void Scheduling::AddNodeToBundle(Node *n, const Block *bb) { 2428 #ifndef PRODUCT 2429 if (_cfg->C->trace_opto_output()) { 2430 tty->print("# AddNodeToBundle: "); 2431 n->dump(); 2432 } 2433 #endif 2434 2435 // Remove this from the available list 2436 uint i; 2437 for (i = 0; i < _available.size(); i++) 2438 if (_available[i] == n) 2439 break; 2440 assert(i < _available.size(), "entry in _available list not found"); 2441 _available.remove(i); 2442 2443 // See if this fits in the current bundle 2444 const Pipeline *node_pipeline = n->pipeline(); 2445 const Pipeline_Use& node_usage = node_pipeline->resourceUse(); 2446 2447 // Check for instructions to be placed in the delay slot. We 2448 // do this before we actually schedule the current instruction, 2449 // because the delay slot follows the current instruction. 2450 if (Pipeline::_branch_has_delay_slot && 2451 node_pipeline->hasBranchDelay() && 2452 !_unconditional_delay_slot) { 2453 2454 uint siz = _available.size(); 2455 2456 // Conditional branches can support an instruction that 2457 // is unconditionally executed and not dependent by the 2458 // branch, OR a conditionally executed instruction if 2459 // the branch is taken. In practice, this means that 2460 // the first instruction at the branch target is 2461 // copied to the delay slot, and the branch goes to 2462 // the instruction after that at the branch target 2463 if ( n->is_MachBranch() ) { 2464 2465 assert( !n->is_MachNullCheck(), "should not look for delay slot for Null Check" ); 2466 assert( !n->is_Catch(), "should not look for delay slot for Catch" ); 2467 2468 #ifndef PRODUCT 2469 _branches++; 2470 #endif 2471 2472 // At least 1 instruction is on the available list 2473 // that is not dependent on the branch 2474 for (uint i = 0; i < siz; i++) { 2475 Node *d = _available[i]; 2476 const Pipeline *avail_pipeline = d->pipeline(); 2477 2478 // Don't allow safepoints in the branch shadow, that will 2479 // cause a number of difficulties 2480 if ( avail_pipeline->instructionCount() == 1 && 2481 !avail_pipeline->hasMultipleBundles() && 2482 !avail_pipeline->hasBranchDelay() && 2483 Pipeline::instr_has_unit_size() && 2484 d->size(_regalloc) == Pipeline::instr_unit_size() && 2485 NodeFitsInBundle(d) && 2486 !node_bundling(d)->used_in_delay()) { 2487 2488 if (d->is_Mach() && !d->is_MachSafePoint()) { 2489 // A node that fits in the delay slot was found, so we need to 2490 // set the appropriate bits in the bundle pipeline information so 2491 // that it correctly indicates resource usage. Later, when we 2492 // attempt to add this instruction to the bundle, we will skip 2493 // setting the resource usage. 2494 _unconditional_delay_slot = d; 2495 node_bundling(n)->set_use_unconditional_delay(); 2496 node_bundling(d)->set_used_in_unconditional_delay(); 2497 _bundle_use.add_usage(avail_pipeline->resourceUse()); 2498 _current_latency[d->_idx] = _bundle_cycle_number; 2499 _next_node = d; 2500 ++_bundle_instr_count; 2501 #ifndef PRODUCT 2502 _unconditional_delays++; 2503 #endif 2504 break; 2505 } 2506 } 2507 } 2508 } 2509 2510 // No delay slot, add a nop to the usage 2511 if (!_unconditional_delay_slot) { 2512 // See if adding an instruction in the delay slot will overflow 2513 // the bundle. 2514 if (!NodeFitsInBundle(_nop)) { 2515 #ifndef PRODUCT 2516 if (_cfg->C->trace_opto_output()) 2517 tty->print("# *** STEP(1 instruction for delay slot) ***\n"); 2518 #endif 2519 step(1); 2520 } 2521 2522 _bundle_use.add_usage(_nop->pipeline()->resourceUse()); 2523 _next_node = _nop; 2524 ++_bundle_instr_count; 2525 } 2526 2527 // See if the instruction in the delay slot requires a 2528 // step of the bundles 2529 if (!NodeFitsInBundle(n)) { 2530 #ifndef PRODUCT 2531 if (_cfg->C->trace_opto_output()) 2532 tty->print("# *** STEP(branch won't fit) ***\n"); 2533 #endif 2534 // Update the state information 2535 _bundle_instr_count = 0; 2536 _bundle_cycle_number += 1; 2537 _bundle_use.step(1); 2538 } 2539 } 2540 2541 // Get the number of instructions 2542 uint instruction_count = node_pipeline->instructionCount(); 2543 if (node_pipeline->mayHaveNoCode() && n->size(_regalloc) == 0) 2544 instruction_count = 0; 2545 2546 // Compute the latency information 2547 uint delay = 0; 2548 2549 if (instruction_count > 0 || !node_pipeline->mayHaveNoCode()) { 2550 int relative_latency = _current_latency[n->_idx] - _bundle_cycle_number; 2551 if (relative_latency < 0) 2552 relative_latency = 0; 2553 2554 delay = _bundle_use.full_latency(relative_latency, node_usage); 2555 2556 // Does not fit in this bundle, start a new one 2557 if (delay > 0) { 2558 step(delay); 2559 2560 #ifndef PRODUCT 2561 if (_cfg->C->trace_opto_output()) 2562 tty->print("# *** STEP(%d) ***\n", delay); 2563 #endif 2564 } 2565 } 2566 2567 // If this was placed in the delay slot, ignore it 2568 if (n != _unconditional_delay_slot) { 2569 2570 if (delay == 0) { 2571 if (node_pipeline->hasMultipleBundles()) { 2572 #ifndef PRODUCT 2573 if (_cfg->C->trace_opto_output()) 2574 tty->print("# *** STEP(multiple instructions) ***\n"); 2575 #endif 2576 step(1); 2577 } 2578 2579 else if (instruction_count + _bundle_instr_count > Pipeline::_max_instrs_per_cycle) { 2580 #ifndef PRODUCT 2581 if (_cfg->C->trace_opto_output()) 2582 tty->print("# *** STEP(%d >= %d instructions) ***\n", 2583 instruction_count + _bundle_instr_count, 2584 Pipeline::_max_instrs_per_cycle); 2585 #endif 2586 step(1); 2587 } 2588 } 2589 2590 if (node_pipeline->hasBranchDelay() && !_unconditional_delay_slot) 2591 _bundle_instr_count++; 2592 2593 // Set the node's latency 2594 _current_latency[n->_idx] = _bundle_cycle_number; 2595 2596 // Now merge the functional unit information 2597 if (instruction_count > 0 || !node_pipeline->mayHaveNoCode()) 2598 _bundle_use.add_usage(node_usage); 2599 2600 // Increment the number of instructions in this bundle 2601 _bundle_instr_count += instruction_count; 2602 2603 // Remember this node for later 2604 if (n->is_Mach()) 2605 _next_node = n; 2606 } 2607 2608 // It's possible to have a BoxLock in the graph and in the _bbs mapping but 2609 // not in the bb->_nodes array. This happens for debug-info-only BoxLocks. 2610 // 'Schedule' them (basically ignore in the schedule) but do not insert them 2611 // into the block. All other scheduled nodes get put in the schedule here. 2612 int op = n->Opcode(); 2613 if( (op == Op_Node && n->req() == 0) || // anti-dependence node OR 2614 (op != Op_Node && // Not an unused antidepedence node and 2615 // not an unallocated boxlock 2616 (OptoReg::is_valid(_regalloc->get_reg_first(n)) || op != Op_BoxLock)) ) { 2617 2618 // Push any trailing projections 2619 if( bb->get_node(bb->number_of_nodes()-1) != n ) { 2620 for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) { 2621 Node *foi = n->fast_out(i); 2622 if( foi->is_Proj() ) 2623 _scheduled.push(foi); 2624 } 2625 } 2626 2627 // Put the instruction in the schedule list 2628 _scheduled.push(n); 2629 } 2630 2631 #ifndef PRODUCT 2632 if (_cfg->C->trace_opto_output()) 2633 dump_available(); 2634 #endif 2635 2636 // Walk all the definitions, decrementing use counts, and 2637 // if a definition has a 0 use count, place it in the available list. 2638 DecrementUseCounts(n,bb); 2639 } 2640 2641 // This method sets the use count within a basic block. We will ignore all 2642 // uses outside the current basic block. As we are doing a backwards walk, 2643 // any node we reach that has a use count of 0 may be scheduled. This also 2644 // avoids the problem of cyclic references from phi nodes, as long as phi 2645 // nodes are at the front of the basic block. This method also initializes 2646 // the available list to the set of instructions that have no uses within this 2647 // basic block. 2648 void Scheduling::ComputeUseCount(const Block *bb) { 2649 #ifndef PRODUCT 2650 if (_cfg->C->trace_opto_output()) 2651 tty->print("# -> ComputeUseCount\n"); 2652 #endif 2653 2654 // Clear the list of available and scheduled instructions, just in case 2655 _available.clear(); 2656 _scheduled.clear(); 2657 2658 // No delay slot specified 2659 _unconditional_delay_slot = nullptr; 2660 2661 #ifdef ASSERT 2662 for( uint i=0; i < bb->number_of_nodes(); i++ ) 2663 assert( _uses[bb->get_node(i)->_idx] == 0, "_use array not clean" ); 2664 #endif 2665 2666 // Force the _uses count to never go to zero for unscheduable pieces 2667 // of the block 2668 for( uint k = 0; k < _bb_start; k++ ) 2669 _uses[bb->get_node(k)->_idx] = 1; 2670 for( uint l = _bb_end; l < bb->number_of_nodes(); l++ ) 2671 _uses[bb->get_node(l)->_idx] = 1; 2672 2673 // Iterate backwards over the instructions in the block. Don't count the 2674 // branch projections at end or the block header instructions. 2675 for( uint j = _bb_end-1; j >= _bb_start; j-- ) { 2676 Node *n = bb->get_node(j); 2677 if( n->is_Proj() ) continue; // Projections handled another way 2678 2679 // Account for all uses 2680 for ( uint k = 0; k < n->len(); k++ ) { 2681 Node *inp = n->in(k); 2682 if (!inp) continue; 2683 assert(inp != n, "no cycles allowed" ); 2684 if (_cfg->get_block_for_node(inp) == bb) { // Block-local use? 2685 if (inp->is_Proj()) { // Skip through Proj's 2686 inp = inp->in(0); 2687 } 2688 ++_uses[inp->_idx]; // Count 1 block-local use 2689 } 2690 } 2691 2692 // If this instruction has a 0 use count, then it is available 2693 if (!_uses[n->_idx]) { 2694 _current_latency[n->_idx] = _bundle_cycle_number; 2695 AddNodeToAvailableList(n); 2696 } 2697 2698 #ifndef PRODUCT 2699 if (_cfg->C->trace_opto_output()) { 2700 tty->print("# uses: %3d: ", _uses[n->_idx]); 2701 n->dump(); 2702 } 2703 #endif 2704 } 2705 2706 #ifndef PRODUCT 2707 if (_cfg->C->trace_opto_output()) 2708 tty->print("# <- ComputeUseCount\n"); 2709 #endif 2710 } 2711 2712 // This routine performs scheduling on each basic block in reverse order, 2713 // using instruction latencies and taking into account function unit 2714 // availability. 2715 void Scheduling::DoScheduling() { 2716 #ifndef PRODUCT 2717 if (_cfg->C->trace_opto_output()) 2718 tty->print("# -> DoScheduling\n"); 2719 #endif 2720 2721 Block *succ_bb = nullptr; 2722 Block *bb; 2723 Compile* C = Compile::current(); 2724 2725 // Walk over all the basic blocks in reverse order 2726 for (int i = _cfg->number_of_blocks() - 1; i >= 0; succ_bb = bb, i--) { 2727 bb = _cfg->get_block(i); 2728 2729 #ifndef PRODUCT 2730 if (_cfg->C->trace_opto_output()) { 2731 tty->print("# Schedule BB#%03d (initial)\n", i); 2732 for (uint j = 0; j < bb->number_of_nodes(); j++) { 2733 bb->get_node(j)->dump(); 2734 } 2735 } 2736 #endif 2737 2738 // On the head node, skip processing 2739 if (bb == _cfg->get_root_block()) { 2740 continue; 2741 } 2742 2743 // Skip empty, connector blocks 2744 if (bb->is_connector()) 2745 continue; 2746 2747 // If the following block is not the sole successor of 2748 // this one, then reset the pipeline information 2749 if (bb->_num_succs != 1 || bb->non_connector_successor(0) != succ_bb) { 2750 #ifndef PRODUCT 2751 if (_cfg->C->trace_opto_output()) { 2752 tty->print("*** bundle start of next BB, node %d, for %d instructions\n", 2753 _next_node->_idx, _bundle_instr_count); 2754 } 2755 #endif 2756 step_and_clear(); 2757 } 2758 2759 // Leave untouched the starting instruction, any Phis, a CreateEx node 2760 // or Top. bb->get_node(_bb_start) is the first schedulable instruction. 2761 _bb_end = bb->number_of_nodes()-1; 2762 for( _bb_start=1; _bb_start <= _bb_end; _bb_start++ ) { 2763 Node *n = bb->get_node(_bb_start); 2764 // Things not matched, like Phinodes and ProjNodes don't get scheduled. 2765 // Also, MachIdealNodes do not get scheduled 2766 if( !n->is_Mach() ) continue; // Skip non-machine nodes 2767 MachNode *mach = n->as_Mach(); 2768 int iop = mach->ideal_Opcode(); 2769 if( iop == Op_CreateEx ) continue; // CreateEx is pinned 2770 if( iop == Op_Con ) continue; // Do not schedule Top 2771 if( iop == Op_Node && // Do not schedule PhiNodes, ProjNodes 2772 mach->pipeline() == MachNode::pipeline_class() && 2773 !n->is_SpillCopy() && !n->is_MachMerge() ) // Breakpoints, Prolog, etc 2774 continue; 2775 break; // Funny loop structure to be sure... 2776 } 2777 // Compute last "interesting" instruction in block - last instruction we 2778 // might schedule. _bb_end points just after last schedulable inst. We 2779 // normally schedule conditional branches (despite them being forced last 2780 // in the block), because they have delay slots we can fill. Calls all 2781 // have their delay slots filled in the template expansions, so we don't 2782 // bother scheduling them. 2783 Node *last = bb->get_node(_bb_end); 2784 // Ignore trailing NOPs. 2785 while (_bb_end > 0 && last->is_Mach() && 2786 last->as_Mach()->ideal_Opcode() == Op_Con) { 2787 last = bb->get_node(--_bb_end); 2788 } 2789 assert(!last->is_Mach() || last->as_Mach()->ideal_Opcode() != Op_Con, ""); 2790 if( last->is_Catch() || 2791 (last->is_Mach() && last->as_Mach()->ideal_Opcode() == Op_Halt) ) { 2792 // There might be a prior call. Skip it. 2793 while (_bb_start < _bb_end && bb->get_node(--_bb_end)->is_MachProj()); 2794 } else if( last->is_MachNullCheck() ) { 2795 // Backup so the last null-checked memory instruction is 2796 // outside the schedulable range. Skip over the nullcheck, 2797 // projection, and the memory nodes. 2798 Node *mem = last->in(1); 2799 do { 2800 _bb_end--; 2801 } while (mem != bb->get_node(_bb_end)); 2802 } else { 2803 // Set _bb_end to point after last schedulable inst. 2804 _bb_end++; 2805 } 2806 2807 assert( _bb_start <= _bb_end, "inverted block ends" ); 2808 2809 // Compute the register antidependencies for the basic block 2810 ComputeRegisterAntidependencies(bb); 2811 if (C->failing()) return; // too many D-U pinch points 2812 2813 // Compute the usage within the block, and set the list of all nodes 2814 // in the block that have no uses within the block. 2815 ComputeUseCount(bb); 2816 2817 // Schedule the remaining instructions in the block 2818 while ( _available.size() > 0 ) { 2819 Node *n = ChooseNodeToBundle(); 2820 guarantee(n != nullptr, "no nodes available"); 2821 AddNodeToBundle(n,bb); 2822 } 2823 2824 assert( _scheduled.size() == _bb_end - _bb_start, "wrong number of instructions" ); 2825 #ifdef ASSERT 2826 for( uint l = _bb_start; l < _bb_end; l++ ) { 2827 Node *n = bb->get_node(l); 2828 uint m; 2829 for( m = 0; m < _bb_end-_bb_start; m++ ) 2830 if( _scheduled[m] == n ) 2831 break; 2832 assert( m < _bb_end-_bb_start, "instruction missing in schedule" ); 2833 } 2834 #endif 2835 2836 // Now copy the instructions (in reverse order) back to the block 2837 for ( uint k = _bb_start; k < _bb_end; k++ ) 2838 bb->map_node(_scheduled[_bb_end-k-1], k); 2839 2840 #ifndef PRODUCT 2841 if (_cfg->C->trace_opto_output()) { 2842 tty->print("# Schedule BB#%03d (final)\n", i); 2843 uint current = 0; 2844 for (uint j = 0; j < bb->number_of_nodes(); j++) { 2845 Node *n = bb->get_node(j); 2846 if( valid_bundle_info(n) ) { 2847 Bundle *bundle = node_bundling(n); 2848 if (bundle->instr_count() > 0 || bundle->flags() > 0) { 2849 tty->print("*** Bundle: "); 2850 bundle->dump(); 2851 } 2852 n->dump(); 2853 } 2854 } 2855 } 2856 #endif 2857 #ifdef ASSERT 2858 verify_good_schedule(bb,"after block local scheduling"); 2859 #endif 2860 } 2861 2862 #ifndef PRODUCT 2863 if (_cfg->C->trace_opto_output()) 2864 tty->print("# <- DoScheduling\n"); 2865 #endif 2866 2867 // Record final node-bundling array location 2868 _regalloc->C->output()->set_node_bundling_base(_node_bundling_base); 2869 2870 } // end DoScheduling 2871 2872 // Verify that no live-range used in the block is killed in the block by a 2873 // wrong DEF. This doesn't verify live-ranges that span blocks. 2874 2875 // Check for edge existence. Used to avoid adding redundant precedence edges. 2876 static bool edge_from_to( Node *from, Node *to ) { 2877 for( uint i=0; i<from->len(); i++ ) 2878 if( from->in(i) == to ) 2879 return true; 2880 return false; 2881 } 2882 2883 #ifdef ASSERT 2884 void Scheduling::verify_do_def( Node *n, OptoReg::Name def, const char *msg ) { 2885 // Check for bad kills 2886 if( OptoReg::is_valid(def) ) { // Ignore stores & control flow 2887 Node *prior_use = _reg_node[def]; 2888 if( prior_use && !edge_from_to(prior_use,n) ) { 2889 tty->print("%s = ",OptoReg::as_VMReg(def)->name()); 2890 n->dump(); 2891 tty->print_cr("..."); 2892 prior_use->dump(); 2893 assert(edge_from_to(prior_use,n), "%s", msg); 2894 } 2895 _reg_node.map(def,nullptr); // Kill live USEs 2896 } 2897 } 2898 2899 void Scheduling::verify_good_schedule( Block *b, const char *msg ) { 2900 2901 // Zap to something reasonable for the verify code 2902 _reg_node.clear(); 2903 2904 // Walk over the block backwards. Check to make sure each DEF doesn't 2905 // kill a live value (other than the one it's supposed to). Add each 2906 // USE to the live set. 2907 for( uint i = b->number_of_nodes()-1; i >= _bb_start; i-- ) { 2908 Node *n = b->get_node(i); 2909 int n_op = n->Opcode(); 2910 if( n_op == Op_MachProj && n->ideal_reg() == MachProjNode::fat_proj ) { 2911 // Fat-proj kills a slew of registers 2912 RegMaskIterator rmi(n->out_RegMask()); 2913 while (rmi.has_next()) { 2914 OptoReg::Name kill = rmi.next(); 2915 verify_do_def(n, kill, msg); 2916 } 2917 } else if( n_op != Op_Node ) { // Avoid brand new antidependence nodes 2918 // Get DEF'd registers the normal way 2919 verify_do_def( n, _regalloc->get_reg_first(n), msg ); 2920 verify_do_def( n, _regalloc->get_reg_second(n), msg ); 2921 } 2922 2923 // Now make all USEs live 2924 for( uint i=1; i<n->req(); i++ ) { 2925 Node *def = n->in(i); 2926 assert(def != nullptr, "input edge required"); 2927 OptoReg::Name reg_lo = _regalloc->get_reg_first(def); 2928 OptoReg::Name reg_hi = _regalloc->get_reg_second(def); 2929 if( OptoReg::is_valid(reg_lo) ) { 2930 assert(!_reg_node[reg_lo] || edge_from_to(_reg_node[reg_lo],def), "%s", msg); 2931 _reg_node.map(reg_lo,n); 2932 } 2933 if( OptoReg::is_valid(reg_hi) ) { 2934 assert(!_reg_node[reg_hi] || edge_from_to(_reg_node[reg_hi],def), "%s", msg); 2935 _reg_node.map(reg_hi,n); 2936 } 2937 } 2938 2939 } 2940 2941 // Zap to something reasonable for the Antidependence code 2942 _reg_node.clear(); 2943 } 2944 #endif 2945 2946 // Conditionally add precedence edges. Avoid putting edges on Projs. 2947 static void add_prec_edge_from_to( Node *from, Node *to ) { 2948 if( from->is_Proj() ) { // Put precedence edge on Proj's input 2949 assert( from->req() == 1 && (from->len() == 1 || from->in(1) == nullptr), "no precedence edges on projections" ); 2950 from = from->in(0); 2951 } 2952 if( from != to && // No cycles (for things like LD L0,[L0+4] ) 2953 !edge_from_to( from, to ) ) // Avoid duplicate edge 2954 from->add_prec(to); 2955 } 2956 2957 void Scheduling::anti_do_def( Block *b, Node *def, OptoReg::Name def_reg, int is_def ) { 2958 if( !OptoReg::is_valid(def_reg) ) // Ignore stores & control flow 2959 return; 2960 2961 if (OptoReg::is_reg(def_reg)) { 2962 VMReg vmreg = OptoReg::as_VMReg(def_reg); 2963 if (vmreg->is_reg() && !vmreg->is_concrete() && !vmreg->prev()->is_concrete()) { 2964 // This is one of the high slots of a vector register. 2965 // ScheduleAndBundle already checked there are no live wide 2966 // vectors in this method so it can be safely ignored. 2967 return; 2968 } 2969 } 2970 2971 Node *pinch = _reg_node[def_reg]; // Get pinch point 2972 if ((pinch == nullptr) || _cfg->get_block_for_node(pinch) != b || // No pinch-point yet? 2973 is_def ) { // Check for a true def (not a kill) 2974 _reg_node.map(def_reg,def); // Record def/kill as the optimistic pinch-point 2975 return; 2976 } 2977 2978 Node *kill = def; // Rename 'def' to more descriptive 'kill' 2979 debug_only( def = (Node*)((intptr_t)0xdeadbeef); ) 2980 2981 // After some number of kills there _may_ be a later def 2982 Node *later_def = nullptr; 2983 2984 Compile* C = Compile::current(); 2985 2986 // Finding a kill requires a real pinch-point. 2987 // Check for not already having a pinch-point. 2988 // Pinch points are Op_Node's. 2989 if( pinch->Opcode() != Op_Node ) { // Or later-def/kill as pinch-point? 2990 later_def = pinch; // Must be def/kill as optimistic pinch-point 2991 if ( _pinch_free_list.size() > 0) { 2992 pinch = _pinch_free_list.pop(); 2993 } else { 2994 pinch = new Node(1); // Pinch point to-be 2995 } 2996 if (pinch->_idx >= _regalloc->node_regs_max_index()) { 2997 DEBUG_ONLY( pinch->dump(); ); 2998 assert(false, "too many D-U pinch points: %d >= %d", pinch->_idx, _regalloc->node_regs_max_index()); 2999 _cfg->C->record_method_not_compilable("too many D-U pinch points"); 3000 return; 3001 } 3002 _cfg->map_node_to_block(pinch, b); // Pretend it's valid in this block (lazy init) 3003 _reg_node.map(def_reg,pinch); // Record pinch-point 3004 //regalloc()->set_bad(pinch->_idx); // Already initialized this way. 3005 if( later_def->outcnt() == 0 || later_def->ideal_reg() == MachProjNode::fat_proj ) { // Distinguish def from kill 3006 pinch->init_req(0, C->top()); // set not null for the next call 3007 add_prec_edge_from_to(later_def,pinch); // Add edge from kill to pinch 3008 later_def = nullptr; // and no later def 3009 } 3010 pinch->set_req(0,later_def); // Hook later def so we can find it 3011 } else { // Else have valid pinch point 3012 if( pinch->in(0) ) // If there is a later-def 3013 later_def = pinch->in(0); // Get it 3014 } 3015 3016 // Add output-dependence edge from later def to kill 3017 if( later_def ) // If there is some original def 3018 add_prec_edge_from_to(later_def,kill); // Add edge from def to kill 3019 3020 // See if current kill is also a use, and so is forced to be the pinch-point. 3021 if( pinch->Opcode() == Op_Node ) { 3022 Node *uses = kill->is_Proj() ? kill->in(0) : kill; 3023 for( uint i=1; i<uses->req(); i++ ) { 3024 if( _regalloc->get_reg_first(uses->in(i)) == def_reg || 3025 _regalloc->get_reg_second(uses->in(i)) == def_reg ) { 3026 // Yes, found a use/kill pinch-point 3027 pinch->set_req(0,nullptr); // 3028 pinch->replace_by(kill); // Move anti-dep edges up 3029 pinch = kill; 3030 _reg_node.map(def_reg,pinch); 3031 return; 3032 } 3033 } 3034 } 3035 3036 // Add edge from kill to pinch-point 3037 add_prec_edge_from_to(kill,pinch); 3038 } 3039 3040 void Scheduling::anti_do_use( Block *b, Node *use, OptoReg::Name use_reg ) { 3041 if( !OptoReg::is_valid(use_reg) ) // Ignore stores & control flow 3042 return; 3043 Node *pinch = _reg_node[use_reg]; // Get pinch point 3044 // Check for no later def_reg/kill in block 3045 if ((pinch != nullptr) && _cfg->get_block_for_node(pinch) == b && 3046 // Use has to be block-local as well 3047 _cfg->get_block_for_node(use) == b) { 3048 if( pinch->Opcode() == Op_Node && // Real pinch-point (not optimistic?) 3049 pinch->req() == 1 ) { // pinch not yet in block? 3050 pinch->del_req(0); // yank pointer to later-def, also set flag 3051 // Insert the pinch-point in the block just after the last use 3052 b->insert_node(pinch, b->find_node(use) + 1); 3053 _bb_end++; // Increase size scheduled region in block 3054 } 3055 3056 add_prec_edge_from_to(pinch,use); 3057 } 3058 } 3059 3060 // We insert antidependences between the reads and following write of 3061 // allocated registers to prevent illegal code motion. Hopefully, the 3062 // number of added references should be fairly small, especially as we 3063 // are only adding references within the current basic block. 3064 void Scheduling::ComputeRegisterAntidependencies(Block *b) { 3065 3066 #ifdef ASSERT 3067 verify_good_schedule(b,"before block local scheduling"); 3068 #endif 3069 3070 // A valid schedule, for each register independently, is an endless cycle 3071 // of: a def, then some uses (connected to the def by true dependencies), 3072 // then some kills (defs with no uses), finally the cycle repeats with a new 3073 // def. The uses are allowed to float relative to each other, as are the 3074 // kills. No use is allowed to slide past a kill (or def). This requires 3075 // antidependencies between all uses of a single def and all kills that 3076 // follow, up to the next def. More edges are redundant, because later defs 3077 // & kills are already serialized with true or antidependencies. To keep 3078 // the edge count down, we add a 'pinch point' node if there's more than 3079 // one use or more than one kill/def. 3080 3081 // We add dependencies in one bottom-up pass. 3082 3083 // For each instruction we handle it's DEFs/KILLs, then it's USEs. 3084 3085 // For each DEF/KILL, we check to see if there's a prior DEF/KILL for this 3086 // register. If not, we record the DEF/KILL in _reg_node, the 3087 // register-to-def mapping. If there is a prior DEF/KILL, we insert a 3088 // "pinch point", a new Node that's in the graph but not in the block. 3089 // We put edges from the prior and current DEF/KILLs to the pinch point. 3090 // We put the pinch point in _reg_node. If there's already a pinch point 3091 // we merely add an edge from the current DEF/KILL to the pinch point. 3092 3093 // After doing the DEF/KILLs, we handle USEs. For each used register, we 3094 // put an edge from the pinch point to the USE. 3095 3096 // To be expedient, the _reg_node array is pre-allocated for the whole 3097 // compilation. _reg_node is lazily initialized; it either contains a null, 3098 // or a valid def/kill/pinch-point, or a leftover node from some prior 3099 // block. Leftover node from some prior block is treated like a null (no 3100 // prior def, so no anti-dependence needed). Valid def is distinguished by 3101 // it being in the current block. 3102 bool fat_proj_seen = false; 3103 uint last_safept = _bb_end-1; 3104 Node* end_node = (_bb_end-1 >= _bb_start) ? b->get_node(last_safept) : nullptr; 3105 Node* last_safept_node = end_node; 3106 for( uint i = _bb_end-1; i >= _bb_start; i-- ) { 3107 Node *n = b->get_node(i); 3108 int is_def = n->outcnt(); // def if some uses prior to adding precedence edges 3109 if( n->is_MachProj() && n->ideal_reg() == MachProjNode::fat_proj ) { 3110 // Fat-proj kills a slew of registers 3111 // This can add edges to 'n' and obscure whether or not it was a def, 3112 // hence the is_def flag. 3113 fat_proj_seen = true; 3114 RegMaskIterator rmi(n->out_RegMask()); 3115 while (rmi.has_next()) { 3116 OptoReg::Name kill = rmi.next(); 3117 anti_do_def(b, n, kill, is_def); 3118 } 3119 } else { 3120 // Get DEF'd registers the normal way 3121 anti_do_def( b, n, _regalloc->get_reg_first(n), is_def ); 3122 anti_do_def( b, n, _regalloc->get_reg_second(n), is_def ); 3123 } 3124 3125 // Kill projections on a branch should appear to occur on the 3126 // branch, not afterwards, so grab the masks from the projections 3127 // and process them. 3128 if (n->is_MachBranch() || (n->is_Mach() && n->as_Mach()->ideal_Opcode() == Op_Jump)) { 3129 for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) { 3130 Node* use = n->fast_out(i); 3131 if (use->is_Proj()) { 3132 RegMaskIterator rmi(use->out_RegMask()); 3133 while (rmi.has_next()) { 3134 OptoReg::Name kill = rmi.next(); 3135 anti_do_def(b, n, kill, false); 3136 } 3137 } 3138 } 3139 } 3140 3141 // Check each register used by this instruction for a following DEF/KILL 3142 // that must occur afterward and requires an anti-dependence edge. 3143 for( uint j=0; j<n->req(); j++ ) { 3144 Node *def = n->in(j); 3145 if( def ) { 3146 assert( !def->is_MachProj() || def->ideal_reg() != MachProjNode::fat_proj, "" ); 3147 anti_do_use( b, n, _regalloc->get_reg_first(def) ); 3148 anti_do_use( b, n, _regalloc->get_reg_second(def) ); 3149 } 3150 } 3151 // Do not allow defs of new derived values to float above GC 3152 // points unless the base is definitely available at the GC point. 3153 3154 Node *m = b->get_node(i); 3155 3156 // Add precedence edge from following safepoint to use of derived pointer 3157 if( last_safept_node != end_node && 3158 m != last_safept_node) { 3159 for (uint k = 1; k < m->req(); k++) { 3160 const Type *t = m->in(k)->bottom_type(); 3161 if( t->isa_oop_ptr() && 3162 t->is_ptr()->offset() != 0 ) { 3163 last_safept_node->add_prec( m ); 3164 break; 3165 } 3166 } 3167 } 3168 3169 if( n->jvms() ) { // Precedence edge from derived to safept 3170 // Check if last_safept_node was moved by pinch-point insertion in anti_do_use() 3171 if( b->get_node(last_safept) != last_safept_node ) { 3172 last_safept = b->find_node(last_safept_node); 3173 } 3174 for( uint j=last_safept; j > i; j-- ) { 3175 Node *mach = b->get_node(j); 3176 if( mach->is_Mach() && mach->as_Mach()->ideal_Opcode() == Op_AddP ) 3177 mach->add_prec( n ); 3178 } 3179 last_safept = i; 3180 last_safept_node = m; 3181 } 3182 } 3183 3184 if (fat_proj_seen) { 3185 // Garbage collect pinch nodes that were not consumed. 3186 // They are usually created by a fat kill MachProj for a call. 3187 garbage_collect_pinch_nodes(); 3188 } 3189 } 3190 3191 // Garbage collect pinch nodes for reuse by other blocks. 3192 // 3193 // The block scheduler's insertion of anti-dependence 3194 // edges creates many pinch nodes when the block contains 3195 // 2 or more Calls. A pinch node is used to prevent a 3196 // combinatorial explosion of edges. If a set of kills for a 3197 // register is anti-dependent on a set of uses (or defs), rather 3198 // than adding an edge in the graph between each pair of kill 3199 // and use (or def), a pinch is inserted between them: 3200 // 3201 // use1 use2 use3 3202 // \ | / 3203 // \ | / 3204 // pinch 3205 // / | \ 3206 // / | \ 3207 // kill1 kill2 kill3 3208 // 3209 // One pinch node is created per register killed when 3210 // the second call is encountered during a backwards pass 3211 // over the block. Most of these pinch nodes are never 3212 // wired into the graph because the register is never 3213 // used or def'ed in the block. 3214 // 3215 void Scheduling::garbage_collect_pinch_nodes() { 3216 #ifndef PRODUCT 3217 if (_cfg->C->trace_opto_output()) tty->print("Reclaimed pinch nodes:"); 3218 #endif 3219 int trace_cnt = 0; 3220 for (uint k = 0; k < _reg_node.max(); k++) { 3221 Node* pinch = _reg_node[k]; 3222 if ((pinch != nullptr) && pinch->Opcode() == Op_Node && 3223 // no predecence input edges 3224 (pinch->req() == pinch->len() || pinch->in(pinch->req()) == nullptr) ) { 3225 cleanup_pinch(pinch); 3226 _pinch_free_list.push(pinch); 3227 _reg_node.map(k, nullptr); 3228 #ifndef PRODUCT 3229 if (_cfg->C->trace_opto_output()) { 3230 trace_cnt++; 3231 if (trace_cnt > 40) { 3232 tty->print("\n"); 3233 trace_cnt = 0; 3234 } 3235 tty->print(" %d", pinch->_idx); 3236 } 3237 #endif 3238 } 3239 } 3240 #ifndef PRODUCT 3241 if (_cfg->C->trace_opto_output()) tty->print("\n"); 3242 #endif 3243 } 3244 3245 // Clean up a pinch node for reuse. 3246 void Scheduling::cleanup_pinch( Node *pinch ) { 3247 assert (pinch && pinch->Opcode() == Op_Node && pinch->req() == 1, "just checking"); 3248 3249 for (DUIterator_Last imin, i = pinch->last_outs(imin); i >= imin; ) { 3250 Node* use = pinch->last_out(i); 3251 uint uses_found = 0; 3252 for (uint j = use->req(); j < use->len(); j++) { 3253 if (use->in(j) == pinch) { 3254 use->rm_prec(j); 3255 uses_found++; 3256 } 3257 } 3258 assert(uses_found > 0, "must be a precedence edge"); 3259 i -= uses_found; // we deleted 1 or more copies of this edge 3260 } 3261 // May have a later_def entry 3262 pinch->set_req(0, nullptr); 3263 } 3264 3265 #ifndef PRODUCT 3266 3267 void Scheduling::dump_available() const { 3268 tty->print("#Availist "); 3269 for (uint i = 0; i < _available.size(); i++) 3270 tty->print(" N%d/l%d", _available[i]->_idx,_current_latency[_available[i]->_idx]); 3271 tty->cr(); 3272 } 3273 3274 // Print Scheduling Statistics 3275 void Scheduling::print_statistics() { 3276 // Print the size added by nops for bundling 3277 tty->print("Nops added %d bytes to total of %d bytes", 3278 _total_nop_size, _total_method_size); 3279 if (_total_method_size > 0) 3280 tty->print(", for %.2f%%", 3281 ((double)_total_nop_size) / ((double) _total_method_size) * 100.0); 3282 tty->print("\n"); 3283 3284 // Print the number of branch shadows filled 3285 if (Pipeline::_branch_has_delay_slot) { 3286 tty->print("Of %d branches, %d had unconditional delay slots filled", 3287 _total_branches, _total_unconditional_delays); 3288 if (_total_branches > 0) 3289 tty->print(", for %.2f%%", 3290 ((double)_total_unconditional_delays) / ((double)_total_branches) * 100.0); 3291 tty->print("\n"); 3292 } 3293 3294 uint total_instructions = 0, total_bundles = 0; 3295 3296 for (uint i = 1; i <= Pipeline::_max_instrs_per_cycle; i++) { 3297 uint bundle_count = _total_instructions_per_bundle[i]; 3298 total_instructions += bundle_count * i; 3299 total_bundles += bundle_count; 3300 } 3301 3302 if (total_bundles > 0) 3303 tty->print("Average ILP (excluding nops) is %.2f\n", 3304 ((double)total_instructions) / ((double)total_bundles)); 3305 } 3306 #endif 3307 3308 //-----------------------init_scratch_buffer_blob------------------------------ 3309 // Construct a temporary BufferBlob and cache it for this compile. 3310 void PhaseOutput::init_scratch_buffer_blob(int const_size) { 3311 // If there is already a scratch buffer blob allocated and the 3312 // constant section is big enough, use it. Otherwise free the 3313 // current and allocate a new one. 3314 BufferBlob* blob = scratch_buffer_blob(); 3315 if ((blob != nullptr) && (const_size <= _scratch_const_size)) { 3316 // Use the current blob. 3317 } else { 3318 if (blob != nullptr) { 3319 BufferBlob::free(blob); 3320 } 3321 3322 ResourceMark rm; 3323 _scratch_const_size = const_size; 3324 int size = C2Compiler::initial_code_buffer_size(const_size); 3325 blob = BufferBlob::create("Compile::scratch_buffer", size); 3326 // Record the buffer blob for next time. 3327 set_scratch_buffer_blob(blob); 3328 // Have we run out of code space? 3329 if (scratch_buffer_blob() == nullptr) { 3330 // Let CompilerBroker disable further compilations. 3331 C->record_failure("Not enough space for scratch buffer in CodeCache"); 3332 return; 3333 } 3334 } 3335 3336 // Initialize the relocation buffers 3337 relocInfo* locs_buf = (relocInfo*) blob->content_end() - MAX_locs_size; 3338 set_scratch_locs_memory(locs_buf); 3339 } 3340 3341 3342 //-----------------------scratch_emit_size------------------------------------- 3343 // Helper function that computes size by emitting code 3344 uint PhaseOutput::scratch_emit_size(const Node* n) { 3345 // Start scratch_emit_size section. 3346 set_in_scratch_emit_size(true); 3347 3348 // Emit into a trash buffer and count bytes emitted. 3349 // This is a pretty expensive way to compute a size, 3350 // but it works well enough if seldom used. 3351 // All common fixed-size instructions are given a size 3352 // method by the AD file. 3353 // Note that the scratch buffer blob and locs memory are 3354 // allocated at the beginning of the compile task, and 3355 // may be shared by several calls to scratch_emit_size. 3356 // The allocation of the scratch buffer blob is particularly 3357 // expensive, since it has to grab the code cache lock. 3358 BufferBlob* blob = this->scratch_buffer_blob(); 3359 assert(blob != nullptr, "Initialize BufferBlob at start"); 3360 assert(blob->size() > MAX_inst_size, "sanity"); 3361 relocInfo* locs_buf = scratch_locs_memory(); 3362 address blob_begin = blob->content_begin(); 3363 address blob_end = (address)locs_buf; 3364 assert(blob->contains(blob_end), "sanity"); 3365 CodeBuffer buf(blob_begin, blob_end - blob_begin); 3366 buf.initialize_consts_size(_scratch_const_size); 3367 buf.initialize_stubs_size(MAX_stubs_size); 3368 assert(locs_buf != nullptr, "sanity"); 3369 int lsize = MAX_locs_size / 3; 3370 buf.consts()->initialize_shared_locs(&locs_buf[lsize * 0], lsize); 3371 buf.insts()->initialize_shared_locs( &locs_buf[lsize * 1], lsize); 3372 buf.stubs()->initialize_shared_locs( &locs_buf[lsize * 2], lsize); 3373 // Mark as scratch buffer. 3374 buf.consts()->set_scratch_emit(); 3375 buf.insts()->set_scratch_emit(); 3376 buf.stubs()->set_scratch_emit(); 3377 3378 // Do the emission. 3379 3380 Label fakeL; // Fake label for branch instructions. 3381 Label* saveL = nullptr; 3382 uint save_bnum = 0; 3383 bool is_branch = n->is_MachBranch(); 3384 C2_MacroAssembler masm(&buf); 3385 masm.bind(fakeL); 3386 if (is_branch) { 3387 n->as_MachBranch()->save_label(&saveL, &save_bnum); 3388 n->as_MachBranch()->label_set(&fakeL, 0); 3389 } 3390 n->emit(&masm, C->regalloc()); 3391 3392 // Emitting into the scratch buffer should not fail 3393 assert(!C->failing_internal() || C->failure_is_artificial(), "Must not have pending failure. Reason is: %s", C->failure_reason()); 3394 3395 if (is_branch) // Restore label. 3396 n->as_MachBranch()->label_set(saveL, save_bnum); 3397 3398 // End scratch_emit_size section. 3399 set_in_scratch_emit_size(false); 3400 3401 return buf.insts_size(); 3402 } 3403 3404 void PhaseOutput::install() { 3405 if (C->should_install_code() && C->stub_function() != nullptr) { 3406 install_stub(C->stub_name()); 3407 } else { 3408 install_code(C->method(), 3409 C->entry_bci(), 3410 CompilerThread::current()->compiler(), 3411 C->has_unsafe_access(), 3412 SharedRuntime::is_wide_vector(C->max_vector_size())); 3413 } 3414 } 3415 3416 void PhaseOutput::install_code(ciMethod* target, 3417 int entry_bci, 3418 AbstractCompiler* compiler, 3419 bool has_unsafe_access, 3420 bool has_wide_vectors) { 3421 // Check if we want to skip execution of all compiled code. 3422 { 3423 #ifndef PRODUCT 3424 if (OptoNoExecute) { 3425 C->record_method_not_compilable("+OptoNoExecute"); // Flag as failed 3426 return; 3427 } 3428 #endif 3429 Compile::TracePhase tp(_t_registerMethod); 3430 3431 if (C->is_osr_compilation()) { 3432 _code_offsets.set_value(CodeOffsets::Verified_Entry, 0); 3433 _code_offsets.set_value(CodeOffsets::OSR_Entry, _first_block_size); 3434 } else { 3435 if (!target->is_static()) { 3436 // The UEP of an nmethod ensures that the VEP is padded. However, the padding of the UEP is placed 3437 // before the inline cache check, so we don't have to execute any nop instructions when dispatching 3438 // through the UEP, yet we can ensure that the VEP is aligned appropriately. 3439 _code_offsets.set_value(CodeOffsets::Entry, _first_block_size - MacroAssembler::ic_check_size()); 3440 } 3441 _code_offsets.set_value(CodeOffsets::Verified_Entry, _first_block_size); 3442 _code_offsets.set_value(CodeOffsets::OSR_Entry, 0); 3443 } 3444 3445 C->env()->register_method(target, 3446 entry_bci, 3447 &_code_offsets, 3448 _orig_pc_slot_offset_in_bytes, 3449 code_buffer(), 3450 frame_size_in_words(), 3451 oop_map_set(), 3452 &_handler_table, 3453 inc_table(), 3454 compiler, 3455 C->has_clinit_barriers(), 3456 C->for_preload(), 3457 has_unsafe_access, 3458 SharedRuntime::is_wide_vector(C->max_vector_size()), 3459 C->has_monitors(), 3460 C->has_scoped_access(), 3461 0, 3462 C->should_install_code()); 3463 3464 if (C->log() != nullptr) { // Print code cache state into compiler log 3465 C->log()->code_cache_state(); 3466 } 3467 if (C->has_clinit_barriers()) { 3468 assert(C->for_preload(), "sanity"); 3469 // Build second version of code without class initialization barriers 3470 if (C->env()->task()->compile_reason() == CompileTask::Reason_PrecompileForPreload) { 3471 // don't automatically precompile a barrier-free version unless explicitly asked 3472 } else { 3473 C->record_failure(C2Compiler::retry_no_clinit_barriers()); 3474 } 3475 } 3476 } 3477 } 3478 void PhaseOutput::install_stub(const char* stub_name) { 3479 // Entry point will be accessed using stub_entry_point(); 3480 if (code_buffer() == nullptr) { 3481 Matcher::soft_match_failure(); 3482 } else { 3483 if (PrintAssembly && (WizardMode || Verbose)) 3484 tty->print_cr("### Stub::%s", stub_name); 3485 3486 if (!C->failing()) { 3487 assert(C->fixed_slots() == 0, "no fixed slots used for runtime stubs"); 3488 3489 // Make the NMethod 3490 // For now we mark the frame as never safe for profile stackwalking 3491 RuntimeStub *rs = RuntimeStub::new_runtime_stub(stub_name, 3492 code_buffer(), 3493 CodeOffsets::frame_never_safe, 3494 // _code_offsets.value(CodeOffsets::Frame_Complete), 3495 frame_size_in_words(), 3496 oop_map_set(), 3497 false); 3498 assert(rs != nullptr && rs->is_runtime_stub(), "sanity check"); 3499 3500 C->set_stub_entry_point(rs->entry_point()); 3501 } 3502 } 3503 } 3504 3505 // Support for bundling info 3506 Bundle* PhaseOutput::node_bundling(const Node *n) { 3507 assert(valid_bundle_info(n), "oob"); 3508 return &_node_bundling_base[n->_idx]; 3509 } 3510 3511 bool PhaseOutput::valid_bundle_info(const Node *n) { 3512 return (_node_bundling_limit > n->_idx); 3513 } 3514 3515 //------------------------------frame_size_in_words----------------------------- 3516 // frame_slots in units of words 3517 int PhaseOutput::frame_size_in_words() const { 3518 // shift is 0 in LP32 and 1 in LP64 3519 const int shift = (LogBytesPerWord - LogBytesPerInt); 3520 int words = _frame_slots >> shift; 3521 assert( words << shift == _frame_slots, "frame size must be properly aligned in LP64" ); 3522 return words; 3523 } 3524 3525 // To bang the stack of this compiled method we use the stack size 3526 // that the interpreter would need in case of a deoptimization. This 3527 // removes the need to bang the stack in the deoptimization blob which 3528 // in turn simplifies stack overflow handling. 3529 int PhaseOutput::bang_size_in_bytes() const { 3530 return MAX2(frame_size_in_bytes() + os::extra_bang_size_in_bytes(), C->interpreter_frame_size()); 3531 } 3532 3533 //------------------------------dump_asm--------------------------------------- 3534 // Dump formatted assembly 3535 #if defined(SUPPORT_OPTO_ASSEMBLY) 3536 void PhaseOutput::dump_asm_on(outputStream* st, int* pcs, uint pc_limit) { 3537 3538 int pc_digits = 3; // #chars required for pc 3539 int sb_chars = 3; // #chars for "start bundle" indicator 3540 int tab_size = 8; 3541 if (pcs != nullptr) { 3542 int max_pc = 0; 3543 for (uint i = 0; i < pc_limit; i++) { 3544 max_pc = (max_pc < pcs[i]) ? pcs[i] : max_pc; 3545 } 3546 pc_digits = ((max_pc < 4096) ? 3 : ((max_pc < 65536) ? 4 : ((max_pc < 65536*256) ? 6 : 8))); // #chars required for pc 3547 } 3548 int prefix_len = ((pc_digits + sb_chars + tab_size - 1)/tab_size)*tab_size; 3549 3550 bool cut_short = false; 3551 st->print_cr("#"); 3552 st->print("# "); C->tf()->dump_on(st); st->cr(); 3553 st->print_cr("#"); 3554 3555 // For all blocks 3556 int pc = 0x0; // Program counter 3557 char starts_bundle = ' '; 3558 C->regalloc()->dump_frame(); 3559 3560 Node *n = nullptr; 3561 for (uint i = 0; i < C->cfg()->number_of_blocks(); i++) { 3562 if (VMThread::should_terminate()) { 3563 cut_short = true; 3564 break; 3565 } 3566 Block* block = C->cfg()->get_block(i); 3567 if (block->is_connector() && !Verbose) { 3568 continue; 3569 } 3570 n = block->head(); 3571 if ((pcs != nullptr) && (n->_idx < pc_limit)) { 3572 pc = pcs[n->_idx]; 3573 st->print("%*.*x", pc_digits, pc_digits, pc); 3574 } 3575 st->fill_to(prefix_len); 3576 block->dump_head(C->cfg(), st); 3577 if (block->is_connector()) { 3578 st->fill_to(prefix_len); 3579 st->print_cr("# Empty connector block"); 3580 } else if (block->num_preds() == 2 && block->pred(1)->is_CatchProj() && block->pred(1)->as_CatchProj()->_con == CatchProjNode::fall_through_index) { 3581 st->fill_to(prefix_len); 3582 st->print_cr("# Block is sole successor of call"); 3583 } 3584 3585 // For all instructions 3586 Node *delay = nullptr; 3587 for (uint j = 0; j < block->number_of_nodes(); j++) { 3588 if (VMThread::should_terminate()) { 3589 cut_short = true; 3590 break; 3591 } 3592 n = block->get_node(j); 3593 if (valid_bundle_info(n)) { 3594 Bundle* bundle = node_bundling(n); 3595 if (bundle->used_in_unconditional_delay()) { 3596 delay = n; 3597 continue; 3598 } 3599 if (bundle->starts_bundle()) { 3600 starts_bundle = '+'; 3601 } 3602 } 3603 3604 if (WizardMode) { 3605 n->dump(); 3606 } 3607 3608 if( !n->is_Region() && // Dont print in the Assembly 3609 !n->is_Phi() && // a few noisely useless nodes 3610 !n->is_Proj() && 3611 !n->is_MachTemp() && 3612 !n->is_SafePointScalarObject() && 3613 !n->is_Catch() && // Would be nice to print exception table targets 3614 !n->is_MergeMem() && // Not very interesting 3615 !n->is_top() && // Debug info table constants 3616 !(n->is_Con() && !n->is_Mach())// Debug info table constants 3617 ) { 3618 if ((pcs != nullptr) && (n->_idx < pc_limit)) { 3619 pc = pcs[n->_idx]; 3620 st->print("%*.*x", pc_digits, pc_digits, pc); 3621 } else { 3622 st->fill_to(pc_digits); 3623 } 3624 st->print(" %c ", starts_bundle); 3625 starts_bundle = ' '; 3626 st->fill_to(prefix_len); 3627 n->format(C->regalloc(), st); 3628 st->cr(); 3629 } 3630 3631 // If we have an instruction with a delay slot, and have seen a delay, 3632 // then back up and print it 3633 if (valid_bundle_info(n) && node_bundling(n)->use_unconditional_delay()) { 3634 // Coverity finding - Explicit null dereferenced. 3635 guarantee(delay != nullptr, "no unconditional delay instruction"); 3636 if (WizardMode) delay->dump(); 3637 3638 if (node_bundling(delay)->starts_bundle()) 3639 starts_bundle = '+'; 3640 if ((pcs != nullptr) && (n->_idx < pc_limit)) { 3641 pc = pcs[n->_idx]; 3642 st->print("%*.*x", pc_digits, pc_digits, pc); 3643 } else { 3644 st->fill_to(pc_digits); 3645 } 3646 st->print(" %c ", starts_bundle); 3647 starts_bundle = ' '; 3648 st->fill_to(prefix_len); 3649 delay->format(C->regalloc(), st); 3650 st->cr(); 3651 delay = nullptr; 3652 } 3653 3654 // Dump the exception table as well 3655 if( n->is_Catch() && (Verbose || WizardMode) ) { 3656 // Print the exception table for this offset 3657 _handler_table.print_subtable_for(pc); 3658 } 3659 st->bol(); // Make sure we start on a new line 3660 } 3661 st->cr(); // one empty line between blocks 3662 assert(cut_short || delay == nullptr, "no unconditional delay branch"); 3663 } // End of per-block dump 3664 3665 if (cut_short) st->print_cr("*** disassembly is cut short ***"); 3666 } 3667 #endif 3668 3669 #ifndef PRODUCT 3670 void PhaseOutput::print_statistics() { 3671 Scheduling::print_statistics(); 3672 } 3673 #endif