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