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