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