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 return_oop = false;
1070   bool return_scalarized = false;
1071   bool has_ea_local_in_scope = sfn->_has_ea_local_in_scope;
1072   bool arg_escape = false;
1073 
1074   // Add the safepoint in the DebugInfoRecorder
1075   if( !mach->is_MachCall() ) {
1076     mcall = nullptr;
1077     C->debug_info()->add_safepoint(safepoint_pc_offset, sfn->_oop_map);
1078   } else {
1079     mcall = mach->as_MachCall();
1080 
1081     if (mcall->is_MachCallJava()) {
1082       arg_escape = mcall->as_MachCallJava()->_arg_escape;
1083     }
1084 
1085     // Check if a call returns an object.
1086     if (mcall->returns_pointer() || mcall->returns_scalarized()) {
1087       return_oop = true;
1088     }
1089     if (mcall->returns_scalarized()) {
1090       return_scalarized = true;
1091     }
1092     safepoint_pc_offset += mcall->ret_addr_offset();
1093     C->debug_info()->add_safepoint(safepoint_pc_offset, mcall->_oop_map);
1094   }
1095 
1096   // Loop over the JVMState list to add scope information
1097   // Do not skip safepoints with a null method, they need monitor info
1098   JVMState* youngest_jvms = sfn->jvms();
1099   int max_depth = youngest_jvms->depth();
1100 
1101   // Allocate the object pool for scalar-replaced objects -- the map from
1102   // small-integer keys (which can be recorded in the local and ostack
1103   // arrays) to descriptions of the object state.
1104   GrowableArray<ScopeValue*> *objs = new GrowableArray<ScopeValue*>();
1105 
1106   // Visit scopes from oldest to youngest.
1107   for (int depth = 1; depth <= max_depth; depth++) {
1108     JVMState* jvms = youngest_jvms->of_depth(depth);
1109     int idx;
1110     ciMethod* method = jvms->has_method() ? jvms->method() : nullptr;
1111     // Safepoints that do not have method() set only provide oop-map and monitor info
1112     // to support GC; these do not support deoptimization.
1113     int num_locs = (method == nullptr) ? 0 : jvms->loc_size();
1114     int num_exps = (method == nullptr) ? 0 : jvms->stk_size();
1115     int num_mon  = jvms->nof_monitors();
1116     assert(method == nullptr || jvms->bci() < 0 || num_locs == method->max_locals(),
1117            "JVMS local count must match that of the method");
1118 
1119     // Add Local and Expression Stack Information
1120 
1121     // Insert locals into the locarray
1122     GrowableArray<ScopeValue*> *locarray = new GrowableArray<ScopeValue*>(num_locs);
1123     for( idx = 0; idx < num_locs; idx++ ) {
1124       FillLocArray( idx, sfn, sfn->local(jvms, idx), locarray, objs );
1125     }
1126 
1127     // Insert expression stack entries into the exparray
1128     GrowableArray<ScopeValue*> *exparray = new GrowableArray<ScopeValue*>(num_exps);
1129     for( idx = 0; idx < num_exps; idx++ ) {
1130       FillLocArray( idx,  sfn, sfn->stack(jvms, idx), exparray, objs );
1131     }
1132 
1133     // Add in mappings of the monitors
1134     assert( !method ||
1135             !method->is_synchronized() ||
1136             method->is_native() ||
1137             num_mon > 0,
1138             "monitors must always exist for synchronized methods");
1139 
1140     // Build the growable array of ScopeValues for exp stack
1141     GrowableArray<MonitorValue*> *monarray = new GrowableArray<MonitorValue*>(num_mon);
1142 
1143     // Loop over monitors and insert into array
1144     for (idx = 0; idx < num_mon; idx++) {
1145       // Grab the node that defines this monitor
1146       Node* box_node = sfn->monitor_box(jvms, idx);
1147       Node* obj_node = sfn->monitor_obj(jvms, idx);
1148 
1149       // Create ScopeValue for object
1150       ScopeValue *scval = nullptr;
1151 
1152       if (obj_node->is_SafePointScalarObject()) {
1153         SafePointScalarObjectNode* spobj = obj_node->as_SafePointScalarObject();
1154         scval = PhaseOutput::sv_for_node_id(objs, spobj->_idx);
1155         if (scval == nullptr) {
1156           const Type *t = spobj->bottom_type();
1157           ciKlass* cik = t->is_oopptr()->exact_klass();
1158           assert(cik->is_instance_klass() ||
1159                  cik->is_array_klass(), "Not supported allocation.");
1160           assert(!cik->is_inlinetype(), "Synchronization on value object?");
1161           ScopeValue* properties = nullptr;
1162           if (cik->is_array_klass() && !cik->is_type_array_klass()) {
1163             jint props = ArrayKlass::ArrayProperties::DEFAULT;
1164             if (cik->as_array_klass()->element_klass()->is_inlinetype()) {
1165               if (cik->as_array_klass()->is_elem_null_free()) {
1166                 props |= ArrayKlass::ArrayProperties::NULL_RESTRICTED;
1167               }
1168               if (!cik->as_array_klass()->is_elem_atomic()) {
1169                 props |= ArrayKlass::ArrayProperties::NON_ATOMIC;
1170               }
1171             }
1172             properties = new ConstantIntValue(props);
1173           }
1174           ObjectValue* sv = new ObjectValue(spobj->_idx,
1175                                             new ConstantOopWriteValue(cik->java_mirror()->constant_encoding()), true, properties);
1176           PhaseOutput::set_sv_for_object_node(objs, sv);
1177 
1178           uint first_ind = spobj->first_index(youngest_jvms);
1179           for (uint i = 0; i < spobj->n_fields(); i++) {
1180             Node* fld_node = sfn->in(first_ind+i);
1181             (void)FillLocArray(sv->field_values()->length(), sfn, fld_node, sv->field_values(), objs);
1182           }
1183           scval = sv;
1184         }
1185       } else if (obj_node->is_SafePointScalarMerge()) {
1186         SafePointScalarMergeNode* smerge = obj_node->as_SafePointScalarMerge();
1187         ObjectMergeValue* mv = (ObjectMergeValue*) sv_for_node_id(objs, smerge->_idx);
1188 
1189         if (mv == nullptr) {
1190           GrowableArray<ScopeValue*> deps;
1191 
1192           int merge_pointer_idx = smerge->merge_pointer_idx(youngest_jvms);
1193           FillLocArray(0, sfn, sfn->in(merge_pointer_idx), &deps, objs);
1194           assert(deps.length() == 1, "missing value");
1195 
1196           int selector_idx = smerge->selector_idx(youngest_jvms);
1197           FillLocArray(1, nullptr, sfn->in(selector_idx), &deps, nullptr);
1198           assert(deps.length() == 2, "missing value");
1199 
1200           mv = new ObjectMergeValue(smerge->_idx, deps.at(0), deps.at(1));
1201           set_sv_for_object_node(objs, mv);
1202 
1203           for (uint i = 1; i < smerge->req(); i++) {
1204             Node* obj_node = smerge->in(i);
1205             int idx = mv->possible_objects()->length();
1206             (void)FillLocArray(idx, sfn, obj_node, mv->possible_objects(), objs);
1207 
1208             // By default ObjectValues that are in 'possible_objects' are not root objects.
1209             // They will be marked as root later if they are directly referenced in a JVMS.
1210             assert(mv->possible_objects()->length() > idx, "Didn't add entry to possible_objects?!");
1211             assert(mv->possible_objects()->at(idx)->is_object(), "Entries in possible_objects should be ObjectValue.");
1212             mv->possible_objects()->at(idx)->as_ObjectValue()->set_root(false);
1213           }
1214         }
1215         scval = mv;
1216       } else if (!obj_node->is_Con()) {
1217         OptoReg::Name obj_reg = C->regalloc()->get_reg_first(obj_node);
1218         if( obj_node->bottom_type()->base() == Type::NarrowOop ) {
1219           scval = new_loc_value( C->regalloc(), obj_reg, Location::narrowoop );
1220         } else {
1221           scval = new_loc_value( C->regalloc(), obj_reg, Location::oop );
1222         }
1223       } else {
1224         const TypePtr *tp = obj_node->get_ptr_type();
1225         scval = new ConstantOopWriteValue(tp->is_oopptr()->const_oop()->constant_encoding());
1226       }
1227 
1228       OptoReg::Name box_reg = BoxLockNode::reg(box_node);
1229       Location basic_lock = Location::new_stk_loc(Location::normal,C->regalloc()->reg2offset(box_reg));
1230       bool eliminated = (box_node->is_BoxLock() && box_node->as_BoxLock()->is_eliminated());
1231       monarray->append(new MonitorValue(scval, basic_lock, eliminated));
1232     }
1233 
1234     // Mark ObjectValue nodes as root nodes if they are directly
1235     // referenced in the JVMS.
1236     for (int i = 0; i < objs->length(); i++) {
1237       ScopeValue* sv = objs->at(i);
1238       if (sv->is_object_merge()) {
1239         ObjectMergeValue* merge = sv->as_ObjectMergeValue();
1240 
1241         for (int j = 0; j< merge->possible_objects()->length(); j++) {
1242           ObjectValue* ov = merge->possible_objects()->at(j)->as_ObjectValue();
1243           if (ov->is_root()) {
1244             // Already flagged as 'root' by something else. We shouldn't change it
1245             // to non-root in a younger JVMS because it may need to be alive in
1246             // a younger JVMS.
1247           } else {
1248             bool is_root = locarray->contains(ov) ||
1249                            exparray->contains(ov) ||
1250                            contains_as_owner(monarray, ov) ||
1251                            contains_as_scalarized_obj(jvms, sfn, objs, ov);
1252             ov->set_root(is_root);
1253           }
1254         }
1255       }
1256     }
1257 
1258     // We dump the object pool first, since deoptimization reads it in first.
1259     C->debug_info()->dump_object_pool(objs);
1260 
1261     // Build first class objects to pass to scope
1262     DebugToken *locvals = C->debug_info()->create_scope_values(locarray);
1263     DebugToken *expvals = C->debug_info()->create_scope_values(exparray);
1264     DebugToken *monvals = C->debug_info()->create_monitor_values(monarray);
1265 
1266     // Make method available for all Safepoints
1267     ciMethod* scope_method = method ? method : C->method();
1268     // Describe the scope here
1269     assert(jvms->bci() >= InvocationEntryBci && jvms->bci() <= 0x10000, "must be a valid or entry BCI");
1270     assert(!jvms->should_reexecute() || depth == max_depth, "reexecute allowed only for the youngest");
1271     // Now we can describe the scope.
1272     methodHandle null_mh;
1273     bool rethrow_exception = false;
1274     C->debug_info()->describe_scope(
1275       safepoint_pc_offset,
1276       null_mh,
1277       scope_method,
1278       jvms->bci(),
1279       jvms->should_reexecute(),
1280       rethrow_exception,
1281       return_oop,
1282       return_scalarized,
1283       has_ea_local_in_scope,
1284       arg_escape,
1285       locvals,
1286       expvals,
1287       monvals
1288     );
1289   } // End jvms loop
1290 
1291   // Mark the end of the scope set.
1292   C->debug_info()->end_safepoint(safepoint_pc_offset);
1293 }
1294 
1295 
1296 
1297 // A simplified version of Process_OopMap_Node, to handle non-safepoints.
1298 class NonSafepointEmitter {
1299     Compile*  C;
1300     JVMState* _pending_jvms;
1301     int       _pending_offset;
1302 
1303     void emit_non_safepoint();
1304 
1305  public:
1306     NonSafepointEmitter(Compile* compile) {
1307       this->C = compile;
1308       _pending_jvms = nullptr;
1309       _pending_offset = 0;
1310     }
1311 
1312     void observe_instruction(Node* n, int pc_offset) {
1313       if (!C->debug_info()->recording_non_safepoints())  return;
1314 
1315       Node_Notes* nn = C->node_notes_at(n->_idx);
1316       if (nn == nullptr || nn->jvms() == nullptr)  return;
1317       if (_pending_jvms != nullptr &&
1318           _pending_jvms->same_calls_as(nn->jvms())) {
1319         // Repeated JVMS?  Stretch it up here.
1320         _pending_offset = pc_offset;
1321       } else {
1322         if (_pending_jvms != nullptr &&
1323             _pending_offset < pc_offset) {
1324           emit_non_safepoint();
1325         }
1326         _pending_jvms = nullptr;
1327         if (pc_offset > C->debug_info()->last_pc_offset()) {
1328           // This is the only way _pending_jvms can become non-null:
1329           _pending_jvms = nn->jvms();
1330           _pending_offset = pc_offset;
1331         }
1332       }
1333     }
1334 
1335     // Stay out of the way of real safepoints:
1336     void observe_safepoint(JVMState* jvms, int pc_offset) {
1337       if (_pending_jvms != nullptr &&
1338           !_pending_jvms->same_calls_as(jvms) &&
1339           _pending_offset < pc_offset) {
1340         emit_non_safepoint();
1341       }
1342       _pending_jvms = nullptr;
1343     }
1344 
1345     void flush_at_end() {
1346       if (_pending_jvms != nullptr) {
1347         emit_non_safepoint();
1348       }
1349       _pending_jvms = nullptr;
1350     }
1351 };
1352 
1353 void NonSafepointEmitter::emit_non_safepoint() {
1354   JVMState* youngest_jvms = _pending_jvms;
1355   int       pc_offset     = _pending_offset;
1356 
1357   // Clear it now:
1358   _pending_jvms = nullptr;
1359 
1360   DebugInformationRecorder* debug_info = C->debug_info();
1361   assert(debug_info->recording_non_safepoints(), "sanity");
1362 
1363   debug_info->add_non_safepoint(pc_offset);
1364   int max_depth = youngest_jvms->depth();
1365 
1366   // Visit scopes from oldest to youngest.
1367   for (int depth = 1; depth <= max_depth; depth++) {
1368     JVMState* jvms = youngest_jvms->of_depth(depth);
1369     ciMethod* method = jvms->has_method() ? jvms->method() : nullptr;
1370     assert(!jvms->should_reexecute() || depth==max_depth, "reexecute allowed only for the youngest");
1371     methodHandle null_mh;
1372     debug_info->describe_scope(pc_offset, null_mh, method, jvms->bci(), jvms->should_reexecute());
1373   }
1374 
1375   // Mark the end of the scope set.
1376   debug_info->end_non_safepoint(pc_offset);
1377 }
1378 
1379 //------------------------------init_buffer------------------------------------
1380 void PhaseOutput::estimate_buffer_size(int& const_req) {
1381 
1382   // Set the initially allocated size
1383   const_req = initial_const_capacity;
1384 
1385   // The extra spacing after the code is necessary on some platforms.
1386   // Sometimes we need to patch in a jump after the last instruction,
1387   // if the nmethod has been deoptimized.  (See 4932387, 4894843.)
1388 
1389   // Compute the byte offset where we can store the deopt pc.
1390   if (C->fixed_slots() != 0) {
1391     _orig_pc_slot_offset_in_bytes = C->regalloc()->reg2offset(OptoReg::stack2reg(_orig_pc_slot));
1392   }
1393 
1394   // Compute prolog code size
1395   _frame_slots = OptoReg::reg2stack(C->matcher()->_old_SP) + C->regalloc()->_framesize;
1396   assert(_frame_slots >= 0 && _frame_slots < 1000000, "sanity check");
1397 
1398   if (C->has_mach_constant_base_node()) {
1399     uint add_size = 0;
1400     // Fill the constant table.
1401     // Note:  This must happen before shorten_branches.
1402     for (uint i = 0; i < C->cfg()->number_of_blocks(); i++) {
1403       Block* b = C->cfg()->get_block(i);
1404 
1405       for (uint j = 0; j < b->number_of_nodes(); j++) {
1406         Node* n = b->get_node(j);
1407 
1408         // If the node is a MachConstantNode evaluate the constant
1409         // value section.
1410         if (n->is_MachConstant()) {
1411           MachConstantNode* machcon = n->as_MachConstant();
1412           machcon->eval_constant(C);
1413         } else if (n->is_Mach()) {
1414           // On Power there are more nodes that issue constants.
1415           add_size += (n->as_Mach()->ins_num_consts() * 8);
1416         }
1417       }
1418     }
1419 
1420     // Calculate the offsets of the constants and the size of the
1421     // constant table (including the padding to the next section).
1422     constant_table().calculate_offsets_and_size();
1423     const_req = constant_table().alignment() + constant_table().size() + add_size;
1424   }
1425 
1426   // Initialize the space for the BufferBlob used to find and verify
1427   // instruction size in MachNode::emit_size()
1428   init_scratch_buffer_blob(const_req);
1429 }
1430 
1431 CodeBuffer* PhaseOutput::init_buffer() {
1432   int stub_req  = _buf_sizes._stub;
1433   int code_req  = _buf_sizes._code;
1434   int const_req = _buf_sizes._const;
1435 
1436   int pad_req   = NativeCall::byte_size();
1437 
1438   BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
1439   stub_req += bs->estimate_stub_size();
1440 
1441   // nmethod and CodeBuffer count stubs & constants as part of method's code.
1442   // class HandlerImpl is platform-specific and defined in the *.ad files.
1443   int exception_handler_req = HandlerImpl::size_exception_handler() + MAX_stubs_size; // add marginal slop for handler
1444   int deopt_handler_req     = HandlerImpl::size_deopt_handler()     + MAX_stubs_size; // add marginal slop for handler
1445   stub_req += MAX_stubs_size;   // ensure per-stub margin
1446   code_req += MAX_inst_size;    // ensure per-instruction margin
1447 
1448   if (StressCodeBuffers)
1449     code_req = const_req = stub_req = exception_handler_req = deopt_handler_req = 0x10;  // force expansion
1450 
1451   int total_req =
1452           const_req +
1453           code_req +
1454           pad_req +
1455           stub_req +
1456           exception_handler_req +
1457           deopt_handler_req;               // deopt handler
1458 
1459   CodeBuffer* cb = code_buffer();
1460   cb->set_const_section_alignment(constant_table().alignment());
1461   cb->initialize(total_req, _buf_sizes._reloc);
1462 
1463   // Have we run out of code space?
1464   if ((cb->blob() == nullptr) || (!CompileBroker::should_compile_new_jobs())) {
1465     C->record_failure("CodeCache is full");
1466     return nullptr;
1467   }
1468   // Configure the code buffer.
1469   cb->initialize_consts_size(const_req);
1470   cb->initialize_stubs_size(stub_req);
1471   cb->initialize_oop_recorder(C->env()->oop_recorder());
1472 
1473   return cb;
1474 }
1475 
1476 //------------------------------fill_buffer------------------------------------
1477 void PhaseOutput::fill_buffer(C2_MacroAssembler* masm, uint* blk_starts) {
1478   // blk_starts[] contains offsets calculated during short branches processing,
1479   // offsets should not be increased during following steps.
1480 
1481   // Compute the size of first NumberOfLoopInstrToAlign instructions at head
1482   // of a loop. It is used to determine the padding for loop alignment.
1483   Compile::TracePhase tp(_t_fillBuffer);
1484 
1485   compute_loop_first_inst_sizes();
1486 
1487   // Create oopmap set.
1488   _oop_map_set = new OopMapSet();
1489 
1490   // !!!!! This preserves old handling of oopmaps for now
1491   C->debug_info()->set_oopmaps(_oop_map_set);
1492 
1493   uint nblocks  = C->cfg()->number_of_blocks();
1494   // Count and start of implicit null check instructions
1495   uint inct_cnt = 0;
1496   uint* inct_starts = NEW_RESOURCE_ARRAY(uint, nblocks+1);
1497 
1498   // Count and start of calls
1499   uint* call_returns = NEW_RESOURCE_ARRAY(uint, nblocks+1);
1500 
1501   uint  return_offset = 0;
1502   int nop_size = (new MachNopNode())->size(C->regalloc());
1503 
1504   int previous_offset = 0;
1505   int current_offset  = 0;
1506   int last_call_offset = -1;
1507   int last_avoid_back_to_back_offset = -1;
1508 #ifdef ASSERT
1509   uint* jmp_target = NEW_RESOURCE_ARRAY(uint,nblocks);
1510   uint* jmp_offset = NEW_RESOURCE_ARRAY(uint,nblocks);
1511   uint* jmp_size   = NEW_RESOURCE_ARRAY(uint,nblocks);
1512   uint* jmp_rule   = NEW_RESOURCE_ARRAY(uint,nblocks);
1513 #endif
1514 
1515   // Create an array of unused labels, one for each basic block, if printing is enabled
1516 #if defined(SUPPORT_OPTO_ASSEMBLY)
1517   int* node_offsets      = nullptr;
1518   uint node_offset_limit = C->unique();
1519 
1520   if (C->print_assembly()) {
1521     node_offsets = NEW_RESOURCE_ARRAY(int, node_offset_limit);
1522   }
1523   if (node_offsets != nullptr) {
1524     // We need to initialize. Unused array elements may contain garbage and mess up PrintOptoAssembly.
1525     memset(node_offsets, 0, node_offset_limit*sizeof(int));
1526   }
1527 #endif
1528 
1529   NonSafepointEmitter non_safepoints(C);  // emit non-safepoints lazily
1530 
1531   // Emit the constant table.
1532   if (C->has_mach_constant_base_node()) {
1533     if (!constant_table().emit(masm)) {
1534       C->record_failure("consts section overflow");
1535       return;
1536     }
1537   }
1538 
1539   // Create an array of labels, one for each basic block
1540   Label* blk_labels = NEW_RESOURCE_ARRAY(Label, nblocks+1);
1541   for (uint i = 0; i <= nblocks; i++) {
1542     blk_labels[i].init();
1543   }
1544 
1545   // Now fill in the code buffer
1546   for (uint i = 0; i < nblocks; i++) {
1547     Block* block = C->cfg()->get_block(i);
1548     _block = block;
1549     Node* head = block->head();
1550 
1551     // If this block needs to start aligned (i.e, can be reached other
1552     // than by falling-thru from the previous block), then force the
1553     // start of a new bundle.
1554     if (Pipeline::requires_bundling() && starts_bundle(head)) {
1555       masm->code()->flush_bundle(true);
1556     }
1557 
1558 #ifdef ASSERT
1559     if (!block->is_connector()) {
1560       stringStream st;
1561       block->dump_head(C->cfg(), &st);
1562       masm->block_comment(st.freeze());
1563     }
1564     jmp_target[i] = 0;
1565     jmp_offset[i] = 0;
1566     jmp_size[i]   = 0;
1567     jmp_rule[i]   = 0;
1568 #endif
1569     int blk_offset = current_offset;
1570 
1571     // Define the label at the beginning of the basic block
1572     masm->bind(blk_labels[block->_pre_order]);
1573 
1574     uint last_inst = block->number_of_nodes();
1575 
1576     // Emit block normally, except for last instruction.
1577     // Emit means "dump code bits into code buffer".
1578     for (uint j = 0; j<last_inst; j++) {
1579       _index = j;
1580 
1581       // Get the node
1582       Node* n = block->get_node(j);
1583 
1584       // If this starts a new instruction group, then flush the current one
1585       // (but allow split bundles)
1586       if (Pipeline::requires_bundling() && starts_bundle(n))
1587         masm->code()->flush_bundle(false);
1588 
1589       // Special handling for SafePoint/Call Nodes
1590       bool is_mcall = false;
1591       if (n->is_Mach()) {
1592         MachNode *mach = n->as_Mach();
1593         is_mcall = n->is_MachCall();
1594         bool is_sfn = n->is_MachSafePoint();
1595 
1596         // If this requires all previous instructions be flushed, then do so
1597         if (is_sfn || is_mcall || mach->alignment_required() != 1) {
1598           masm->code()->flush_bundle(true);
1599           current_offset = masm->offset();
1600         }
1601 
1602         // align the instruction if necessary
1603         int padding = mach->compute_padding(current_offset);
1604         // Make sure safepoint node for polling is distinct from a call's
1605         // return by adding a nop if needed.
1606         if (is_sfn && !is_mcall && padding == 0 && current_offset == last_call_offset) {
1607           padding = nop_size;
1608         }
1609         if (padding == 0 && mach->avoid_back_to_back(MachNode::AVOID_BEFORE) &&
1610             current_offset == last_avoid_back_to_back_offset) {
1611           // Avoid back to back some instructions.
1612           padding = nop_size;
1613         }
1614 
1615         if (padding > 0) {
1616           assert((padding % nop_size) == 0, "padding is not a multiple of NOP size");
1617           int nops_cnt = padding / nop_size;
1618           MachNode *nop = new MachNopNode(nops_cnt);
1619           block->insert_node(nop, j++);
1620           last_inst++;
1621           C->cfg()->map_node_to_block(nop, block);
1622           // Ensure enough space.
1623           masm->code()->insts()->maybe_expand_to_ensure_remaining(MAX_inst_size);
1624           if ((masm->code()->blob() == nullptr) || (!CompileBroker::should_compile_new_jobs())) {
1625             C->record_failure("CodeCache is full");
1626             return;
1627           }
1628           nop->emit(masm, C->regalloc());
1629           masm->code()->flush_bundle(true);
1630           current_offset = masm->offset();
1631         }
1632 
1633         bool observe_safepoint = is_sfn;
1634         // Remember the start of the last call in a basic block
1635         if (is_mcall) {
1636           MachCallNode *mcall = mach->as_MachCall();
1637 
1638           if (mcall->entry_point() != nullptr) {
1639             // This destination address is NOT PC-relative
1640             mcall->method_set((intptr_t)mcall->entry_point());
1641           }
1642 
1643           // Save the return address
1644           call_returns[block->_pre_order] = current_offset + mcall->ret_addr_offset();
1645 
1646           observe_safepoint = mcall->guaranteed_safepoint();
1647         }
1648 
1649         // sfn will be valid whenever mcall is valid now because of inheritance
1650         if (observe_safepoint) {
1651           // Handle special safepoint nodes for synchronization
1652           if (!is_mcall) {
1653             MachSafePointNode *sfn = mach->as_MachSafePoint();
1654             // !!!!! Stubs only need an oopmap right now, so bail out
1655             if (sfn->jvms()->method() == nullptr) {
1656               // Write the oopmap directly to the code blob??!!
1657               continue;
1658             }
1659           } // End synchronization
1660 
1661           non_safepoints.observe_safepoint(mach->as_MachSafePoint()->jvms(),
1662                                            current_offset);
1663           Process_OopMap_Node(mach, current_offset);
1664         } // End if safepoint
1665 
1666           // If this is a null check, then add the start of the previous instruction to the list
1667         else if( mach->is_MachNullCheck() ) {
1668           inct_starts[inct_cnt++] = previous_offset;
1669         }
1670 
1671           // If this is a branch, then fill in the label with the target BB's label
1672         else if (mach->is_MachBranch()) {
1673           // This requires the TRUE branch target be in succs[0]
1674           uint block_num = block->non_connector_successor(0)->_pre_order;
1675 
1676           // Try to replace long branch,
1677           // it is mostly for back branches since forward branch's
1678           // distance is not updated yet.
1679           if (mach->may_be_short_branch()) {
1680             int br_size = n->size(C->regalloc());
1681             int offset = blk_starts[block_num] - current_offset;
1682             if (block_num >= i) {
1683               // Current and following block's offset are not
1684               // finalized yet, adjust distance by the difference
1685               // between calculated and final offsets of current block.
1686               offset -= (blk_starts[i] - blk_offset);
1687             }
1688             // In the following code a nop could be inserted before
1689             // the branch which will increase the backward distance.
1690             bool needs_padding = (current_offset == last_avoid_back_to_back_offset);
1691             if (needs_padding && offset <= 0)
1692               offset -= nop_size;
1693 
1694             if (C->matcher()->is_short_branch_offset(mach->rule(), br_size, offset)) {
1695               // We've got a winner.  Replace this branch.
1696               MachNode* replacement = mach->as_MachBranch()->short_branch_version();
1697 
1698               // Update the jmp_size.
1699               int new_size = replacement->size(C->regalloc());
1700               assert((br_size - new_size) >= (int)nop_size, "short_branch size should be smaller");
1701               // Insert padding between avoid_back_to_back branches.
1702               if (needs_padding && replacement->avoid_back_to_back(MachNode::AVOID_BEFORE)) {
1703                 MachNode *nop = new MachNopNode();
1704                 block->insert_node(nop, j++);
1705                 C->cfg()->map_node_to_block(nop, block);
1706                 last_inst++;
1707                 nop->emit(masm, C->regalloc());
1708                 masm->code()->flush_bundle(true);
1709                 current_offset = masm->offset();
1710               }
1711 #ifdef ASSERT
1712               jmp_target[i] = block_num;
1713               jmp_offset[i] = current_offset - blk_offset;
1714               jmp_size[i]   = new_size;
1715               jmp_rule[i]   = mach->rule();
1716 #endif
1717               block->map_node(replacement, j);
1718               mach->subsume_by(replacement, C);
1719               n    = replacement;
1720               mach = replacement;
1721             }
1722           }
1723           mach->as_MachBranch()->label_set( &blk_labels[block_num], block_num );
1724         } else if (mach->ideal_Opcode() == Op_Jump) {
1725           for (uint h = 0; h < block->_num_succs; h++) {
1726             Block* succs_block = block->_succs[h];
1727             for (uint j = 1; j < succs_block->num_preds(); j++) {
1728               Node* jpn = succs_block->pred(j);
1729               if (jpn->is_JumpProj() && jpn->in(0) == mach) {
1730                 uint block_num = succs_block->non_connector()->_pre_order;
1731                 Label *blkLabel = &blk_labels[block_num];
1732                 mach->add_case_label(jpn->as_JumpProj()->proj_no(), blkLabel);
1733               }
1734             }
1735           }
1736         } else if (!n->is_Proj()) {
1737           // Remember the beginning of the previous instruction, in case
1738           // it's followed by a flag-kill and a null-check.  Happens on
1739           // Intel all the time, with add-to-memory kind of opcodes.
1740           previous_offset = current_offset;
1741         }
1742 
1743         // Not an else-if!
1744         // If this is a trap based cmp then add its offset to the list.
1745         if (mach->is_TrapBasedCheckNode()) {
1746           inct_starts[inct_cnt++] = current_offset;
1747         }
1748       }
1749 
1750       // Verify that there is sufficient space remaining
1751       masm->code()->insts()->maybe_expand_to_ensure_remaining(MAX_inst_size);
1752       if ((masm->code()->blob() == nullptr) || (!CompileBroker::should_compile_new_jobs())) {
1753         C->record_failure("CodeCache is full");
1754         return;
1755       }
1756 
1757       // Save the offset for the listing
1758 #if defined(SUPPORT_OPTO_ASSEMBLY)
1759       if ((node_offsets != nullptr) && (n->_idx < node_offset_limit)) {
1760         node_offsets[n->_idx] = masm->offset();
1761       }
1762 #endif
1763       assert(!C->failing_internal() || C->failure_is_artificial(), "Should not reach here if failing.");
1764 
1765       // "Normal" instruction case
1766       DEBUG_ONLY(uint instr_offset = masm->offset());
1767       n->emit(masm, C->regalloc());
1768       current_offset = masm->offset();
1769 
1770       // Above we only verified that there is enough space in the instruction section.
1771       // However, the instruction may emit stubs that cause code buffer expansion.
1772       // Bail out here if expansion failed due to a lack of code cache space.
1773       if (C->failing()) {
1774         return;
1775       }
1776 
1777       assert(!is_mcall || (call_returns[block->_pre_order] <= (uint)current_offset),
1778              "ret_addr_offset() not within emitted code");
1779 #ifdef ASSERT
1780       uint n_size = n->size(C->regalloc());
1781       if (n_size < (current_offset-instr_offset)) {
1782         MachNode* mach = n->as_Mach();
1783         n->dump();
1784         mach->dump_format(C->regalloc(), tty);
1785         tty->print_cr(" n_size (%d), current_offset (%d), instr_offset (%d)", n_size, current_offset, instr_offset);
1786         Disassembler::decode(masm->code()->insts_begin() + instr_offset, masm->code()->insts_begin() + current_offset + 1, tty);
1787         tty->print_cr(" ------------------- ");
1788         BufferBlob* blob = this->scratch_buffer_blob();
1789         address blob_begin = blob->content_begin();
1790         Disassembler::decode(blob_begin, blob_begin + n_size + 1, tty);
1791         assert(false, "wrong size of mach node");
1792       }
1793 #endif
1794       non_safepoints.observe_instruction(n, current_offset);
1795 
1796       // mcall is last "call" that can be a safepoint
1797       // record it so we can see if a poll will directly follow it
1798       // in which case we'll need a pad to make the PcDesc sites unique
1799       // see  5010568. This can be slightly inaccurate but conservative
1800       // in the case that return address is not actually at current_offset.
1801       // This is a small price to pay.
1802 
1803       if (is_mcall) {
1804         last_call_offset = current_offset;
1805       }
1806 
1807       if (n->is_Mach() && n->as_Mach()->avoid_back_to_back(MachNode::AVOID_AFTER)) {
1808         // Avoid back to back some instructions.
1809         last_avoid_back_to_back_offset = current_offset;
1810       }
1811 
1812     } // End for all instructions in block
1813 
1814     // If the next block is the top of a loop, pad this block out to align
1815     // the loop top a little. Helps prevent pipe stalls at loop back branches.
1816     if (i < nblocks-1) {
1817       Block *nb = C->cfg()->get_block(i + 1);
1818       int padding = nb->alignment_padding(current_offset);
1819       if( padding > 0 ) {
1820         MachNode *nop = new MachNopNode(padding / nop_size);
1821         block->insert_node(nop, block->number_of_nodes());
1822         C->cfg()->map_node_to_block(nop, block);
1823         nop->emit(masm, C->regalloc());
1824         current_offset = masm->offset();
1825       }
1826     }
1827     // Verify that the distance for generated before forward
1828     // short branches is still valid.
1829     guarantee((int)(blk_starts[i+1] - blk_starts[i]) >= (current_offset - blk_offset), "shouldn't increase block size");
1830 
1831     // Save new block start offset
1832     blk_starts[i] = blk_offset;
1833   } // End of for all blocks
1834   blk_starts[nblocks] = current_offset;
1835 
1836   non_safepoints.flush_at_end();
1837 
1838   // Offset too large?
1839   if (C->failing())  return;
1840 
1841   // Define a pseudo-label at the end of the code
1842   masm->bind( blk_labels[nblocks] );
1843 
1844   // Compute the size of the first block
1845   _first_block_size = blk_labels[1].loc_pos() - blk_labels[0].loc_pos();
1846 
1847 #ifdef ASSERT
1848   for (uint i = 0; i < nblocks; i++) { // For all blocks
1849     if (jmp_target[i] != 0) {
1850       int br_size = jmp_size[i];
1851       int offset = blk_starts[jmp_target[i]]-(blk_starts[i] + jmp_offset[i]);
1852       if (!C->matcher()->is_short_branch_offset(jmp_rule[i], br_size, offset)) {
1853         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]);
1854         assert(false, "Displacement too large for short jmp");
1855       }
1856     }
1857   }
1858 #endif
1859 
1860   if (!masm->code()->finalize_stubs()) {
1861     C->record_failure("CodeCache is full");
1862     return;
1863   }
1864 
1865   BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
1866   bs->emit_stubs(*masm->code());
1867   if (C->failing())  return;
1868 
1869   // Fill in stubs.
1870   assert(masm->inst_mark() == nullptr, "should be.");
1871   _stub_list.emit(*masm);
1872   if (C->failing())  return;
1873 
1874 #ifndef PRODUCT
1875   // Information on the size of the method, without the extraneous code
1876   Scheduling::increment_method_size(masm->offset());
1877 #endif
1878 
1879   // ------------------
1880   // Fill in exception table entries.
1881   FillExceptionTables(inct_cnt, call_returns, inct_starts, blk_labels);
1882 
1883   // Only java methods have exception handlers and deopt handlers
1884   // class HandlerImpl is platform-specific and defined in the *.ad files.
1885   if (C->method()) {
1886     // Emit the exception handler code.
1887     _code_offsets.set_value(CodeOffsets::Exceptions, HandlerImpl::emit_exception_handler(masm));
1888     if (C->failing()) {
1889       return; // CodeBuffer::expand failed
1890     }
1891     // Emit the deopt handler code.
1892     _code_offsets.set_value(CodeOffsets::Deopt, HandlerImpl::emit_deopt_handler(masm));
1893   }
1894 
1895   // One last check for failed CodeBuffer::expand:
1896   if ((masm->code()->blob() == nullptr) || (!CompileBroker::should_compile_new_jobs())) {
1897     C->record_failure("CodeCache is full");
1898     return;
1899   }
1900 
1901 #if defined(SUPPORT_ABSTRACT_ASSEMBLY) || defined(SUPPORT_ASSEMBLY) || defined(SUPPORT_OPTO_ASSEMBLY)
1902   if (C->print_assembly()) {
1903     tty->cr();
1904     tty->print_cr("============================= C2-compiled nmethod ==============================");
1905   }
1906 #endif
1907 
1908 #if defined(SUPPORT_OPTO_ASSEMBLY)
1909   // Dump the assembly code, including basic-block numbers
1910   if (C->print_assembly()) {
1911     ttyLocker ttyl;  // keep the following output all in one block
1912     if (!VMThread::should_terminate()) {  // test this under the tty lock
1913       // print_metadata and dump_asm may safepoint which makes us loose the ttylock.
1914       // We call them first and write to a stringStream, then we retake the lock to
1915       // make sure the end tag is coherent, and that xmlStream->pop_tag is done thread safe.
1916       ResourceMark rm;
1917       stringStream method_metadata_str;
1918       if (C->method() != nullptr) {
1919         C->method()->print_metadata(&method_metadata_str);
1920       }
1921       stringStream dump_asm_str;
1922       dump_asm_on(&dump_asm_str, node_offsets, node_offset_limit);
1923 
1924       NoSafepointVerifier nsv;
1925       ttyLocker ttyl2;
1926       // This output goes directly to the tty, not the compiler log.
1927       // To enable tools to match it up with the compilation activity,
1928       // be sure to tag this tty output with the compile ID.
1929       if (xtty != nullptr) {
1930         xtty->head("opto_assembly compile_id='%d'%s", C->compile_id(),
1931                    C->is_osr_compilation() ? " compile_kind='osr'" : "");
1932       }
1933       if (C->method() != nullptr) {
1934         tty->print_cr("----------------------- MetaData before Compile_id = %d ------------------------", C->compile_id());
1935         tty->print_raw(method_metadata_str.freeze());
1936       } else if (C->stub_name() != nullptr) {
1937         tty->print_cr("----------------------------- RuntimeStub %s -------------------------------", C->stub_name());
1938       }
1939       tty->cr();
1940       tty->print_cr("------------------------ OptoAssembly for Compile_id = %d -----------------------", C->compile_id());
1941       tty->print_raw(dump_asm_str.freeze());
1942       tty->print_cr("--------------------------------------------------------------------------------");
1943       if (xtty != nullptr) {
1944         xtty->tail("opto_assembly");
1945       }
1946     }
1947   }
1948 #endif
1949 }
1950 
1951 void PhaseOutput::FillExceptionTables(uint cnt, uint *call_returns, uint *inct_starts, Label *blk_labels) {
1952   _inc_table.set_size(cnt);
1953 
1954   uint inct_cnt = 0;
1955   for (uint i = 0; i < C->cfg()->number_of_blocks(); i++) {
1956     Block* block = C->cfg()->get_block(i);
1957     Node *n = nullptr;
1958     int j;
1959 
1960     // Find the branch; ignore trailing NOPs.
1961     for (j = block->number_of_nodes() - 1; j >= 0; j--) {
1962       n = block->get_node(j);
1963       if (!n->is_Mach() || n->as_Mach()->ideal_Opcode() != Op_Con) {
1964         break;
1965       }
1966     }
1967 
1968     // If we didn't find anything, continue
1969     if (j < 0) {
1970       continue;
1971     }
1972 
1973     // Compute ExceptionHandlerTable subtable entry and add it
1974     // (skip empty blocks)
1975     if (n->is_Catch()) {
1976 
1977       // Get the offset of the return from the call
1978       uint call_return = call_returns[block->_pre_order];
1979 #ifdef ASSERT
1980       assert( call_return > 0, "no call seen for this basic block" );
1981       while (block->get_node(--j)->is_MachProj()) ;
1982       assert(block->get_node(j)->is_MachCall(), "CatchProj must follow call");
1983 #endif
1984       // last instruction is a CatchNode, find it's CatchProjNodes
1985       int nof_succs = block->_num_succs;
1986       // allocate space
1987       GrowableArray<intptr_t> handler_bcis(nof_succs);
1988       GrowableArray<intptr_t> handler_pcos(nof_succs);
1989       // iterate through all successors
1990       for (int j = 0; j < nof_succs; j++) {
1991         Block* s = block->_succs[j];
1992         bool found_p = false;
1993         for (uint k = 1; k < s->num_preds(); k++) {
1994           Node* pk = s->pred(k);
1995           if (pk->is_CatchProj() && pk->in(0) == n) {
1996             const CatchProjNode* p = pk->as_CatchProj();
1997             found_p = true;
1998             // add the corresponding handler bci & pco information
1999             if (p->_con != CatchProjNode::fall_through_index) {
2000               // p leads to an exception handler (and is not fall through)
2001               assert(s == C->cfg()->get_block(s->_pre_order), "bad numbering");
2002               // no duplicates, please
2003               if (!handler_bcis.contains(p->handler_bci())) {
2004                 uint block_num = s->non_connector()->_pre_order;
2005                 handler_bcis.append(p->handler_bci());
2006                 handler_pcos.append(blk_labels[block_num].loc_pos());
2007               }
2008             }
2009           }
2010         }
2011         assert(found_p, "no matching predecessor found");
2012         // Note:  Due to empty block removal, one block may have
2013         // several CatchProj inputs, from the same Catch.
2014       }
2015 
2016       // Set the offset of the return from the call
2017       assert(handler_bcis.find(-1) != -1, "must have default handler");
2018       _handler_table.add_subtable(call_return, &handler_bcis, nullptr, &handler_pcos);
2019       continue;
2020     }
2021 
2022     // Handle implicit null exception table updates
2023     if (n->is_MachNullCheck()) {
2024       MachNode* access = n->in(1)->as_Mach();
2025       assert(access->barrier_data() == 0 ||
2026              access->is_late_expanded_null_check_candidate(),
2027              "Implicit null checks on memory accesses with barriers are only supported on nodes explicitly marked as null-check candidates");
2028       uint block_num = block->non_connector_successor(0)->_pre_order;
2029       _inc_table.append(inct_starts[inct_cnt++], blk_labels[block_num].loc_pos());
2030       continue;
2031     }
2032     // Handle implicit exception table updates: trap instructions.
2033     if (n->is_Mach() && n->as_Mach()->is_TrapBasedCheckNode()) {
2034       uint block_num = block->non_connector_successor(0)->_pre_order;
2035       _inc_table.append(inct_starts[inct_cnt++], blk_labels[block_num].loc_pos());
2036       continue;
2037     }
2038   } // End of for all blocks fill in exception table entries
2039 }
2040 
2041 // Static Variables
2042 #ifndef PRODUCT
2043 uint Scheduling::_total_nop_size = 0;
2044 uint Scheduling::_total_method_size = 0;
2045 uint Scheduling::_total_instructions_per_bundle[Pipeline::_max_instrs_per_cycle+1];
2046 #endif
2047 
2048 // Initializer for class Scheduling
2049 
2050 Scheduling::Scheduling(Arena *arena, Compile &compile)
2051         : _arena(arena),
2052           _cfg(compile.cfg()),
2053           _regalloc(compile.regalloc()),
2054           _scheduled(arena),
2055           _available(arena),
2056           _reg_node(arena),
2057           _pinch_free_list(arena),
2058           _next_node(nullptr),
2059           _bundle_instr_count(0),
2060           _bundle_cycle_number(0),
2061           _bundle_use(0, 0, resource_count, &_bundle_use_elements[0])
2062 {
2063   // Save the count
2064   _node_bundling_limit = compile.unique();
2065   uint node_max = _regalloc->node_regs_max_index();
2066 
2067   compile.output()->set_node_bundling_limit(_node_bundling_limit);
2068 
2069   // This one is persistent within the Compile class
2070   _node_bundling_base = NEW_ARENA_ARRAY(compile.comp_arena(), Bundle, node_max);
2071 
2072   // Allocate space for fixed-size arrays
2073   _uses            = NEW_ARENA_ARRAY(arena, short,          node_max);
2074   _current_latency = NEW_ARENA_ARRAY(arena, unsigned short, node_max);
2075 
2076   // Clear the arrays
2077   for (uint i = 0; i < node_max; i++) {
2078     ::new (&_node_bundling_base[i]) Bundle();
2079   }
2080   memset(_uses,               0, node_max * sizeof(short));
2081   memset(_current_latency,    0, node_max * sizeof(unsigned short));
2082 
2083   // Clear the bundling information
2084   memcpy(_bundle_use_elements, Pipeline_Use::elaborated_elements, sizeof(Pipeline_Use::elaborated_elements));
2085 
2086   // Get the last node
2087   Block* block = _cfg->get_block(_cfg->number_of_blocks() - 1);
2088 
2089   _next_node = block->get_node(block->number_of_nodes() - 1);
2090 }
2091 
2092 // Step ahead "i" cycles
2093 void Scheduling::step(uint i) {
2094 
2095   Bundle *bundle = node_bundling(_next_node);
2096   bundle->set_starts_bundle();
2097 
2098   // Update the bundle record, but leave the flags information alone
2099   if (_bundle_instr_count > 0) {
2100     bundle->set_instr_count(_bundle_instr_count);
2101     bundle->set_resources_used(_bundle_use.resourcesUsed());
2102   }
2103 
2104   // Update the state information
2105   _bundle_instr_count = 0;
2106   _bundle_cycle_number += i;
2107   _bundle_use.step(i);
2108 }
2109 
2110 void Scheduling::step_and_clear() {
2111   Bundle *bundle = node_bundling(_next_node);
2112   bundle->set_starts_bundle();
2113 
2114   // Update the bundle record
2115   if (_bundle_instr_count > 0) {
2116     bundle->set_instr_count(_bundle_instr_count);
2117     bundle->set_resources_used(_bundle_use.resourcesUsed());
2118 
2119     _bundle_cycle_number += 1;
2120   }
2121 
2122   // Clear the bundling information
2123   _bundle_instr_count = 0;
2124   _bundle_use.reset();
2125 
2126   memcpy(_bundle_use_elements,
2127          Pipeline_Use::elaborated_elements,
2128          sizeof(Pipeline_Use::elaborated_elements));
2129 }
2130 
2131 // Perform instruction scheduling and bundling over the sequence of
2132 // instructions in backwards order.
2133 void PhaseOutput::ScheduleAndBundle() {
2134 
2135   // Don't optimize this if it isn't a method
2136   if (!C->method())
2137     return;
2138 
2139   // Don't optimize this if scheduling is disabled
2140   if (!C->do_scheduling())
2141     return;
2142 
2143   // Scheduling code works only with pairs (8 bytes) maximum.
2144   // And when the scalable vector register is used, we may spill/unspill
2145   // the whole reg regardless of the max vector size.
2146   if (C->max_vector_size() > 8 ||
2147       (C->max_vector_size() > 0 && Matcher::supports_scalable_vector())) {
2148     return;
2149   }
2150 
2151   Compile::TracePhase tp(_t_instrSched);
2152 
2153   // Create a data structure for all the scheduling information
2154   Scheduling scheduling(Thread::current()->resource_area(), *C);
2155 
2156   // Walk backwards over each basic block, computing the needed alignment
2157   // Walk over all the basic blocks
2158   scheduling.DoScheduling();
2159 
2160 #ifndef PRODUCT
2161   if (C->trace_opto_output()) {
2162     // Buffer and print all at once
2163     ResourceMark rm;
2164     stringStream ss;
2165     ss.print("\n---- After ScheduleAndBundle ----\n");
2166     print_scheduling(&ss);
2167     tty->print("%s", ss.as_string());
2168   }
2169 #endif
2170 }
2171 
2172 #ifndef PRODUCT
2173 // Separated out so that it can be called directly from debugger
2174 void PhaseOutput::print_scheduling() {
2175   print_scheduling(tty);
2176 }
2177 
2178 void PhaseOutput::print_scheduling(outputStream* output_stream) {
2179   for (uint i = 0; i < C->cfg()->number_of_blocks(); i++) {
2180     output_stream->print("\nBB#%03d:\n", i);
2181     Block* block = C->cfg()->get_block(i);
2182     for (uint j = 0; j < block->number_of_nodes(); j++) {
2183       Node* n = block->get_node(j);
2184       OptoReg::Name reg = C->regalloc()->get_reg_first(n);
2185       output_stream->print(" %-6s ", reg >= 0 && reg < REG_COUNT ? Matcher::regName[reg] : "");
2186       n->dump("\n", false, output_stream);
2187     }
2188   }
2189 }
2190 #endif
2191 
2192 // See if this node fits into the present instruction bundle
2193 bool Scheduling::NodeFitsInBundle(Node *n) {
2194   uint n_idx = n->_idx;
2195 
2196   // If the node cannot be scheduled this cycle, skip it
2197   if (_current_latency[n_idx] > _bundle_cycle_number) {
2198 #ifndef PRODUCT
2199     if (_cfg->C->trace_opto_output())
2200       tty->print("#     NodeFitsInBundle [%4d]: FALSE; latency %4d > %d\n",
2201                  n->_idx, _current_latency[n_idx], _bundle_cycle_number);
2202 #endif
2203     return (false);
2204   }
2205 
2206   const Pipeline *node_pipeline = n->pipeline();
2207 
2208   uint instruction_count = node_pipeline->instructionCount();
2209   if (node_pipeline->mayHaveNoCode() && n->size(_regalloc) == 0)
2210     instruction_count = 0;
2211 
2212   if (_bundle_instr_count + instruction_count > Pipeline::_max_instrs_per_cycle) {
2213 #ifndef PRODUCT
2214     if (_cfg->C->trace_opto_output())
2215       tty->print("#     NodeFitsInBundle [%4d]: FALSE; too many instructions: %d > %d\n",
2216                  n->_idx, _bundle_instr_count + instruction_count, Pipeline::_max_instrs_per_cycle);
2217 #endif
2218     return (false);
2219   }
2220 
2221   // Don't allow non-machine nodes to be handled this way
2222   if (!n->is_Mach() && instruction_count == 0)
2223     return (false);
2224 
2225   // See if there is any overlap
2226   uint delay = _bundle_use.full_latency(0, node_pipeline->resourceUse());
2227 
2228   if (delay > 0) {
2229 #ifndef PRODUCT
2230     if (_cfg->C->trace_opto_output())
2231       tty->print("#     NodeFitsInBundle [%4d]: FALSE; functional units overlap\n", n_idx);
2232 #endif
2233     return false;
2234   }
2235 
2236 #ifndef PRODUCT
2237   if (_cfg->C->trace_opto_output())
2238     tty->print("#     NodeFitsInBundle [%4d]:  TRUE\n", n_idx);
2239 #endif
2240 
2241   return true;
2242 }
2243 
2244 Node * Scheduling::ChooseNodeToBundle() {
2245   uint siz = _available.size();
2246 
2247   if (siz == 0) {
2248 
2249 #ifndef PRODUCT
2250     if (_cfg->C->trace_opto_output())
2251       tty->print("#   ChooseNodeToBundle: null\n");
2252 #endif
2253     return (nullptr);
2254   }
2255 
2256   // Fast path, if only 1 instruction in the bundle
2257   if (siz == 1) {
2258 #ifndef PRODUCT
2259     if (_cfg->C->trace_opto_output()) {
2260       tty->print("#   ChooseNodeToBundle (only 1): ");
2261       _available[0]->dump();
2262     }
2263 #endif
2264     return (_available[0]);
2265   }
2266 
2267   // Don't bother, if the bundle is already full
2268   if (_bundle_instr_count < Pipeline::_max_instrs_per_cycle) {
2269     for ( uint i = 0; i < siz; i++ ) {
2270       Node *n = _available[i];
2271 
2272       // Skip projections, we'll handle them another way
2273       if (n->is_Proj())
2274         continue;
2275 
2276       // This presupposed that instructions are inserted into the
2277       // available list in a legality order; i.e. instructions that
2278       // must be inserted first are at the head of the list
2279       if (NodeFitsInBundle(n)) {
2280 #ifndef PRODUCT
2281         if (_cfg->C->trace_opto_output()) {
2282           tty->print("#   ChooseNodeToBundle: ");
2283           n->dump();
2284         }
2285 #endif
2286         return (n);
2287       }
2288     }
2289   }
2290 
2291   // Nothing fits in this bundle, choose the highest priority
2292 #ifndef PRODUCT
2293   if (_cfg->C->trace_opto_output()) {
2294     tty->print("#   ChooseNodeToBundle: ");
2295     _available[0]->dump();
2296   }
2297 #endif
2298 
2299   return _available[0];
2300 }
2301 
2302 int Scheduling::compare_two_spill_nodes(Node* first, Node* second) {
2303   assert(first->is_MachSpillCopy() && second->is_MachSpillCopy(), "");
2304 
2305   OptoReg::Name first_src_lo = _regalloc->get_reg_first(first->in(1));
2306   OptoReg::Name first_dst_lo = _regalloc->get_reg_first(first);
2307   OptoReg::Name second_src_lo = _regalloc->get_reg_first(second->in(1));
2308   OptoReg::Name second_dst_lo = _regalloc->get_reg_first(second);
2309 
2310   // Comparison between stack -> reg and stack -> reg
2311   if (OptoReg::is_stack(first_src_lo) && OptoReg::is_stack(second_src_lo) &&
2312       OptoReg::is_reg(first_dst_lo) && OptoReg::is_reg(second_dst_lo)) {
2313     return _regalloc->reg2offset(first_src_lo) - _regalloc->reg2offset(second_src_lo);
2314   }
2315 
2316   // Comparison between reg -> stack and reg -> stack
2317   if (OptoReg::is_stack(first_dst_lo) && OptoReg::is_stack(second_dst_lo) &&
2318       OptoReg::is_reg(first_src_lo) && OptoReg::is_reg(second_src_lo)) {
2319     return _regalloc->reg2offset(first_dst_lo) - _regalloc->reg2offset(second_dst_lo);
2320   }
2321 
2322   return 0; // Not comparable
2323 }
2324 
2325 void Scheduling::AddNodeToAvailableList(Node *n) {
2326   assert( !n->is_Proj(), "projections never directly made available" );
2327 #ifndef PRODUCT
2328   if (_cfg->C->trace_opto_output()) {
2329     tty->print("#   AddNodeToAvailableList: ");
2330     n->dump();
2331   }
2332 #endif
2333 
2334   int latency = _current_latency[n->_idx];
2335 
2336   // Insert in latency order (insertion sort). If two MachSpillCopyNodes
2337   // for stack spilling or unspilling have the same latency, we sort
2338   // them in the order of stack offset. Some ports (e.g. aarch64) may also
2339   // have more opportunities to do ld/st merging
2340   uint i;
2341   for (i = 0; i < _available.size(); i++) {
2342     if (_current_latency[_available[i]->_idx] > latency) {
2343       break;
2344     } else if (_current_latency[_available[i]->_idx] == latency &&
2345                n->is_MachSpillCopy() && _available[i]->is_MachSpillCopy() &&
2346                compare_two_spill_nodes(n, _available[i]) > 0) {
2347       break;
2348     }
2349   }
2350 
2351   // Special Check for compares following branches
2352   if( n->is_Mach() && _scheduled.size() > 0 ) {
2353     int op = n->as_Mach()->ideal_Opcode();
2354     Node *last = _scheduled[0];
2355     if( last->is_MachIf() && last->in(1) == n &&
2356         ( op == Op_CmpI ||
2357           op == Op_CmpU ||
2358           op == Op_CmpUL ||
2359           op == Op_CmpP ||
2360           op == Op_CmpF ||
2361           op == Op_CmpD ||
2362           op == Op_CmpL ) ) {
2363 
2364       // Recalculate position, moving to front of same latency
2365       for ( i=0 ; i < _available.size(); i++ )
2366         if (_current_latency[_available[i]->_idx] >= latency)
2367           break;
2368     }
2369   }
2370 
2371   // Insert the node in the available list
2372   _available.insert(i, n);
2373 
2374 #ifndef PRODUCT
2375   if (_cfg->C->trace_opto_output())
2376     dump_available();
2377 #endif
2378 }
2379 
2380 void Scheduling::DecrementUseCounts(Node *n, const Block *bb) {
2381   for ( uint i=0; i < n->len(); i++ ) {
2382     Node *def = n->in(i);
2383     if (!def) continue;
2384     if( def->is_Proj() )        // If this is a machine projection, then
2385       def = def->in(0);         // propagate usage thru to the base instruction
2386 
2387     if(_cfg->get_block_for_node(def) != bb) { // Ignore if not block-local
2388       continue;
2389     }
2390 
2391     // Compute the latency
2392     uint l = _bundle_cycle_number + n->latency(i);
2393     if (_current_latency[def->_idx] < l)
2394       _current_latency[def->_idx] = l;
2395 
2396     // If this does not have uses then schedule it
2397     if ((--_uses[def->_idx]) == 0)
2398       AddNodeToAvailableList(def);
2399   }
2400 }
2401 
2402 void Scheduling::AddNodeToBundle(Node *n, const Block *bb) {
2403 #ifndef PRODUCT
2404   if (_cfg->C->trace_opto_output()) {
2405     tty->print("#   AddNodeToBundle: ");
2406     n->dump();
2407   }
2408 #endif
2409 
2410   // Remove this from the available list
2411   uint i;
2412   for (i = 0; i < _available.size(); i++)
2413     if (_available[i] == n)
2414       break;
2415   assert(i < _available.size(), "entry in _available list not found");
2416   _available.remove(i);
2417 
2418   // See if this fits in the current bundle
2419   const Pipeline *node_pipeline = n->pipeline();
2420   const Pipeline_Use& node_usage = node_pipeline->resourceUse();
2421 
2422 
2423   // Get the number of instructions
2424   uint instruction_count = node_pipeline->instructionCount();
2425   if (node_pipeline->mayHaveNoCode() && n->size(_regalloc) == 0)
2426     instruction_count = 0;
2427 
2428   // Compute the latency information
2429   uint delay = 0;
2430 
2431   if (instruction_count > 0 || !node_pipeline->mayHaveNoCode()) {
2432     int relative_latency = _current_latency[n->_idx] - _bundle_cycle_number;
2433     if (relative_latency < 0)
2434       relative_latency = 0;
2435 
2436     delay = _bundle_use.full_latency(relative_latency, node_usage);
2437 
2438     // Does not fit in this bundle, start a new one
2439     if (delay > 0) {
2440       step(delay);
2441 
2442 #ifndef PRODUCT
2443       if (_cfg->C->trace_opto_output())
2444         tty->print("#  *** STEP(%d) ***\n", delay);
2445 #endif
2446     }
2447   }
2448 
2449   if (delay == 0) {
2450     if (node_pipeline->hasMultipleBundles()) {
2451 #ifndef PRODUCT
2452       if (_cfg->C->trace_opto_output())
2453         tty->print("#  *** STEP(multiple instructions) ***\n");
2454 #endif
2455       step(1);
2456     }
2457 
2458     else if (instruction_count + _bundle_instr_count > Pipeline::_max_instrs_per_cycle) {
2459 #ifndef PRODUCT
2460       if (_cfg->C->trace_opto_output())
2461         tty->print("#  *** STEP(%d >= %d instructions) ***\n",
2462                    instruction_count + _bundle_instr_count,
2463                    Pipeline::_max_instrs_per_cycle);
2464 #endif
2465       step(1);
2466     }
2467   }
2468 
2469   // Set the node's latency
2470   _current_latency[n->_idx] = _bundle_cycle_number;
2471 
2472   // Now merge the functional unit information
2473   if (instruction_count > 0 || !node_pipeline->mayHaveNoCode())
2474     _bundle_use.add_usage(node_usage);
2475 
2476   // Increment the number of instructions in this bundle
2477   _bundle_instr_count += instruction_count;
2478 
2479   // Remember this node for later
2480   if (n->is_Mach())
2481     _next_node = n;
2482 
2483   // It's possible to have a BoxLock in the graph and in the _bbs mapping but
2484   // not in the bb->_nodes array.  This happens for debug-info-only BoxLocks.
2485   // 'Schedule' them (basically ignore in the schedule) but do not insert them
2486   // into the block.  All other scheduled nodes get put in the schedule here.
2487   int op = n->Opcode();
2488   if( (op == Op_Node && n->req() == 0) || // anti-dependence node OR
2489       (op != Op_Node &&         // Not an unused antidepedence node and
2490        // not an unallocated boxlock
2491        (OptoReg::is_valid(_regalloc->get_reg_first(n)) || op != Op_BoxLock)) ) {
2492 
2493     // Push any trailing projections
2494     if( bb->get_node(bb->number_of_nodes()-1) != n ) {
2495       for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
2496         Node *foi = n->fast_out(i);
2497         if( foi->is_Proj() )
2498           _scheduled.push(foi);
2499       }
2500     }
2501 
2502     // Put the instruction in the schedule list
2503     _scheduled.push(n);
2504   }
2505 
2506 #ifndef PRODUCT
2507   if (_cfg->C->trace_opto_output())
2508     dump_available();
2509 #endif
2510 
2511   // Walk all the definitions, decrementing use counts, and
2512   // if a definition has a 0 use count, place it in the available list.
2513   DecrementUseCounts(n,bb);
2514 }
2515 
2516 // This method sets the use count within a basic block.  We will ignore all
2517 // uses outside the current basic block.  As we are doing a backwards walk,
2518 // any node we reach that has a use count of 0 may be scheduled.  This also
2519 // avoids the problem of cyclic references from phi nodes, as long as phi
2520 // nodes are at the front of the basic block.  This method also initializes
2521 // the available list to the set of instructions that have no uses within this
2522 // basic block.
2523 void Scheduling::ComputeUseCount(const Block *bb) {
2524 #ifndef PRODUCT
2525   if (_cfg->C->trace_opto_output())
2526     tty->print("# -> ComputeUseCount\n");
2527 #endif
2528 
2529   // Clear the list of available and scheduled instructions, just in case
2530   _available.clear();
2531   _scheduled.clear();
2532 
2533 #ifdef ASSERT
2534   for( uint i=0; i < bb->number_of_nodes(); i++ )
2535     assert( _uses[bb->get_node(i)->_idx] == 0, "_use array not clean" );
2536 #endif
2537 
2538   // Force the _uses count to never go to zero for unscheduable pieces
2539   // of the block
2540   for( uint k = 0; k < _bb_start; k++ )
2541     _uses[bb->get_node(k)->_idx] = 1;
2542   for( uint l = _bb_end; l < bb->number_of_nodes(); l++ )
2543     _uses[bb->get_node(l)->_idx] = 1;
2544 
2545   // Iterate backwards over the instructions in the block.  Don't count the
2546   // branch projections at end or the block header instructions.
2547   for( uint j = _bb_end-1; j >= _bb_start; j-- ) {
2548     Node *n = bb->get_node(j);
2549     if( n->is_Proj() ) continue; // Projections handled another way
2550 
2551     // Account for all uses
2552     for ( uint k = 0; k < n->len(); k++ ) {
2553       Node *inp = n->in(k);
2554       if (!inp) continue;
2555       assert(inp != n, "no cycles allowed" );
2556       if (_cfg->get_block_for_node(inp) == bb) { // Block-local use?
2557         if (inp->is_Proj()) { // Skip through Proj's
2558           inp = inp->in(0);
2559         }
2560         ++_uses[inp->_idx];     // Count 1 block-local use
2561       }
2562     }
2563 
2564     // If this instruction has a 0 use count, then it is available
2565     if (!_uses[n->_idx]) {
2566       _current_latency[n->_idx] = _bundle_cycle_number;
2567       AddNodeToAvailableList(n);
2568     }
2569 
2570 #ifndef PRODUCT
2571     if (_cfg->C->trace_opto_output()) {
2572       tty->print("#   uses: %3d: ", _uses[n->_idx]);
2573       n->dump();
2574     }
2575 #endif
2576   }
2577 
2578 #ifndef PRODUCT
2579   if (_cfg->C->trace_opto_output())
2580     tty->print("# <- ComputeUseCount\n");
2581 #endif
2582 }
2583 
2584 // This routine performs scheduling on each basic block in reverse order,
2585 // using instruction latencies and taking into account function unit
2586 // availability.
2587 void Scheduling::DoScheduling() {
2588 #ifndef PRODUCT
2589   if (_cfg->C->trace_opto_output())
2590     tty->print("# -> DoScheduling\n");
2591 #endif
2592 
2593   Block *succ_bb = nullptr;
2594   Block *bb;
2595   Compile* C = Compile::current();
2596 
2597   // Walk over all the basic blocks in reverse order
2598   for (int i = _cfg->number_of_blocks() - 1; i >= 0; succ_bb = bb, i--) {
2599     bb = _cfg->get_block(i);
2600 
2601 #ifndef PRODUCT
2602     if (_cfg->C->trace_opto_output()) {
2603       tty->print("#  Schedule BB#%03d (initial)\n", i);
2604       for (uint j = 0; j < bb->number_of_nodes(); j++) {
2605         bb->get_node(j)->dump();
2606       }
2607     }
2608 #endif
2609 
2610     // On the head node, skip processing
2611     if (bb == _cfg->get_root_block()) {
2612       continue;
2613     }
2614 
2615     // Skip empty, connector blocks
2616     if (bb->is_connector())
2617       continue;
2618 
2619     // If the following block is not the sole successor of
2620     // this one, then reset the pipeline information
2621     if (bb->_num_succs != 1 || bb->non_connector_successor(0) != succ_bb) {
2622 #ifndef PRODUCT
2623       if (_cfg->C->trace_opto_output()) {
2624         tty->print("*** bundle start of next BB, node %d, for %d instructions\n",
2625                    _next_node->_idx, _bundle_instr_count);
2626       }
2627 #endif
2628       step_and_clear();
2629     }
2630 
2631     // Leave untouched the starting instruction, any Phis, a CreateEx node
2632     // or Top.  bb->get_node(_bb_start) is the first schedulable instruction.
2633     _bb_end = bb->number_of_nodes()-1;
2634     for( _bb_start=1; _bb_start <= _bb_end; _bb_start++ ) {
2635       Node *n = bb->get_node(_bb_start);
2636       // Things not matched, like Phinodes and ProjNodes don't get scheduled.
2637       // Also, MachIdealNodes do not get scheduled
2638       if( !n->is_Mach() ) continue;     // Skip non-machine nodes
2639       MachNode *mach = n->as_Mach();
2640       int iop = mach->ideal_Opcode();
2641       if( iop == Op_CreateEx ) continue; // CreateEx is pinned
2642       if( iop == Op_Con ) continue;      // Do not schedule Top
2643       if( iop == Op_Node &&     // Do not schedule PhiNodes, ProjNodes
2644           mach->pipeline() == MachNode::pipeline_class() &&
2645           !n->is_SpillCopy() && !n->is_MachMerge() )  // Breakpoints, Prolog, etc
2646         continue;
2647       break;                    // Funny loop structure to be sure...
2648     }
2649     // Compute last "interesting" instruction in block - last instruction we
2650     // might schedule.  _bb_end points just after last schedulable inst.
2651     Node *last = bb->get_node(_bb_end);
2652     // Ignore trailing NOPs.
2653     while (_bb_end > 0 && last->is_Mach() &&
2654            last->as_Mach()->ideal_Opcode() == Op_Con) {
2655       last = bb->get_node(--_bb_end);
2656     }
2657     assert(!last->is_Mach() || last->as_Mach()->ideal_Opcode() != Op_Con, "");
2658     if( last->is_Catch() ||
2659         (last->is_Mach() && last->as_Mach()->ideal_Opcode() == Op_Halt) ) {
2660       // There might be a prior call.  Skip it.
2661       while (_bb_start < _bb_end && bb->get_node(--_bb_end)->is_MachProj());
2662     } else if( last->is_MachNullCheck() ) {
2663       // Backup so the last null-checked memory instruction is
2664       // outside the schedulable range. Skip over the nullcheck,
2665       // projection, and the memory nodes.
2666       Node *mem = last->in(1);
2667       do {
2668         _bb_end--;
2669       } while (mem != bb->get_node(_bb_end));
2670     } else {
2671       // Set _bb_end to point after last schedulable inst.
2672       _bb_end++;
2673     }
2674 
2675     assert( _bb_start <= _bb_end, "inverted block ends" );
2676 
2677     // Compute the register antidependencies for the basic block
2678     ComputeRegisterAntidependencies(bb);
2679     if (C->failing())  return;  // too many D-U pinch points
2680 
2681     // Compute the usage within the block, and set the list of all nodes
2682     // in the block that have no uses within the block.
2683     ComputeUseCount(bb);
2684 
2685     // Schedule the remaining instructions in the block
2686     while ( _available.size() > 0 ) {
2687       Node *n = ChooseNodeToBundle();
2688       guarantee(n != nullptr, "no nodes available");
2689       AddNodeToBundle(n,bb);
2690     }
2691 
2692     assert( _scheduled.size() == _bb_end - _bb_start, "wrong number of instructions" );
2693 #ifdef ASSERT
2694     for( uint l = _bb_start; l < _bb_end; l++ ) {
2695       Node *n = bb->get_node(l);
2696       uint m;
2697       for( m = 0; m < _bb_end-_bb_start; m++ )
2698         if( _scheduled[m] == n )
2699           break;
2700       assert( m < _bb_end-_bb_start, "instruction missing in schedule" );
2701     }
2702 #endif
2703 
2704     // Now copy the instructions (in reverse order) back to the block
2705     for ( uint k = _bb_start; k < _bb_end; k++ )
2706       bb->map_node(_scheduled[_bb_end-k-1], k);
2707 
2708 #ifndef PRODUCT
2709     if (_cfg->C->trace_opto_output()) {
2710       tty->print("#  Schedule BB#%03d (final)\n", i);
2711       uint current = 0;
2712       for (uint j = 0; j < bb->number_of_nodes(); j++) {
2713         Node *n = bb->get_node(j);
2714         if( valid_bundle_info(n) ) {
2715           Bundle *bundle = node_bundling(n);
2716           if (bundle->instr_count() > 0) {
2717             tty->print("*** Bundle: ");
2718             bundle->dump();
2719           }
2720           n->dump();
2721         }
2722       }
2723     }
2724 #endif
2725 #ifdef ASSERT
2726     verify_good_schedule(bb,"after block local scheduling");
2727 #endif
2728   }
2729 
2730 #ifndef PRODUCT
2731   if (_cfg->C->trace_opto_output())
2732     tty->print("# <- DoScheduling\n");
2733 #endif
2734 
2735   // Record final node-bundling array location
2736   _regalloc->C->output()->set_node_bundling_base(_node_bundling_base);
2737 
2738 } // end DoScheduling
2739 
2740 // Verify that no live-range used in the block is killed in the block by a
2741 // wrong DEF.  This doesn't verify live-ranges that span blocks.
2742 
2743 // Check for edge existence.  Used to avoid adding redundant precedence edges.
2744 static bool edge_from_to( Node *from, Node *to ) {
2745   for( uint i=0; i<from->len(); i++ )
2746     if( from->in(i) == to )
2747       return true;
2748   return false;
2749 }
2750 
2751 #ifdef ASSERT
2752 void Scheduling::verify_do_def( Node *n, OptoReg::Name def, const char *msg ) {
2753   // Check for bad kills
2754   if( OptoReg::is_valid(def) ) { // Ignore stores & control flow
2755     Node *prior_use = _reg_node[def];
2756     if( prior_use && !edge_from_to(prior_use,n) ) {
2757       tty->print("%s = ",OptoReg::as_VMReg(def)->name());
2758       n->dump();
2759       tty->print_cr("...");
2760       prior_use->dump();
2761       assert(edge_from_to(prior_use,n), "%s", msg);
2762     }
2763     _reg_node.map(def,nullptr); // Kill live USEs
2764   }
2765 }
2766 
2767 void Scheduling::verify_good_schedule( Block *b, const char *msg ) {
2768 
2769   // Zap to something reasonable for the verify code
2770   _reg_node.clear();
2771 
2772   // Walk over the block backwards.  Check to make sure each DEF doesn't
2773   // kill a live value (other than the one it's supposed to).  Add each
2774   // USE to the live set.
2775   for( uint i = b->number_of_nodes()-1; i >= _bb_start; i-- ) {
2776     Node *n = b->get_node(i);
2777     int n_op = n->Opcode();
2778     if( n_op == Op_MachProj && n->ideal_reg() == MachProjNode::fat_proj ) {
2779       // Fat-proj kills a slew of registers
2780       RegMaskIterator rmi(n->out_RegMask());
2781       while (rmi.has_next()) {
2782         OptoReg::Name kill = rmi.next();
2783         verify_do_def(n, kill, msg);
2784       }
2785     } else if( n_op != Op_Node ) { // Avoid brand new antidependence nodes
2786       // Get DEF'd registers the normal way
2787       verify_do_def( n, _regalloc->get_reg_first(n), msg );
2788       verify_do_def( n, _regalloc->get_reg_second(n), msg );
2789     }
2790 
2791     // Now make all USEs live
2792     for( uint i=1; i<n->req(); i++ ) {
2793       Node *def = n->in(i);
2794       assert(def != nullptr, "input edge required");
2795       OptoReg::Name reg_lo = _regalloc->get_reg_first(def);
2796       OptoReg::Name reg_hi = _regalloc->get_reg_second(def);
2797       if( OptoReg::is_valid(reg_lo) ) {
2798         assert(!_reg_node[reg_lo] || edge_from_to(_reg_node[reg_lo],def), "%s", msg);
2799         _reg_node.map(reg_lo,n);
2800       }
2801       if( OptoReg::is_valid(reg_hi) ) {
2802         assert(!_reg_node[reg_hi] || edge_from_to(_reg_node[reg_hi],def), "%s", msg);
2803         _reg_node.map(reg_hi,n);
2804       }
2805     }
2806 
2807   }
2808 
2809   // Zap to something reasonable for the Antidependence code
2810   _reg_node.clear();
2811 }
2812 #endif
2813 
2814 // Conditionally add precedence edges.  Avoid putting edges on Projs.
2815 static void add_prec_edge_from_to( Node *from, Node *to ) {
2816   if( from->is_Proj() ) {       // Put precedence edge on Proj's input
2817     assert( from->req() == 1 && (from->len() == 1 || from->in(1) == nullptr), "no precedence edges on projections" );
2818     from = from->in(0);
2819   }
2820   if( from != to &&             // No cycles (for things like LD L0,[L0+4] )
2821       !edge_from_to( from, to ) ) // Avoid duplicate edge
2822     from->add_prec(to);
2823 }
2824 
2825 void Scheduling::anti_do_def( Block *b, Node *def, OptoReg::Name def_reg, int is_def ) {
2826   if( !OptoReg::is_valid(def_reg) ) // Ignore stores & control flow
2827     return;
2828 
2829   if (OptoReg::is_reg(def_reg)) {
2830     VMReg vmreg = OptoReg::as_VMReg(def_reg);
2831     if (vmreg->is_reg() && !vmreg->is_concrete() && !vmreg->prev()->is_concrete()) {
2832       // This is one of the high slots of a vector register.
2833       // ScheduleAndBundle already checked there are no live wide
2834       // vectors in this method so it can be safely ignored.
2835       return;
2836     }
2837   }
2838 
2839   Node *pinch = _reg_node[def_reg]; // Get pinch point
2840   if ((pinch == nullptr) || _cfg->get_block_for_node(pinch) != b || // No pinch-point yet?
2841       is_def ) {    // Check for a true def (not a kill)
2842     _reg_node.map(def_reg,def); // Record def/kill as the optimistic pinch-point
2843     return;
2844   }
2845 
2846   Node *kill = def;             // Rename 'def' to more descriptive 'kill'
2847   DEBUG_ONLY( def = (Node*)((intptr_t)0xdeadbeef); )
2848 
2849   // After some number of kills there _may_ be a later def
2850   Node *later_def = nullptr;
2851 
2852   Compile* C = Compile::current();
2853 
2854   // Finding a kill requires a real pinch-point.
2855   // Check for not already having a pinch-point.
2856   // Pinch points are Op_Node's.
2857   if( pinch->Opcode() != Op_Node ) { // Or later-def/kill as pinch-point?
2858     later_def = pinch;            // Must be def/kill as optimistic pinch-point
2859     if ( _pinch_free_list.size() > 0) {
2860       pinch = _pinch_free_list.pop();
2861     } else {
2862       pinch = new Node(1); // Pinch point to-be
2863     }
2864     if (pinch->_idx >= _regalloc->node_regs_max_index()) {
2865       DEBUG_ONLY( pinch->dump(); );
2866       assert(false, "too many D-U pinch points: %d >= %d", pinch->_idx, _regalloc->node_regs_max_index());
2867       _cfg->C->record_method_not_compilable("too many D-U pinch points");
2868       return;
2869     }
2870     _cfg->map_node_to_block(pinch, b);      // Pretend it's valid in this block (lazy init)
2871     _reg_node.map(def_reg,pinch); // Record pinch-point
2872     //regalloc()->set_bad(pinch->_idx); // Already initialized this way.
2873     if( later_def->outcnt() == 0 || later_def->ideal_reg() == MachProjNode::fat_proj ) { // Distinguish def from kill
2874       pinch->init_req(0, C->top());     // set not null for the next call
2875       add_prec_edge_from_to(later_def,pinch); // Add edge from kill to pinch
2876       later_def = nullptr;           // and no later def
2877     }
2878     pinch->set_req(0,later_def);  // Hook later def so we can find it
2879   } else {                        // Else have valid pinch point
2880     if( pinch->in(0) )            // If there is a later-def
2881       later_def = pinch->in(0);   // Get it
2882   }
2883 
2884   // Add output-dependence edge from later def to kill
2885   if( later_def )               // If there is some original def
2886     add_prec_edge_from_to(later_def,kill); // Add edge from def to kill
2887 
2888   // See if current kill is also a use, and so is forced to be the pinch-point.
2889   if( pinch->Opcode() == Op_Node ) {
2890     Node *uses = kill->is_Proj() ? kill->in(0) : kill;
2891     for( uint i=1; i<uses->req(); i++ ) {
2892       if( _regalloc->get_reg_first(uses->in(i)) == def_reg ||
2893           _regalloc->get_reg_second(uses->in(i)) == def_reg ) {
2894         // Yes, found a use/kill pinch-point
2895         pinch->set_req(0,nullptr);  //
2896         pinch->replace_by(kill); // Move anti-dep edges up
2897         pinch = kill;
2898         _reg_node.map(def_reg,pinch);
2899         return;
2900       }
2901     }
2902   }
2903 
2904   // Add edge from kill to pinch-point
2905   add_prec_edge_from_to(kill,pinch);
2906 }
2907 
2908 void Scheduling::anti_do_use( Block *b, Node *use, OptoReg::Name use_reg ) {
2909   if( !OptoReg::is_valid(use_reg) ) // Ignore stores & control flow
2910     return;
2911   Node *pinch = _reg_node[use_reg]; // Get pinch point
2912   // Check for no later def_reg/kill in block
2913   if ((pinch != nullptr) && _cfg->get_block_for_node(pinch) == b &&
2914       // Use has to be block-local as well
2915       _cfg->get_block_for_node(use) == b) {
2916     if( pinch->Opcode() == Op_Node && // Real pinch-point (not optimistic?)
2917         pinch->req() == 1 ) {   // pinch not yet in block?
2918       pinch->del_req(0);        // yank pointer to later-def, also set flag
2919       // Insert the pinch-point in the block just after the last use
2920       b->insert_node(pinch, b->find_node(use) + 1);
2921       _bb_end++;                // Increase size scheduled region in block
2922     }
2923 
2924     add_prec_edge_from_to(pinch,use);
2925   }
2926 }
2927 
2928 // We insert antidependences between the reads and following write of
2929 // allocated registers to prevent illegal code motion. Hopefully, the
2930 // number of added references should be fairly small, especially as we
2931 // are only adding references within the current basic block.
2932 void Scheduling::ComputeRegisterAntidependencies(Block *b) {
2933 
2934 #ifdef ASSERT
2935   verify_good_schedule(b,"before block local scheduling");
2936 #endif
2937 
2938   // A valid schedule, for each register independently, is an endless cycle
2939   // of: a def, then some uses (connected to the def by true dependencies),
2940   // then some kills (defs with no uses), finally the cycle repeats with a new
2941   // def.  The uses are allowed to float relative to each other, as are the
2942   // kills.  No use is allowed to slide past a kill (or def).  This requires
2943   // antidependencies between all uses of a single def and all kills that
2944   // follow, up to the next def.  More edges are redundant, because later defs
2945   // & kills are already serialized with true or antidependencies.  To keep
2946   // the edge count down, we add a 'pinch point' node if there's more than
2947   // one use or more than one kill/def.
2948 
2949   // We add dependencies in one bottom-up pass.
2950 
2951   // For each instruction we handle it's DEFs/KILLs, then it's USEs.
2952 
2953   // For each DEF/KILL, we check to see if there's a prior DEF/KILL for this
2954   // register.  If not, we record the DEF/KILL in _reg_node, the
2955   // register-to-def mapping.  If there is a prior DEF/KILL, we insert a
2956   // "pinch point", a new Node that's in the graph but not in the block.
2957   // We put edges from the prior and current DEF/KILLs to the pinch point.
2958   // We put the pinch point in _reg_node.  If there's already a pinch point
2959   // we merely add an edge from the current DEF/KILL to the pinch point.
2960 
2961   // After doing the DEF/KILLs, we handle USEs.  For each used register, we
2962   // put an edge from the pinch point to the USE.
2963 
2964   // To be expedient, the _reg_node array is pre-allocated for the whole
2965   // compilation.  _reg_node is lazily initialized; it either contains a null,
2966   // or a valid def/kill/pinch-point, or a leftover node from some prior
2967   // block.  Leftover node from some prior block is treated like a null (no
2968   // prior def, so no anti-dependence needed).  Valid def is distinguished by
2969   // it being in the current block.
2970   bool fat_proj_seen = false;
2971   uint last_safept = _bb_end-1;
2972   Node* end_node         = (_bb_end-1 >= _bb_start) ? b->get_node(last_safept) : nullptr;
2973   Node* last_safept_node = end_node;
2974   for( uint i = _bb_end-1; i >= _bb_start; i-- ) {
2975     Node *n = b->get_node(i);
2976     int is_def = n->outcnt();   // def if some uses prior to adding precedence edges
2977     if( n->is_MachProj() && n->ideal_reg() == MachProjNode::fat_proj ) {
2978       // Fat-proj kills a slew of registers
2979       // This can add edges to 'n' and obscure whether or not it was a def,
2980       // hence the is_def flag.
2981       fat_proj_seen = true;
2982       RegMaskIterator rmi(n->out_RegMask());
2983       while (rmi.has_next()) {
2984         OptoReg::Name kill = rmi.next();
2985         anti_do_def(b, n, kill, is_def);
2986       }
2987     } else {
2988       // Get DEF'd registers the normal way
2989       anti_do_def( b, n, _regalloc->get_reg_first(n), is_def );
2990       anti_do_def( b, n, _regalloc->get_reg_second(n), is_def );
2991     }
2992 
2993     // Kill projections on a branch should appear to occur on the
2994     // branch, not afterwards, so grab the masks from the projections
2995     // and process them.
2996     if (n->is_MachBranch() || (n->is_Mach() && n->as_Mach()->ideal_Opcode() == Op_Jump)) {
2997       for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
2998         Node* use = n->fast_out(i);
2999         if (use->is_Proj()) {
3000           RegMaskIterator rmi(use->out_RegMask());
3001           while (rmi.has_next()) {
3002             OptoReg::Name kill = rmi.next();
3003             anti_do_def(b, n, kill, false);
3004           }
3005         }
3006       }
3007     }
3008 
3009     // Check each register used by this instruction for a following DEF/KILL
3010     // that must occur afterward and requires an anti-dependence edge.
3011     for( uint j=0; j<n->req(); j++ ) {
3012       Node *def = n->in(j);
3013       if( def ) {
3014         assert( !def->is_MachProj() || def->ideal_reg() != MachProjNode::fat_proj, "" );
3015         anti_do_use( b, n, _regalloc->get_reg_first(def) );
3016         anti_do_use( b, n, _regalloc->get_reg_second(def) );
3017       }
3018     }
3019     // Do not allow defs of new derived values to float above GC
3020     // points unless the base is definitely available at the GC point.
3021 
3022     Node *m = b->get_node(i);
3023 
3024     // Add precedence edge from following safepoint to use of derived pointer
3025     if( last_safept_node != end_node &&
3026         m != last_safept_node) {
3027       for (uint k = 1; k < m->req(); k++) {
3028         const Type *t = m->in(k)->bottom_type();
3029         if( t->isa_oop_ptr() &&
3030             t->is_ptr()->offset() != 0 ) {
3031           last_safept_node->add_prec( m );
3032           break;
3033         }
3034       }
3035 
3036       // Do not allow a CheckCastPP node whose input is a raw pointer to
3037       // float past a safepoint.  This can occur when a buffered inline
3038       // type is allocated in a loop and the CheckCastPP from that
3039       // allocation is reused outside the loop.  If the use inside the
3040       // loop is scalarized the CheckCastPP will no longer be connected
3041       // to the loop safepoint.  See JDK-8264340.
3042       if (m->is_Mach() && m->as_Mach()->ideal_Opcode() == Op_CheckCastPP) {
3043         Node *def = m->in(1);
3044         if (def != nullptr && def->bottom_type()->base() == Type::RawPtr) {
3045           last_safept_node->add_prec(m);
3046         }
3047       }
3048     }
3049 
3050     if( n->jvms() ) {           // Precedence edge from derived to safept
3051       // Check if last_safept_node was moved by pinch-point insertion in anti_do_use()
3052       if( b->get_node(last_safept) != last_safept_node ) {
3053         last_safept = b->find_node(last_safept_node);
3054       }
3055       for( uint j=last_safept; j > i; j-- ) {
3056         Node *mach = b->get_node(j);
3057         if( mach->is_Mach() && mach->as_Mach()->ideal_Opcode() == Op_AddP )
3058           mach->add_prec( n );
3059       }
3060       last_safept = i;
3061       last_safept_node = m;
3062     }
3063   }
3064 
3065   if (fat_proj_seen) {
3066     // Garbage collect pinch nodes that were not consumed.
3067     // They are usually created by a fat kill MachProj for a call.
3068     garbage_collect_pinch_nodes();
3069   }
3070 }
3071 
3072 // Garbage collect pinch nodes for reuse by other blocks.
3073 //
3074 // The block scheduler's insertion of anti-dependence
3075 // edges creates many pinch nodes when the block contains
3076 // 2 or more Calls.  A pinch node is used to prevent a
3077 // combinatorial explosion of edges.  If a set of kills for a
3078 // register is anti-dependent on a set of uses (or defs), rather
3079 // than adding an edge in the graph between each pair of kill
3080 // and use (or def), a pinch is inserted between them:
3081 //
3082 //            use1   use2  use3
3083 //                \   |   /
3084 //                 \  |  /
3085 //                  pinch
3086 //                 /  |  \
3087 //                /   |   \
3088 //            kill1 kill2 kill3
3089 //
3090 // One pinch node is created per register killed when
3091 // the second call is encountered during a backwards pass
3092 // over the block.  Most of these pinch nodes are never
3093 // wired into the graph because the register is never
3094 // used or def'ed in the block.
3095 //
3096 void Scheduling::garbage_collect_pinch_nodes() {
3097 #ifndef PRODUCT
3098   if (_cfg->C->trace_opto_output()) tty->print("Reclaimed pinch nodes:");
3099 #endif
3100   int trace_cnt = 0;
3101   for (uint k = 0; k < _reg_node.max(); k++) {
3102     Node* pinch = _reg_node[k];
3103     if ((pinch != nullptr) && pinch->Opcode() == Op_Node &&
3104         // no predecence input edges
3105         (pinch->req() == pinch->len() || pinch->in(pinch->req()) == nullptr) ) {
3106       cleanup_pinch(pinch);
3107       _pinch_free_list.push(pinch);
3108       _reg_node.map(k, nullptr);
3109 #ifndef PRODUCT
3110       if (_cfg->C->trace_opto_output()) {
3111         trace_cnt++;
3112         if (trace_cnt > 40) {
3113           tty->print("\n");
3114           trace_cnt = 0;
3115         }
3116         tty->print(" %d", pinch->_idx);
3117       }
3118 #endif
3119     }
3120   }
3121 #ifndef PRODUCT
3122   if (_cfg->C->trace_opto_output()) tty->print("\n");
3123 #endif
3124 }
3125 
3126 // Clean up a pinch node for reuse.
3127 void Scheduling::cleanup_pinch( Node *pinch ) {
3128   assert (pinch && pinch->Opcode() == Op_Node && pinch->req() == 1, "just checking");
3129 
3130   for (DUIterator_Last imin, i = pinch->last_outs(imin); i >= imin; ) {
3131     Node* use = pinch->last_out(i);
3132     uint uses_found = 0;
3133     for (uint j = use->req(); j < use->len(); j++) {
3134       if (use->in(j) == pinch) {
3135         use->rm_prec(j);
3136         uses_found++;
3137       }
3138     }
3139     assert(uses_found > 0, "must be a precedence edge");
3140     i -= uses_found;    // we deleted 1 or more copies of this edge
3141   }
3142   // May have a later_def entry
3143   pinch->set_req(0, nullptr);
3144 }
3145 
3146 #ifndef PRODUCT
3147 
3148 void Scheduling::dump_available() const {
3149   tty->print("#Availist  ");
3150   for (uint i = 0; i < _available.size(); i++)
3151     tty->print(" N%d/l%d", _available[i]->_idx,_current_latency[_available[i]->_idx]);
3152   tty->cr();
3153 }
3154 
3155 // Print Scheduling Statistics
3156 void Scheduling::print_statistics() {
3157   // Print the size added by nops for bundling
3158   tty->print("Nops added %d bytes to total of %d bytes",
3159              _total_nop_size, _total_method_size);
3160   if (_total_method_size > 0)
3161     tty->print(", for %.2f%%",
3162                ((double)_total_nop_size) / ((double) _total_method_size) * 100.0);
3163   tty->print("\n");
3164 
3165   uint total_instructions = 0, total_bundles = 0;
3166 
3167   for (uint i = 1; i <= Pipeline::_max_instrs_per_cycle; i++) {
3168     uint bundle_count   = _total_instructions_per_bundle[i];
3169     total_instructions += bundle_count * i;
3170     total_bundles      += bundle_count;
3171   }
3172 
3173   if (total_bundles > 0)
3174     tty->print("Average ILP (excluding nops) is %.2f\n",
3175                ((double)total_instructions) / ((double)total_bundles));
3176 }
3177 #endif
3178 
3179 //-----------------------init_scratch_buffer_blob------------------------------
3180 // Construct a temporary BufferBlob and cache it for this compile.
3181 void PhaseOutput::init_scratch_buffer_blob(int const_size) {
3182   // If there is already a scratch buffer blob allocated and the
3183   // constant section is big enough, use it.  Otherwise free the
3184   // current and allocate a new one.
3185   BufferBlob* blob = scratch_buffer_blob();
3186   if ((blob != nullptr) && (const_size <= _scratch_const_size)) {
3187     // Use the current blob.
3188   } else {
3189     if (blob != nullptr) {
3190       BufferBlob::free(blob);
3191     }
3192 
3193     ResourceMark rm;
3194     _scratch_const_size = const_size;
3195     int size = C2Compiler::initial_code_buffer_size(const_size);
3196     if (C->has_scalarized_args()) {
3197       // Inline type entry points (MachVEPNodes) require lots of space for GC barriers and oop verification
3198       // when loading object fields from the buffered argument. Increase scratch buffer size accordingly.
3199       ciMethod* method = C->method();
3200       int barrier_size = UseZGC ? 200 : (7 DEBUG_ONLY(+ 37));
3201       int arg_num = 0;
3202       if (!method->is_static()) {
3203         if (method->is_scalarized_arg(arg_num)) {
3204           size += method->holder()->as_inline_klass()->oop_count() * barrier_size;
3205         }
3206         arg_num++;
3207       }
3208       for (ciSignatureStream str(method->signature()); !str.at_return_type(); str.next()) {
3209         if (method->is_scalarized_arg(arg_num)) {
3210           size += str.type()->as_inline_klass()->oop_count() * barrier_size;
3211         }
3212         arg_num++;
3213       }
3214     }
3215     blob = BufferBlob::create("Compile::scratch_buffer", size);
3216     // Record the buffer blob for next time.
3217     set_scratch_buffer_blob(blob);
3218     // Have we run out of code space?
3219     if (scratch_buffer_blob() == nullptr) {
3220       // Let CompilerBroker disable further compilations.
3221       C->record_failure("Not enough space for scratch buffer in CodeCache");
3222       return;
3223     }
3224   }
3225 
3226   // Initialize the relocation buffers
3227   relocInfo* locs_buf = (relocInfo*) blob->content_end() - MAX_locs_size;
3228   set_scratch_locs_memory(locs_buf);
3229 }
3230 
3231 
3232 //-----------------------scratch_emit_size-------------------------------------
3233 // Helper function that computes size by emitting code
3234 uint PhaseOutput::scratch_emit_size(const Node* n) {
3235   // Start scratch_emit_size section.
3236   set_in_scratch_emit_size(true);
3237 
3238   // Emit into a trash buffer and count bytes emitted.
3239   // This is a pretty expensive way to compute a size,
3240   // but it works well enough if seldom used.
3241   // All common fixed-size instructions are given a size
3242   // method by the AD file.
3243   // Note that the scratch buffer blob and locs memory are
3244   // allocated at the beginning of the compile task, and
3245   // may be shared by several calls to scratch_emit_size.
3246   // The allocation of the scratch buffer blob is particularly
3247   // expensive, since it has to grab the code cache lock.
3248   BufferBlob* blob = this->scratch_buffer_blob();
3249   assert(blob != nullptr, "Initialize BufferBlob at start");
3250   assert(blob->size() > MAX_inst_size, "sanity");
3251   relocInfo* locs_buf = scratch_locs_memory();
3252   address blob_begin = blob->content_begin();
3253   address blob_end   = (address)locs_buf;
3254   assert(blob->contains(blob_end), "sanity");
3255   CodeBuffer buf(blob_begin, blob_end - blob_begin);
3256   buf.initialize_consts_size(_scratch_const_size);
3257   buf.initialize_stubs_size(MAX_stubs_size);
3258   assert(locs_buf != nullptr, "sanity");
3259   int lsize = MAX_locs_size / 3;
3260   buf.consts()->initialize_shared_locs(&locs_buf[lsize * 0], lsize);
3261   buf.insts()->initialize_shared_locs( &locs_buf[lsize * 1], lsize);
3262   buf.stubs()->initialize_shared_locs( &locs_buf[lsize * 2], lsize);
3263   // Mark as scratch buffer.
3264   buf.consts()->set_scratch_emit();
3265   buf.insts()->set_scratch_emit();
3266   buf.stubs()->set_scratch_emit();
3267 
3268   // Do the emission.
3269 
3270   Label fakeL; // Fake label for branch instructions.
3271   Label*   saveL = nullptr;
3272   uint save_bnum = 0;
3273   bool is_branch = n->is_MachBranch();
3274   C2_MacroAssembler masm(&buf);
3275   masm.bind(fakeL);
3276   if (is_branch) {
3277     n->as_MachBranch()->save_label(&saveL, &save_bnum);
3278     n->as_MachBranch()->label_set(&fakeL, 0);
3279   }
3280   n->emit(&masm, C->regalloc());
3281 
3282   // Emitting into the scratch buffer should not fail
3283   assert(!C->failing_internal() || C->failure_is_artificial(), "Must not have pending failure. Reason is: %s", C->failure_reason());
3284 
3285   // Restore label.
3286   if (is_branch) {
3287     n->as_MachBranch()->label_set(saveL, save_bnum);
3288   }
3289 
3290   // End scratch_emit_size section.
3291   set_in_scratch_emit_size(false);
3292 
3293   return buf.insts_size();
3294 }
3295 
3296 void PhaseOutput::install() {
3297   if (!C->should_install_code()) {
3298     return;
3299   } else if (C->stub_function() != nullptr) {
3300     install_stub(C->stub_name());
3301   } else {
3302     install_code(C->method(),
3303                  C->entry_bci(),
3304                  CompileBroker::compiler2(),
3305                  C->has_unsafe_access(),
3306                  SharedRuntime::is_wide_vector(C->max_vector_size()));
3307   }
3308 }
3309 
3310 void PhaseOutput::install_code(ciMethod*         target,
3311                                int               entry_bci,
3312                                AbstractCompiler* compiler,
3313                                bool              has_unsafe_access,
3314                                bool              has_wide_vectors) {
3315   // Check if we want to skip execution of all compiled code.
3316   {
3317 #ifndef PRODUCT
3318     if (OptoNoExecute) {
3319       C->record_method_not_compilable("+OptoNoExecute");  // Flag as failed
3320       return;
3321     }
3322 #endif
3323     Compile::TracePhase tp(_t_registerMethod);
3324 
3325     if (C->is_osr_compilation()) {
3326       _code_offsets.set_value(CodeOffsets::Verified_Entry, 0);
3327       _code_offsets.set_value(CodeOffsets::OSR_Entry, _first_block_size);
3328     } else {
3329       _code_offsets.set_value(CodeOffsets::Verified_Entry, _first_block_size);
3330       if (_code_offsets.value(CodeOffsets::Verified_Inline_Entry) == -1) {
3331         _code_offsets.set_value(CodeOffsets::Verified_Inline_Entry, _first_block_size);
3332       }
3333       if (_code_offsets.value(CodeOffsets::Verified_Inline_Entry_RO) == -1) {
3334         _code_offsets.set_value(CodeOffsets::Verified_Inline_Entry_RO, _first_block_size);
3335       }
3336       if (_code_offsets.value(CodeOffsets::Entry) == -1) {
3337         _code_offsets.set_value(CodeOffsets::Entry, _first_block_size);
3338       }
3339       _code_offsets.set_value(CodeOffsets::OSR_Entry, 0);
3340     }
3341 
3342     C->env()->register_method(target,
3343                               entry_bci,
3344                               &_code_offsets,
3345                               _orig_pc_slot_offset_in_bytes,
3346                               code_buffer(),
3347                               frame_size_in_words(),
3348                               _oop_map_set,
3349                               &_handler_table,
3350                               inc_table(),
3351                               compiler,
3352                               has_unsafe_access,
3353                               SharedRuntime::is_wide_vector(C->max_vector_size()),
3354                               C->has_monitors(),
3355                               C->has_scoped_access(),
3356                               0);
3357 
3358     if (C->log() != nullptr) { // Print code cache state into compiler log
3359       C->log()->code_cache_state();
3360     }
3361   }
3362 }
3363 void PhaseOutput::install_stub(const char* stub_name) {
3364   // Entry point will be accessed using stub_entry_point();
3365   if (code_buffer() == nullptr) {
3366     Matcher::soft_match_failure();
3367   } else {
3368     if (PrintAssembly && (WizardMode || Verbose))
3369       tty->print_cr("### Stub::%s", stub_name);
3370 
3371     if (!C->failing()) {
3372       assert(C->fixed_slots() == 0, "no fixed slots used for runtime stubs");
3373 
3374       // Make the NMethod
3375       // For now we mark the frame as never safe for profile stackwalking
3376       RuntimeStub *rs = RuntimeStub::new_runtime_stub(stub_name,
3377                                                       code_buffer(),
3378                                                       CodeOffsets::frame_never_safe,
3379                                                       // _code_offsets.value(CodeOffsets::Frame_Complete),
3380                                                       frame_size_in_words(),
3381                                                       oop_map_set(),
3382                                                       false,
3383                                                       false);
3384 
3385       if (rs == nullptr) {
3386         C->record_failure("CodeCache is full");
3387       } else {
3388         assert(rs->is_runtime_stub(), "sanity check");
3389         C->set_stub_entry_point(rs->entry_point());
3390         BlobId blob_id = StubInfo::blob(C->stub_id());
3391         AOTCodeCache::store_code_blob(*rs, AOTCodeEntry::C2Blob, blob_id);
3392       }
3393     }
3394   }
3395 }
3396 
3397 // Support for bundling info
3398 Bundle* PhaseOutput::node_bundling(const Node *n) {
3399   assert(valid_bundle_info(n), "oob");
3400   return &_node_bundling_base[n->_idx];
3401 }
3402 
3403 bool PhaseOutput::valid_bundle_info(const Node *n) {
3404   return (_node_bundling_limit > n->_idx);
3405 }
3406 
3407 //------------------------------frame_size_in_words-----------------------------
3408 // frame_slots in units of words
3409 int PhaseOutput::frame_size_in_words() const {
3410   // shift is 0 in LP32 and 1 in LP64
3411   const int shift = (LogBytesPerWord - LogBytesPerInt);
3412   int words = _frame_slots >> shift;
3413   assert( words << shift == _frame_slots, "frame size must be properly aligned in LP64" );
3414   return words;
3415 }
3416 
3417 // To bang the stack of this compiled method we use the stack size
3418 // that the interpreter would need in case of a deoptimization. This
3419 // removes the need to bang the stack in the deoptimization blob which
3420 // in turn simplifies stack overflow handling.
3421 int PhaseOutput::bang_size_in_bytes() const {
3422   return MAX2(frame_size_in_bytes() + os::extra_bang_size_in_bytes(), C->interpreter_frame_size());
3423 }
3424 
3425 //------------------------------dump_asm---------------------------------------
3426 // Dump formatted assembly
3427 #if defined(SUPPORT_OPTO_ASSEMBLY)
3428 void PhaseOutput::dump_asm_on(outputStream* st, int* pcs, uint pc_limit) {
3429 
3430   int pc_digits = 3; // #chars required for pc
3431   int sb_chars  = 3; // #chars for "start bundle" indicator
3432   int tab_size  = 8;
3433   if (pcs != nullptr) {
3434     int max_pc = 0;
3435     for (uint i = 0; i < pc_limit; i++) {
3436       max_pc = (max_pc < pcs[i]) ? pcs[i] : max_pc;
3437     }
3438     pc_digits  = ((max_pc < 4096) ? 3 : ((max_pc < 65536) ? 4 : ((max_pc < 65536*256) ? 6 : 8))); // #chars required for pc
3439   }
3440   int prefix_len = ((pc_digits + sb_chars + tab_size - 1)/tab_size)*tab_size;
3441 
3442   bool cut_short = false;
3443   st->print_cr("#");
3444   st->print("#  ");  C->tf()->dump_on(st);  st->cr();
3445   st->print_cr("#");
3446 
3447   // For all blocks
3448   int pc = 0x0;                 // Program counter
3449   char starts_bundle = ' ';
3450   C->regalloc()->dump_frame();
3451 
3452   Node *n = nullptr;
3453   for (uint i = 0; i < C->cfg()->number_of_blocks(); i++) {
3454     if (VMThread::should_terminate()) {
3455       cut_short = true;
3456       break;
3457     }
3458     Block* block = C->cfg()->get_block(i);
3459     if (block->is_connector() && !Verbose) {
3460       continue;
3461     }
3462     n = block->head();
3463     if ((pcs != nullptr) && (n->_idx < pc_limit)) {
3464       pc = pcs[n->_idx];
3465       st->print("%*.*x", pc_digits, pc_digits, pc);
3466     }
3467     st->fill_to(prefix_len);
3468     block->dump_head(C->cfg(), st);
3469     if (block->is_connector()) {
3470       st->fill_to(prefix_len);
3471       st->print_cr("# Empty connector block");
3472     } else if (block->num_preds() == 2 && block->pred(1)->is_CatchProj() && block->pred(1)->as_CatchProj()->_con == CatchProjNode::fall_through_index) {
3473       st->fill_to(prefix_len);
3474       st->print_cr("# Block is sole successor of call");
3475     }
3476 
3477     // For all instructions
3478     for (uint j = 0; j < block->number_of_nodes(); j++) {
3479       if (VMThread::should_terminate()) {
3480         cut_short = true;
3481         break;
3482       }
3483       n = block->get_node(j);
3484       if (valid_bundle_info(n)) {
3485         Bundle* bundle = node_bundling(n);
3486         if (bundle->starts_bundle()) {
3487           starts_bundle = '+';
3488         }
3489       }
3490 
3491       if (WizardMode) {
3492         n->dump();
3493       }
3494 
3495       if( !n->is_Region() &&    // Dont print in the Assembly
3496           !n->is_Phi() &&       // a few noisely useless nodes
3497           !n->is_Proj() &&
3498           !n->is_MachTemp() &&
3499           !n->is_SafePointScalarObject() &&
3500           !n->is_Catch() &&     // Would be nice to print exception table targets
3501           !n->is_MergeMem() &&  // Not very interesting
3502           !n->is_top() &&       // Debug info table constants
3503           !(n->is_Con() && !n->is_Mach())// Debug info table constants
3504           ) {
3505         if ((pcs != nullptr) && (n->_idx < pc_limit)) {
3506           pc = pcs[n->_idx];
3507           st->print("%*.*x", pc_digits, pc_digits, pc);
3508         } else {
3509           st->fill_to(pc_digits);
3510         }
3511         st->print(" %c ", starts_bundle);
3512         starts_bundle = ' ';
3513         st->fill_to(prefix_len);
3514         n->format(C->regalloc(), st);
3515         st->cr();
3516       }
3517 
3518       // Dump the exception table as well
3519       if( n->is_Catch() && (Verbose || WizardMode) ) {
3520         // Print the exception table for this offset
3521         _handler_table.print_subtable_for(pc);
3522       }
3523       st->bol(); // Make sure we start on a new line
3524     }
3525     st->cr(); // one empty line between blocks
3526   } // End of per-block dump
3527 
3528   if (cut_short)  st->print_cr("*** disassembly is cut short ***");
3529 }
3530 #endif
3531 
3532 #ifndef PRODUCT
3533 void PhaseOutput::print_statistics() {
3534   Scheduling::print_statistics();
3535 }
3536 #endif