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