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