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