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