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