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