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