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