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