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