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