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