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