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