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