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/compiledIC.hpp"
  27 #include "code/debugInfo.hpp"
  28 #include "code/debugInfoRec.hpp"
  29 #include "compiler/compileBroker.hpp"
  30 #include "compiler/compilerDirectives.hpp"
  31 #include "compiler/disassembler.hpp"
  32 #include "compiler/oopMap.hpp"
  33 #include "gc/shared/barrierSet.hpp"
  34 #include "gc/shared/c2/barrierSetC2.hpp"
  35 #include "memory/allocation.hpp"
  36 #include "opto/ad.hpp"
  37 #include "opto/block.hpp"
  38 #include "opto/c2compiler.hpp"
  39 #include "opto/c2_MacroAssembler.hpp"
  40 #include "opto/callnode.hpp"
  41 #include "opto/cfgnode.hpp"
  42 #include "opto/locknode.hpp"
  43 #include "opto/machnode.hpp"
  44 #include "opto/node.hpp"
  45 #include "opto/optoreg.hpp"
  46 #include "opto/output.hpp"
  47 #include "opto/regalloc.hpp"
  48 #include "opto/type.hpp"
  49 #include "runtime/sharedRuntime.hpp"
  50 #include "utilities/macros.hpp"
  51 #include "utilities/powerOfTwo.hpp"
  52 #include "utilities/xmlstream.hpp"
  53 
  54 #ifndef PRODUCT
  55 #define DEBUG_ARG(x) , x
  56 #else
  57 #define DEBUG_ARG(x)
  58 #endif
  59 
  60 //------------------------------Scheduling----------------------------------
  61 // This class contains all the information necessary to implement instruction
  62 // scheduling and bundling.
  63 class Scheduling {
  64 
  65 private:
  66   // Arena to use
  67   Arena *_arena;
  68 
  69   // Control-Flow Graph info
  70   PhaseCFG *_cfg;
  71 
  72   // Register Allocation info
  73   PhaseRegAlloc *_regalloc;
  74 
  75   // Number of nodes in the method
  76   uint _node_bundling_limit;
  77 
  78   // List of scheduled nodes. Generated in reverse order
  79   Node_List _scheduled;
  80 
  81   // List of nodes currently available for choosing for scheduling
  82   Node_List _available;
  83 
  84   // For each instruction beginning a bundle, the number of following
  85   // nodes to be bundled with it.
  86   Bundle *_node_bundling_base;
  87 
  88   // Mapping from register to Node
  89   Node_List _reg_node;
  90 
  91   // Free list for pinch nodes.
  92   Node_List _pinch_free_list;
  93 
  94   // Number of uses of this node within the containing basic block.
  95   short *_uses;
  96 
  97   // Schedulable portion of current block.  Skips Region/Phi/CreateEx up
  98   // front, branch+proj at end.  Also skips Catch/CProj (same as
  99   // branch-at-end), plus just-prior exception-throwing call.
 100   uint _bb_start, _bb_end;
 101 
 102   // Latency from the end of the basic block as scheduled
 103   unsigned short *_current_latency;
 104 
 105   // Remember the next node
 106   Node *_next_node;
 107 
 108   // Use this for an unconditional branch delay slot
 109   Node *_unconditional_delay_slot;
 110 
 111   // Pointer to a Nop
 112   MachNopNode *_nop;
 113 
 114   // Length of the current bundle, in instructions
 115   uint _bundle_instr_count;
 116 
 117   // Current Cycle number, for computing latencies and bundling
 118   uint _bundle_cycle_number;
 119 
 120   // Bundle information
 121   Pipeline_Use_Element _bundle_use_elements[resource_count];
 122   Pipeline_Use         _bundle_use;
 123 
 124   // Dump the available list
 125   void dump_available() const;
 126 
 127 public:
 128   Scheduling(Arena *arena, Compile &compile);
 129 
 130   // Destructor
 131   NOT_PRODUCT( ~Scheduling(); )
 132 
 133   // Step ahead "i" cycles
 134   void step(uint i);
 135 
 136   // Step ahead 1 cycle, and clear the bundle state (for example,
 137   // at a branch target)
 138   void step_and_clear();
 139 
 140   Bundle* node_bundling(const Node *n) {
 141     assert(valid_bundle_info(n), "oob");
 142     return (&_node_bundling_base[n->_idx]);
 143   }
 144 
 145   bool valid_bundle_info(const Node *n) const {
 146     return (_node_bundling_limit > n->_idx);
 147   }
 148 
 149   bool starts_bundle(const Node *n) const {
 150     return (_node_bundling_limit > n->_idx && _node_bundling_base[n->_idx].starts_bundle());
 151   }
 152 
 153   // Do the scheduling
 154   void DoScheduling();
 155 
 156   // Compute the register antidependencies within a basic block
 157   void ComputeRegisterAntidependencies(Block *bb);
 158   void verify_do_def( Node *n, OptoReg::Name def, const char *msg );
 159   void verify_good_schedule( Block *b, const char *msg );
 160   void anti_do_def( Block *b, Node *def, OptoReg::Name def_reg, int is_def );
 161   void anti_do_use( Block *b, Node *use, OptoReg::Name use_reg );
 162 
 163   // Add a node to the current bundle
 164   void AddNodeToBundle(Node *n, const Block *bb);
 165 
 166   // Return an integer less than, equal to, or greater than zero
 167   // if the stack offset of the first argument is respectively
 168   // less than, equal to, or greater than the second.
 169   int compare_two_spill_nodes(Node* first, Node* second);
 170 
 171   // Add a node to the list of available nodes
 172   void AddNodeToAvailableList(Node *n);
 173 
 174   // Compute the local use count for the nodes in a block, and compute
 175   // the list of instructions with no uses in the block as available
 176   void ComputeUseCount(const Block *bb);
 177 
 178   // Choose an instruction from the available list to add to the bundle
 179   Node * ChooseNodeToBundle();
 180 
 181   // See if this Node fits into the currently accumulating bundle
 182   bool NodeFitsInBundle(Node *n);
 183 
 184   // Decrement the use count for a node
 185  void DecrementUseCounts(Node *n, const Block *bb);
 186 
 187   // Garbage collect pinch nodes for reuse by other blocks.
 188   void garbage_collect_pinch_nodes();
 189   // Clean up a pinch node for reuse (helper for above).
 190   void cleanup_pinch( Node *pinch );
 191 
 192   // Information for statistics gathering
 193 #ifndef PRODUCT
 194 private:
 195   // Gather information on size of nops relative to total
 196   uint _branches, _unconditional_delays;
 197 
 198   static uint _total_nop_size, _total_method_size;
 199   static uint _total_branches, _total_unconditional_delays;
 200   static uint _total_instructions_per_bundle[Pipeline::_max_instrs_per_cycle+1];
 201 
 202 public:
 203   static void print_statistics();
 204 
 205   static void increment_instructions_per_bundle(uint i) {
 206     _total_instructions_per_bundle[i]++;
 207   }
 208 
 209   static void increment_nop_size(uint s) {
 210     _total_nop_size += s;
 211   }
 212 
 213   static void increment_method_size(uint s) {
 214     _total_method_size += s;
 215   }
 216 #endif
 217 
 218 };
 219 
 220 PhaseOutput::PhaseOutput()
 221   : Phase(Phase::Output),
 222     _code_buffer("Compile::Fill_buffer"),
 223     _first_block_size(0),
 224     _handler_table(),
 225     _inc_table(),
 226     _stub_list(),
 227     _oop_map_set(nullptr),
 228     _scratch_buffer_blob(nullptr),
 229     _scratch_locs_memory(nullptr),
 230     _scratch_const_size(-1),
 231     _in_scratch_emit_size(false),
 232     _frame_slots(0),
 233     _code_offsets(),
 234     _node_bundling_limit(0),
 235     _node_bundling_base(nullptr),
 236     _orig_pc_slot(0),
 237     _orig_pc_slot_offset_in_bytes(0),
 238     _buf_sizes(),
 239     _block(nullptr),
 240     _index(0) {
 241   C->set_output(this);
 242   if (C->stub_name() == nullptr) {
 243     _orig_pc_slot = C->fixed_slots() - (sizeof(address) / VMRegImpl::stack_slot_size);
 244   }
 245 }
 246 
 247 PhaseOutput::~PhaseOutput() {
 248   C->set_output(nullptr);
 249   if (_scratch_buffer_blob != nullptr) {
 250     BufferBlob::free(_scratch_buffer_blob);
 251   }
 252 }
 253 
 254 void PhaseOutput::perform_mach_node_analysis() {
 255   // Late barrier analysis must be done after schedule and bundle
 256   // Otherwise liveness based spilling will fail
 257   BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
 258   bs->late_barrier_analysis();
 259 
 260   pd_perform_mach_node_analysis();
 261 
 262   C->print_method(CompilerPhaseType::PHASE_MACH_ANALYSIS, 3);
 263 }
 264 
 265 // Convert Nodes to instruction bits and pass off to the VM
 266 void PhaseOutput::Output() {
 267   // RootNode goes
 268   assert( C->cfg()->get_root_block()->number_of_nodes() == 0, "" );
 269 
 270   // The number of new nodes (mostly MachNop) is proportional to
 271   // the number of java calls and inner loops which are aligned.
 272   if ( C->check_node_count((NodeLimitFudgeFactor + C->java_calls()*3 +
 273                             C->inner_loops()*(OptoLoopAlignment-1)),
 274                            "out of nodes before code generation" ) ) {
 275     return;
 276   }
 277   // Make sure I can find the Start Node
 278   Block *entry = C->cfg()->get_block(1);
 279   Block *broot = C->cfg()->get_root_block();
 280 
 281   const StartNode *start = entry->head()->as_Start();
 282 
 283   // Replace StartNode with prolog
 284   MachPrologNode *prolog = new MachPrologNode();
 285   entry->map_node(prolog, 0);
 286   C->cfg()->map_node_to_block(prolog, entry);
 287   C->cfg()->unmap_node_from_block(start); // start is no longer in any block
 288 
 289   // Virtual methods need an unverified entry point
 290 
 291   if( C->is_osr_compilation() ) {
 292     if( PoisonOSREntry ) {
 293       // TODO: Should use a ShouldNotReachHereNode...
 294       C->cfg()->insert( broot, 0, new MachBreakpointNode() );
 295     }
 296   } else {
 297     if( C->method() && !C->method()->flags().is_static() ) {
 298       // Insert unvalidated entry point
 299       C->cfg()->insert( broot, 0, new MachUEPNode() );
 300     }
 301 
 302   }
 303 
 304   // Break before main entry point
 305   if ((C->method() && C->directive()->BreakAtExecuteOption) ||
 306       (OptoBreakpoint && C->is_method_compilation())       ||
 307       (OptoBreakpointOSR && C->is_osr_compilation())       ||
 308       (OptoBreakpointC2R && !C->method())                   ) {
 309     // checking for C->method() means that OptoBreakpoint does not apply to
 310     // runtime stubs or frame converters
 311     C->cfg()->insert( entry, 1, new MachBreakpointNode() );
 312   }
 313 
 314   // Insert epilogs before every return
 315   for (uint i = 0; i < C->cfg()->number_of_blocks(); i++) {
 316     Block* block = C->cfg()->get_block(i);
 317     if (!block->is_connector() && block->non_connector_successor(0) == C->cfg()->get_root_block()) { // Found a program exit point?
 318       Node* m = block->end();
 319       if (m->is_Mach() && m->as_Mach()->ideal_Opcode() != Op_Halt) {
 320         MachEpilogNode* epilog = new MachEpilogNode(m->as_Mach()->ideal_Opcode() == Op_Return);
 321         block->add_inst(epilog);
 322         C->cfg()->map_node_to_block(epilog, block);
 323       }
 324     }
 325   }
 326 
 327   // Keeper of sizing aspects
 328   _buf_sizes = BufferSizingData();
 329 
 330   // Initialize code buffer
 331   estimate_buffer_size(_buf_sizes._const);
 332   if (C->failing()) return;
 333 
 334   // Pre-compute the length of blocks and replace
 335   // long branches with short if machine supports it.
 336   // Must be done before ScheduleAndBundle due to SPARC delay slots
 337   uint* blk_starts = NEW_RESOURCE_ARRAY(uint, C->cfg()->number_of_blocks() + 1);
 338   blk_starts[0] = 0;
 339   shorten_branches(blk_starts);
 340 
 341   ScheduleAndBundle();
 342   if (C->failing()) {
 343     return;
 344   }
 345 
 346   perform_mach_node_analysis();
 347 
 348   // Complete sizing of codebuffer
 349   CodeBuffer* cb = init_buffer();
 350   if (cb == nullptr || C->failing()) {
 351     return;
 352   }
 353 
 354   BuildOopMaps();
 355 
 356   if (C->failing())  {
 357     return;
 358   }
 359 
 360   C2_MacroAssembler masm(cb);
 361   fill_buffer(&masm, blk_starts);
 362 }
 363 
 364 bool PhaseOutput::need_stack_bang(int frame_size_in_bytes) const {
 365   // Determine if we need to generate a stack overflow check.
 366   // Do it if the method is not a stub function and
 367   // has java calls or has frame size > vm_page_size/8.
 368   // The debug VM checks that deoptimization doesn't trigger an
 369   // unexpected stack overflow (compiled method stack banging should
 370   // guarantee it doesn't happen) so we always need the stack bang in
 371   // a debug VM.
 372   return (C->stub_function() == nullptr &&
 373           (C->has_java_calls() || frame_size_in_bytes > (int)(os::vm_page_size())>>3
 374            DEBUG_ONLY(|| true)));
 375 }
 376 
 377 bool PhaseOutput::need_register_stack_bang() const {
 378   // Determine if we need to generate a register stack overflow check.
 379   // This is only used on architectures which have split register
 380   // and memory stacks.
 381   // Bang if the method is not a stub function and has java calls
 382   return (C->stub_function() == nullptr && C->has_java_calls());
 383 }
 384 
 385 
 386 // Compute the size of first NumberOfLoopInstrToAlign instructions at the top
 387 // of a loop. When aligning a loop we need to provide enough instructions
 388 // in cpu's fetch buffer to feed decoders. The loop alignment could be
 389 // avoided if we have enough instructions in fetch buffer at the head of a loop.
 390 // By default, the size is set to 999999 by Block's constructor so that
 391 // a loop will be aligned if the size is not reset here.
 392 //
 393 // Note: Mach instructions could contain several HW instructions
 394 // so the size is estimated only.
 395 //
 396 void PhaseOutput::compute_loop_first_inst_sizes() {
 397   // The next condition is used to gate the loop alignment optimization.
 398   // Don't aligned a loop if there are enough instructions at the head of a loop
 399   // or alignment padding is larger then MaxLoopPad. By default, MaxLoopPad
 400   // is equal to OptoLoopAlignment-1 except on new Intel cpus, where it is
 401   // equal to 11 bytes which is the largest address NOP instruction.
 402   if (MaxLoopPad < OptoLoopAlignment - 1) {
 403     uint last_block = C->cfg()->number_of_blocks() - 1;
 404     for (uint i = 1; i <= last_block; i++) {
 405       Block* block = C->cfg()->get_block(i);
 406       // Check the first loop's block which requires an alignment.
 407       if (block->loop_alignment() > (uint)relocInfo::addr_unit()) {
 408         uint sum_size = 0;
 409         uint inst_cnt = NumberOfLoopInstrToAlign;
 410         inst_cnt = block->compute_first_inst_size(sum_size, inst_cnt, C->regalloc());
 411 
 412         // Check subsequent fallthrough blocks if the loop's first
 413         // block(s) does not have enough instructions.
 414         Block *nb = block;
 415         while(inst_cnt > 0 &&
 416               i < last_block &&
 417               !C->cfg()->get_block(i + 1)->has_loop_alignment() &&
 418               !nb->has_successor(block)) {
 419           i++;
 420           nb = C->cfg()->get_block(i);
 421           inst_cnt  = nb->compute_first_inst_size(sum_size, inst_cnt, C->regalloc());
 422         } // while( inst_cnt > 0 && i < last_block  )
 423 
 424         block->set_first_inst_size(sum_size);
 425       } // f( b->head()->is_Loop() )
 426     } // for( i <= last_block )
 427   } // if( MaxLoopPad < OptoLoopAlignment-1 )
 428 }
 429 
 430 // The architecture description provides short branch variants for some long
 431 // branch instructions. Replace eligible long branches with short branches.
 432 void PhaseOutput::shorten_branches(uint* blk_starts) {
 433 
 434   Compile::TracePhase tp(_t_shortenBranches);
 435 
 436   // Compute size of each block, method size, and relocation information size
 437   uint nblocks  = C->cfg()->number_of_blocks();
 438 
 439   uint*      jmp_offset = NEW_RESOURCE_ARRAY(uint,nblocks);
 440   uint*      jmp_size   = NEW_RESOURCE_ARRAY(uint,nblocks);
 441   int*       jmp_nidx   = NEW_RESOURCE_ARRAY(int ,nblocks);
 442 
 443   // Collect worst case block paddings
 444   int* block_worst_case_pad = NEW_RESOURCE_ARRAY(int, nblocks);
 445   memset(block_worst_case_pad, 0, nblocks * sizeof(int));
 446 
 447   DEBUG_ONLY( uint *jmp_target = NEW_RESOURCE_ARRAY(uint,nblocks); )
 448   DEBUG_ONLY( uint *jmp_rule = NEW_RESOURCE_ARRAY(uint,nblocks); )
 449 
 450   bool has_short_branch_candidate = false;
 451 
 452   // Initialize the sizes to 0
 453   int code_size  = 0;          // Size in bytes of generated code
 454   int stub_size  = 0;          // Size in bytes of all stub entries
 455   // Size in bytes of all relocation entries, including those in local stubs.
 456   // Start with 2-bytes of reloc info for the unvalidated entry point
 457   int reloc_size = 1;          // Number of relocation entries
 458 
 459   // Make three passes.  The first computes pessimistic blk_starts,
 460   // relative jmp_offset and reloc_size information.  The second performs
 461   // short branch substitution using the pessimistic sizing.  The
 462   // third inserts nops where needed.
 463 
 464   // Step one, perform a pessimistic sizing pass.
 465   uint last_call_adr = max_juint;
 466   uint last_avoid_back_to_back_adr = max_juint;
 467   uint nop_size = (new MachNopNode())->size(C->regalloc());
 468   for (uint i = 0; i < nblocks; i++) { // For all blocks
 469     Block* block = C->cfg()->get_block(i);
 470     _block = block;
 471 
 472     // During short branch replacement, we store the relative (to blk_starts)
 473     // offset of jump in jmp_offset, rather than the absolute offset of jump.
 474     // This is so that we do not need to recompute sizes of all nodes when
 475     // we compute correct blk_starts in our next sizing pass.
 476     jmp_offset[i] = 0;
 477     jmp_size[i]   = 0;
 478     jmp_nidx[i]   = -1;
 479     DEBUG_ONLY( jmp_target[i] = 0; )
 480     DEBUG_ONLY( jmp_rule[i]   = 0; )
 481 
 482     // Sum all instruction sizes to compute block size
 483     uint last_inst = block->number_of_nodes();
 484     uint blk_size = 0;
 485     for (uint j = 0; j < last_inst; j++) {
 486       _index = j;
 487       Node* nj = block->get_node(_index);
 488       // Handle machine instruction nodes
 489       if (nj->is_Mach()) {
 490         MachNode* mach = nj->as_Mach();
 491         blk_size += (mach->alignment_required() - 1) * relocInfo::addr_unit(); // assume worst case padding
 492         reloc_size += mach->reloc();
 493         if (mach->is_MachCall()) {
 494           // add size information for trampoline stub
 495           // class CallStubImpl is platform-specific and defined in the *.ad files.
 496           stub_size  += CallStubImpl::size_call_trampoline();
 497           reloc_size += CallStubImpl::reloc_call_trampoline();
 498 
 499           MachCallNode *mcall = mach->as_MachCall();
 500           // This destination address is NOT PC-relative
 501 
 502           mcall->method_set((intptr_t)mcall->entry_point());
 503 
 504           if (mcall->is_MachCallJava() && mcall->as_MachCallJava()->_method) {
 505             stub_size  += CompiledDirectCall::to_interp_stub_size();
 506             reloc_size += CompiledDirectCall::reloc_to_interp_stub();
 507           }
 508         } else if (mach->is_MachSafePoint()) {
 509           // If call/safepoint are adjacent, account for possible
 510           // nop to disambiguate the two safepoints.
 511           // ScheduleAndBundle() can rearrange nodes in a block,
 512           // check for all offsets inside this block.
 513           if (last_call_adr >= blk_starts[i]) {
 514             blk_size += nop_size;
 515           }
 516         }
 517         if (mach->avoid_back_to_back(MachNode::AVOID_BEFORE)) {
 518           // Nop is inserted between "avoid back to back" instructions.
 519           // ScheduleAndBundle() can rearrange nodes in a block,
 520           // check for all offsets inside this block.
 521           if (last_avoid_back_to_back_adr >= blk_starts[i]) {
 522             blk_size += nop_size;
 523           }
 524         }
 525         if (mach->may_be_short_branch()) {
 526           if (!nj->is_MachBranch()) {
 527 #ifndef PRODUCT
 528             nj->dump(3);
 529 #endif
 530             Unimplemented();
 531           }
 532           assert(jmp_nidx[i] == -1, "block should have only one branch");
 533           jmp_offset[i] = blk_size;
 534           jmp_size[i]   = nj->size(C->regalloc());
 535           jmp_nidx[i]   = j;
 536           has_short_branch_candidate = true;
 537         }
 538       }
 539       blk_size += nj->size(C->regalloc());
 540       // Remember end of call offset
 541       if (nj->is_MachCall() && !nj->is_MachCallLeaf()) {
 542         last_call_adr = blk_starts[i]+blk_size;
 543       }
 544       // Remember end of avoid_back_to_back offset
 545       if (nj->is_Mach() && nj->as_Mach()->avoid_back_to_back(MachNode::AVOID_AFTER)) {
 546         last_avoid_back_to_back_adr = blk_starts[i]+blk_size;
 547       }
 548     }
 549 
 550     // When the next block starts a loop, we may insert pad NOP
 551     // instructions.  Since we cannot know our future alignment,
 552     // assume the worst.
 553     if (i < nblocks - 1) {
 554       Block* nb = C->cfg()->get_block(i + 1);
 555       int max_loop_pad = nb->code_alignment()-relocInfo::addr_unit();
 556       if (max_loop_pad > 0) {
 557         assert(is_power_of_2(max_loop_pad+relocInfo::addr_unit()), "");
 558         // Adjust last_call_adr and/or last_avoid_back_to_back_adr.
 559         // If either is the last instruction in this block, bump by
 560         // max_loop_pad in lock-step with blk_size, so sizing
 561         // calculations in subsequent blocks still can conservatively
 562         // detect that it may the last instruction in this block.
 563         if (last_call_adr == blk_starts[i]+blk_size) {
 564           last_call_adr += max_loop_pad;
 565         }
 566         if (last_avoid_back_to_back_adr == blk_starts[i]+blk_size) {
 567           last_avoid_back_to_back_adr += max_loop_pad;
 568         }
 569         blk_size += max_loop_pad;
 570         block_worst_case_pad[i + 1] = max_loop_pad;
 571       }
 572     }
 573 
 574     // Save block size; update total method size
 575     blk_starts[i+1] = blk_starts[i]+blk_size;
 576   }
 577 
 578   // Step two, replace eligible long jumps.
 579   bool progress = true;
 580   uint last_may_be_short_branch_adr = max_juint;
 581   while (has_short_branch_candidate && progress) {
 582     progress = false;
 583     has_short_branch_candidate = false;
 584     int adjust_block_start = 0;
 585     for (uint i = 0; i < nblocks; i++) {
 586       Block* block = C->cfg()->get_block(i);
 587       int idx = jmp_nidx[i];
 588       MachNode* mach = (idx == -1) ? nullptr: block->get_node(idx)->as_Mach();
 589       if (mach != nullptr && mach->may_be_short_branch()) {
 590 #ifdef ASSERT
 591         assert(jmp_size[i] > 0 && mach->is_MachBranch(), "sanity");
 592         int j;
 593         // Find the branch; ignore trailing NOPs.
 594         for (j = block->number_of_nodes()-1; j>=0; j--) {
 595           Node* n = block->get_node(j);
 596           if (!n->is_Mach() || n->as_Mach()->ideal_Opcode() != Op_Con)
 597             break;
 598         }
 599         assert(j >= 0 && j == idx && block->get_node(j) == (Node*)mach, "sanity");
 600 #endif
 601         int br_size = jmp_size[i];
 602         int br_offs = blk_starts[i] + jmp_offset[i];
 603 
 604         // This requires the TRUE branch target be in succs[0]
 605         uint bnum = block->non_connector_successor(0)->_pre_order;
 606         int offset = blk_starts[bnum] - br_offs;
 607         if (bnum > i) { // adjust following block's offset
 608           offset -= adjust_block_start;
 609         }
 610 
 611         // This block can be a loop header, account for the padding
 612         // in the previous block.
 613         int block_padding = block_worst_case_pad[i];
 614         assert(i == 0 || block_padding == 0 || br_offs >= block_padding, "Should have at least a padding on top");
 615         // In the following code a nop could be inserted before
 616         // the branch which will increase the backward distance.
 617         bool needs_padding = ((uint)(br_offs - block_padding) == last_may_be_short_branch_adr);
 618         assert(!needs_padding || jmp_offset[i] == 0, "padding only branches at the beginning of block");
 619 
 620         if (needs_padding && offset <= 0)
 621           offset -= nop_size;
 622 
 623         if (C->matcher()->is_short_branch_offset(mach->rule(), br_size, offset)) {
 624           // We've got a winner.  Replace this branch.
 625           MachNode* replacement = mach->as_MachBranch()->short_branch_version();
 626 
 627           // Update the jmp_size.
 628           int new_size = replacement->size(C->regalloc());
 629           int diff     = br_size - new_size;
 630           assert(diff >= (int)nop_size, "short_branch size should be smaller");
 631           // Conservatively take into account padding between
 632           // avoid_back_to_back branches. Previous branch could be
 633           // converted into avoid_back_to_back branch during next
 634           // rounds.
 635           if (needs_padding && replacement->avoid_back_to_back(MachNode::AVOID_BEFORE)) {
 636             jmp_offset[i] += nop_size;
 637             diff -= nop_size;
 638           }
 639           adjust_block_start += diff;
 640           block->map_node(replacement, idx);
 641           mach->subsume_by(replacement, C);
 642           mach = replacement;
 643           progress = true;
 644 
 645           jmp_size[i] = new_size;
 646           DEBUG_ONLY( jmp_target[i] = bnum; );
 647           DEBUG_ONLY( jmp_rule[i] = mach->rule(); );
 648         } else {
 649           // The jump distance is not short, try again during next iteration.
 650           has_short_branch_candidate = true;
 651         }
 652       } // (mach->may_be_short_branch())
 653       if (mach != nullptr && (mach->may_be_short_branch() ||
 654                            mach->avoid_back_to_back(MachNode::AVOID_AFTER))) {
 655         last_may_be_short_branch_adr = blk_starts[i] + jmp_offset[i] + jmp_size[i];
 656       }
 657       blk_starts[i+1] -= adjust_block_start;
 658     }
 659   }
 660 
 661 #ifdef ASSERT
 662   for (uint i = 0; i < nblocks; i++) { // For all blocks
 663     if (jmp_target[i] != 0) {
 664       int br_size = jmp_size[i];
 665       int offset = blk_starts[jmp_target[i]]-(blk_starts[i] + jmp_offset[i]);
 666       if (!C->matcher()->is_short_branch_offset(jmp_rule[i], br_size, offset)) {
 667         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]);
 668       }
 669       assert(C->matcher()->is_short_branch_offset(jmp_rule[i], br_size, offset), "Displacement too large for short jmp");
 670     }
 671   }
 672 #endif
 673 
 674   // Step 3, compute the offsets of all blocks, will be done in fill_buffer()
 675   // after ScheduleAndBundle().
 676 
 677   // ------------------
 678   // Compute size for code buffer
 679   code_size = blk_starts[nblocks];
 680 
 681   // Relocation records
 682   reloc_size += 1;              // Relo entry for exception handler
 683 
 684   // Adjust reloc_size to number of record of relocation info
 685   // Min is 2 bytes, max is probably 6 or 8, with a tax up to 25% for
 686   // a relocation index.
 687   // The CodeBuffer will expand the locs array if this estimate is too low.
 688   reloc_size *= 10 / sizeof(relocInfo);
 689 
 690   _buf_sizes._reloc = reloc_size;
 691   _buf_sizes._code  = code_size;
 692   _buf_sizes._stub  = stub_size;
 693 }
 694 
 695 //------------------------------FillLocArray-----------------------------------
 696 // Create a bit of debug info and append it to the array.  The mapping is from
 697 // Java local or expression stack to constant, register or stack-slot.  For
 698 // doubles, insert 2 mappings and return 1 (to tell the caller that the next
 699 // entry has been taken care of and caller should skip it).
 700 static LocationValue *new_loc_value( PhaseRegAlloc *ra, OptoReg::Name regnum, Location::Type l_type ) {
 701   // This should never have accepted Bad before
 702   assert(OptoReg::is_valid(regnum), "location must be valid");
 703   return (OptoReg::is_reg(regnum))
 704          ? new LocationValue(Location::new_reg_loc(l_type, OptoReg::as_VMReg(regnum)) )
 705          : new LocationValue(Location::new_stk_loc(l_type,  ra->reg2offset(regnum)));
 706 }
 707 
 708 
 709 ObjectValue*
 710 PhaseOutput::sv_for_node_id(GrowableArray<ScopeValue*> *objs, int id) {
 711   for (int i = 0; i < objs->length(); i++) {
 712     assert(objs->at(i)->is_object(), "corrupt object cache");
 713     ObjectValue* sv = objs->at(i)->as_ObjectValue();
 714     if (sv->id() == id) {
 715       return sv;
 716     }
 717   }
 718   // Otherwise..
 719   return nullptr;
 720 }
 721 
 722 void PhaseOutput::set_sv_for_object_node(GrowableArray<ScopeValue*> *objs,
 723                                      ObjectValue* sv ) {
 724   assert(sv_for_node_id(objs, sv->id()) == nullptr, "Precondition");
 725   objs->append(sv);
 726 }
 727 
 728 
 729 void PhaseOutput::FillLocArray( int idx, MachSafePointNode* sfpt, Node *local,
 730                             GrowableArray<ScopeValue*> *array,
 731                             GrowableArray<ScopeValue*> *objs ) {
 732   assert( local, "use _top instead of null" );
 733   if (array->length() != idx) {
 734     assert(array->length() == idx + 1, "Unexpected array count");
 735     // Old functionality:
 736     //   return
 737     // New functionality:
 738     //   Assert if the local is not top. In product mode let the new node
 739     //   override the old entry.
 740     assert(local == C->top(), "LocArray collision");
 741     if (local == C->top()) {
 742       return;
 743     }
 744     array->pop();
 745   }
 746   const Type *t = local->bottom_type();
 747 
 748   // Is it a safepoint scalar object node?
 749   if (local->is_SafePointScalarObject()) {
 750     SafePointScalarObjectNode* spobj = local->as_SafePointScalarObject();
 751 
 752     ObjectValue* sv = sv_for_node_id(objs, spobj->_idx);
 753     if (sv == nullptr) {
 754       ciKlass* cik = t->is_oopptr()->exact_klass();
 755       assert(cik->is_instance_klass() ||
 756              cik->is_array_klass(), "Not supported allocation.");
 757       sv = new ObjectValue(spobj->_idx,
 758                            new ConstantOopWriteValue(cik->java_mirror()->constant_encoding()));
 759       set_sv_for_object_node(objs, sv);
 760 
 761       uint first_ind = spobj->first_index(sfpt->jvms());
 762       for (uint i = 0; i < spobj->n_fields(); i++) {
 763         Node* fld_node = sfpt->in(first_ind+i);
 764         (void)FillLocArray(sv->field_values()->length(), sfpt, fld_node, sv->field_values(), objs);
 765       }
 766     }
 767     array->append(sv);
 768     return;
 769   } else if (local->is_SafePointScalarMerge()) {
 770     SafePointScalarMergeNode* smerge = local->as_SafePointScalarMerge();
 771     ObjectMergeValue* mv = (ObjectMergeValue*) sv_for_node_id(objs, smerge->_idx);
 772 
 773     if (mv == nullptr) {
 774       GrowableArray<ScopeValue*> deps;
 775 
 776       int merge_pointer_idx = smerge->merge_pointer_idx(sfpt->jvms());
 777       (void)FillLocArray(0, sfpt, sfpt->in(merge_pointer_idx), &deps, objs);
 778       assert(deps.length() == 1, "missing value");
 779 
 780       int selector_idx = smerge->selector_idx(sfpt->jvms());
 781       (void)FillLocArray(1, nullptr, sfpt->in(selector_idx), &deps, nullptr);
 782       assert(deps.length() == 2, "missing value");
 783 
 784       mv = new ObjectMergeValue(smerge->_idx, deps.at(0), deps.at(1));
 785       set_sv_for_object_node(objs, mv);
 786 
 787       for (uint i = 1; i < smerge->req(); i++) {
 788         Node* obj_node = smerge->in(i);
 789         int idx = mv->possible_objects()->length();
 790         (void)FillLocArray(idx, sfpt, obj_node, mv->possible_objects(), objs);
 791 
 792         // By default ObjectValues that are in 'possible_objects' are not root objects.
 793         // They will be marked as root later if they are directly referenced in a JVMS.
 794         assert(mv->possible_objects()->length() > idx, "Didn't add entry to possible_objects?!");
 795         assert(mv->possible_objects()->at(idx)->is_object(), "Entries in possible_objects should be ObjectValue.");
 796         mv->possible_objects()->at(idx)->as_ObjectValue()->set_root(false);
 797       }
 798     }
 799     array->append(mv);
 800     return;
 801   }
 802 
 803   // Grab the register number for the local
 804   OptoReg::Name regnum = C->regalloc()->get_reg_first(local);
 805   if( OptoReg::is_valid(regnum) ) {// Got a register/stack?
 806     // Record the double as two float registers.
 807     // The register mask for such a value always specifies two adjacent
 808     // float registers, with the lower register number even.
 809     // Normally, the allocation of high and low words to these registers
 810     // is irrelevant, because nearly all operations on register pairs
 811     // (e.g., StoreD) treat them as a single unit.
 812     // Here, we assume in addition that the words in these two registers
 813     // stored "naturally" (by operations like StoreD and double stores
 814     // within the interpreter) such that the lower-numbered register
 815     // is written to the lower memory address.  This may seem like
 816     // a machine dependency, but it is not--it is a requirement on
 817     // the author of the <arch>.ad file to ensure that, for every
 818     // even/odd double-register pair to which a double may be allocated,
 819     // the word in the even single-register is stored to the first
 820     // memory word.  (Note that register numbers are completely
 821     // arbitrary, and are not tied to any machine-level encodings.)
 822 #ifdef _LP64
 823     if( t->base() == Type::DoubleBot || t->base() == Type::DoubleCon ) {
 824       array->append(new ConstantIntValue((jint)0));
 825       array->append(new_loc_value( C->regalloc(), regnum, Location::dbl ));
 826     } else if ( t->base() == Type::Long ) {
 827       array->append(new ConstantIntValue((jint)0));
 828       array->append(new_loc_value( C->regalloc(), regnum, Location::lng ));
 829     } else if ( t->base() == Type::RawPtr ) {
 830       // jsr/ret return address which must be restored into the full
 831       // width 64-bit stack slot.
 832       array->append(new_loc_value( C->regalloc(), regnum, Location::lng ));
 833     }
 834 #else //_LP64
 835     if( t->base() == Type::DoubleBot || t->base() == Type::DoubleCon || t->base() == Type::Long ) {
 836       // Repack the double/long as two jints.
 837       // The convention the interpreter uses is that the second local
 838       // holds the first raw word of the native double representation.
 839       // This is actually reasonable, since locals and stack arrays
 840       // grow downwards in all implementations.
 841       // (If, on some machine, the interpreter's Java locals or stack
 842       // were to grow upwards, the embedded doubles would be word-swapped.)
 843       array->append(new_loc_value( C->regalloc(), OptoReg::add(regnum,1), Location::normal ));
 844       array->append(new_loc_value( C->regalloc(),              regnum   , Location::normal ));
 845     }
 846 #endif //_LP64
 847     else if( (t->base() == Type::FloatBot || t->base() == Type::FloatCon) &&
 848              OptoReg::is_reg(regnum) ) {
 849       array->append(new_loc_value( C->regalloc(), regnum, Matcher::float_in_double()
 850                                                       ? Location::float_in_dbl : Location::normal ));
 851     } else if( t->base() == Type::Int && OptoReg::is_reg(regnum) ) {
 852       array->append(new_loc_value( C->regalloc(), regnum, Matcher::int_in_long
 853                                                       ? Location::int_in_long : Location::normal ));
 854     } else if( t->base() == Type::NarrowOop ) {
 855       array->append(new_loc_value( C->regalloc(), regnum, Location::narrowoop ));
 856     } else if (t->base() == Type::VectorA || t->base() == Type::VectorS ||
 857                t->base() == Type::VectorD || t->base() == Type::VectorX ||
 858                t->base() == Type::VectorY || t->base() == Type::VectorZ) {
 859       array->append(new_loc_value( C->regalloc(), regnum, Location::vector ));
 860     } else if (C->regalloc()->is_oop(local)) {
 861       assert(t->base() == Type::OopPtr || t->base() == Type::InstPtr ||
 862              t->base() == Type::AryPtr,
 863              "Unexpected type: %s", t->msg());
 864       array->append(new_loc_value( C->regalloc(), regnum, Location::oop ));
 865     } else {
 866       assert(t->base() == Type::Int || t->base() == Type::Half ||
 867              t->base() == Type::FloatCon || t->base() == Type::FloatBot,
 868              "Unexpected type: %s", t->msg());
 869       array->append(new_loc_value( C->regalloc(), regnum, Location::normal ));
 870     }
 871     return;
 872   }
 873 
 874   // No register.  It must be constant data.
 875   switch (t->base()) {
 876     case Type::Half:              // Second half of a double
 877       ShouldNotReachHere();       // Caller should skip 2nd halves
 878       break;
 879     case Type::AnyPtr:
 880       array->append(new ConstantOopWriteValue(nullptr));
 881       break;
 882     case Type::AryPtr:
 883     case Type::InstPtr:          // fall through
 884       array->append(new ConstantOopWriteValue(t->isa_oopptr()->const_oop()->constant_encoding()));
 885       break;
 886     case Type::NarrowOop:
 887       if (t == TypeNarrowOop::NULL_PTR) {
 888         array->append(new ConstantOopWriteValue(nullptr));
 889       } else {
 890         array->append(new ConstantOopWriteValue(t->make_ptr()->isa_oopptr()->const_oop()->constant_encoding()));
 891       }
 892       break;
 893     case Type::Int:
 894       array->append(new ConstantIntValue(t->is_int()->get_con()));
 895       break;
 896     case Type::RawPtr:
 897       // A return address (T_ADDRESS).
 898       assert((intptr_t)t->is_ptr()->get_con() < (intptr_t)0x10000, "must be a valid BCI");
 899 #ifdef _LP64
 900       // Must be restored to the full-width 64-bit stack slot.
 901       array->append(new ConstantLongValue(t->is_ptr()->get_con()));
 902 #else
 903       array->append(new ConstantIntValue(t->is_ptr()->get_con()));
 904 #endif
 905       break;
 906     case Type::FloatCon: {
 907       float f = t->is_float_constant()->getf();
 908       array->append(new ConstantIntValue(jint_cast(f)));
 909       break;
 910     }
 911     case Type::DoubleCon: {
 912       jdouble d = t->is_double_constant()->getd();
 913 #ifdef _LP64
 914       array->append(new ConstantIntValue((jint)0));
 915       array->append(new ConstantDoubleValue(d));
 916 #else
 917       // Repack the double as two jints.
 918     // The convention the interpreter uses is that the second local
 919     // holds the first raw word of the native double representation.
 920     // This is actually reasonable, since locals and stack arrays
 921     // grow downwards in all implementations.
 922     // (If, on some machine, the interpreter's Java locals or stack
 923     // were to grow upwards, the embedded doubles would be word-swapped.)
 924     jlong_accessor acc;
 925     acc.long_value = jlong_cast(d);
 926     array->append(new ConstantIntValue(acc.words[1]));
 927     array->append(new ConstantIntValue(acc.words[0]));
 928 #endif
 929       break;
 930     }
 931     case Type::Long: {
 932       jlong d = t->is_long()->get_con();
 933 #ifdef _LP64
 934       array->append(new ConstantIntValue((jint)0));
 935       array->append(new ConstantLongValue(d));
 936 #else
 937       // Repack the long as two jints.
 938     // The convention the interpreter uses is that the second local
 939     // holds the first raw word of the native double representation.
 940     // This is actually reasonable, since locals and stack arrays
 941     // grow downwards in all implementations.
 942     // (If, on some machine, the interpreter's Java locals or stack
 943     // were to grow upwards, the embedded doubles would be word-swapped.)
 944     jlong_accessor acc;
 945     acc.long_value = d;
 946     array->append(new ConstantIntValue(acc.words[1]));
 947     array->append(new ConstantIntValue(acc.words[0]));
 948 #endif
 949       break;
 950     }
 951     case Type::Top:               // Add an illegal value here
 952       array->append(new LocationValue(Location()));
 953       break;
 954     default:
 955       ShouldNotReachHere();
 956       break;
 957   }
 958 }
 959 
 960 // Determine if this node starts a bundle
 961 bool PhaseOutput::starts_bundle(const Node *n) const {
 962   return (_node_bundling_limit > n->_idx &&
 963           _node_bundling_base[n->_idx].starts_bundle());
 964 }
 965 
 966 // Determine if there is a monitor that has 'ov' as its owner.
 967 bool PhaseOutput::contains_as_owner(GrowableArray<MonitorValue*> *monarray, ObjectValue *ov) const {
 968   for (int k = 0; k < monarray->length(); k++) {
 969     MonitorValue* mv = monarray->at(k);
 970     if (mv->owner() == ov) {
 971       return true;
 972     }
 973   }
 974 
 975   return false;
 976 }
 977 
 978 // Determine if there is a scalar replaced object description represented by 'ov'.
 979 bool PhaseOutput::contains_as_scalarized_obj(JVMState* jvms, MachSafePointNode* sfn,
 980                                              GrowableArray<ScopeValue*>* objs,
 981                                              ObjectValue* ov) const {
 982   for (int i = 0; i < jvms->scl_size(); i++) {
 983     Node* n = sfn->scalarized_obj(jvms, i);
 984     // Other kinds of nodes that we may encounter here, for instance constants
 985     // representing values of fields of objects scalarized, aren't relevant for
 986     // us, since they don't map to ObjectValue.
 987     if (!n->is_SafePointScalarObject()) {
 988       continue;
 989     }
 990 
 991     ObjectValue* other = sv_for_node_id(objs, n->_idx);
 992     if (ov == other) {
 993       return true;
 994     }
 995   }
 996   return false;
 997 }
 998 
 999 //--------------------------Process_OopMap_Node--------------------------------
