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