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