1000 void PhaseOutput::Process_OopMap_Node(MachNode *mach, int current_offset) {
1001   // Handle special safepoint nodes for synchronization
1002   MachSafePointNode *sfn   = mach->as_MachSafePoint();
1003   MachCallNode      *mcall;
1004 
1005   int safepoint_pc_offset = current_offset;
1006   bool is_method_handle_invoke = false;
1007   bool return_oop = false;
1008   bool has_ea_local_in_scope = sfn->_has_ea_local_in_scope;
1009   bool arg_escape = false;
1010 
1011   // Add the safepoint in the DebugInfoRecorder
1012   if( !mach->is_MachCall() ) {
1013     mcall = nullptr;
1014     C->debug_info()->add_safepoint(safepoint_pc_offset, sfn->_oop_map);
1015   } else {
1016     mcall = mach->as_MachCall();
1017 
1018     // Is the call a MethodHandle call?
1019     if (mcall->is_MachCallJava()) {
1020       if (mcall->as_MachCallJava()->_method_handle_invoke) {
1021         assert(C->has_method_handle_invokes(), "must have been set during call generation");
1022         is_method_handle_invoke = true;
1023       }
1024       arg_escape = mcall->as_MachCallJava()->_arg_escape;
1025     }
1026 
1027     // Check if a call returns an object.
1028     if (mcall->returns_pointer()) {
1029       return_oop = true;
1030     }
1031     safepoint_pc_offset += mcall->ret_addr_offset();
1032     C->debug_info()->add_safepoint(safepoint_pc_offset, mcall->_oop_map);
1033   }
1034 
1035   // Loop over the JVMState list to add scope information
1036   // Do not skip safepoints with a null method, they need monitor info
1037   JVMState* youngest_jvms = sfn->jvms();
1038   int max_depth = youngest_jvms->depth();
1039 
1040   // Allocate the object pool for scalar-replaced objects -- the map from
1041   // small-integer keys (which can be recorded in the local and ostack
1042   // arrays) to descriptions of the object state.
1043   GrowableArray<ScopeValue*> *objs = new GrowableArray<ScopeValue*>();
1044 
1045   // Visit scopes from oldest to youngest.
1046   for (int depth = 1; depth <= max_depth; depth++) {
1047     JVMState* jvms = youngest_jvms->of_depth(depth);
1048     int idx;
1049     ciMethod* method = jvms->has_method() ? jvms->method() : nullptr;
1050     // Safepoints that do not have method() set only provide oop-map and monitor info
1051     // to support GC; these do not support deoptimization.
1052     int num_locs = (method == nullptr) ? 0 : jvms->loc_size();
1053     int num_exps = (method == nullptr) ? 0 : jvms->stk_size();
1054     int num_mon  = jvms->nof_monitors();
1055     assert(method == nullptr || jvms->bci() < 0 || num_locs == method->max_locals(),
1056            "JVMS local count must match that of the method");
1057 
1058     // Add Local and Expression Stack Information
1059 
1060     // Insert locals into the locarray
1061     GrowableArray<ScopeValue*> *locarray = new GrowableArray<ScopeValue*>(num_locs);
1062     for( idx = 0; idx < num_locs; idx++ ) {
1063       FillLocArray( idx, sfn, sfn->local(jvms, idx), locarray, objs );
1064     }
1065 
1066     // Insert expression stack entries into the exparray
1067     GrowableArray<ScopeValue*> *exparray = new GrowableArray<ScopeValue*>(num_exps);
1068     for( idx = 0; idx < num_exps; idx++ ) {
1069       FillLocArray( idx,  sfn, sfn->stack(jvms, idx), exparray, objs );
1070     }
1071 
1072     // Add in mappings of the monitors
1073     assert( !method ||
1074             !method->is_synchronized() ||
1075             method->is_native() ||
1076             num_mon > 0 ||
1077             !GenerateSynchronizationCode,
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       }
1926       if (C->method() != nullptr) {
1927         tty->print_cr("----------------------- MetaData before Compile_id = %d ------------------------", C->compile_id());
1928         tty->print_raw(method_metadata_str.freeze());
1929       } else if (C->stub_name() != nullptr) {
1930         tty->print_cr("----------------------------- RuntimeStub %s -------------------------------", C->stub_name());
1931       }
1932       tty->cr();
1933       tty->print_cr("------------------------ OptoAssembly for Compile_id = %d -----------------------", C->compile_id());
1934       tty->print_raw(dump_asm_str.freeze());
1935       tty->print_cr("--------------------------------------------------------------------------------");
1936       if (xtty != nullptr) {
1937         xtty->tail("opto_assembly");
1938       }
1939     }
1940   }
1941 #endif
1942 }
1943 
1944 void PhaseOutput::FillExceptionTables(uint cnt, uint *call_returns, uint *inct_starts, Label *blk_labels) {
1945   _inc_table.set_size(cnt);
1946 
1947   uint inct_cnt = 0;
1948   for (uint i = 0; i < C->cfg()->number_of_blocks(); i++) {
1949     Block* block = C->cfg()->get_block(i);
1950     Node *n = nullptr;
1951     int j;
1952 
1953     // Find the branch; ignore trailing NOPs.
1954     for (j = block->number_of_nodes() - 1; j >= 0; j--) {
1955       n = block->get_node(j);
1956       if (!n->is_Mach() || n->as_Mach()->ideal_Opcode() != Op_Con) {
1957         break;
1958       }
1959     }
1960 
1961     // If we didn't find anything, continue
1962     if (j < 0) {
1963       continue;
1964     }
1965 
1966     // Compute ExceptionHandlerTable subtable entry and add it
1967     // (skip empty blocks)
1968     if (n->is_Catch()) {
1969 
1970       // Get the offset of the return from the call
1971       uint call_return = call_returns[block->_pre_order];
1972 #ifdef ASSERT
1973       assert( call_return > 0, "no call seen for this basic block" );
1974       while (block->get_node(--j)->is_MachProj()) ;
1975       assert(block->get_node(j)->is_MachCall(), "CatchProj must follow call");
1976 #endif
1977       // last instruction is a CatchNode, find it's CatchProjNodes
1978       int nof_succs = block->_num_succs;
1979       // allocate space
1980       GrowableArray<intptr_t> handler_bcis(nof_succs);
1981       GrowableArray<intptr_t> handler_pcos(nof_succs);
1982       // iterate through all successors
1983       for (int j = 0; j < nof_succs; j++) {
1984         Block* s = block->_succs[j];
1985         bool found_p = false;
1986         for (uint k = 1; k < s->num_preds(); k++) {
1987           Node* pk = s->pred(k);
1988           if (pk->is_CatchProj() && pk->in(0) == n) {
1989             const CatchProjNode* p = pk->as_CatchProj();
1990             found_p = true;
1991             // add the corresponding handler bci & pco information
1992             if (p->_con != CatchProjNode::fall_through_index) {
1993               // p leads to an exception handler (and is not fall through)
1994               assert(s == C->cfg()->get_block(s->_pre_order), "bad numbering");
1995               // no duplicates, please
1996               if (!handler_bcis.contains(p->handler_bci())) {
1997                 uint block_num = s->non_connector()->_pre_order;
1998                 handler_bcis.append(p->handler_bci());
1999                 handler_pcos.append(blk_labels[block_num].loc_pos());
2000               }
2001             }
2002           }
2003         }
2004         assert(found_p, "no matching predecessor found");
2005         // Note:  Due to empty block removal, one block may have
2006         // several CatchProj inputs, from the same Catch.
2007       }
2008 
2009       // Set the offset of the return from the call
2010       assert(handler_bcis.find(-1) != -1, "must have default handler");
2011       _handler_table.add_subtable(call_return, &handler_bcis, nullptr, &handler_pcos);
2012       continue;
2013     }
2014 
2015     // Handle implicit null exception table updates
2016     if (n->is_MachNullCheck()) {
2017       assert(n->in(1)->as_Mach()->barrier_data() == 0,
2018              "Implicit null checks on memory accesses with barriers are not yet supported");
2019       uint block_num = block->non_connector_successor(0)->_pre_order;
2020       _inc_table.append(inct_starts[inct_cnt++], blk_labels[block_num].loc_pos());
2021       continue;
2022     }
2023     // Handle implicit exception table updates: trap instructions.
2024     if (n->is_Mach() && n->as_Mach()->is_TrapBasedCheckNode()) {
2025       uint block_num = block->non_connector_successor(0)->_pre_order;
2026       _inc_table.append(inct_starts[inct_cnt++], blk_labels[block_num].loc_pos());
2027       continue;
2028     }
2029   } // End of for all blocks fill in exception table entries
2030 }
2031 
2032 // Static Variables
2033 #ifndef PRODUCT
2034 uint Scheduling::_total_nop_size = 0;
2035 uint Scheduling::_total_method_size = 0;
2036 uint Scheduling::_total_branches = 0;
2037 uint Scheduling::_total_unconditional_delays = 0;
2038 uint Scheduling::_total_instructions_per_bundle[Pipeline::_max_instrs_per_cycle+1];
2039 #endif
2040 
2041 // Initializer for class Scheduling
2042 
2043 Scheduling::Scheduling(Arena *arena, Compile &compile)
2044         : _arena(arena),
2045           _cfg(compile.cfg()),
2046           _regalloc(compile.regalloc()),
2047           _scheduled(arena),
2048           _available(arena),
2049           _reg_node(arena),
2050           _pinch_free_list(arena),
2051           _next_node(nullptr),
2052           _bundle_instr_count(0),
2053           _bundle_cycle_number(0),
2054           _bundle_use(0, 0, resource_count, &_bundle_use_elements[0])
2055 #ifndef PRODUCT
2056         , _branches(0)
2057         , _unconditional_delays(0)
2058 #endif
2059 {
2060   // Create a MachNopNode
2061   _nop = new MachNopNode();
2062 
2063   // Now that the nops are in the array, save the count
2064   // (but allow entries for the nops)
2065   _node_bundling_limit = compile.unique();
2066   uint node_max = _regalloc->node_regs_max_index();
2067 
2068   compile.output()->set_node_bundling_limit(_node_bundling_limit);
2069 
2070   // This one is persistent within the Compile class
2071   _node_bundling_base = NEW_ARENA_ARRAY(compile.comp_arena(), Bundle, node_max);
2072 
2073   // Allocate space for fixed-size arrays
2074   _uses            = NEW_ARENA_ARRAY(arena, short,          node_max);
2075   _current_latency = NEW_ARENA_ARRAY(arena, unsigned short, node_max);
2076 
2077   // Clear the arrays
2078   for (uint i = 0; i < node_max; i++) {
2079     ::new (&_node_bundling_base[i]) Bundle();
2080   }
2081   memset(_uses,               0, node_max * sizeof(short));
2082   memset(_current_latency,    0, node_max * sizeof(unsigned short));
2083 
2084   // Clear the bundling information
2085   memcpy(_bundle_use_elements, Pipeline_Use::elaborated_elements, sizeof(Pipeline_Use::elaborated_elements));
2086 
2087   // Get the last node
2088   Block* block = _cfg->get_block(_cfg->number_of_blocks() - 1);
2089 
2090   _next_node = block->get_node(block->number_of_nodes() - 1);
2091 }
2092 
2093 #ifndef PRODUCT
2094 // Scheduling destructor
2095 Scheduling::~Scheduling() {
2096   _total_branches             += _branches;
2097   _total_unconditional_delays += _unconditional_delays;
2098 }
2099 #endif
2100 
2101 // Step ahead "i" cycles
2102 void Scheduling::step(uint i) {
2103 
2104   Bundle *bundle = node_bundling(_next_node);
2105   bundle->set_starts_bundle();
2106 
2107   // Update the bundle record, but leave the flags information alone
2108   if (_bundle_instr_count > 0) {
2109     bundle->set_instr_count(_bundle_instr_count);
2110     bundle->set_resources_used(_bundle_use.resourcesUsed());
2111   }
2112 
2113   // Update the state information
2114   _bundle_instr_count = 0;
2115   _bundle_cycle_number += i;
2116   _bundle_use.step(i);
2117 }
2118 
2119 void Scheduling::step_and_clear() {
2120   Bundle *bundle = node_bundling(_next_node);
2121   bundle->set_starts_bundle();
2122 
2123   // Update the bundle record
2124   if (_bundle_instr_count > 0) {
2125     bundle->set_instr_count(_bundle_instr_count);
2126     bundle->set_resources_used(_bundle_use.resourcesUsed());
2127 
2128     _bundle_cycle_number += 1;
2129   }
2130 
2131   // Clear the bundling information
2132   _bundle_instr_count = 0;
2133   _bundle_use.reset();
2134 
2135   memcpy(_bundle_use_elements,
2136          Pipeline_Use::elaborated_elements,
2137          sizeof(Pipeline_Use::elaborated_elements));
2138 }
2139 
2140 // Perform instruction scheduling and bundling over the sequence of
2141 // instructions in backwards order.
2142 void PhaseOutput::ScheduleAndBundle() {
2143 
2144   // Don't optimize this if it isn't a method
2145   if (!C->method())
2146     return;
2147 
2148   // Don't optimize this if scheduling is disabled
2149   if (!C->do_scheduling())
2150     return;
2151 
2152   // Scheduling code works only with pairs (8 bytes) maximum.
2153   // And when the scalable vector register is used, we may spill/unspill
2154   // the whole reg regardless of the max vector size.
2155   if (C->max_vector_size() > 8 ||
2156       (C->max_vector_size() > 0 && Matcher::supports_scalable_vector())) {
2157     return;
2158   }
2159 
2160   Compile::TracePhase tp(_t_instrSched);
2161 
2162   // Create a data structure for all the scheduling information
2163   Scheduling scheduling(Thread::current()->resource_area(), *C);
2164 
2165   // Walk backwards over each basic block, computing the needed alignment
2166   // Walk over all the basic blocks
2167   scheduling.DoScheduling();
2168 
2169 #ifndef PRODUCT
2170   if (C->trace_opto_output()) {
2171     // Buffer and print all at once
2172     ResourceMark rm;
2173     stringStream ss;
2174     ss.print("\n---- After ScheduleAndBundle ----\n");
2175     print_scheduling(&ss);
2176     tty->print("%s", ss.as_string());
2177   }
2178 #endif
2179 }
2180 
2181 #ifndef PRODUCT
2182 // Separated out so that it can be called directly from debugger
2183 void PhaseOutput::print_scheduling() {
2184   print_scheduling(tty);
2185 }
2186 
2187 void PhaseOutput::print_scheduling(outputStream* output_stream) {
2188   for (uint i = 0; i < C->cfg()->number_of_blocks(); i++) {
2189     output_stream->print("\nBB#%03d:\n", i);
2190     Block* block = C->cfg()->get_block(i);
2191     for (uint j = 0; j < block->number_of_nodes(); j++) {
2192       Node* n = block->get_node(j);
2193       OptoReg::Name reg = C->regalloc()->get_reg_first(n);
2194       output_stream->print(" %-6s ", reg >= 0 && reg < REG_COUNT ? Matcher::regName[reg] : "");
2195       n->dump("\n", false, output_stream);
2196     }
2197   }
2198 }
2199 #endif
2200 
2201 // See if this node fits into the present instruction bundle
2202 bool Scheduling::NodeFitsInBundle(Node *n) {
2203   uint n_idx = n->_idx;
2204 
2205   // If this is the unconditional delay instruction, then it fits
2206   if (n == _unconditional_delay_slot) {
2207 #ifndef PRODUCT
2208     if (_cfg->C->trace_opto_output())
2209       tty->print("#     NodeFitsInBundle [%4d]: TRUE; is in unconditional delay slot\n", n->_idx);
2210 #endif
2211     return (true);
2212   }
2213 
2214   // If the node cannot be scheduled this cycle, skip it
2215   if (_current_latency[n_idx] > _bundle_cycle_number) {
2216 #ifndef PRODUCT
2217     if (_cfg->C->trace_opto_output())
2218       tty->print("#     NodeFitsInBundle [%4d]: FALSE; latency %4d > %d\n",
2219                  n->_idx, _current_latency[n_idx], _bundle_cycle_number);
2220 #endif
2221     return (false);
2222   }
2223 
2224   const Pipeline *node_pipeline = n->pipeline();
2225 
2226   uint instruction_count = node_pipeline->instructionCount();
2227   if (node_pipeline->mayHaveNoCode() && n->size(_regalloc) == 0)
2228     instruction_count = 0;
2229   else if (node_pipeline->hasBranchDelay() && !_unconditional_delay_slot)
2230     instruction_count++;
2231 
2232   if (_bundle_instr_count + instruction_count > Pipeline::_max_instrs_per_cycle) {
2233 #ifndef PRODUCT
2234     if (_cfg->C->trace_opto_output())
2235       tty->print("#     NodeFitsInBundle [%4d]: FALSE; too many instructions: %d > %d\n",
2236                  n->_idx, _bundle_instr_count + instruction_count, Pipeline::_max_instrs_per_cycle);
2237 #endif
2238     return (false);
2239   }
2240 
2241   // Don't allow non-machine nodes to be handled this way
2242   if (!n->is_Mach() && instruction_count == 0)
2243     return (false);
2244 
2245   // See if there is any overlap
2246   uint delay = _bundle_use.full_latency(0, node_pipeline->resourceUse());
2247 
2248   if (delay > 0) {
2249 #ifndef PRODUCT
2250     if (_cfg->C->trace_opto_output())
2251       tty->print("#     NodeFitsInBundle [%4d]: FALSE; functional units overlap\n", n_idx);
2252 #endif
2253     return false;
2254   }
2255 
2256 #ifndef PRODUCT
2257   if (_cfg->C->trace_opto_output())
2258     tty->print("#     NodeFitsInBundle [%4d]:  TRUE\n", n_idx);
2259 #endif
2260 
2261   return true;
2262 }
2263 
2264 Node * Scheduling::ChooseNodeToBundle() {
2265   uint siz = _available.size();
2266 
2267   if (siz == 0) {
2268 
2269 #ifndef PRODUCT
2270     if (_cfg->C->trace_opto_output())
2271       tty->print("#   ChooseNodeToBundle: null\n");
2272 #endif
2273     return (nullptr);
2274   }
2275 
2276   // Fast path, if only 1 instruction in the bundle
2277   if (siz == 1) {
2278 #ifndef PRODUCT
2279     if (_cfg->C->trace_opto_output()) {
2280       tty->print("#   ChooseNodeToBundle (only 1): ");
2281       _available[0]->dump();
2282     }
2283 #endif
2284     return (_available[0]);
2285   }
2286 
2287   // Don't bother, if the bundle is already full
2288   if (_bundle_instr_count < Pipeline::_max_instrs_per_cycle) {
2289     for ( uint i = 0; i < siz; i++ ) {
2290       Node *n = _available[i];
2291 
2292       // Skip projections, we'll handle them another way
2293       if (n->is_Proj())
2294         continue;
2295 
2296       // This presupposed that instructions are inserted into the
2297       // available list in a legality order; i.e. instructions that
2298       // must be inserted first are at the head of the list
2299       if (NodeFitsInBundle(n)) {
2300 #ifndef PRODUCT
2301         if (_cfg->C->trace_opto_output()) {
2302           tty->print("#   ChooseNodeToBundle: ");
2303           n->dump();
2304         }
2305 #endif
2306         return (n);
2307       }
2308     }
2309   }
2310 
2311   // Nothing fits in this bundle, choose the highest priority
2312 #ifndef PRODUCT
2313   if (_cfg->C->trace_opto_output()) {
2314     tty->print("#   ChooseNodeToBundle: ");
2315     _available[0]->dump();
2316   }
2317 #endif
2318 
2319   return _available[0];
2320 }
2321 
2322 int Scheduling::compare_two_spill_nodes(Node* first, Node* second) {
2323   assert(first->is_MachSpillCopy() && second->is_MachSpillCopy(), "");
2324 
2325   OptoReg::Name first_src_lo = _regalloc->get_reg_first(first->in(1));
2326   OptoReg::Name first_dst_lo = _regalloc->get_reg_first(first);
2327   OptoReg::Name second_src_lo = _regalloc->get_reg_first(second->in(1));
2328   OptoReg::Name second_dst_lo = _regalloc->get_reg_first(second);
2329 
2330   // Comparison between stack -> reg and stack -> reg
2331   if (OptoReg::is_stack(first_src_lo) && OptoReg::is_stack(second_src_lo) &&
2332       OptoReg::is_reg(first_dst_lo) && OptoReg::is_reg(second_dst_lo)) {
2333     return _regalloc->reg2offset(first_src_lo) - _regalloc->reg2offset(second_src_lo);
2334   }
2335 
2336   // Comparison between reg -> stack and reg -> stack
2337   if (OptoReg::is_stack(first_dst_lo) && OptoReg::is_stack(second_dst_lo) &&
2338       OptoReg::is_reg(first_src_lo) && OptoReg::is_reg(second_src_lo)) {
2339     return _regalloc->reg2offset(first_dst_lo) - _regalloc->reg2offset(second_dst_lo);
2340   }
2341 
2342   return 0; // Not comparable
2343 }
2344 
2345 void Scheduling::AddNodeToAvailableList(Node *n) {
2346   assert( !n->is_Proj(), "projections never directly made available" );
2347 #ifndef PRODUCT
2348   if (_cfg->C->trace_opto_output()) {
2349     tty->print("#   AddNodeToAvailableList: ");
2350     n->dump();
2351   }
2352 #endif
2353 
2354   int latency = _current_latency[n->_idx];
2355 
2356   // Insert in latency order (insertion sort). If two MachSpillCopyNodes
2357   // for stack spilling or unspilling have the same latency, we sort
2358   // them in the order of stack offset. Some ports (e.g. aarch64) may also
2359   // have more opportunities to do ld/st merging
2360   uint i;
2361   for (i = 0; i < _available.size(); i++) {
2362     if (_current_latency[_available[i]->_idx] > latency) {
2363       break;
2364     } else if (_current_latency[_available[i]->_idx] == latency &&
2365                n->is_MachSpillCopy() && _available[i]->is_MachSpillCopy() &&
2366                compare_two_spill_nodes(n, _available[i]) > 0) {
2367       break;
2368     }
2369   }
2370 
2371   // Special Check for compares following branches
2372   if( n->is_Mach() && _scheduled.size() > 0 ) {
2373     int op = n->as_Mach()->ideal_Opcode();
2374     Node *last = _scheduled[0];
2375     if( last->is_MachIf() && last->in(1) == n &&
2376         ( op == Op_CmpI ||
2377           op == Op_CmpU ||
2378           op == Op_CmpUL ||
2379           op == Op_CmpP ||
2380           op == Op_CmpF ||
2381           op == Op_CmpD ||
2382           op == Op_CmpL ) ) {
2383 
2384       // Recalculate position, moving to front of same latency
2385       for ( i=0 ; i < _available.size(); i++ )
2386         if (_current_latency[_available[i]->_idx] >= latency)
2387           break;
2388     }
2389   }
2390 
2391   // Insert the node in the available list
2392   _available.insert(i, n);
2393 
2394 #ifndef PRODUCT
2395   if (_cfg->C->trace_opto_output())
2396     dump_available();
2397 #endif
2398 }
2399 
2400 void Scheduling::DecrementUseCounts(Node *n, const Block *bb) {
2401   for ( uint i=0; i < n->len(); i++ ) {
2402     Node *def = n->in(i);
2403     if (!def) continue;
2404     if( def->is_Proj() )        // If this is a machine projection, then
2405       def = def->in(0);         // propagate usage thru to the base instruction
2406 
2407     if(_cfg->get_block_for_node(def) != bb) { // Ignore if not block-local
2408       continue;
2409     }
2410 
2411     // Compute the latency
2412     uint l = _bundle_cycle_number + n->latency(i);
2413     if (_current_latency[def->_idx] < l)
2414       _current_latency[def->_idx] = l;
2415 
2416     // If this does not have uses then schedule it
2417     if ((--_uses[def->_idx]) == 0)
2418       AddNodeToAvailableList(def);
2419   }
2420 }
2421 
2422 void Scheduling::AddNodeToBundle(Node *n, const Block *bb) {
2423 #ifndef PRODUCT
2424   if (_cfg->C->trace_opto_output()) {
2425     tty->print("#   AddNodeToBundle: ");
2426     n->dump();
2427   }
2428 #endif
2429 
2430   // Remove this from the available list
2431   uint i;
2432   for (i = 0; i < _available.size(); i++)
2433     if (_available[i] == n)
2434       break;
2435   assert(i < _available.size(), "entry in _available list not found");
2436   _available.remove(i);
2437 
2438   // See if this fits in the current bundle
2439   const Pipeline *node_pipeline = n->pipeline();
2440   const Pipeline_Use& node_usage = node_pipeline->resourceUse();
2441 
2442   // Check for instructions to be placed in the delay slot. We
2443   // do this before we actually schedule the current instruction,
2444   // because the delay slot follows the current instruction.
2445   if (Pipeline::_branch_has_delay_slot &&
2446       node_pipeline->hasBranchDelay() &&
2447       !_unconditional_delay_slot) {
2448 
2449     uint siz = _available.size();
2450 
2451     // Conditional branches can support an instruction that
2452     // is unconditionally executed and not dependent by the
2453     // branch, OR a conditionally executed instruction if
2454     // the branch is taken.  In practice, this means that
2455     // the first instruction at the branch target is
2456     // copied to the delay slot, and the branch goes to
2457     // the instruction after that at the branch target
2458     if ( n->is_MachBranch() ) {
2459 
2460       assert( !n->is_MachNullCheck(), "should not look for delay slot for Null Check" );
2461       assert( !n->is_Catch(),         "should not look for delay slot for Catch" );
2462 
2463 #ifndef PRODUCT
2464       _branches++;
2465 #endif
2466 
2467       // At least 1 instruction is on the available list
2468       // that is not dependent on the branch
2469       for (uint i = 0; i < siz; i++) {
2470         Node *d = _available[i];
2471         const Pipeline *avail_pipeline = d->pipeline();
2472 
2473         // Don't allow safepoints in the branch shadow, that will
2474         // cause a number of difficulties
2475         if ( avail_pipeline->instructionCount() == 1 &&
2476              !avail_pipeline->hasMultipleBundles() &&
2477              !avail_pipeline->hasBranchDelay() &&
2478              Pipeline::instr_has_unit_size() &&
2479              d->size(_regalloc) == Pipeline::instr_unit_size() &&
2480              NodeFitsInBundle(d) &&
2481              !node_bundling(d)->used_in_delay()) {
2482 
2483           if (d->is_Mach() && !d->is_MachSafePoint()) {
2484             // A node that fits in the delay slot was found, so we need to
2485             // set the appropriate bits in the bundle pipeline information so
2486             // that it correctly indicates resource usage.  Later, when we
2487             // attempt to add this instruction to the bundle, we will skip
2488             // setting the resource usage.
2489             _unconditional_delay_slot = d;
2490             node_bundling(n)->set_use_unconditional_delay();
2491             node_bundling(d)->set_used_in_unconditional_delay();
2492             _bundle_use.add_usage(avail_pipeline->resourceUse());
2493             _current_latency[d->_idx] = _bundle_cycle_number;
2494             _next_node = d;
2495             ++_bundle_instr_count;
2496 #ifndef PRODUCT
2497             _unconditional_delays++;
2498 #endif
2499             break;
2500           }
2501         }
2502       }
2503     }
2504 
2505     // No delay slot, add a nop to the usage
2506     if (!_unconditional_delay_slot) {
2507       // See if adding an instruction in the delay slot will overflow
2508       // the bundle.
2509       if (!NodeFitsInBundle(_nop)) {
2510 #ifndef PRODUCT
2511         if (_cfg->C->trace_opto_output())
2512           tty->print("#  *** STEP(1 instruction for delay slot) ***\n");
2513 #endif
2514         step(1);
2515       }
2516 
2517       _bundle_use.add_usage(_nop->pipeline()->resourceUse());
2518       _next_node = _nop;
2519       ++_bundle_instr_count;
2520     }
2521 
2522     // See if the instruction in the delay slot requires a
2523     // step of the bundles
2524     if (!NodeFitsInBundle(n)) {
2525 #ifndef PRODUCT
2526       if (_cfg->C->trace_opto_output())
2527         tty->print("#  *** STEP(branch won't fit) ***\n");
2528 #endif
2529       // Update the state information
2530       _bundle_instr_count = 0;
2531       _bundle_cycle_number += 1;
2532       _bundle_use.step(1);
2533     }
2534   }
2535 
2536   // Get the number of instructions
2537   uint instruction_count = node_pipeline->instructionCount();
2538   if (node_pipeline->mayHaveNoCode() && n->size(_regalloc) == 0)
2539     instruction_count = 0;
2540 
2541   // Compute the latency information
2542   uint delay = 0;
2543 
2544   if (instruction_count > 0 || !node_pipeline->mayHaveNoCode()) {
2545     int relative_latency = _current_latency[n->_idx] - _bundle_cycle_number;
2546     if (relative_latency < 0)
2547       relative_latency = 0;
2548 
2549     delay = _bundle_use.full_latency(relative_latency, node_usage);
2550 
2551     // Does not fit in this bundle, start a new one
2552     if (delay > 0) {
2553       step(delay);
2554 
2555 #ifndef PRODUCT
2556       if (_cfg->C->trace_opto_output())
2557         tty->print("#  *** STEP(%d) ***\n", delay);
2558 #endif
2559     }
2560   }
2561 
2562   // If this was placed in the delay slot, ignore it
2563   if (n != _unconditional_delay_slot) {
2564 
2565     if (delay == 0) {
2566       if (node_pipeline->hasMultipleBundles()) {
2567 #ifndef PRODUCT
2568         if (_cfg->C->trace_opto_output())
2569           tty->print("#  *** STEP(multiple instructions) ***\n");
2570 #endif
2571         step(1);
2572       }
2573 
2574       else if (instruction_count + _bundle_instr_count > Pipeline::_max_instrs_per_cycle) {
2575 #ifndef PRODUCT
2576         if (_cfg->C->trace_opto_output())
2577           tty->print("#  *** STEP(%d >= %d instructions) ***\n",
2578                      instruction_count + _bundle_instr_count,
2579                      Pipeline::_max_instrs_per_cycle);
2580 #endif
2581         step(1);
2582       }
2583     }
2584 
2585     if (node_pipeline->hasBranchDelay() && !_unconditional_delay_slot)
2586       _bundle_instr_count++;
2587 
2588     // Set the node's latency
2589     _current_latency[n->_idx] = _bundle_cycle_number;
2590 
2591     // Now merge the functional unit information
2592     if (instruction_count > 0 || !node_pipeline->mayHaveNoCode())
2593       _bundle_use.add_usage(node_usage);
2594 
2595     // Increment the number of instructions in this bundle
2596     _bundle_instr_count += instruction_count;
2597 
2598     // Remember this node for later
2599     if (n->is_Mach())
2600       _next_node = n;
2601   }
2602 
2603   // It's possible to have a BoxLock in the graph and in the _bbs mapping but
2604   // not in the bb->_nodes array.  This happens for debug-info-only BoxLocks.
2605   // 'Schedule' them (basically ignore in the schedule) but do not insert them
2606   // into the block.  All other scheduled nodes get put in the schedule here.
2607   int op = n->Opcode();
2608   if( (op == Op_Node && n->req() == 0) || // anti-dependence node OR
2609       (op != Op_Node &&         // Not an unused antidepedence node and
2610        // not an unallocated boxlock
2611        (OptoReg::is_valid(_regalloc->get_reg_first(n)) || op != Op_BoxLock)) ) {
2612 
2613     // Push any trailing projections
2614     if( bb->get_node(bb->number_of_nodes()-1) != n ) {
2615       for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
2616         Node *foi = n->fast_out(i);
2617         if( foi->is_Proj() )
2618           _scheduled.push(foi);
2619       }
2620     }
2621 
2622     // Put the instruction in the schedule list
2623     _scheduled.push(n);
2624   }
2625 
2626 #ifndef PRODUCT
2627   if (_cfg->C->trace_opto_output())
2628     dump_available();
2629 #endif
2630 
2631   // Walk all the definitions, decrementing use counts, and
2632   // if a definition has a 0 use count, place it in the available list.
2633   DecrementUseCounts(n,bb);
2634 }
2635 
2636 // This method sets the use count within a basic block.  We will ignore all
2637 // uses outside the current basic block.  As we are doing a backwards walk,
2638 // any node we reach that has a use count of 0 may be scheduled.  This also
2639 // avoids the problem of cyclic references from phi nodes, as long as phi
2640 // nodes are at the front of the basic block.  This method also initializes
2641 // the available list to the set of instructions that have no uses within this
2642 // basic block.
2643 void Scheduling::ComputeUseCount(const Block *bb) {
2644 #ifndef PRODUCT
2645   if (_cfg->C->trace_opto_output())
2646     tty->print("# -> ComputeUseCount\n");
2647 #endif
2648 
2649   // Clear the list of available and scheduled instructions, just in case
2650   _available.clear();
2651   _scheduled.clear();
2652 
2653   // No delay slot specified
2654   _unconditional_delay_slot = nullptr;
2655 
2656 #ifdef ASSERT
2657   for( uint i=0; i < bb->number_of_nodes(); i++ )
2658     assert( _uses[bb->get_node(i)->_idx] == 0, "_use array not clean" );
2659 #endif
2660 
2661   // Force the _uses count to never go to zero for unscheduable pieces
2662   // of the block
2663   for( uint k = 0; k < _bb_start; k++ )
2664     _uses[bb->get_node(k)->_idx] = 1;
2665   for( uint l = _bb_end; l < bb->number_of_nodes(); l++ )
2666     _uses[bb->get_node(l)->_idx] = 1;
2667 
2668   // Iterate backwards over the instructions in the block.  Don't count the
2669   // branch projections at end or the block header instructions.
2670   for( uint j = _bb_end-1; j >= _bb_start; j-- ) {
2671     Node *n = bb->get_node(j);
2672     if( n->is_Proj() ) continue; // Projections handled another way
2673 
2674     // Account for all uses
2675     for ( uint k = 0; k < n->len(); k++ ) {
2676       Node *inp = n->in(k);
2677       if (!inp) continue;
2678       assert(inp != n, "no cycles allowed" );
2679       if (_cfg->get_block_for_node(inp) == bb) { // Block-local use?
2680         if (inp->is_Proj()) { // Skip through Proj's
2681           inp = inp->in(0);
2682         }
2683         ++_uses[inp->_idx];     // Count 1 block-local use
2684       }
2685     }
2686 
2687     // If this instruction has a 0 use count, then it is available
2688     if (!_uses[n->_idx]) {
2689       _current_latency[n->_idx] = _bundle_cycle_number;
2690       AddNodeToAvailableList(n);
2691     }
2692 
2693 #ifndef PRODUCT
2694     if (_cfg->C->trace_opto_output()) {
2695       tty->print("#   uses: %3d: ", _uses[n->_idx]);
2696       n->dump();
2697     }
2698 #endif
2699   }
2700 
2701 #ifndef PRODUCT
2702   if (_cfg->C->trace_opto_output())
2703     tty->print("# <- ComputeUseCount\n");
2704 #endif
2705 }
2706 
2707 // This routine performs scheduling on each basic block in reverse order,
2708 // using instruction latencies and taking into account function unit
2709 // availability.
2710 void Scheduling::DoScheduling() {
2711 #ifndef PRODUCT
2712   if (_cfg->C->trace_opto_output())
2713     tty->print("# -> DoScheduling\n");
2714 #endif
2715 
2716   Block *succ_bb = nullptr;
2717   Block *bb;
2718   Compile* C = Compile::current();
2719 
2720   // Walk over all the basic blocks in reverse order
2721   for (int i = _cfg->number_of_blocks() - 1; i >= 0; succ_bb = bb, i--) {
2722     bb = _cfg->get_block(i);
2723 
2724 #ifndef PRODUCT
2725     if (_cfg->C->trace_opto_output()) {
2726       tty->print("#  Schedule BB#%03d (initial)\n", i);
2727       for (uint j = 0; j < bb->number_of_nodes(); j++) {
2728         bb->get_node(j)->dump();
2729       }
2730     }
2731 #endif
2732 
2733     // On the head node, skip processing
2734     if (bb == _cfg->get_root_block()) {
2735       continue;
2736     }
2737 
2738     // Skip empty, connector blocks
2739     if (bb->is_connector())
2740       continue;
2741 
2742     // If the following block is not the sole successor of
2743     // this one, then reset the pipeline information
2744     if (bb->_num_succs != 1 || bb->non_connector_successor(0) != succ_bb) {
2745 #ifndef PRODUCT
2746       if (_cfg->C->trace_opto_output()) {
2747         tty->print("*** bundle start of next BB, node %d, for %d instructions\n",
2748                    _next_node->_idx, _bundle_instr_count);
2749       }
2750 #endif
2751       step_and_clear();
2752     }
2753 
2754     // Leave untouched the starting instruction, any Phis, a CreateEx node
2755     // or Top.  bb->get_node(_bb_start) is the first schedulable instruction.
2756     _bb_end = bb->number_of_nodes()-1;
2757     for( _bb_start=1; _bb_start <= _bb_end; _bb_start++ ) {
2758       Node *n = bb->get_node(_bb_start);
2759       // Things not matched, like Phinodes and ProjNodes don't get scheduled.
2760       // Also, MachIdealNodes do not get scheduled
2761       if( !n->is_Mach() ) continue;     // Skip non-machine nodes
2762       MachNode *mach = n->as_Mach();
2763       int iop = mach->ideal_Opcode();
2764       if( iop == Op_CreateEx ) continue; // CreateEx is pinned
2765       if( iop == Op_Con ) continue;      // Do not schedule Top
2766       if( iop == Op_Node &&     // Do not schedule PhiNodes, ProjNodes
2767           mach->pipeline() == MachNode::pipeline_class() &&
2768           !n->is_SpillCopy() && !n->is_MachMerge() )  // Breakpoints, Prolog, etc
2769         continue;
2770       break;                    // Funny loop structure to be sure...
2771     }
2772     // Compute last "interesting" instruction in block - last instruction we
2773     // might schedule.  _bb_end points just after last schedulable inst.  We
2774     // normally schedule conditional branches (despite them being forced last
2775     // in the block), because they have delay slots we can fill.  Calls all
2776     // have their delay slots filled in the template expansions, so we don't
2777     // bother scheduling them.
2778     Node *last = bb->get_node(_bb_end);
2779     // Ignore trailing NOPs.
2780     while (_bb_end > 0 && last->is_Mach() &&
2781            last->as_Mach()->ideal_Opcode() == Op_Con) {
2782       last = bb->get_node(--_bb_end);
2783     }
2784     assert(!last->is_Mach() || last->as_Mach()->ideal_Opcode() != Op_Con, "");
2785     if( last->is_Catch() ||
2786         (last->is_Mach() && last->as_Mach()->ideal_Opcode() == Op_Halt) ) {
2787       // There might be a prior call.  Skip it.
2788       while (_bb_start < _bb_end && bb->get_node(--_bb_end)->is_MachProj());
2789     } else if( last->is_MachNullCheck() ) {
2790       // Backup so the last null-checked memory instruction is
2791       // outside the schedulable range. Skip over the nullcheck,
2792       // projection, and the memory nodes.
2793       Node *mem = last->in(1);
2794       do {
2795         _bb_end--;
2796       } while (mem != bb->get_node(_bb_end));
2797     } else {
2798       // Set _bb_end to point after last schedulable inst.
2799       _bb_end++;
2800     }
2801 
2802     assert( _bb_start <= _bb_end, "inverted block ends" );
2803 
2804     // Compute the register antidependencies for the basic block
2805     ComputeRegisterAntidependencies(bb);
2806     if (C->failing())  return;  // too many D-U pinch points
2807 
2808     // Compute the usage within the block, and set the list of all nodes
2809     // in the block that have no uses within the block.
2810     ComputeUseCount(bb);
2811 
2812     // Schedule the remaining instructions in the block
2813     while ( _available.size() > 0 ) {
2814       Node *n = ChooseNodeToBundle();
2815       guarantee(n != nullptr, "no nodes available");
2816       AddNodeToBundle(n,bb);
2817     }
2818 
2819     assert( _scheduled.size() == _bb_end - _bb_start, "wrong number of instructions" );
2820 #ifdef ASSERT
2821     for( uint l = _bb_start; l < _bb_end; l++ ) {
2822       Node *n = bb->get_node(l);
2823       uint m;
2824       for( m = 0; m < _bb_end-_bb_start; m++ )
2825         if( _scheduled[m] == n )
2826           break;
2827       assert( m < _bb_end-_bb_start, "instruction missing in schedule" );
2828     }
2829 #endif
2830 
2831     // Now copy the instructions (in reverse order) back to the block
2832     for ( uint k = _bb_start; k < _bb_end; k++ )
2833       bb->map_node(_scheduled[_bb_end-k-1], k);
2834 
2835 #ifndef PRODUCT
2836     if (_cfg->C->trace_opto_output()) {
2837       tty->print("#  Schedule BB#%03d (final)\n", i);
2838       uint current = 0;
2839       for (uint j = 0; j < bb->number_of_nodes(); j++) {
2840         Node *n = bb->get_node(j);
2841         if( valid_bundle_info(n) ) {
2842           Bundle *bundle = node_bundling(n);
2843           if (bundle->instr_count() > 0 || bundle->flags() > 0) {
2844             tty->print("*** Bundle: ");
2845             bundle->dump();
2846           }
2847           n->dump();
2848         }
2849       }
2850     }
2851 #endif
2852 #ifdef ASSERT
2853     verify_good_schedule(bb,"after block local scheduling");
2854 #endif
2855   }
2856 
2857 #ifndef PRODUCT
2858   if (_cfg->C->trace_opto_output())
2859     tty->print("# <- DoScheduling\n");
2860 #endif
2861 
2862   // Record final node-bundling array location
2863   _regalloc->C->output()->set_node_bundling_base(_node_bundling_base);
2864 
2865 } // end DoScheduling
2866 
2867 // Verify that no live-range used in the block is killed in the block by a
2868 // wrong DEF.  This doesn't verify live-ranges that span blocks.
2869 
2870 // Check for edge existence.  Used to avoid adding redundant precedence edges.
2871 static bool edge_from_to( Node *from, Node *to ) {
2872   for( uint i=0; i<from->len(); i++ )
2873     if( from->in(i) == to )
2874       return true;
2875   return false;
2876 }
2877 
2878 #ifdef ASSERT
2879 void Scheduling::verify_do_def( Node *n, OptoReg::Name def, const char *msg ) {
2880   // Check for bad kills
2881   if( OptoReg::is_valid(def) ) { // Ignore stores & control flow
2882     Node *prior_use = _reg_node[def];
2883     if( prior_use && !edge_from_to(prior_use,n) ) {
2884       tty->print("%s = ",OptoReg::as_VMReg(def)->name());
2885       n->dump();
2886       tty->print_cr("...");
2887       prior_use->dump();
2888       assert(edge_from_to(prior_use,n), "%s", msg);
2889     }
2890     _reg_node.map(def,nullptr); // Kill live USEs
2891   }
2892 }
2893 
2894 void Scheduling::verify_good_schedule( Block *b, const char *msg ) {
2895 
2896   // Zap to something reasonable for the verify code
2897   _reg_node.clear();
2898 
2899   // Walk over the block backwards.  Check to make sure each DEF doesn't
2900   // kill a live value (other than the one it's supposed to).  Add each
2901   // USE to the live set.
2902   for( uint i = b->number_of_nodes()-1; i >= _bb_start; i-- ) {
2903     Node *n = b->get_node(i);
2904     int n_op = n->Opcode();
2905     if( n_op == Op_MachProj && n->ideal_reg() == MachProjNode::fat_proj ) {
2906       // Fat-proj kills a slew of registers
2907       RegMaskIterator rmi(n->out_RegMask());
2908       while (rmi.has_next()) {
2909         OptoReg::Name kill = rmi.next();
2910         verify_do_def(n, kill, msg);
2911       }
2912     } else if( n_op != Op_Node ) { // Avoid brand new antidependence nodes
2913       // Get DEF'd registers the normal way
2914       verify_do_def( n, _regalloc->get_reg_first(n), msg );
2915       verify_do_def( n, _regalloc->get_reg_second(n), msg );
2916     }
2917 
2918     // Now make all USEs live
2919     for( uint i=1; i<n->req(); i++ ) {
2920       Node *def = n->in(i);
2921       assert(def != nullptr, "input edge required");
2922       OptoReg::Name reg_lo = _regalloc->get_reg_first(def);
2923       OptoReg::Name reg_hi = _regalloc->get_reg_second(def);
2924       if( OptoReg::is_valid(reg_lo) ) {
2925         assert(!_reg_node[reg_lo] || edge_from_to(_reg_node[reg_lo],def), "%s", msg);
2926         _reg_node.map(reg_lo,n);
2927       }
2928       if( OptoReg::is_valid(reg_hi) ) {
2929         assert(!_reg_node[reg_hi] || edge_from_to(_reg_node[reg_hi],def), "%s", msg);
2930         _reg_node.map(reg_hi,n);
2931       }
2932     }
2933 
2934   }
2935 
2936   // Zap to something reasonable for the Antidependence code
2937   _reg_node.clear();
2938 }
2939 #endif
2940 
2941 // Conditionally add precedence edges.  Avoid putting edges on Projs.
2942 static void add_prec_edge_from_to( Node *from, Node *to ) {
2943   if( from->is_Proj() ) {       // Put precedence edge on Proj's input
2944     assert( from->req() == 1 && (from->len() == 1 || from->in(1) == nullptr), "no precedence edges on projections" );
2945     from = from->in(0);
2946   }
2947   if( from != to &&             // No cycles (for things like LD L0,[L0+4] )
2948       !edge_from_to( from, to ) ) // Avoid duplicate edge
2949     from->add_prec(to);
2950 }
2951 
2952 void Scheduling::anti_do_def( Block *b, Node *def, OptoReg::Name def_reg, int is_def ) {
2953   if( !OptoReg::is_valid(def_reg) ) // Ignore stores & control flow
2954     return;
2955 
2956   if (OptoReg::is_reg(def_reg)) {
2957     VMReg vmreg = OptoReg::as_VMReg(def_reg);
2958     if (vmreg->is_reg() && !vmreg->is_concrete() && !vmreg->prev()->is_concrete()) {
2959       // This is one of the high slots of a vector register.
2960       // ScheduleAndBundle already checked there are no live wide
2961       // vectors in this method so it can be safely ignored.
2962       return;
2963     }
2964   }
2965 
2966   Node *pinch = _reg_node[def_reg]; // Get pinch point
2967   if ((pinch == nullptr) || _cfg->get_block_for_node(pinch) != b || // No pinch-point yet?
2968       is_def ) {    // Check for a true def (not a kill)
2969     _reg_node.map(def_reg,def); // Record def/kill as the optimistic pinch-point
2970     return;
2971   }
2972 
2973   Node *kill = def;             // Rename 'def' to more descriptive 'kill'
2974   debug_only( def = (Node*)((intptr_t)0xdeadbeef); )
2975 
2976   // After some number of kills there _may_ be a later def
2977   Node *later_def = nullptr;
2978 
2979   Compile* C = Compile::current();
2980 
2981   // Finding a kill requires a real pinch-point.
2982   // Check for not already having a pinch-point.
2983   // Pinch points are Op_Node's.
2984   if( pinch->Opcode() != Op_Node ) { // Or later-def/kill as pinch-point?
2985     later_def = pinch;            // Must be def/kill as optimistic pinch-point
2986     if ( _pinch_free_list.size() > 0) {
2987       pinch = _pinch_free_list.pop();
2988     } else {
2989       pinch = new Node(1); // Pinch point to-be
2990     }
2991     if (pinch->_idx >= _regalloc->node_regs_max_index()) {
2992       DEBUG_ONLY( pinch->dump(); );
2993       assert(false, "too many D-U pinch points: %d >= %d", pinch->_idx, _regalloc->node_regs_max_index());
2994       _cfg->C->record_method_not_compilable("too many D-U pinch points");
2995       return;
2996     }
2997     _cfg->map_node_to_block(pinch, b);      // Pretend it's valid in this block (lazy init)
2998     _reg_node.map(def_reg,pinch); // Record pinch-point
2999     //regalloc()->set_bad(pinch->_idx); // Already initialized this way.
3000     if( later_def->outcnt() == 0 || later_def->ideal_reg() == MachProjNode::fat_proj ) { // Distinguish def from kill
3001       pinch->init_req(0, C->top());     // set not null for the next call
3002       add_prec_edge_from_to(later_def,pinch); // Add edge from kill to pinch
3003       later_def = nullptr;           // and no later def
3004     }
3005     pinch->set_req(0,later_def);  // Hook later def so we can find it
3006   } else {                        // Else have valid pinch point
3007     if( pinch->in(0) )            // If there is a later-def
3008       later_def = pinch->in(0);   // Get it
3009   }
3010 
3011   // Add output-dependence edge from later def to kill
3012   if( later_def )               // If there is some original def
3013     add_prec_edge_from_to(later_def,kill); // Add edge from def to kill
3014 
3015   // See if current kill is also a use, and so is forced to be the pinch-point.
3016   if( pinch->Opcode() == Op_Node ) {
3017     Node *uses = kill->is_Proj() ? kill->in(0) : kill;
3018     for( uint i=1; i<uses->req(); i++ ) {
3019       if( _regalloc->get_reg_first(uses->in(i)) == def_reg ||
3020           _regalloc->get_reg_second(uses->in(i)) == def_reg ) {
3021         // Yes, found a use/kill pinch-point
3022         pinch->set_req(0,nullptr);  //
3023         pinch->replace_by(kill); // Move anti-dep edges up
3024         pinch = kill;
3025         _reg_node.map(def_reg,pinch);
3026         return;
3027       }
3028     }
3029   }
3030 
3031   // Add edge from kill to pinch-point
3032   add_prec_edge_from_to(kill,pinch);
3033 }
3034 
3035 void Scheduling::anti_do_use( Block *b, Node *use, OptoReg::Name use_reg ) {
3036   if( !OptoReg::is_valid(use_reg) ) // Ignore stores & control flow
3037     return;
3038   Node *pinch = _reg_node[use_reg]; // Get pinch point
3039   // Check for no later def_reg/kill in block
3040   if ((pinch != nullptr) && _cfg->get_block_for_node(pinch) == b &&
3041       // Use has to be block-local as well
3042       _cfg->get_block_for_node(use) == b) {
3043     if( pinch->Opcode() == Op_Node && // Real pinch-point (not optimistic?)
3044         pinch->req() == 1 ) {   // pinch not yet in block?
3045       pinch->del_req(0);        // yank pointer to later-def, also set flag
3046       // Insert the pinch-point in the block just after the last use
3047       b->insert_node(pinch, b->find_node(use) + 1);
3048       _bb_end++;                // Increase size scheduled region in block
3049     }
3050 
3051     add_prec_edge_from_to(pinch,use);
3052   }
3053 }
3054 
3055 // We insert antidependences between the reads and following write of
3056 // allocated registers to prevent illegal code motion. Hopefully, the
3057 // number of added references should be fairly small, especially as we
3058 // are only adding references within the current basic block.
3059 void Scheduling::ComputeRegisterAntidependencies(Block *b) {
3060 
3061 #ifdef ASSERT
3062   verify_good_schedule(b,"before block local scheduling");
3063 #endif
3064 
3065   // A valid schedule, for each register independently, is an endless cycle
3066   // of: a def, then some uses (connected to the def by true dependencies),
3067   // then some kills (defs with no uses), finally the cycle repeats with a new
3068   // def.  The uses are allowed to float relative to each other, as are the
3069   // kills.  No use is allowed to slide past a kill (or def).  This requires
3070   // antidependencies between all uses of a single def and all kills that
3071   // follow, up to the next def.  More edges are redundant, because later defs
3072   // & kills are already serialized with true or antidependencies.  To keep
3073   // the edge count down, we add a 'pinch point' node if there's more than
3074   // one use or more than one kill/def.
3075 
3076   // We add dependencies in one bottom-up pass.
3077 
3078   // For each instruction we handle it's DEFs/KILLs, then it's USEs.
3079 
3080   // For each DEF/KILL, we check to see if there's a prior DEF/KILL for this
3081   // register.  If not, we record the DEF/KILL in _reg_node, the
3082   // register-to-def mapping.  If there is a prior DEF/KILL, we insert a
3083   // "pinch point", a new Node that's in the graph but not in the block.
3084   // We put edges from the prior and current DEF/KILLs to the pinch point.
3085   // We put the pinch point in _reg_node.  If there's already a pinch point
3086   // we merely add an edge from the current DEF/KILL to the pinch point.
3087 
3088   // After doing the DEF/KILLs, we handle USEs.  For each used register, we
3089   // put an edge from the pinch point to the USE.
3090 
3091   // To be expedient, the _reg_node array is pre-allocated for the whole
3092   // compilation.  _reg_node is lazily initialized; it either contains a null,
3093   // or a valid def/kill/pinch-point, or a leftover node from some prior
3094   // block.  Leftover node from some prior block is treated like a null (no
3095   // prior def, so no anti-dependence needed).  Valid def is distinguished by
3096   // it being in the current block.
3097   bool fat_proj_seen = false;
3098   uint last_safept = _bb_end-1;
3099   Node* end_node         = (_bb_end-1 >= _bb_start) ? b->get_node(last_safept) : nullptr;
3100   Node* last_safept_node = end_node;
3101   for( uint i = _bb_end-1; i >= _bb_start; i-- ) {
3102     Node *n = b->get_node(i);
3103     int is_def = n->outcnt();   // def if some uses prior to adding precedence edges
3104     if( n->is_MachProj() && n->ideal_reg() == MachProjNode::fat_proj ) {
3105       // Fat-proj kills a slew of registers
3106       // This can add edges to 'n' and obscure whether or not it was a def,
3107       // hence the is_def flag.
3108       fat_proj_seen = true;
3109       RegMaskIterator rmi(n->out_RegMask());
3110       while (rmi.has_next()) {
3111         OptoReg::Name kill = rmi.next();
3112         anti_do_def(b, n, kill, is_def);
3113       }
3114     } else {
3115       // Get DEF'd registers the normal way
3116       anti_do_def( b, n, _regalloc->get_reg_first(n), is_def );
3117       anti_do_def( b, n, _regalloc->get_reg_second(n), is_def );
3118     }
3119 
3120     // Kill projections on a branch should appear to occur on the
3121     // branch, not afterwards, so grab the masks from the projections
3122     // and process them.
3123     if (n->is_MachBranch() || (n->is_Mach() && n->as_Mach()->ideal_Opcode() == Op_Jump)) {
3124       for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
3125         Node* use = n->fast_out(i);
3126         if (use->is_Proj()) {
3127           RegMaskIterator rmi(use->out_RegMask());
3128           while (rmi.has_next()) {
3129             OptoReg::Name kill = rmi.next();
3130             anti_do_def(b, n, kill, false);
3131           }
3132         }
3133       }
3134     }
3135 
3136     // Check each register used by this instruction for a following DEF/KILL
3137     // that must occur afterward and requires an anti-dependence edge.
3138     for( uint j=0; j<n->req(); j++ ) {
3139       Node *def = n->in(j);
3140       if( def ) {
3141         assert( !def->is_MachProj() || def->ideal_reg() != MachProjNode::fat_proj, "" );
3142         anti_do_use( b, n, _regalloc->get_reg_first(def) );
3143         anti_do_use( b, n, _regalloc->get_reg_second(def) );
3144       }
3145     }
3146     // Do not allow defs of new derived values to float above GC
3147     // points unless the base is definitely available at the GC point.
3148 
3149     Node *m = b->get_node(i);
3150 
3151     // Add precedence edge from following safepoint to use of derived pointer
3152     if( last_safept_node != end_node &&
3153         m != last_safept_node) {
3154       for (uint k = 1; k < m->req(); k++) {
3155         const Type *t = m->in(k)->bottom_type();
3156         if( t->isa_oop_ptr() &&
3157             t->is_ptr()->offset() != 0 ) {
3158           last_safept_node->add_prec( m );
3159           break;
3160         }
3161       }
3162     }
3163 
3164     if( n->jvms() ) {           // Precedence edge from derived to safept
3165       // Check if last_safept_node was moved by pinch-point insertion in anti_do_use()
3166       if( b->get_node(last_safept) != last_safept_node ) {
3167         last_safept = b->find_node(last_safept_node);
3168       }
3169       for( uint j=last_safept; j > i; j-- ) {
3170         Node *mach = b->get_node(j);
3171         if( mach->is_Mach() && mach->as_Mach()->ideal_Opcode() == Op_AddP )
3172           mach->add_prec( n );
3173       }
3174       last_safept = i;
3175       last_safept_node = m;
3176     }
3177   }
3178 
3179   if (fat_proj_seen) {
3180     // Garbage collect pinch nodes that were not consumed.
3181     // They are usually created by a fat kill MachProj for a call.
3182     garbage_collect_pinch_nodes();
3183   }
3184 }
3185 
3186 // Garbage collect pinch nodes for reuse by other blocks.
3187 //
3188 // The block scheduler's insertion of anti-dependence
3189 // edges creates many pinch nodes when the block contains
3190 // 2 or more Calls.  A pinch node is used to prevent a
3191 // combinatorial explosion of edges.  If a set of kills for a
3192 // register is anti-dependent on a set of uses (or defs), rather
3193 // than adding an edge in the graph between each pair of kill
3194 // and use (or def), a pinch is inserted between them:
3195 //
3196 //            use1   use2  use3
3197 //                \   |   /
3198 //                 \  |  /
3199 //                  pinch
3200 //                 /  |  \
3201 //                /   |   \
3202 //            kill1 kill2 kill3
3203 //
3204 // One pinch node is created per register killed when
3205 // the second call is encountered during a backwards pass
3206 // over the block.  Most of these pinch nodes are never
3207 // wired into the graph because the register is never
3208 // used or def'ed in the block.
3209 //
3210 void Scheduling::garbage_collect_pinch_nodes() {
3211 #ifndef PRODUCT
3212   if (_cfg->C->trace_opto_output()) tty->print("Reclaimed pinch nodes:");
3213 #endif
3214   int trace_cnt = 0;
3215   for (uint k = 0; k < _reg_node.max(); k++) {
3216     Node* pinch = _reg_node[k];
3217     if ((pinch != nullptr) && pinch->Opcode() == Op_Node &&
3218         // no predecence input edges
3219         (pinch->req() == pinch->len() || pinch->in(pinch->req()) == nullptr) ) {
3220       cleanup_pinch(pinch);
3221       _pinch_free_list.push(pinch);
3222       _reg_node.map(k, nullptr);
3223 #ifndef PRODUCT
3224       if (_cfg->C->trace_opto_output()) {
3225         trace_cnt++;
3226         if (trace_cnt > 40) {
3227           tty->print("\n");
3228           trace_cnt = 0;
3229         }
3230         tty->print(" %d", pinch->_idx);
3231       }
3232 #endif
3233     }
3234   }
3235 #ifndef PRODUCT
3236   if (_cfg->C->trace_opto_output()) tty->print("\n");
3237 #endif
3238 }
3239 
3240 // Clean up a pinch node for reuse.
3241 void Scheduling::cleanup_pinch( Node *pinch ) {
3242   assert (pinch && pinch->Opcode() == Op_Node && pinch->req() == 1, "just checking");
3243 
3244   for (DUIterator_Last imin, i = pinch->last_outs(imin); i >= imin; ) {
3245     Node* use = pinch->last_out(i);
3246     uint uses_found = 0;
3247     for (uint j = use->req(); j < use->len(); j++) {
3248       if (use->in(j) == pinch) {
3249         use->rm_prec(j);
3250         uses_found++;
3251       }
3252     }
3253     assert(uses_found > 0, "must be a precedence edge");
3254     i -= uses_found;    // we deleted 1 or more copies of this edge
3255   }
3256   // May have a later_def entry
3257   pinch->set_req(0, nullptr);
3258 }
3259 
3260 #ifndef PRODUCT
3261 
3262 void Scheduling::dump_available() const {
3263   tty->print("#Availist  ");
3264   for (uint i = 0; i < _available.size(); i++)
3265     tty->print(" N%d/l%d", _available[i]->_idx,_current_latency[_available[i]->_idx]);
3266   tty->cr();
3267 }
3268 
3269 // Print Scheduling Statistics
3270 void Scheduling::print_statistics() {
3271   // Print the size added by nops for bundling
3272   tty->print("Nops added %d bytes to total of %d bytes",
3273              _total_nop_size, _total_method_size);
3274   if (_total_method_size > 0)
3275     tty->print(", for %.2f%%",
3276                ((double)_total_nop_size) / ((double) _total_method_size) * 100.0);
3277   tty->print("\n");
3278 
3279   // Print the number of branch shadows filled
3280   if (Pipeline::_branch_has_delay_slot) {
3281     tty->print("Of %d branches, %d had unconditional delay slots filled",
3282                _total_branches, _total_unconditional_delays);
3283     if (_total_branches > 0)
3284       tty->print(", for %.2f%%",
3285                  ((double)_total_unconditional_delays) / ((double)_total_branches) * 100.0);
3286     tty->print("\n");
3287   }
3288 
3289   uint total_instructions = 0, total_bundles = 0;
3290 
3291   for (uint i = 1; i <= Pipeline::_max_instrs_per_cycle; i++) {
3292     uint bundle_count   = _total_instructions_per_bundle[i];
3293     total_instructions += bundle_count * i;
3294     total_bundles      += bundle_count;
3295   }
3296 
3297   if (total_bundles > 0)
3298     tty->print("Average ILP (excluding nops) is %.2f\n",
3299                ((double)total_instructions) / ((double)total_bundles));
3300 }
3301 #endif
3302 
3303 //-----------------------init_scratch_buffer_blob------------------------------
3304 // Construct a temporary BufferBlob and cache it for this compile.
3305 void PhaseOutput::init_scratch_buffer_blob(int const_size) {
3306   // If there is already a scratch buffer blob allocated and the
3307   // constant section is big enough, use it.  Otherwise free the
3308   // current and allocate a new one.
3309   BufferBlob* blob = scratch_buffer_blob();
3310   if ((blob != nullptr) && (const_size <= _scratch_const_size)) {
3311     // Use the current blob.
3312   } else {
3313     if (blob != nullptr) {
3314       BufferBlob::free(blob);
3315     }
3316 
3317     ResourceMark rm;
3318     _scratch_const_size = const_size;
3319     int size = C2Compiler::initial_code_buffer_size(const_size);
3320     blob = BufferBlob::create("Compile::scratch_buffer", size);
3321     // Record the buffer blob for next time.
3322     set_scratch_buffer_blob(blob);
3323     // Have we run out of code space?
3324     if (scratch_buffer_blob() == nullptr) {
3325       // Let CompilerBroker disable further compilations.
3326       C->record_failure("Not enough space for scratch buffer in CodeCache");
3327       return;
3328     }
3329   }
3330 
3331   // Initialize the relocation buffers
3332   relocInfo* locs_buf = (relocInfo*) blob->content_end() - MAX_locs_size;
3333   set_scratch_locs_memory(locs_buf);
3334 }
3335 
3336 
3337 //-----------------------scratch_emit_size-------------------------------------
3338 // Helper function that computes size by emitting code
3339 uint PhaseOutput::scratch_emit_size(const Node* n) {
3340   // Start scratch_emit_size section.
3341   set_in_scratch_emit_size(true);
3342 
3343   // Emit into a trash buffer and count bytes emitted.
3344   // This is a pretty expensive way to compute a size,
3345   // but it works well enough if seldom used.
3346   // All common fixed-size instructions are given a size
3347   // method by the AD file.
3348   // Note that the scratch buffer blob and locs memory are
3349   // allocated at the beginning of the compile task, and
3350   // may be shared by several calls to scratch_emit_size.
3351   // The allocation of the scratch buffer blob is particularly
3352   // expensive, since it has to grab the code cache lock.
3353   BufferBlob* blob = this->scratch_buffer_blob();
3354   assert(blob != nullptr, "Initialize BufferBlob at start");
3355   assert(blob->size() > MAX_inst_size, "sanity");
3356   relocInfo* locs_buf = scratch_locs_memory();
3357   address blob_begin = blob->content_begin();
3358   address blob_end   = (address)locs_buf;
3359   assert(blob->contains(blob_end), "sanity");
3360   CodeBuffer buf(blob_begin, blob_end - blob_begin);
3361   buf.initialize_consts_size(_scratch_const_size);
3362   buf.initialize_stubs_size(MAX_stubs_size);
3363   assert(locs_buf != nullptr, "sanity");
3364   int lsize = MAX_locs_size / 3;
3365   buf.consts()->initialize_shared_locs(&locs_buf[lsize * 0], lsize);
3366   buf.insts()->initialize_shared_locs( &locs_buf[lsize * 1], lsize);
3367   buf.stubs()->initialize_shared_locs( &locs_buf[lsize * 2], lsize);
3368   // Mark as scratch buffer.
3369   buf.consts()->set_scratch_emit();
3370   buf.insts()->set_scratch_emit();
3371   buf.stubs()->set_scratch_emit();
3372 
3373   // Do the emission.
3374 
3375   Label fakeL; // Fake label for branch instructions.
3376   Label*   saveL = nullptr;
3377   uint save_bnum = 0;
3378   bool is_branch = n->is_MachBranch();
3379   C2_MacroAssembler masm(&buf);
3380   masm.bind(fakeL);
3381   if (is_branch) {
3382     n->as_MachBranch()->save_label(&saveL, &save_bnum);
3383     n->as_MachBranch()->label_set(&fakeL, 0);
3384   }
3385   n->emit(&masm, C->regalloc());
3386 
3387   // Emitting into the scratch buffer should not fail
3388   assert(!C->failing_internal() || C->failure_is_artificial(), "Must not have pending failure. Reason is: %s", C->failure_reason());
3389 
3390   if (is_branch) // Restore label.
3391     n->as_MachBranch()->label_set(saveL, save_bnum);
3392 
3393   // End scratch_emit_size section.
3394   set_in_scratch_emit_size(false);
3395 
3396   return buf.insts_size();
3397 }
3398 
3399 void PhaseOutput::install() {
3400   if (!C->should_install_code()) {
3401     return;
3402   } else if (C->stub_function() != nullptr) {
3403     install_stub(C->stub_name());
3404   } else {
3405     install_code(C->method(),
3406                  C->entry_bci(),
3407                  CompileBroker::compiler2(),
3408                  C->has_unsafe_access(),
3409                  SharedRuntime::is_wide_vector(C->max_vector_size()));
3410   }
3411 }
3412 
3413 void PhaseOutput::install_code(ciMethod*         target,
3414                                int               entry_bci,
3415                                AbstractCompiler* compiler,
3416                                bool              has_unsafe_access,
3417                                bool              has_wide_vectors) {
3418   // Check if we want to skip execution of all compiled code.
3419   {
3420 #ifndef PRODUCT
3421     if (OptoNoExecute) {
3422       C->record_method_not_compilable("+OptoNoExecute");  // Flag as failed
3423       return;
3424     }
3425 #endif
3426     Compile::TracePhase tp(_t_registerMethod);
3427 
3428     if (C->is_osr_compilation()) {
3429       _code_offsets.set_value(CodeOffsets::Verified_Entry, 0);
3430       _code_offsets.set_value(CodeOffsets::OSR_Entry, _first_block_size);
3431     } else {
3432       if (!target->is_static()) {
3433         // The UEP of an nmethod ensures that the VEP is padded. However, the padding of the UEP is placed
3434         // before the inline cache check, so we don't have to execute any nop instructions when dispatching
3435         // through the UEP, yet we can ensure that the VEP is aligned appropriately.
3436         _code_offsets.set_value(CodeOffsets::Entry, _first_block_size - MacroAssembler::ic_check_size());
3437       }
3438       _code_offsets.set_value(CodeOffsets::Verified_Entry, _first_block_size);
3439       _code_offsets.set_value(CodeOffsets::OSR_Entry, 0);
3440     }
3441 
3442     C->env()->register_method(target,
3443                                      entry_bci,
3444                                      &_code_offsets,
3445                                      _orig_pc_slot_offset_in_bytes,
3446                                      code_buffer(),
3447                                      frame_size_in_words(),
3448                                      oop_map_set(),
3449                                      &_handler_table,
3450                                      inc_table(),
3451                                      compiler,
3452                                      has_unsafe_access,
3453                                      SharedRuntime::is_wide_vector(C->max_vector_size()),
3454                                      C->has_monitors(),
3455                                      C->has_scoped_access(),
3456                                      0);
3457 
3458     if (C->log() != nullptr) { // Print code cache state into compiler log
3459       C->log()->code_cache_state();
3460     }
3461   }
3462 }
3463 void PhaseOutput::install_stub(const char* stub_name) {
3464   // Entry point will be accessed using stub_entry_point();
3465   if (code_buffer() == nullptr) {
3466     Matcher::soft_match_failure();
3467   } else {
3468     if (PrintAssembly && (WizardMode || Verbose))
3469       tty->print_cr("### Stub::%s", stub_name);
3470 
3471     if (!C->failing()) {
3472       assert(C->fixed_slots() == 0, "no fixed slots used for runtime stubs");
3473 
3474       // Make the NMethod
3475       // For now we mark the frame as never safe for profile stackwalking
3476       RuntimeStub *rs = RuntimeStub::new_runtime_stub(stub_name,
3477                                                       code_buffer(),
3478                                                       CodeOffsets::frame_never_safe,
3479                                                       // _code_offsets.value(CodeOffsets::Frame_Complete),
3480                                                       frame_size_in_words(),
3481                                                       oop_map_set(),
3482                                                       false);
3483       assert(rs != nullptr && rs->is_runtime_stub(), "sanity check");
3484 
3485       C->set_stub_entry_point(rs->entry_point());
3486     }
3487   }
3488 }
3489 
3490 // Support for bundling info
3491 Bundle* PhaseOutput::node_bundling(const Node *n) {
3492   assert(valid_bundle_info(n), "oob");
3493   return &_node_bundling_base[n->_idx];
3494 }
3495 
3496 bool PhaseOutput::valid_bundle_info(const Node *n) {
3497   return (_node_bundling_limit > n->_idx);
3498 }
3499 
3500 //------------------------------frame_size_in_words-----------------------------
3501 // frame_slots in units of words
3502 int PhaseOutput::frame_size_in_words() const {
3503   // shift is 0 in LP32 and 1 in LP64
3504   const int shift = (LogBytesPerWord - LogBytesPerInt);
3505   int words = _frame_slots >> shift;
3506   assert( words << shift == _frame_slots, "frame size must be properly aligned in LP64" );
3507   return words;
3508 }
3509 
3510 // To bang the stack of this compiled method we use the stack size
3511 // that the interpreter would need in case of a deoptimization. This
3512 // removes the need to bang the stack in the deoptimization blob which
3513 // in turn simplifies stack overflow handling.
3514 int PhaseOutput::bang_size_in_bytes() const {
3515   return MAX2(frame_size_in_bytes() + os::extra_bang_size_in_bytes(), C->interpreter_frame_size());
3516 }
3517 
3518 //------------------------------dump_asm---------------------------------------
3519 // Dump formatted assembly
3520 #if defined(SUPPORT_OPTO_ASSEMBLY)
3521 void PhaseOutput::dump_asm_on(outputStream* st, int* pcs, uint pc_limit) {
3522 
3523   int pc_digits = 3; // #chars required for pc
3524   int sb_chars  = 3; // #chars for "start bundle" indicator
3525   int tab_size  = 8;
3526   if (pcs != nullptr) {
3527     int max_pc = 0;
3528     for (uint i = 0; i < pc_limit; i++) {
3529       max_pc = (max_pc < pcs[i]) ? pcs[i] : max_pc;
3530     }
3531     pc_digits  = ((max_pc < 4096) ? 3 : ((max_pc < 65536) ? 4 : ((max_pc < 65536*256) ? 6 : 8))); // #chars required for pc
3532   }
3533   int prefix_len = ((pc_digits + sb_chars + tab_size - 1)/tab_size)*tab_size;
3534 
3535   bool cut_short = false;
3536   st->print_cr("#");
3537   st->print("#  ");  C->tf()->dump_on(st);  st->cr();
3538   st->print_cr("#");
3539 
3540   // For all blocks
3541   int pc = 0x0;                 // Program counter
3542   char starts_bundle = ' ';
3543   C->regalloc()->dump_frame();
3544 
3545   Node *n = nullptr;
3546   for (uint i = 0; i < C->cfg()->number_of_blocks(); i++) {
3547     if (VMThread::should_terminate()) {
3548       cut_short = true;
3549       break;
3550     }
3551     Block* block = C->cfg()->get_block(i);
3552     if (block->is_connector() && !Verbose) {
3553       continue;
3554     }
3555     n = block->head();
3556     if ((pcs != nullptr) && (n->_idx < pc_limit)) {
3557       pc = pcs[n->_idx];
3558       st->print("%*.*x", pc_digits, pc_digits, pc);
3559     }
3560     st->fill_to(prefix_len);
3561     block->dump_head(C->cfg(), st);
3562     if (block->is_connector()) {
3563       st->fill_to(prefix_len);
3564       st->print_cr("# Empty connector block");
3565     } else if (block->num_preds() == 2 && block->pred(1)->is_CatchProj() && block->pred(1)->as_CatchProj()->_con == CatchProjNode::fall_through_index) {
3566       st->fill_to(prefix_len);
3567       st->print_cr("# Block is sole successor of call");
3568     }
3569 
3570     // For all instructions
3571     Node *delay = nullptr;
3572     for (uint j = 0; j < block->number_of_nodes(); j++) {
3573       if (VMThread::should_terminate()) {
3574         cut_short = true;
3575         break;
3576       }
3577       n = block->get_node(j);
3578       if (valid_bundle_info(n)) {
3579         Bundle* bundle = node_bundling(n);
3580         if (bundle->used_in_unconditional_delay()) {
3581           delay = n;
3582           continue;
3583         }
3584         if (bundle->starts_bundle()) {
3585           starts_bundle = '+';
3586         }
3587       }
3588 
3589       if (WizardMode) {
3590         n->dump();
3591       }
3592 
3593       if( !n->is_Region() &&    // Dont print in the Assembly
3594           !n->is_Phi() &&       // a few noisely useless nodes
3595           !n->is_Proj() &&
3596           !n->is_MachTemp() &&
3597           !n->is_SafePointScalarObject() &&
3598           !n->is_Catch() &&     // Would be nice to print exception table targets
3599           !n->is_MergeMem() &&  // Not very interesting
3600           !n->is_top() &&       // Debug info table constants
3601           !(n->is_Con() && !n->is_Mach())// Debug info table constants
3602           ) {
3603         if ((pcs != nullptr) && (n->_idx < pc_limit)) {
3604           pc = pcs[n->_idx];
3605           st->print("%*.*x", pc_digits, pc_digits, pc);
3606         } else {
3607           st->fill_to(pc_digits);
3608         }
3609         st->print(" %c ", starts_bundle);
3610         starts_bundle = ' ';
3611         st->fill_to(prefix_len);
3612         n->format(C->regalloc(), st);
3613         st->cr();
3614       }
3615 
3616       // If we have an instruction with a delay slot, and have seen a delay,
3617       // then back up and print it
3618       if (valid_bundle_info(n) && node_bundling(n)->use_unconditional_delay()) {
3619         // Coverity finding - Explicit null dereferenced.
3620         guarantee(delay != nullptr, "no unconditional delay instruction");
3621         if (WizardMode) delay->dump();
3622 
3623         if (node_bundling(delay)->starts_bundle())
3624           starts_bundle = '+';
3625         if ((pcs != nullptr) && (n->_idx < pc_limit)) {
3626           pc = pcs[n->_idx];
3627           st->print("%*.*x", pc_digits, pc_digits, pc);
3628         } else {
3629           st->fill_to(pc_digits);
3630         }
3631         st->print(" %c ", starts_bundle);
3632         starts_bundle = ' ';
3633         st->fill_to(prefix_len);
3634         delay->format(C->regalloc(), st);
3635         st->cr();
3636         delay = nullptr;
3637       }
3638 
3639       // Dump the exception table as well
3640       if( n->is_Catch() && (Verbose || WizardMode) ) {
3641         // Print the exception table for this offset
3642         _handler_table.print_subtable_for(pc);
3643       }
3644       st->bol(); // Make sure we start on a new line
3645     }
3646     st->cr(); // one empty line between blocks
3647     assert(cut_short || delay == nullptr, "no unconditional delay branch");
3648   } // End of per-block dump
3649 
3650   if (cut_short)  st->print_cr("*** disassembly is cut short ***");
3651 }
3652 #endif
3653 
3654 #ifndef PRODUCT
3655 void PhaseOutput::print_statistics() {
3656   Scheduling::print_statistics();
3657 }
3658 #endif