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