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