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