1 /*
   2  * Copyright 1998-2010 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
  20  * CA 95054 USA or visit www.sun.com if you need additional information or
  21  * have any questions.
  22  *
  23  */
  24 
  25 #include "incls/_precompiled.incl"
  26 #include "incls/_output.cpp.incl"
  27 
  28 extern uint size_java_to_interp();
  29 extern uint reloc_java_to_interp();
  30 extern uint size_exception_handler();
  31 extern uint size_deopt_handler();
  32 
  33 #ifndef PRODUCT
  34 #define DEBUG_ARG(x) , x
  35 #else
  36 #define DEBUG_ARG(x)
  37 #endif
  38 
  39 extern int emit_exception_handler(CodeBuffer &cbuf);
  40 extern int emit_deopt_handler(CodeBuffer &cbuf);
  41 
  42 //------------------------------Output-----------------------------------------
  43 // Convert Nodes to instruction bits and pass off to the VM
  44 void Compile::Output() {
  45   // RootNode goes
  46   assert( _cfg->_broot->_nodes.size() == 0, "" );
  47 
  48   // Initialize the space for the BufferBlob used to find and verify
  49   // instruction size in MachNode::emit_size()
  50   init_scratch_buffer_blob();
  51   if (failing())  return; // Out of memory
  52 
  53   // The number of new nodes (mostly MachNop) is proportional to
  54   // the number of java calls and inner loops which are aligned.
  55   if ( C->check_node_count((NodeLimitFudgeFactor + C->java_calls()*3 +
  56                             C->inner_loops()*(OptoLoopAlignment-1)),
  57                            "out of nodes before code generation" ) ) {
  58     return;
  59   }
  60   // Make sure I can find the Start Node
  61   Block_Array& bbs = _cfg->_bbs;
  62   Block *entry = _cfg->_blocks[1];
  63   Block *broot = _cfg->_broot;
  64 
  65   const StartNode *start = entry->_nodes[0]->as_Start();
  66 
  67   // Replace StartNode with prolog
  68   MachPrologNode *prolog = new (this) MachPrologNode();
  69   entry->_nodes.map( 0, prolog );
  70   bbs.map( prolog->_idx, entry );
  71   bbs.map( start->_idx, NULL ); // start is no longer in any block
  72 
  73   // Virtual methods need an unverified entry point
  74 
  75   if( is_osr_compilation() ) {
  76     if( PoisonOSREntry ) {
  77       // TODO: Should use a ShouldNotReachHereNode...
  78       _cfg->insert( broot, 0, new (this) MachBreakpointNode() );
  79     }
  80   } else {
  81     if( _method && !_method->flags().is_static() ) {
  82       // Insert unvalidated entry point
  83       _cfg->insert( broot, 0, new (this) MachUEPNode() );
  84     }
  85 
  86   }
  87 
  88 
  89   // Break before main entry point
  90   if( (_method && _method->break_at_execute())
  91 #ifndef PRODUCT
  92     ||(OptoBreakpoint && is_method_compilation())
  93     ||(OptoBreakpointOSR && is_osr_compilation())
  94     ||(OptoBreakpointC2R && !_method)
  95 #endif
  96     ) {
  97     // checking for _method means that OptoBreakpoint does not apply to
  98     // runtime stubs or frame converters
  99     _cfg->insert( entry, 1, new (this) MachBreakpointNode() );
 100   }
 101 
 102   // Insert epilogs before every return
 103   for( uint i=0; i<_cfg->_num_blocks; i++ ) {
 104     Block *b = _cfg->_blocks[i];
 105     if( !b->is_connector() && b->non_connector_successor(0) == _cfg->_broot ) { // Found a program exit point?
 106       Node *m = b->end();
 107       if( m->is_Mach() && m->as_Mach()->ideal_Opcode() != Op_Halt ) {
 108         MachEpilogNode *epilog = new (this) MachEpilogNode(m->as_Mach()->ideal_Opcode() == Op_Return);
 109         b->add_inst( epilog );
 110         bbs.map(epilog->_idx, b);
 111         //_regalloc->set_bad(epilog->_idx); // Already initialized this way.
 112       }
 113     }
 114   }
 115 
 116 # ifdef ENABLE_ZAP_DEAD_LOCALS
 117   if ( ZapDeadCompiledLocals )  Insert_zap_nodes();
 118 # endif
 119 
 120   ScheduleAndBundle();
 121 
 122 #ifndef PRODUCT
 123   if (trace_opto_output()) {
 124     tty->print("\n---- After ScheduleAndBundle ----\n");
 125     for (uint i = 0; i < _cfg->_num_blocks; i++) {
 126       tty->print("\nBB#%03d:\n", i);
 127       Block *bb = _cfg->_blocks[i];
 128       for (uint j = 0; j < bb->_nodes.size(); j++) {
 129         Node *n = bb->_nodes[j];
 130         OptoReg::Name reg = _regalloc->get_reg_first(n);
 131         tty->print(" %-6s ", reg >= 0 && reg < REG_COUNT ? Matcher::regName[reg] : "");
 132         n->dump();
 133       }
 134     }
 135   }
 136 #endif
 137 
 138   if (failing())  return;
 139 
 140   BuildOopMaps();
 141 
 142   if (failing())  return;
 143 
 144   Fill_buffer();
 145 }
 146 
 147 bool Compile::need_stack_bang(int frame_size_in_bytes) const {
 148   // Determine if we need to generate a stack overflow check.
 149   // Do it if the method is not a stub function and
 150   // has java calls or has frame size > vm_page_size/8.
 151   return (stub_function() == NULL &&
 152           (has_java_calls() || frame_size_in_bytes > os::vm_page_size()>>3));
 153 }
 154 
 155 bool Compile::need_register_stack_bang() const {
 156   // Determine if we need to generate a register stack overflow check.
 157   // This is only used on architectures which have split register
 158   // and memory stacks (ie. IA64).
 159   // Bang if the method is not a stub function and has java calls
 160   return (stub_function() == NULL && has_java_calls());
 161 }
 162 
 163 # ifdef ENABLE_ZAP_DEAD_LOCALS
 164 
 165 
 166 // In order to catch compiler oop-map bugs, we have implemented
 167 // a debugging mode called ZapDeadCompilerLocals.
 168 // This mode causes the compiler to insert a call to a runtime routine,
 169 // "zap_dead_locals", right before each place in compiled code
 170 // that could potentially be a gc-point (i.e., a safepoint or oop map point).
 171 // The runtime routine checks that locations mapped as oops are really
 172 // oops, that locations mapped as values do not look like oops,
 173 // and that locations mapped as dead are not used later
 174 // (by zapping them to an invalid address).
 175 
 176 int Compile::_CompiledZap_count = 0;
 177 
 178 void Compile::Insert_zap_nodes() {
 179   bool skip = false;
 180 
 181 
 182   // Dink with static counts because code code without the extra
 183   // runtime calls is MUCH faster for debugging purposes
 184 
 185        if ( CompileZapFirst  ==  0  ) ; // nothing special
 186   else if ( CompileZapFirst  >  CompiledZap_count() )  skip = true;
 187   else if ( CompileZapFirst  == CompiledZap_count() )
 188     warning("starting zap compilation after skipping");
 189 
 190        if ( CompileZapLast  ==  -1  ) ; // nothing special
 191   else if ( CompileZapLast  <   CompiledZap_count() )  skip = true;
 192   else if ( CompileZapLast  ==  CompiledZap_count() )
 193     warning("about to compile last zap");
 194 
 195   ++_CompiledZap_count; // counts skipped zaps, too
 196 
 197   if ( skip )  return;
 198 
 199 
 200   if ( _method == NULL )
 201     return; // no safepoints/oopmaps emitted for calls in stubs,so we don't care
 202 
 203   // Insert call to zap runtime stub before every node with an oop map
 204   for( uint i=0; i<_cfg->_num_blocks; i++ ) {
 205     Block *b = _cfg->_blocks[i];
 206     for ( uint j = 0;  j < b->_nodes.size();  ++j ) {
 207       Node *n = b->_nodes[j];
 208 
 209       // Determining if we should insert a zap-a-lot node in output.
 210       // We do that for all nodes that has oopmap info, except for calls
 211       // to allocation.  Calls to allocation passes in the old top-of-eden pointer
 212       // and expect the C code to reset it.  Hence, there can be no safepoints between
 213       // the inlined-allocation and the call to new_Java, etc.
 214       // We also cannot zap monitor calls, as they must hold the microlock
 215       // during the call to Zap, which also wants to grab the microlock.
 216       bool insert = n->is_MachSafePoint() && (n->as_MachSafePoint()->oop_map() != NULL);
 217       if ( insert ) { // it is MachSafePoint
 218         if ( !n->is_MachCall() ) {
 219           insert = false;
 220         } else if ( n->is_MachCall() ) {
 221           MachCallNode* call = n->as_MachCall();
 222           if (call->entry_point() == OptoRuntime::new_instance_Java() ||
 223               call->entry_point() == OptoRuntime::new_array_Java() ||
 224               call->entry_point() == OptoRuntime::multianewarray2_Java() ||
 225               call->entry_point() == OptoRuntime::multianewarray3_Java() ||
 226               call->entry_point() == OptoRuntime::multianewarray4_Java() ||
 227               call->entry_point() == OptoRuntime::multianewarray5_Java() ||
 228               call->entry_point() == OptoRuntime::slow_arraycopy_Java() ||
 229               call->entry_point() == OptoRuntime::complete_monitor_locking_Java()
 230               ) {
 231             insert = false;
 232           }
 233         }
 234         if (insert) {
 235           Node *zap = call_zap_node(n->as_MachSafePoint(), i);
 236           b->_nodes.insert( j, zap );
 237           _cfg->_bbs.map( zap->_idx, b );
 238           ++j;
 239         }
 240       }
 241     }
 242   }
 243 }
 244 
 245 
 246 Node* Compile::call_zap_node(MachSafePointNode* node_to_check, int block_no) {
 247   const TypeFunc *tf = OptoRuntime::zap_dead_locals_Type();
 248   CallStaticJavaNode* ideal_node =
 249     new (this, tf->domain()->cnt()) CallStaticJavaNode( tf,
 250          OptoRuntime::zap_dead_locals_stub(_method->flags().is_native()),
 251                             "call zap dead locals stub", 0, TypePtr::BOTTOM);
 252   // We need to copy the OopMap from the site we're zapping at.
 253   // We have to make a copy, because the zap site might not be
 254   // a call site, and zap_dead is a call site.
 255   OopMap* clone = node_to_check->oop_map()->deep_copy();
 256 
 257   // Add the cloned OopMap to the zap node
 258   ideal_node->set_oop_map(clone);
 259   return _matcher->match_sfpt(ideal_node);
 260 }
 261 
 262 //------------------------------is_node_getting_a_safepoint--------------------
 263 bool Compile::is_node_getting_a_safepoint( Node* n) {
 264   // This code duplicates the logic prior to the call of add_safepoint
 265   // below in this file.
 266   if( n->is_MachSafePoint() ) return true;
 267   return false;
 268 }
 269 
 270 # endif // ENABLE_ZAP_DEAD_LOCALS
 271 
 272 //------------------------------compute_loop_first_inst_sizes------------------
 273 // Compute the size of first NumberOfLoopInstrToAlign instructions at the top
 274 // of a loop. When aligning a loop we need to provide enough instructions
 275 // in cpu's fetch buffer to feed decoders. The loop alignment could be
 276 // avoided if we have enough instructions in fetch buffer at the head of a loop.
 277 // By default, the size is set to 999999 by Block's constructor so that
 278 // a loop will be aligned if the size is not reset here.
 279 //
 280 // Note: Mach instructions could contain several HW instructions
 281 // so the size is estimated only.
 282 //
 283 void Compile::compute_loop_first_inst_sizes() {
 284   // The next condition is used to gate the loop alignment optimization.
 285   // Don't aligned a loop if there are enough instructions at the head of a loop
 286   // or alignment padding is larger then MaxLoopPad. By default, MaxLoopPad
 287   // is equal to OptoLoopAlignment-1 except on new Intel cpus, where it is
 288   // equal to 11 bytes which is the largest address NOP instruction.
 289   if( MaxLoopPad < OptoLoopAlignment-1 ) {
 290     uint last_block = _cfg->_num_blocks-1;
 291     for( uint i=1; i <= last_block; i++ ) {
 292       Block *b = _cfg->_blocks[i];
 293       // Check the first loop's block which requires an alignment.
 294       if( b->loop_alignment() > (uint)relocInfo::addr_unit() ) {
 295         uint sum_size = 0;
 296         uint inst_cnt = NumberOfLoopInstrToAlign;
 297         inst_cnt = b->compute_first_inst_size(sum_size, inst_cnt, _regalloc);
 298 
 299         // Check subsequent fallthrough blocks if the loop's first
 300         // block(s) does not have enough instructions.
 301         Block *nb = b;
 302         while( inst_cnt > 0 &&
 303                i < last_block &&
 304                !_cfg->_blocks[i+1]->has_loop_alignment() &&
 305                !nb->has_successor(b) ) {
 306           i++;
 307           nb = _cfg->_blocks[i];
 308           inst_cnt  = nb->compute_first_inst_size(sum_size, inst_cnt, _regalloc);
 309         } // while( inst_cnt > 0 && i < last_block  )
 310 
 311         b->set_first_inst_size(sum_size);
 312       } // f( b->head()->is_Loop() )
 313     } // for( i <= last_block )
 314   } // if( MaxLoopPad < OptoLoopAlignment-1 )
 315 }
 316 
 317 //----------------------Shorten_branches---------------------------------------
 318 // The architecture description provides short branch variants for some long
 319 // branch instructions. Replace eligible long branches with short branches.
 320 void Compile::Shorten_branches(Label *labels, int& code_size, int& reloc_size, int& stub_size, int& const_size) {
 321 
 322   // fill in the nop array for bundling computations
 323   MachNode *_nop_list[Bundle::_nop_count];
 324   Bundle::initialize_nops(_nop_list, this);
 325 
 326   // ------------------
 327   // Compute size of each block, method size, and relocation information size
 328   uint *jmp_end    = NEW_RESOURCE_ARRAY(uint,_cfg->_num_blocks);
 329   uint *blk_starts = NEW_RESOURCE_ARRAY(uint,_cfg->_num_blocks+1);
 330   DEBUG_ONLY( uint *jmp_target = NEW_RESOURCE_ARRAY(uint,_cfg->_num_blocks); )
 331   DEBUG_ONLY( uint *jmp_rule = NEW_RESOURCE_ARRAY(uint,_cfg->_num_blocks); )
 332   blk_starts[0]    = 0;
 333 
 334   // Initialize the sizes to 0
 335   code_size  = 0;          // Size in bytes of generated code
 336   stub_size  = 0;          // Size in bytes of all stub entries
 337   // Size in bytes of all relocation entries, including those in local stubs.
 338   // Start with 2-bytes of reloc info for the unvalidated entry point
 339   reloc_size = 1;          // Number of relocation entries
 340   const_size = 0;          // size of fp constants in words
 341 
 342   // Make three passes.  The first computes pessimistic blk_starts,
 343   // relative jmp_end, reloc_size and const_size information.
 344   // The second performs short branch substitution using the pessimistic
 345   // sizing. The third inserts nops where needed.
 346 
 347   Node *nj; // tmp
 348 
 349   // Step one, perform a pessimistic sizing pass.
 350   uint i;
 351   uint min_offset_from_last_call = 1;  // init to a positive value
 352   uint nop_size = (new (this) MachNopNode())->size(_regalloc);
 353   for( i=0; i<_cfg->_num_blocks; i++ ) { // For all blocks
 354     Block *b = _cfg->_blocks[i];
 355 
 356     // Sum all instruction sizes to compute block size
 357     uint last_inst = b->_nodes.size();
 358     uint blk_size = 0;
 359     for( uint j = 0; j<last_inst; j++ ) {
 360       nj = b->_nodes[j];
 361       uint inst_size = nj->size(_regalloc);
 362       blk_size += inst_size;
 363       // Handle machine instruction nodes
 364       if( nj->is_Mach() ) {
 365         MachNode *mach = nj->as_Mach();
 366         blk_size += (mach->alignment_required() - 1) * relocInfo::addr_unit(); // assume worst case padding
 367         reloc_size += mach->reloc();
 368         const_size += mach->const_size();
 369         if( mach->is_MachCall() ) {
 370           MachCallNode *mcall = mach->as_MachCall();
 371           // This destination address is NOT PC-relative
 372 
 373           mcall->method_set((intptr_t)mcall->entry_point());
 374 
 375           if( mcall->is_MachCallJava() && mcall->as_MachCallJava()->_method ) {
 376             stub_size  += size_java_to_interp();
 377             reloc_size += reloc_java_to_interp();
 378           }
 379         } else if (mach->is_MachSafePoint()) {
 380           // If call/safepoint are adjacent, account for possible
 381           // nop to disambiguate the two safepoints.
 382           if (min_offset_from_last_call == 0) {
 383             blk_size += nop_size;
 384           }
 385         }
 386       }
 387       min_offset_from_last_call += inst_size;
 388       // Remember end of call offset
 389       if (nj->is_MachCall() && nj->as_MachCall()->is_safepoint_node()) {
 390         min_offset_from_last_call = 0;
 391       }
 392     }
 393 
 394     // During short branch replacement, we store the relative (to blk_starts)
 395     // end of jump in jmp_end, rather than the absolute end of jump.  This
 396     // is so that we do not need to recompute sizes of all nodes when we compute
 397     // correct blk_starts in our next sizing pass.
 398     jmp_end[i] = blk_size;
 399     DEBUG_ONLY( jmp_target[i] = 0; )
 400 
 401     // When the next block starts a loop, we may insert pad NOP
 402     // instructions.  Since we cannot know our future alignment,
 403     // assume the worst.
 404     if( i<_cfg->_num_blocks-1 ) {
 405       Block *nb = _cfg->_blocks[i+1];
 406       int max_loop_pad = nb->code_alignment()-relocInfo::addr_unit();
 407       if( max_loop_pad > 0 ) {
 408         assert(is_power_of_2(max_loop_pad+relocInfo::addr_unit()), "");
 409         blk_size += max_loop_pad;
 410       }
 411     }
 412 
 413     // Save block size; update total method size
 414     blk_starts[i+1] = blk_starts[i]+blk_size;
 415   }
 416 
 417   // Step two, replace eligible long jumps.
 418 
 419   // Note: this will only get the long branches within short branch
 420   //   range. Another pass might detect more branches that became
 421   //   candidates because the shortening in the first pass exposed
 422   //   more opportunities. Unfortunately, this would require
 423   //   recomputing the starting and ending positions for the blocks
 424   for( i=0; i<_cfg->_num_blocks; i++ ) {
 425     Block *b = _cfg->_blocks[i];
 426 
 427     int j;
 428     // Find the branch; ignore trailing NOPs.
 429     for( j = b->_nodes.size()-1; j>=0; j-- ) {
 430       nj = b->_nodes[j];
 431       if( !nj->is_Mach() || nj->as_Mach()->ideal_Opcode() != Op_Con )
 432         break;
 433     }
 434 
 435     if (j >= 0) {
 436       if( nj->is_Mach() && nj->as_Mach()->may_be_short_branch() ) {
 437         MachNode *mach = nj->as_Mach();
 438         // This requires the TRUE branch target be in succs[0]
 439         uint bnum = b->non_connector_successor(0)->_pre_order;
 440         uintptr_t target = blk_starts[bnum];
 441         if( mach->is_pc_relative() ) {
 442           int offset = target-(blk_starts[i] + jmp_end[i]);
 443           if (_matcher->is_short_branch_offset(mach->rule(), offset)) {
 444             // We've got a winner.  Replace this branch.
 445             MachNode* replacement = mach->short_branch_version(this);
 446             b->_nodes.map(j, replacement);
 447             mach->subsume_by(replacement);
 448 
 449             // Update the jmp_end size to save time in our
 450             // next pass.
 451             jmp_end[i] -= (mach->size(_regalloc) - replacement->size(_regalloc));
 452             DEBUG_ONLY( jmp_target[i] = bnum; );
 453             DEBUG_ONLY( jmp_rule[i] = mach->rule(); );
 454           }
 455         } else {
 456 #ifndef PRODUCT
 457           mach->dump(3);
 458 #endif
 459           Unimplemented();
 460         }
 461       }
 462     }
 463   }
 464 
 465   // Compute the size of first NumberOfLoopInstrToAlign instructions at head
 466   // of a loop. It is used to determine the padding for loop alignment.
 467   compute_loop_first_inst_sizes();
 468 
 469   // Step 3, compute the offsets of all the labels
 470   uint last_call_adr = max_uint;
 471   for( i=0; i<_cfg->_num_blocks; i++ ) { // For all blocks
 472     // copy the offset of the beginning to the corresponding label
 473     assert(labels[i].is_unused(), "cannot patch at this point");
 474     labels[i].bind_loc(blk_starts[i], CodeBuffer::SECT_INSTS);
 475 
 476     // insert padding for any instructions that need it
 477     Block *b = _cfg->_blocks[i];
 478     uint last_inst = b->_nodes.size();
 479     uint adr = blk_starts[i];
 480     for( uint j = 0; j<last_inst; j++ ) {
 481       nj = b->_nodes[j];
 482       if( nj->is_Mach() ) {
 483         int padding = nj->as_Mach()->compute_padding(adr);
 484         // If call/safepoint are adjacent insert a nop (5010568)
 485         if (padding == 0 && nj->is_MachSafePoint() && !nj->is_MachCall() &&
 486             adr == last_call_adr ) {
 487           padding = nop_size;
 488         }
 489         if(padding > 0) {
 490           assert((padding % nop_size) == 0, "padding is not a multiple of NOP size");
 491           int nops_cnt = padding / nop_size;
 492           MachNode *nop = new (this) MachNopNode(nops_cnt);
 493           b->_nodes.insert(j++, nop);
 494           _cfg->_bbs.map( nop->_idx, b );
 495           adr += padding;
 496           last_inst++;
 497         }
 498       }
 499       adr += nj->size(_regalloc);
 500 
 501       // Remember end of call offset
 502       if (nj->is_MachCall() && nj->as_MachCall()->is_safepoint_node()) {
 503         last_call_adr = adr;
 504       }
 505     }
 506 
 507     if ( i != _cfg->_num_blocks-1) {
 508       // Get the size of the block
 509       uint blk_size = adr - blk_starts[i];
 510 
 511       // When the next block is the top of a loop, we may insert pad NOP
 512       // instructions.
 513       Block *nb = _cfg->_blocks[i+1];
 514       int current_offset = blk_starts[i] + blk_size;
 515       current_offset += nb->alignment_padding(current_offset);
 516       // Save block size; update total method size
 517       blk_starts[i+1] = current_offset;
 518     }
 519   }
 520 
 521 #ifdef ASSERT
 522   for( i=0; i<_cfg->_num_blocks; i++ ) { // For all blocks
 523     if( jmp_target[i] != 0 ) {
 524       int offset = blk_starts[jmp_target[i]]-(blk_starts[i] + jmp_end[i]);
 525       if (!_matcher->is_short_branch_offset(jmp_rule[i], offset)) {
 526         tty->print_cr("target (%d) - jmp_end(%d) = offset (%d), jmp_block B%d, target_block B%d", blk_starts[jmp_target[i]], blk_starts[i] + jmp_end[i], offset, i, jmp_target[i]);
 527       }
 528       assert(_matcher->is_short_branch_offset(jmp_rule[i], offset), "Displacement too large for short jmp");
 529     }
 530   }
 531 #endif
 532 
 533   // ------------------
 534   // Compute size for code buffer
 535   code_size   = blk_starts[i-1] + jmp_end[i-1];
 536 
 537   // Relocation records
 538   reloc_size += 1;              // Relo entry for exception handler
 539 
 540   // Adjust reloc_size to number of record of relocation info
 541   // Min is 2 bytes, max is probably 6 or 8, with a tax up to 25% for
 542   // a relocation index.
 543   // The CodeBuffer will expand the locs array if this estimate is too low.
 544   reloc_size   *= 10 / sizeof(relocInfo);
 545 
 546   // Adjust const_size to number of bytes
 547   const_size   *= 2*jintSize; // both float and double take two words per entry
 548 
 549 }
 550 
 551 //------------------------------FillLocArray-----------------------------------
 552 // Create a bit of debug info and append it to the array.  The mapping is from
 553 // Java local or expression stack to constant, register or stack-slot.  For
 554 // doubles, insert 2 mappings and return 1 (to tell the caller that the next
 555 // entry has been taken care of and caller should skip it).
 556 static LocationValue *new_loc_value( PhaseRegAlloc *ra, OptoReg::Name regnum, Location::Type l_type ) {
 557   // This should never have accepted Bad before
 558   assert(OptoReg::is_valid(regnum), "location must be valid");
 559   return (OptoReg::is_reg(regnum))
 560     ? new LocationValue(Location::new_reg_loc(l_type, OptoReg::as_VMReg(regnum)) )
 561     : new LocationValue(Location::new_stk_loc(l_type,  ra->reg2offset(regnum)));
 562 }
 563 
 564 
 565 ObjectValue*
 566 Compile::sv_for_node_id(GrowableArray<ScopeValue*> *objs, int id) {
 567   for (int i = 0; i < objs->length(); i++) {
 568     assert(objs->at(i)->is_object(), "corrupt object cache");
 569     ObjectValue* sv = (ObjectValue*) objs->at(i);
 570     if (sv->id() == id) {
 571       return sv;
 572     }
 573   }
 574   // Otherwise..
 575   return NULL;
 576 }
 577 
 578 void Compile::set_sv_for_object_node(GrowableArray<ScopeValue*> *objs,
 579                                      ObjectValue* sv ) {
 580   assert(sv_for_node_id(objs, sv->id()) == NULL, "Precondition");
 581   objs->append(sv);
 582 }
 583 
 584 
 585 void Compile::FillLocArray( int idx, MachSafePointNode* sfpt, Node *local,
 586                             GrowableArray<ScopeValue*> *array,
 587                             GrowableArray<ScopeValue*> *objs ) {
 588   assert( local, "use _top instead of null" );
 589   if (array->length() != idx) {
 590     assert(array->length() == idx + 1, "Unexpected array count");
 591     // Old functionality:
 592     //   return
 593     // New functionality:
 594     //   Assert if the local is not top. In product mode let the new node
 595     //   override the old entry.
 596     assert(local == top(), "LocArray collision");
 597     if (local == top()) {
 598       return;
 599     }
 600     array->pop();
 601   }
 602   const Type *t = local->bottom_type();
 603 
 604   // Is it a safepoint scalar object node?
 605   if (local->is_SafePointScalarObject()) {
 606     SafePointScalarObjectNode* spobj = local->as_SafePointScalarObject();
 607 
 608     ObjectValue* sv = Compile::sv_for_node_id(objs, spobj->_idx);
 609     if (sv == NULL) {
 610       ciKlass* cik = t->is_oopptr()->klass();
 611       assert(cik->is_instance_klass() ||
 612              cik->is_array_klass(), "Not supported allocation.");
 613       sv = new ObjectValue(spobj->_idx,
 614                            new ConstantOopWriteValue(cik->constant_encoding()));
 615       Compile::set_sv_for_object_node(objs, sv);
 616 
 617       uint first_ind = spobj->first_index();
 618       for (uint i = 0; i < spobj->n_fields(); i++) {
 619         Node* fld_node = sfpt->in(first_ind+i);
 620         (void)FillLocArray(sv->field_values()->length(), sfpt, fld_node, sv->field_values(), objs);
 621       }
 622     }
 623     array->append(sv);
 624     return;
 625   }
 626 
 627   // Grab the register number for the local
 628   OptoReg::Name regnum = _regalloc->get_reg_first(local);
 629   if( OptoReg::is_valid(regnum) ) {// Got a register/stack?
 630     // Record the double as two float registers.
 631     // The register mask for such a value always specifies two adjacent
 632     // float registers, with the lower register number even.
 633     // Normally, the allocation of high and low words to these registers
 634     // is irrelevant, because nearly all operations on register pairs
 635     // (e.g., StoreD) treat them as a single unit.
 636     // Here, we assume in addition that the words in these two registers
 637     // stored "naturally" (by operations like StoreD and double stores
 638     // within the interpreter) such that the lower-numbered register
 639     // is written to the lower memory address.  This may seem like
 640     // a machine dependency, but it is not--it is a requirement on
 641     // the author of the <arch>.ad file to ensure that, for every
 642     // even/odd double-register pair to which a double may be allocated,
 643     // the word in the even single-register is stored to the first
 644     // memory word.  (Note that register numbers are completely
 645     // arbitrary, and are not tied to any machine-level encodings.)
 646 #ifdef _LP64
 647     if( t->base() == Type::DoubleBot || t->base() == Type::DoubleCon ) {
 648       array->append(new ConstantIntValue(0));
 649       array->append(new_loc_value( _regalloc, regnum, Location::dbl ));
 650     } else if ( t->base() == Type::Long ) {
 651       array->append(new ConstantIntValue(0));
 652       array->append(new_loc_value( _regalloc, regnum, Location::lng ));
 653     } else if ( t->base() == Type::RawPtr ) {
 654       // jsr/ret return address which must be restored into a the full
 655       // width 64-bit stack slot.
 656       array->append(new_loc_value( _regalloc, regnum, Location::lng ));
 657     }
 658 #else //_LP64
 659 #ifdef SPARC
 660     if (t->base() == Type::Long && OptoReg::is_reg(regnum)) {
 661       // For SPARC we have to swap high and low words for
 662       // long values stored in a single-register (g0-g7).
 663       array->append(new_loc_value( _regalloc,              regnum   , Location::normal ));
 664       array->append(new_loc_value( _regalloc, OptoReg::add(regnum,1), Location::normal ));
 665     } else
 666 #endif //SPARC
 667     if( t->base() == Type::DoubleBot || t->base() == Type::DoubleCon || t->base() == Type::Long ) {
 668       // Repack the double/long as two jints.
 669       // The convention the interpreter uses is that the second local
 670       // holds the first raw word of the native double representation.
 671       // This is actually reasonable, since locals and stack arrays
 672       // grow downwards in all implementations.
 673       // (If, on some machine, the interpreter's Java locals or stack
 674       // were to grow upwards, the embedded doubles would be word-swapped.)
 675       array->append(new_loc_value( _regalloc, OptoReg::add(regnum,1), Location::normal ));
 676       array->append(new_loc_value( _regalloc,              regnum   , Location::normal ));
 677     }
 678 #endif //_LP64
 679     else if( (t->base() == Type::FloatBot || t->base() == Type::FloatCon) &&
 680                OptoReg::is_reg(regnum) ) {
 681       array->append(new_loc_value( _regalloc, regnum, Matcher::float_in_double
 682                                    ? Location::float_in_dbl : Location::normal ));
 683     } else if( t->base() == Type::Int && OptoReg::is_reg(regnum) ) {
 684       array->append(new_loc_value( _regalloc, regnum, Matcher::int_in_long
 685                                    ? Location::int_in_long : Location::normal ));
 686     } else if( t->base() == Type::NarrowOop ) {
 687       array->append(new_loc_value( _regalloc, regnum, Location::narrowoop ));
 688     } else {
 689       array->append(new_loc_value( _regalloc, regnum, _regalloc->is_oop(local) ? Location::oop : Location::normal ));
 690     }
 691     return;
 692   }
 693 
 694   // No register.  It must be constant data.
 695   switch (t->base()) {
 696   case Type::Half:              // Second half of a double
 697     ShouldNotReachHere();       // Caller should skip 2nd halves
 698     break;
 699   case Type::AnyPtr:
 700     array->append(new ConstantOopWriteValue(NULL));
 701     break;
 702   case Type::AryPtr:
 703   case Type::InstPtr:
 704   case Type::KlassPtr:          // fall through
 705     array->append(new ConstantOopWriteValue(t->isa_oopptr()->const_oop()->constant_encoding()));
 706     break;
 707   case Type::NarrowOop:
 708     if (t == TypeNarrowOop::NULL_PTR) {
 709       array->append(new ConstantOopWriteValue(NULL));
 710     } else {
 711       array->append(new ConstantOopWriteValue(t->make_ptr()->isa_oopptr()->const_oop()->constant_encoding()));
 712     }
 713     break;
 714   case Type::Int:
 715     array->append(new ConstantIntValue(t->is_int()->get_con()));
 716     break;
 717   case Type::RawPtr:
 718     // A return address (T_ADDRESS).
 719     assert((intptr_t)t->is_ptr()->get_con() < (intptr_t)0x10000, "must be a valid BCI");
 720 #ifdef _LP64
 721     // Must be restored to the full-width 64-bit stack slot.
 722     array->append(new ConstantLongValue(t->is_ptr()->get_con()));
 723 #else
 724     array->append(new ConstantIntValue(t->is_ptr()->get_con()));
 725 #endif
 726     break;
 727   case Type::FloatCon: {
 728     float f = t->is_float_constant()->getf();
 729     array->append(new ConstantIntValue(jint_cast(f)));
 730     break;
 731   }
 732   case Type::DoubleCon: {
 733     jdouble d = t->is_double_constant()->getd();
 734 #ifdef _LP64
 735     array->append(new ConstantIntValue(0));
 736     array->append(new ConstantDoubleValue(d));
 737 #else
 738     // Repack the double as two jints.
 739     // The convention the interpreter uses is that the second local
 740     // holds the first raw word of the native double representation.
 741     // This is actually reasonable, since locals and stack arrays
 742     // grow downwards in all implementations.
 743     // (If, on some machine, the interpreter's Java locals or stack
 744     // were to grow upwards, the embedded doubles would be word-swapped.)
 745     jint   *dp = (jint*)&d;
 746     array->append(new ConstantIntValue(dp[1]));
 747     array->append(new ConstantIntValue(dp[0]));
 748 #endif
 749     break;
 750   }
 751   case Type::Long: {
 752     jlong d = t->is_long()->get_con();
 753 #ifdef _LP64
 754     array->append(new ConstantIntValue(0));
 755     array->append(new ConstantLongValue(d));
 756 #else
 757     // Repack the long as two jints.
 758     // The convention the interpreter uses is that the second local
 759     // holds the first raw word of the native double representation.
 760     // This is actually reasonable, since locals and stack arrays
 761     // grow downwards in all implementations.
 762     // (If, on some machine, the interpreter's Java locals or stack
 763     // were to grow upwards, the embedded doubles would be word-swapped.)
 764     jint *dp = (jint*)&d;
 765     array->append(new ConstantIntValue(dp[1]));
 766     array->append(new ConstantIntValue(dp[0]));
 767 #endif
 768     break;
 769   }
 770   case Type::Top:               // Add an illegal value here
 771     array->append(new LocationValue(Location()));
 772     break;
 773   default:
 774     ShouldNotReachHere();
 775     break;
 776   }
 777 }
 778 
 779 // Determine if this node starts a bundle
 780 bool Compile::starts_bundle(const Node *n) const {
 781   return (_node_bundling_limit > n->_idx &&
 782           _node_bundling_base[n->_idx].starts_bundle());
 783 }
 784 
 785 //--------------------------Process_OopMap_Node--------------------------------
 786 void Compile::Process_OopMap_Node(MachNode *mach, int current_offset) {
 787 
 788   // Handle special safepoint nodes for synchronization
 789   MachSafePointNode *sfn   = mach->as_MachSafePoint();
 790   MachCallNode      *mcall;
 791 
 792 #ifdef ENABLE_ZAP_DEAD_LOCALS
 793   assert( is_node_getting_a_safepoint(mach),  "logic does not match; false negative");
 794 #endif
 795 
 796   int safepoint_pc_offset = current_offset;
 797   bool is_method_handle_invoke = false;
 798 
 799   // Add the safepoint in the DebugInfoRecorder
 800   if( !mach->is_MachCall() ) {
 801     mcall = NULL;
 802     debug_info()->add_safepoint(safepoint_pc_offset, sfn->_oop_map);
 803   } else {
 804     mcall = mach->as_MachCall();
 805 
 806     // Is the call a MethodHandle call?
 807     if (mcall->is_MachCallJava())
 808       is_method_handle_invoke = mcall->as_MachCallJava()->_method_handle_invoke;
 809 
 810     safepoint_pc_offset += mcall->ret_addr_offset();
 811     debug_info()->add_safepoint(safepoint_pc_offset, mcall->_oop_map);
 812   }
 813 
 814   // Loop over the JVMState list to add scope information
 815   // Do not skip safepoints with a NULL method, they need monitor info
 816   JVMState* youngest_jvms = sfn->jvms();
 817   int max_depth = youngest_jvms->depth();
 818 
 819   // Allocate the object pool for scalar-replaced objects -- the map from
 820   // small-integer keys (which can be recorded in the local and ostack
 821   // arrays) to descriptions of the object state.
 822   GrowableArray<ScopeValue*> *objs = new GrowableArray<ScopeValue*>();
 823 
 824   // Visit scopes from oldest to youngest.
 825   for (int depth = 1; depth <= max_depth; depth++) {
 826     JVMState* jvms = youngest_jvms->of_depth(depth);
 827     int idx;
 828     ciMethod* method = jvms->has_method() ? jvms->method() : NULL;
 829     // Safepoints that do not have method() set only provide oop-map and monitor info
 830     // to support GC; these do not support deoptimization.
 831     int num_locs = (method == NULL) ? 0 : jvms->loc_size();
 832     int num_exps = (method == NULL) ? 0 : jvms->stk_size();
 833     int num_mon  = jvms->nof_monitors();
 834     assert(method == NULL || jvms->bci() < 0 || num_locs == method->max_locals(),
 835            "JVMS local count must match that of the method");
 836 
 837     // Add Local and Expression Stack Information
 838 
 839     // Insert locals into the locarray
 840     GrowableArray<ScopeValue*> *locarray = new GrowableArray<ScopeValue*>(num_locs);
 841     for( idx = 0; idx < num_locs; idx++ ) {
 842       FillLocArray( idx, sfn, sfn->local(jvms, idx), locarray, objs );
 843     }
 844 
 845     // Insert expression stack entries into the exparray
 846     GrowableArray<ScopeValue*> *exparray = new GrowableArray<ScopeValue*>(num_exps);
 847     for( idx = 0; idx < num_exps; idx++ ) {
 848       FillLocArray( idx,  sfn, sfn->stack(jvms, idx), exparray, objs );
 849     }
 850 
 851     // Add in mappings of the monitors
 852     assert( !method ||
 853             !method->is_synchronized() ||
 854             method->is_native() ||
 855             num_mon > 0 ||
 856             !GenerateSynchronizationCode,
 857             "monitors must always exist for synchronized methods");
 858 
 859     // Build the growable array of ScopeValues for exp stack
 860     GrowableArray<MonitorValue*> *monarray = new GrowableArray<MonitorValue*>(num_mon);
 861 
 862     // Loop over monitors and insert into array
 863     for(idx = 0; idx < num_mon; idx++) {
 864       // Grab the node that defines this monitor
 865       Node* box_node = sfn->monitor_box(jvms, idx);
 866       Node* obj_node = sfn->monitor_obj(jvms, idx);
 867 
 868       // Create ScopeValue for object
 869       ScopeValue *scval = NULL;
 870 
 871       if( obj_node->is_SafePointScalarObject() ) {
 872         SafePointScalarObjectNode* spobj = obj_node->as_SafePointScalarObject();
 873         scval = Compile::sv_for_node_id(objs, spobj->_idx);
 874         if (scval == NULL) {
 875           const Type *t = obj_node->bottom_type();
 876           ciKlass* cik = t->is_oopptr()->klass();
 877           assert(cik->is_instance_klass() ||
 878                  cik->is_array_klass(), "Not supported allocation.");
 879           ObjectValue* sv = new ObjectValue(spobj->_idx,
 880                                 new ConstantOopWriteValue(cik->constant_encoding()));
 881           Compile::set_sv_for_object_node(objs, sv);
 882 
 883           uint first_ind = spobj->first_index();
 884           for (uint i = 0; i < spobj->n_fields(); i++) {
 885             Node* fld_node = sfn->in(first_ind+i);
 886             (void)FillLocArray(sv->field_values()->length(), sfn, fld_node, sv->field_values(), objs);
 887           }
 888           scval = sv;
 889         }
 890       } else if( !obj_node->is_Con() ) {
 891         OptoReg::Name obj_reg = _regalloc->get_reg_first(obj_node);
 892         if( obj_node->bottom_type()->base() == Type::NarrowOop ) {
 893           scval = new_loc_value( _regalloc, obj_reg, Location::narrowoop );
 894         } else {
 895           scval = new_loc_value( _regalloc, obj_reg, Location::oop );
 896         }
 897       } else {
 898         const TypePtr *tp = obj_node->bottom_type()->make_ptr();
 899         scval = new ConstantOopWriteValue(tp->is_instptr()->const_oop()->constant_encoding());
 900       }
 901 
 902       OptoReg::Name box_reg = BoxLockNode::stack_slot(box_node);
 903       Location basic_lock = Location::new_stk_loc(Location::normal,_regalloc->reg2offset(box_reg));
 904       while( !box_node->is_BoxLock() )  box_node = box_node->in(1);
 905       monarray->append(new MonitorValue(scval, basic_lock, box_node->as_BoxLock()->is_eliminated()));
 906     }
 907 
 908     // We dump the object pool first, since deoptimization reads it in first.
 909     debug_info()->dump_object_pool(objs);
 910 
 911     // Build first class objects to pass to scope
 912     DebugToken *locvals = debug_info()->create_scope_values(locarray);
 913     DebugToken *expvals = debug_info()->create_scope_values(exparray);
 914     DebugToken *monvals = debug_info()->create_monitor_values(monarray);
 915 
 916     // Make method available for all Safepoints
 917     ciMethod* scope_method = method ? method : _method;
 918     // Describe the scope here
 919     assert(jvms->bci() >= InvocationEntryBci && jvms->bci() <= 0x10000, "must be a valid or entry BCI");
 920     assert(!jvms->should_reexecute() || depth == max_depth, "reexecute allowed only for the youngest");
 921     // Now we can describe the scope.
 922     debug_info()->describe_scope(safepoint_pc_offset, scope_method, jvms->bci(), jvms->should_reexecute(), is_method_handle_invoke, locvals, expvals, monvals);
 923   } // End jvms loop
 924 
 925   // Mark the end of the scope set.
 926   debug_info()->end_safepoint(safepoint_pc_offset);
 927 }
 928 
 929 
 930 
 931 // A simplified version of Process_OopMap_Node, to handle non-safepoints.
 932 class NonSafepointEmitter {
 933   Compile*  C;
 934   JVMState* _pending_jvms;
 935   int       _pending_offset;
 936 
 937   void emit_non_safepoint();
 938 
 939  public:
 940   NonSafepointEmitter(Compile* compile) {
 941     this->C = compile;
 942     _pending_jvms = NULL;
 943     _pending_offset = 0;
 944   }
 945 
 946   void observe_instruction(Node* n, int pc_offset) {
 947     if (!C->debug_info()->recording_non_safepoints())  return;
 948 
 949     Node_Notes* nn = C->node_notes_at(n->_idx);
 950     if (nn == NULL || nn->jvms() == NULL)  return;
 951     if (_pending_jvms != NULL &&
 952         _pending_jvms->same_calls_as(nn->jvms())) {
 953       // Repeated JVMS?  Stretch it up here.
 954       _pending_offset = pc_offset;
 955     } else {
 956       if (_pending_jvms != NULL &&
 957           _pending_offset < pc_offset) {
 958         emit_non_safepoint();
 959       }
 960       _pending_jvms = NULL;
 961       if (pc_offset > C->debug_info()->last_pc_offset()) {
 962         // This is the only way _pending_jvms can become non-NULL:
 963         _pending_jvms = nn->jvms();
 964         _pending_offset = pc_offset;
 965       }
 966     }
 967   }
 968 
 969   // Stay out of the way of real safepoints:
 970   void observe_safepoint(JVMState* jvms, int pc_offset) {
 971     if (_pending_jvms != NULL &&
 972         !_pending_jvms->same_calls_as(jvms) &&
 973         _pending_offset < pc_offset) {
 974       emit_non_safepoint();
 975     }
 976     _pending_jvms = NULL;
 977   }
 978 
 979   void flush_at_end() {
 980     if (_pending_jvms != NULL) {
 981       emit_non_safepoint();
 982     }
 983     _pending_jvms = NULL;
 984   }
 985 };
 986 
 987 void NonSafepointEmitter::emit_non_safepoint() {
 988   JVMState* youngest_jvms = _pending_jvms;
 989   int       pc_offset     = _pending_offset;
 990 
 991   // Clear it now:
 992   _pending_jvms = NULL;
 993 
 994   DebugInformationRecorder* debug_info = C->debug_info();
 995   assert(debug_info->recording_non_safepoints(), "sanity");
 996 
 997   debug_info->add_non_safepoint(pc_offset);
 998   int max_depth = youngest_jvms->depth();
 999 
1000   // Visit scopes from oldest to youngest.
1001   for (int depth = 1; depth <= max_depth; depth++) {
1002     JVMState* jvms = youngest_jvms->of_depth(depth);
1003     ciMethod* method = jvms->has_method() ? jvms->method() : NULL;
1004     assert(!jvms->should_reexecute() || depth==max_depth, "reexecute allowed only for the youngest");
1005     debug_info->describe_scope(pc_offset, method, jvms->bci(), jvms->should_reexecute());
1006   }
1007 
1008   // Mark the end of the scope set.
1009   debug_info->end_non_safepoint(pc_offset);
1010 }
1011 
1012 
1013 
1014 // helper for Fill_buffer bailout logic
1015 static void turn_off_compiler(Compile* C) {
1016   if (CodeCache::unallocated_capacity() >= CodeCacheMinimumFreeSpace*10) {
1017     // Do not turn off compilation if a single giant method has
1018     // blown the code cache size.
1019     C->record_failure("excessive request to CodeCache");
1020   } else {
1021     // Let CompilerBroker disable further compilations.
1022     C->record_failure("CodeCache is full");
1023   }
1024 }
1025 
1026 
1027 //------------------------------Fill_buffer------------------------------------
1028 void Compile::Fill_buffer() {
1029 
1030   // Set the initially allocated size
1031   int  code_req   = initial_code_capacity;
1032   int  locs_req   = initial_locs_capacity;
1033   int  stub_req   = TraceJumps ? initial_stub_capacity * 10 : initial_stub_capacity;
1034   int  const_req  = initial_const_capacity;
1035   bool labels_not_set = true;
1036 
1037   int  pad_req    = NativeCall::instruction_size;
1038   // The extra spacing after the code is necessary on some platforms.
1039   // Sometimes we need to patch in a jump after the last instruction,
1040   // if the nmethod has been deoptimized.  (See 4932387, 4894843.)
1041 
1042   uint i;
1043   // Compute the byte offset where we can store the deopt pc.
1044   if (fixed_slots() != 0) {
1045     _orig_pc_slot_offset_in_bytes = _regalloc->reg2offset(OptoReg::stack2reg(_orig_pc_slot));
1046   }
1047 
1048   // Compute prolog code size
1049   _method_size = 0;
1050   _frame_slots = OptoReg::reg2stack(_matcher->_old_SP)+_regalloc->_framesize;
1051 #ifdef IA64
1052   if (save_argument_registers()) {
1053     // 4815101: this is a stub with implicit and unknown precision fp args.
1054     // The usual spill mechanism can only generate stfd's in this case, which
1055     // doesn't work if the fp reg to spill contains a single-precision denorm.
1056     // Instead, we hack around the normal spill mechanism using stfspill's and
1057     // ldffill's in the MachProlog and MachEpilog emit methods.  We allocate
1058     // space here for the fp arg regs (f8-f15) we're going to thusly spill.
1059     //
1060     // If we ever implement 16-byte 'registers' == stack slots, we can
1061     // get rid of this hack and have SpillCopy generate stfspill/ldffill
1062     // instead of stfd/stfs/ldfd/ldfs.
1063     _frame_slots += 8*(16/BytesPerInt);
1064   }
1065 #endif
1066   assert( _frame_slots >= 0 && _frame_slots < 1000000, "sanity check" );
1067 
1068   // Create an array of unused labels, one for each basic block
1069   Label *blk_labels = NEW_RESOURCE_ARRAY(Label, _cfg->_num_blocks+1);
1070 
1071   for( i=0; i <= _cfg->_num_blocks; i++ ) {
1072     blk_labels[i].init();
1073   }
1074 
1075   // If this machine supports different size branch offsets, then pre-compute
1076   // the length of the blocks
1077   if( _matcher->is_short_branch_offset(-1, 0) ) {
1078     Shorten_branches(blk_labels, code_req, locs_req, stub_req, const_req);
1079     labels_not_set = false;
1080   }
1081 
1082   // nmethod and CodeBuffer count stubs & constants as part of method's code.
1083   int exception_handler_req = size_exception_handler();
1084   int deopt_handler_req = size_deopt_handler();
1085   exception_handler_req += MAX_stubs_size; // add marginal slop for handler
1086   deopt_handler_req += MAX_stubs_size; // add marginal slop for handler
1087   stub_req += MAX_stubs_size;   // ensure per-stub margin
1088   code_req += MAX_inst_size;    // ensure per-instruction margin
1089   if (StressCodeBuffers)
1090     code_req = const_req = stub_req = exception_handler_req = deopt_handler_req = 0x10;  // force expansion
1091   int total_req = code_req + pad_req + stub_req + exception_handler_req + deopt_handler_req + const_req;
1092   CodeBuffer* cb = code_buffer();
1093   cb->initialize(total_req, locs_req);
1094 
1095   // Have we run out of code space?
1096   if ((cb->blob() == NULL) || (!CompileBroker::should_compile_new_jobs())) {
1097     turn_off_compiler(this);
1098     return;
1099   }
1100   // Configure the code buffer.
1101   cb->initialize_consts_size(const_req);
1102   cb->initialize_stubs_size(stub_req);
1103   cb->initialize_oop_recorder(env()->oop_recorder());
1104 
1105   // fill in the nop array for bundling computations
1106   MachNode *_nop_list[Bundle::_nop_count];
1107   Bundle::initialize_nops(_nop_list, this);
1108 
1109   // Create oopmap set.
1110   _oop_map_set = new OopMapSet();
1111 
1112   // !!!!! This preserves old handling of oopmaps for now
1113   debug_info()->set_oopmaps(_oop_map_set);
1114 
1115   // Count and start of implicit null check instructions
1116   uint inct_cnt = 0;
1117   uint *inct_starts = NEW_RESOURCE_ARRAY(uint, _cfg->_num_blocks+1);
1118 
1119   // Count and start of calls
1120   uint *call_returns = NEW_RESOURCE_ARRAY(uint, _cfg->_num_blocks+1);
1121 
1122   uint  return_offset = 0;
1123   int nop_size = (new (this) MachNopNode())->size(_regalloc);
1124 
1125   int previous_offset = 0;
1126   int current_offset  = 0;
1127   int last_call_offset = -1;
1128 
1129   // Create an array of unused labels, one for each basic block, if printing is enabled
1130 #ifndef PRODUCT
1131   int *node_offsets      = NULL;
1132   uint  node_offset_limit = unique();
1133 
1134 
1135   if ( print_assembly() )
1136     node_offsets         = NEW_RESOURCE_ARRAY(int, node_offset_limit);
1137 #endif
1138 
1139   NonSafepointEmitter non_safepoints(this);  // emit non-safepoints lazily
1140 
1141   // ------------------
1142   // Now fill in the code buffer
1143   Node *delay_slot = NULL;
1144 
1145   for( i=0; i < _cfg->_num_blocks; i++ ) {
1146     Block *b = _cfg->_blocks[i];
1147 
1148     Node *head = b->head();
1149 
1150     // If this block needs to start aligned (i.e, can be reached other
1151     // than by falling-thru from the previous block), then force the
1152     // start of a new bundle.
1153     if( Pipeline::requires_bundling() && starts_bundle(head) )
1154       cb->flush_bundle(true);
1155 
1156     // Define the label at the beginning of the basic block
1157     if( labels_not_set )
1158       MacroAssembler(cb).bind( blk_labels[b->_pre_order] );
1159 
1160     else
1161       assert( blk_labels[b->_pre_order].loc_pos() == cb->code_size(),
1162               "label position does not match code offset" );
1163 
1164     uint last_inst = b->_nodes.size();
1165 
1166     // Emit block normally, except for last instruction.
1167     // Emit means "dump code bits into code buffer".
1168     for( uint j = 0; j<last_inst; j++ ) {
1169 
1170       // Get the node
1171       Node* n = b->_nodes[j];
1172 
1173       // See if delay slots are supported
1174       if (valid_bundle_info(n) &&
1175           node_bundling(n)->used_in_unconditional_delay()) {
1176         assert(delay_slot == NULL, "no use of delay slot node");
1177         assert(n->size(_regalloc) == Pipeline::instr_unit_size(), "delay slot instruction wrong size");
1178 
1179         delay_slot = n;
1180         continue;
1181       }
1182 
1183       // If this starts a new instruction group, then flush the current one
1184       // (but allow split bundles)
1185       if( Pipeline::requires_bundling() && starts_bundle(n) )
1186         cb->flush_bundle(false);
1187 
1188       // The following logic is duplicated in the code ifdeffed for
1189       // ENABLE_ZAP_DEAD_LOCALS which appears above in this file.  It
1190       // should be factored out.  Or maybe dispersed to the nodes?
1191 
1192       // Special handling for SafePoint/Call Nodes
1193       bool is_mcall = false;
1194       if( n->is_Mach() ) {
1195         MachNode *mach = n->as_Mach();
1196         is_mcall = n->is_MachCall();
1197         bool is_sfn = n->is_MachSafePoint();
1198 
1199         // If this requires all previous instructions be flushed, then do so
1200         if( is_sfn || is_mcall || mach->alignment_required() != 1) {
1201           cb->flush_bundle(true);
1202           current_offset = cb->code_size();
1203         }
1204 
1205         // align the instruction if necessary
1206         int padding = mach->compute_padding(current_offset);
1207         // Make sure safepoint node for polling is distinct from a call's
1208         // return by adding a nop if needed.
1209         if (is_sfn && !is_mcall && padding == 0 && current_offset == last_call_offset ) {
1210           padding = nop_size;
1211         }
1212         assert( labels_not_set || padding == 0, "instruction should already be aligned")
1213 
1214         if(padding > 0) {
1215           assert((padding % nop_size) == 0, "padding is not a multiple of NOP size");
1216           int nops_cnt = padding / nop_size;
1217           MachNode *nop = new (this) MachNopNode(nops_cnt);
1218           b->_nodes.insert(j++, nop);
1219           last_inst++;
1220           _cfg->_bbs.map( nop->_idx, b );
1221           nop->emit(*cb, _regalloc);
1222           cb->flush_bundle(true);
1223           current_offset = cb->code_size();
1224         }
1225 
1226         // Remember the start of the last call in a basic block
1227         if (is_mcall) {
1228           MachCallNode *mcall = mach->as_MachCall();
1229 
1230           // This destination address is NOT PC-relative
1231           mcall->method_set((intptr_t)mcall->entry_point());
1232 
1233           // Save the return address
1234           call_returns[b->_pre_order] = current_offset + mcall->ret_addr_offset();
1235 
1236           if (!mcall->is_safepoint_node()) {
1237             is_mcall = false;
1238             is_sfn = false;
1239           }
1240         }
1241 
1242         // sfn will be valid whenever mcall is valid now because of inheritance
1243         if( is_sfn || is_mcall ) {
1244 
1245           // Handle special safepoint nodes for synchronization
1246           if( !is_mcall ) {
1247             MachSafePointNode *sfn = mach->as_MachSafePoint();
1248             // !!!!! Stubs only need an oopmap right now, so bail out
1249             if( sfn->jvms()->method() == NULL) {
1250               // Write the oopmap directly to the code blob??!!
1251 #             ifdef ENABLE_ZAP_DEAD_LOCALS
1252               assert( !is_node_getting_a_safepoint(sfn),  "logic does not match; false positive");
1253 #             endif
1254               continue;
1255             }
1256           } // End synchronization
1257 
1258           non_safepoints.observe_safepoint(mach->as_MachSafePoint()->jvms(),
1259                                            current_offset);
1260           Process_OopMap_Node(mach, current_offset);
1261         } // End if safepoint
1262 
1263         // If this is a null check, then add the start of the previous instruction to the list
1264         else if( mach->is_MachNullCheck() ) {
1265           inct_starts[inct_cnt++] = previous_offset;
1266         }
1267 
1268         // If this is a branch, then fill in the label with the target BB's label
1269         else if ( mach->is_Branch() ) {
1270 
1271           if ( mach->ideal_Opcode() == Op_Jump ) {
1272             for (uint h = 0; h < b->_num_succs; h++ ) {
1273               Block* succs_block = b->_succs[h];
1274               for (uint j = 1; j < succs_block->num_preds(); j++) {
1275                 Node* jpn = succs_block->pred(j);
1276                 if ( jpn->is_JumpProj() && jpn->in(0) == mach ) {
1277                   uint block_num = succs_block->non_connector()->_pre_order;
1278                   Label *blkLabel = &blk_labels[block_num];
1279                   mach->add_case_label(jpn->as_JumpProj()->proj_no(), blkLabel);
1280                 }
1281               }
1282             }
1283           } else {
1284             // For Branchs
1285             // This requires the TRUE branch target be in succs[0]
1286             uint block_num = b->non_connector_successor(0)->_pre_order;
1287             mach->label_set( blk_labels[block_num], block_num );
1288           }
1289         }
1290 
1291 #ifdef ASSERT
1292         // Check that oop-store precedes the card-mark
1293         else if( mach->ideal_Opcode() == Op_StoreCM ) {
1294           uint storeCM_idx = j;
1295           Node *oop_store = mach->in(mach->_cnt);  // First precedence edge
1296           assert( oop_store != NULL, "storeCM expects a precedence edge");
1297           uint i4;
1298           for( i4 = 0; i4 < last_inst; ++i4 ) {
1299             if( b->_nodes[i4] == oop_store ) break;
1300           }
1301           // Note: This test can provide a false failure if other precedence
1302           // edges have been added to the storeCMNode.
1303           assert( i4 == last_inst || i4 < storeCM_idx, "CM card-mark executes before oop-store");
1304         }
1305 #endif
1306 
1307         else if( !n->is_Proj() ) {
1308           // Remember the beginning of the previous instruction, in case
1309           // it's followed by a flag-kill and a null-check.  Happens on
1310           // Intel all the time, with add-to-memory kind of opcodes.
1311           previous_offset = current_offset;
1312         }
1313       }
1314 
1315       // Verify that there is sufficient space remaining
1316       cb->insts()->maybe_expand_to_ensure_remaining(MAX_inst_size);
1317       if ((cb->blob() == NULL) || (!CompileBroker::should_compile_new_jobs())) {
1318         turn_off_compiler(this);
1319         return;
1320       }
1321 
1322       // Save the offset for the listing
1323 #ifndef PRODUCT
1324       if( node_offsets && n->_idx < node_offset_limit )
1325         node_offsets[n->_idx] = cb->code_size();
1326 #endif
1327 
1328       // "Normal" instruction case
1329       n->emit(*cb, _regalloc);
1330       current_offset  = cb->code_size();
1331       non_safepoints.observe_instruction(n, current_offset);
1332 
1333       // mcall is last "call" that can be a safepoint
1334       // record it so we can see if a poll will directly follow it
1335       // in which case we'll need a pad to make the PcDesc sites unique
1336       // see  5010568. This can be slightly inaccurate but conservative
1337       // in the case that return address is not actually at current_offset.
1338       // This is a small price to pay.
1339 
1340       if (is_mcall) {
1341         last_call_offset = current_offset;
1342       }
1343 
1344       // See if this instruction has a delay slot
1345       if ( valid_bundle_info(n) && node_bundling(n)->use_unconditional_delay()) {
1346         assert(delay_slot != NULL, "expecting delay slot node");
1347 
1348         // Back up 1 instruction
1349         cb->set_code_end(
1350           cb->code_end()-Pipeline::instr_unit_size());
1351 
1352         // Save the offset for the listing
1353 #ifndef PRODUCT
1354         if( node_offsets && delay_slot->_idx < node_offset_limit )
1355           node_offsets[delay_slot->_idx] = cb->code_size();
1356 #endif
1357 
1358         // Support a SafePoint in the delay slot
1359         if( delay_slot->is_MachSafePoint() ) {
1360           MachNode *mach = delay_slot->as_Mach();
1361           // !!!!! Stubs only need an oopmap right now, so bail out
1362           if( !mach->is_MachCall() && mach->as_MachSafePoint()->jvms()->method() == NULL ) {
1363             // Write the oopmap directly to the code blob??!!
1364 #           ifdef ENABLE_ZAP_DEAD_LOCALS
1365             assert( !is_node_getting_a_safepoint(mach),  "logic does not match; false positive");
1366 #           endif
1367             delay_slot = NULL;
1368             continue;
1369           }
1370 
1371           int adjusted_offset = current_offset - Pipeline::instr_unit_size();
1372           non_safepoints.observe_safepoint(mach->as_MachSafePoint()->jvms(),
1373                                            adjusted_offset);
1374           // Generate an OopMap entry
1375           Process_OopMap_Node(mach, adjusted_offset);
1376         }
1377 
1378         // Insert the delay slot instruction
1379         delay_slot->emit(*cb, _regalloc);
1380 
1381         // Don't reuse it
1382         delay_slot = NULL;
1383       }
1384 
1385     } // End for all instructions in block
1386 
1387     // If the next block is the top of a loop, pad this block out to align
1388     // the loop top a little. Helps prevent pipe stalls at loop back branches.
1389     if( i<_cfg->_num_blocks-1 ) {
1390       Block *nb = _cfg->_blocks[i+1];
1391       uint padding = nb->alignment_padding(current_offset);
1392       if( padding > 0 ) {
1393         MachNode *nop = new (this) MachNopNode(padding / nop_size);
1394         b->_nodes.insert( b->_nodes.size(), nop );
1395         _cfg->_bbs.map( nop->_idx, b );
1396         nop->emit(*cb, _regalloc);
1397         current_offset = cb->code_size();
1398       }
1399     }
1400 
1401   } // End of for all blocks
1402 
1403   non_safepoints.flush_at_end();
1404 
1405   // Offset too large?
1406   if (failing())  return;
1407 
1408   // Define a pseudo-label at the end of the code
1409   MacroAssembler(cb).bind( blk_labels[_cfg->_num_blocks] );
1410 
1411   // Compute the size of the first block
1412   _first_block_size = blk_labels[1].loc_pos() - blk_labels[0].loc_pos();
1413 
1414   assert(cb->code_size() < 500000, "method is unreasonably large");
1415 
1416   // ------------------
1417 
1418 #ifndef PRODUCT
1419   // Information on the size of the method, without the extraneous code
1420   Scheduling::increment_method_size(cb->code_size());
1421 #endif
1422 
1423   // ------------------
1424   // Fill in exception table entries.
1425   FillExceptionTables(inct_cnt, call_returns, inct_starts, blk_labels);
1426 
1427   // Only java methods have exception handlers and deopt handlers
1428   if (_method) {
1429     // Emit the exception handler code.
1430     _code_offsets.set_value(CodeOffsets::Exceptions, emit_exception_handler(*cb));
1431     // Emit the deopt handler code.
1432     _code_offsets.set_value(CodeOffsets::Deopt, emit_deopt_handler(*cb));
1433     // Emit the MethodHandle deopt handler code.  We can use the same
1434     // code as for the normal deopt handler, we just need a different
1435     // entry point address.
1436     _code_offsets.set_value(CodeOffsets::DeoptMH, emit_deopt_handler(*cb));
1437   }
1438 
1439   // One last check for failed CodeBuffer::expand:
1440   if ((cb->blob() == NULL) || (!CompileBroker::should_compile_new_jobs())) {
1441     turn_off_compiler(this);
1442     return;
1443   }
1444 
1445 #ifndef PRODUCT
1446   // Dump the assembly code, including basic-block numbers
1447   if (print_assembly()) {
1448     ttyLocker ttyl;  // keep the following output all in one block
1449     if (!VMThread::should_terminate()) {  // test this under the tty lock
1450       // This output goes directly to the tty, not the compiler log.
1451       // To enable tools to match it up with the compilation activity,
1452       // be sure to tag this tty output with the compile ID.
1453       if (xtty != NULL) {
1454         xtty->head("opto_assembly compile_id='%d'%s", compile_id(),
1455                    is_osr_compilation()    ? " compile_kind='osr'" :
1456                    "");
1457       }
1458       if (method() != NULL) {
1459         method()->print_oop();
1460         print_codes();
1461       }
1462       dump_asm(node_offsets, node_offset_limit);
1463       if (xtty != NULL) {
1464         xtty->tail("opto_assembly");
1465       }
1466     }
1467   }
1468 #endif
1469 
1470 }
1471 
1472 void Compile::FillExceptionTables(uint cnt, uint *call_returns, uint *inct_starts, Label *blk_labels) {
1473   _inc_table.set_size(cnt);
1474 
1475   uint inct_cnt = 0;
1476   for( uint i=0; i<_cfg->_num_blocks; i++ ) {
1477     Block *b = _cfg->_blocks[i];
1478     Node *n = NULL;
1479     int j;
1480 
1481     // Find the branch; ignore trailing NOPs.
1482     for( j = b->_nodes.size()-1; j>=0; j-- ) {
1483       n = b->_nodes[j];
1484       if( !n->is_Mach() || n->as_Mach()->ideal_Opcode() != Op_Con )
1485         break;
1486     }
1487 
1488     // If we didn't find anything, continue
1489     if( j < 0 ) continue;
1490 
1491     // Compute ExceptionHandlerTable subtable entry and add it
1492     // (skip empty blocks)
1493     if( n->is_Catch() ) {
1494 
1495       // Get the offset of the return from the call
1496       uint call_return = call_returns[b->_pre_order];
1497 #ifdef ASSERT
1498       assert( call_return > 0, "no call seen for this basic block" );
1499       while( b->_nodes[--j]->Opcode() == Op_MachProj ) ;
1500       assert( b->_nodes[j]->is_Call(), "CatchProj must follow call" );
1501 #endif
1502       // last instruction is a CatchNode, find it's CatchProjNodes
1503       int nof_succs = b->_num_succs;
1504       // allocate space
1505       GrowableArray<intptr_t> handler_bcis(nof_succs);
1506       GrowableArray<intptr_t> handler_pcos(nof_succs);
1507       // iterate through all successors
1508       for (int j = 0; j < nof_succs; j++) {
1509         Block* s = b->_succs[j];
1510         bool found_p = false;
1511         for( uint k = 1; k < s->num_preds(); k++ ) {
1512           Node *pk = s->pred(k);
1513           if( pk->is_CatchProj() && pk->in(0) == n ) {
1514             const CatchProjNode* p = pk->as_CatchProj();
1515             found_p = true;
1516             // add the corresponding handler bci & pco information
1517             if( p->_con != CatchProjNode::fall_through_index ) {
1518               // p leads to an exception handler (and is not fall through)
1519               assert(s == _cfg->_blocks[s->_pre_order],"bad numbering");
1520               // no duplicates, please
1521               if( !handler_bcis.contains(p->handler_bci()) ) {
1522                 uint block_num = s->non_connector()->_pre_order;
1523                 handler_bcis.append(p->handler_bci());
1524                 handler_pcos.append(blk_labels[block_num].loc_pos());
1525               }
1526             }
1527           }
1528         }
1529         assert(found_p, "no matching predecessor found");
1530         // Note:  Due to empty block removal, one block may have
1531         // several CatchProj inputs, from the same Catch.
1532       }
1533 
1534       // Set the offset of the return from the call
1535       _handler_table.add_subtable(call_return, &handler_bcis, NULL, &handler_pcos);
1536       continue;
1537     }
1538 
1539     // Handle implicit null exception table updates
1540     if( n->is_MachNullCheck() ) {
1541       uint block_num = b->non_connector_successor(0)->_pre_order;
1542       _inc_table.append( inct_starts[inct_cnt++], blk_labels[block_num].loc_pos() );
1543       continue;
1544     }
1545   } // End of for all blocks fill in exception table entries
1546 }
1547 
1548 // Static Variables
1549 #ifndef PRODUCT
1550 uint Scheduling::_total_nop_size = 0;
1551 uint Scheduling::_total_method_size = 0;
1552 uint Scheduling::_total_branches = 0;
1553 uint Scheduling::_total_unconditional_delays = 0;
1554 uint Scheduling::_total_instructions_per_bundle[Pipeline::_max_instrs_per_cycle+1];
1555 #endif
1556 
1557 // Initializer for class Scheduling
1558 
1559 Scheduling::Scheduling(Arena *arena, Compile &compile)
1560   : _arena(arena),
1561     _cfg(compile.cfg()),
1562     _bbs(compile.cfg()->_bbs),
1563     _regalloc(compile.regalloc()),
1564     _reg_node(arena),
1565     _bundle_instr_count(0),
1566     _bundle_cycle_number(0),
1567     _scheduled(arena),
1568     _available(arena),
1569     _next_node(NULL),
1570     _bundle_use(0, 0, resource_count, &_bundle_use_elements[0]),
1571     _pinch_free_list(arena)
1572 #ifndef PRODUCT
1573   , _branches(0)
1574   , _unconditional_delays(0)
1575 #endif
1576 {
1577   // Create a MachNopNode
1578   _nop = new (&compile) MachNopNode();
1579 
1580   // Now that the nops are in the array, save the count
1581   // (but allow entries for the nops)
1582   _node_bundling_limit = compile.unique();
1583   uint node_max = _regalloc->node_regs_max_index();
1584 
1585   compile.set_node_bundling_limit(_node_bundling_limit);
1586 
1587   // This one is persistent within the Compile class
1588   _node_bundling_base = NEW_ARENA_ARRAY(compile.comp_arena(), Bundle, node_max);
1589 
1590   // Allocate space for fixed-size arrays
1591   _node_latency    = NEW_ARENA_ARRAY(arena, unsigned short, node_max);
1592   _uses            = NEW_ARENA_ARRAY(arena, short,          node_max);
1593   _current_latency = NEW_ARENA_ARRAY(arena, unsigned short, node_max);
1594 
1595   // Clear the arrays
1596   memset(_node_bundling_base, 0, node_max * sizeof(Bundle));
1597   memset(_node_latency,       0, node_max * sizeof(unsigned short));
1598   memset(_uses,               0, node_max * sizeof(short));
1599   memset(_current_latency,    0, node_max * sizeof(unsigned short));
1600 
1601   // Clear the bundling information
1602   memcpy(_bundle_use_elements,
1603     Pipeline_Use::elaborated_elements,
1604     sizeof(Pipeline_Use::elaborated_elements));
1605 
1606   // Get the last node
1607   Block *bb = _cfg->_blocks[_cfg->_blocks.size()-1];
1608 
1609   _next_node = bb->_nodes[bb->_nodes.size()-1];
1610 }
1611 
1612 #ifndef PRODUCT
1613 // Scheduling destructor
1614 Scheduling::~Scheduling() {
1615   _total_branches             += _branches;
1616   _total_unconditional_delays += _unconditional_delays;
1617 }
1618 #endif
1619 
1620 // Step ahead "i" cycles
1621 void Scheduling::step(uint i) {
1622 
1623   Bundle *bundle = node_bundling(_next_node);
1624   bundle->set_starts_bundle();
1625 
1626   // Update the bundle record, but leave the flags information alone
1627   if (_bundle_instr_count > 0) {
1628     bundle->set_instr_count(_bundle_instr_count);
1629     bundle->set_resources_used(_bundle_use.resourcesUsed());
1630   }
1631 
1632   // Update the state information
1633   _bundle_instr_count = 0;
1634   _bundle_cycle_number += i;
1635   _bundle_use.step(i);
1636 }
1637 
1638 void Scheduling::step_and_clear() {
1639   Bundle *bundle = node_bundling(_next_node);
1640   bundle->set_starts_bundle();
1641 
1642   // Update the bundle record
1643   if (_bundle_instr_count > 0) {
1644     bundle->set_instr_count(_bundle_instr_count);
1645     bundle->set_resources_used(_bundle_use.resourcesUsed());
1646 
1647     _bundle_cycle_number += 1;
1648   }
1649 
1650   // Clear the bundling information
1651   _bundle_instr_count = 0;
1652   _bundle_use.reset();
1653 
1654   memcpy(_bundle_use_elements,
1655     Pipeline_Use::elaborated_elements,
1656     sizeof(Pipeline_Use::elaborated_elements));
1657 }
1658 
1659 //------------------------------ScheduleAndBundle------------------------------
1660 // Perform instruction scheduling and bundling over the sequence of
1661 // instructions in backwards order.
1662 void Compile::ScheduleAndBundle() {
1663 
1664   // Don't optimize this if it isn't a method
1665   if (!_method)
1666     return;
1667 
1668   // Don't optimize this if scheduling is disabled
1669   if (!do_scheduling())
1670     return;
1671 
1672   NOT_PRODUCT( TracePhase t2("isched", &_t_instrSched, TimeCompiler); )
1673 
1674   // Create a data structure for all the scheduling information
1675   Scheduling scheduling(Thread::current()->resource_area(), *this);
1676 
1677   // Walk backwards over each basic block, computing the needed alignment
1678   // Walk over all the basic blocks
1679   scheduling.DoScheduling();
1680 }
1681 
1682 //------------------------------ComputeLocalLatenciesForward-------------------
1683 // Compute the latency of all the instructions.  This is fairly simple,
1684 // because we already have a legal ordering.  Walk over the instructions
1685 // from first to last, and compute the latency of the instruction based
1686 // on the latency of the preceding instruction(s).
1687 void Scheduling::ComputeLocalLatenciesForward(const Block *bb) {
1688 #ifndef PRODUCT
1689   if (_cfg->C->trace_opto_output())
1690     tty->print("# -> ComputeLocalLatenciesForward\n");
1691 #endif
1692 
1693   // Walk over all the schedulable instructions
1694   for( uint j=_bb_start; j < _bb_end; j++ ) {
1695 
1696     // This is a kludge, forcing all latency calculations to start at 1.
1697     // Used to allow latency 0 to force an instruction to the beginning
1698     // of the bb
1699     uint latency = 1;
1700     Node *use = bb->_nodes[j];
1701     uint nlen = use->len();
1702 
1703     // Walk over all the inputs
1704     for ( uint k=0; k < nlen; k++ ) {
1705       Node *def = use->in(k);
1706       if (!def)
1707         continue;
1708 
1709       uint l = _node_latency[def->_idx] + use->latency(k);
1710       if (latency < l)
1711         latency = l;
1712     }
1713 
1714     _node_latency[use->_idx] = latency;
1715 
1716 #ifndef PRODUCT
1717     if (_cfg->C->trace_opto_output()) {
1718       tty->print("# latency %4d: ", latency);
1719       use->dump();
1720     }
1721 #endif
1722   }
1723 
1724 #ifndef PRODUCT
1725   if (_cfg->C->trace_opto_output())
1726     tty->print("# <- ComputeLocalLatenciesForward\n");
1727 #endif
1728 
1729 } // end ComputeLocalLatenciesForward
1730 
1731 // See if this node fits into the present instruction bundle
1732 bool Scheduling::NodeFitsInBundle(Node *n) {
1733   uint n_idx = n->_idx;
1734 
1735   // If this is the unconditional delay instruction, then it fits
1736   if (n == _unconditional_delay_slot) {
1737 #ifndef PRODUCT
1738     if (_cfg->C->trace_opto_output())
1739       tty->print("#     NodeFitsInBundle [%4d]: TRUE; is in unconditional delay slot\n", n->_idx);
1740 #endif
1741     return (true);
1742   }
1743 
1744   // If the node cannot be scheduled this cycle, skip it
1745   if (_current_latency[n_idx] > _bundle_cycle_number) {
1746 #ifndef PRODUCT
1747     if (_cfg->C->trace_opto_output())
1748       tty->print("#     NodeFitsInBundle [%4d]: FALSE; latency %4d > %d\n",
1749         n->_idx, _current_latency[n_idx], _bundle_cycle_number);
1750 #endif
1751     return (false);
1752   }
1753 
1754   const Pipeline *node_pipeline = n->pipeline();
1755 
1756   uint instruction_count = node_pipeline->instructionCount();
1757   if (node_pipeline->mayHaveNoCode() && n->size(_regalloc) == 0)
1758     instruction_count = 0;
1759   else if (node_pipeline->hasBranchDelay() && !_unconditional_delay_slot)
1760     instruction_count++;
1761 
1762   if (_bundle_instr_count + instruction_count > Pipeline::_max_instrs_per_cycle) {
1763 #ifndef PRODUCT
1764     if (_cfg->C->trace_opto_output())
1765       tty->print("#     NodeFitsInBundle [%4d]: FALSE; too many instructions: %d > %d\n",
1766         n->_idx, _bundle_instr_count + instruction_count, Pipeline::_max_instrs_per_cycle);
1767 #endif
1768     return (false);
1769   }
1770 
1771   // Don't allow non-machine nodes to be handled this way
1772   if (!n->is_Mach() && instruction_count == 0)
1773     return (false);
1774 
1775   // See if there is any overlap
1776   uint delay = _bundle_use.full_latency(0, node_pipeline->resourceUse());
1777 
1778   if (delay > 0) {
1779 #ifndef PRODUCT
1780     if (_cfg->C->trace_opto_output())
1781       tty->print("#     NodeFitsInBundle [%4d]: FALSE; functional units overlap\n", n_idx);
1782 #endif
1783     return false;
1784   }
1785 
1786 #ifndef PRODUCT
1787   if (_cfg->C->trace_opto_output())
1788     tty->print("#     NodeFitsInBundle [%4d]:  TRUE\n", n_idx);
1789 #endif
1790 
1791   return true;
1792 }
1793 
1794 Node * Scheduling::ChooseNodeToBundle() {
1795   uint siz = _available.size();
1796 
1797   if (siz == 0) {
1798 
1799 #ifndef PRODUCT
1800     if (_cfg->C->trace_opto_output())
1801       tty->print("#   ChooseNodeToBundle: NULL\n");
1802 #endif
1803     return (NULL);
1804   }
1805 
1806   // Fast path, if only 1 instruction in the bundle
1807   if (siz == 1) {
1808 #ifndef PRODUCT
1809     if (_cfg->C->trace_opto_output()) {
1810       tty->print("#   ChooseNodeToBundle (only 1): ");
1811       _available[0]->dump();
1812     }
1813 #endif
1814     return (_available[0]);
1815   }
1816 
1817   // Don't bother, if the bundle is already full
1818   if (_bundle_instr_count < Pipeline::_max_instrs_per_cycle) {
1819     for ( uint i = 0; i < siz; i++ ) {
1820       Node *n = _available[i];
1821 
1822       // Skip projections, we'll handle them another way
1823       if (n->is_Proj())
1824         continue;
1825 
1826       // This presupposed that instructions are inserted into the
1827       // available list in a legality order; i.e. instructions that
1828       // must be inserted first are at the head of the list
1829       if (NodeFitsInBundle(n)) {
1830 #ifndef PRODUCT
1831         if (_cfg->C->trace_opto_output()) {
1832           tty->print("#   ChooseNodeToBundle: ");
1833           n->dump();
1834         }
1835 #endif
1836         return (n);
1837       }
1838     }
1839   }
1840 
1841   // Nothing fits in this bundle, choose the highest priority
1842 #ifndef PRODUCT
1843   if (_cfg->C->trace_opto_output()) {
1844     tty->print("#   ChooseNodeToBundle: ");
1845     _available[0]->dump();
1846   }
1847 #endif
1848 
1849   return _available[0];
1850 }
1851 
1852 //------------------------------AddNodeToAvailableList-------------------------
1853 void Scheduling::AddNodeToAvailableList(Node *n) {
1854   assert( !n->is_Proj(), "projections never directly made available" );
1855 #ifndef PRODUCT
1856   if (_cfg->C->trace_opto_output()) {
1857     tty->print("#   AddNodeToAvailableList: ");
1858     n->dump();
1859   }
1860 #endif
1861 
1862   int latency = _current_latency[n->_idx];
1863 
1864   // Insert in latency order (insertion sort)
1865   uint i;
1866   for ( i=0; i < _available.size(); i++ )
1867     if (_current_latency[_available[i]->_idx] > latency)
1868       break;
1869 
1870   // Special Check for compares following branches
1871   if( n->is_Mach() && _scheduled.size() > 0 ) {
1872     int op = n->as_Mach()->ideal_Opcode();
1873     Node *last = _scheduled[0];
1874     if( last->is_MachIf() && last->in(1) == n &&
1875         ( op == Op_CmpI ||
1876           op == Op_CmpU ||
1877           op == Op_CmpP ||
1878           op == Op_CmpF ||
1879           op == Op_CmpD ||
1880           op == Op_CmpL ) ) {
1881 
1882       // Recalculate position, moving to front of same latency
1883       for ( i=0 ; i < _available.size(); i++ )
1884         if (_current_latency[_available[i]->_idx] >= latency)
1885           break;
1886     }
1887   }
1888 
1889   // Insert the node in the available list
1890   _available.insert(i, n);
1891 
1892 #ifndef PRODUCT
1893   if (_cfg->C->trace_opto_output())
1894     dump_available();
1895 #endif
1896 }
1897 
1898 //------------------------------DecrementUseCounts-----------------------------
1899 void Scheduling::DecrementUseCounts(Node *n, const Block *bb) {
1900   for ( uint i=0; i < n->len(); i++ ) {
1901     Node *def = n->in(i);
1902     if (!def) continue;
1903     if( def->is_Proj() )        // If this is a machine projection, then
1904       def = def->in(0);         // propagate usage thru to the base instruction
1905 
1906     if( _bbs[def->_idx] != bb ) // Ignore if not block-local
1907       continue;
1908 
1909     // Compute the latency
1910     uint l = _bundle_cycle_number + n->latency(i);
1911     if (_current_latency[def->_idx] < l)
1912       _current_latency[def->_idx] = l;
1913 
1914     // If this does not have uses then schedule it
1915     if ((--_uses[def->_idx]) == 0)
1916       AddNodeToAvailableList(def);
1917   }
1918 }
1919 
1920 //------------------------------AddNodeToBundle--------------------------------
1921 void Scheduling::AddNodeToBundle(Node *n, const Block *bb) {
1922 #ifndef PRODUCT
1923   if (_cfg->C->trace_opto_output()) {
1924     tty->print("#   AddNodeToBundle: ");
1925     n->dump();
1926   }
1927 #endif
1928 
1929   // Remove this from the available list
1930   uint i;
1931   for (i = 0; i < _available.size(); i++)
1932     if (_available[i] == n)
1933       break;
1934   assert(i < _available.size(), "entry in _available list not found");
1935   _available.remove(i);
1936 
1937   // See if this fits in the current bundle
1938   const Pipeline *node_pipeline = n->pipeline();
1939   const Pipeline_Use& node_usage = node_pipeline->resourceUse();
1940 
1941   // Check for instructions to be placed in the delay slot. We
1942   // do this before we actually schedule the current instruction,
1943   // because the delay slot follows the current instruction.
1944   if (Pipeline::_branch_has_delay_slot &&
1945       node_pipeline->hasBranchDelay() &&
1946       !_unconditional_delay_slot) {
1947 
1948     uint siz = _available.size();
1949 
1950     // Conditional branches can support an instruction that
1951     // is unconditionally executed and not dependent by the
1952     // branch, OR a conditionally executed instruction if
1953     // the branch is taken.  In practice, this means that
1954     // the first instruction at the branch target is
1955     // copied to the delay slot, and the branch goes to
1956     // the instruction after that at the branch target
1957     if ( n->is_Mach() && n->is_Branch() ) {
1958 
1959       assert( !n->is_MachNullCheck(), "should not look for delay slot for Null Check" );
1960       assert( !n->is_Catch(),         "should not look for delay slot for Catch" );
1961 
1962 #ifndef PRODUCT
1963       _branches++;
1964 #endif
1965 
1966       // At least 1 instruction is on the available list
1967       // that is not dependent on the branch
1968       for (uint i = 0; i < siz; i++) {
1969         Node *d = _available[i];
1970         const Pipeline *avail_pipeline = d->pipeline();
1971 
1972         // Don't allow safepoints in the branch shadow, that will
1973         // cause a number of difficulties
1974         if ( avail_pipeline->instructionCount() == 1 &&
1975             !avail_pipeline->hasMultipleBundles() &&
1976             !avail_pipeline->hasBranchDelay() &&
1977             Pipeline::instr_has_unit_size() &&
1978             d->size(_regalloc) == Pipeline::instr_unit_size() &&
1979             NodeFitsInBundle(d) &&
1980             !node_bundling(d)->used_in_delay()) {
1981 
1982           if (d->is_Mach() && !d->is_MachSafePoint()) {
1983             // A node that fits in the delay slot was found, so we need to
1984             // set the appropriate bits in the bundle pipeline information so
1985             // that it correctly indicates resource usage.  Later, when we
1986             // attempt to add this instruction to the bundle, we will skip
1987             // setting the resource usage.
1988             _unconditional_delay_slot = d;
1989             node_bundling(n)->set_use_unconditional_delay();
1990             node_bundling(d)->set_used_in_unconditional_delay();
1991             _bundle_use.add_usage(avail_pipeline->resourceUse());
1992             _current_latency[d->_idx] = _bundle_cycle_number;
1993             _next_node = d;
1994             ++_bundle_instr_count;
1995 #ifndef PRODUCT
1996             _unconditional_delays++;
1997 #endif
1998             break;
1999           }
2000         }
2001       }
2002     }
2003 
2004     // No delay slot, add a nop to the usage
2005     if (!_unconditional_delay_slot) {
2006       // See if adding an instruction in the delay slot will overflow
2007       // the bundle.
2008       if (!NodeFitsInBundle(_nop)) {
2009 #ifndef PRODUCT
2010         if (_cfg->C->trace_opto_output())
2011           tty->print("#  *** STEP(1 instruction for delay slot) ***\n");
2012 #endif
2013         step(1);
2014       }
2015 
2016       _bundle_use.add_usage(_nop->pipeline()->resourceUse());
2017       _next_node = _nop;
2018       ++_bundle_instr_count;
2019     }
2020 
2021     // See if the instruction in the delay slot requires a
2022     // step of the bundles
2023     if (!NodeFitsInBundle(n)) {
2024 #ifndef PRODUCT
2025         if (_cfg->C->trace_opto_output())
2026           tty->print("#  *** STEP(branch won't fit) ***\n");
2027 #endif
2028         // Update the state information
2029         _bundle_instr_count = 0;
2030         _bundle_cycle_number += 1;
2031         _bundle_use.step(1);
2032     }
2033   }
2034 
2035   // Get the number of instructions
2036   uint instruction_count = node_pipeline->instructionCount();
2037   if (node_pipeline->mayHaveNoCode() && n->size(_regalloc) == 0)
2038     instruction_count = 0;
2039 
2040   // Compute the latency information
2041   uint delay = 0;
2042 
2043   if (instruction_count > 0 || !node_pipeline->mayHaveNoCode()) {
2044     int relative_latency = _current_latency[n->_idx] - _bundle_cycle_number;
2045     if (relative_latency < 0)
2046       relative_latency = 0;
2047 
2048     delay = _bundle_use.full_latency(relative_latency, node_usage);
2049 
2050     // Does not fit in this bundle, start a new one
2051     if (delay > 0) {
2052       step(delay);
2053 
2054 #ifndef PRODUCT
2055       if (_cfg->C->trace_opto_output())
2056         tty->print("#  *** STEP(%d) ***\n", delay);
2057 #endif
2058     }
2059   }
2060 
2061   // If this was placed in the delay slot, ignore it
2062   if (n != _unconditional_delay_slot) {
2063 
2064     if (delay == 0) {
2065       if (node_pipeline->hasMultipleBundles()) {
2066 #ifndef PRODUCT
2067         if (_cfg->C->trace_opto_output())
2068           tty->print("#  *** STEP(multiple instructions) ***\n");
2069 #endif
2070         step(1);
2071       }
2072 
2073       else if (instruction_count + _bundle_instr_count > Pipeline::_max_instrs_per_cycle) {
2074 #ifndef PRODUCT
2075         if (_cfg->C->trace_opto_output())
2076           tty->print("#  *** STEP(%d >= %d instructions) ***\n",
2077             instruction_count + _bundle_instr_count,
2078             Pipeline::_max_instrs_per_cycle);
2079 #endif
2080         step(1);
2081       }
2082     }
2083 
2084     if (node_pipeline->hasBranchDelay() && !_unconditional_delay_slot)
2085       _bundle_instr_count++;
2086 
2087     // Set the node's latency
2088     _current_latency[n->_idx] = _bundle_cycle_number;
2089 
2090     // Now merge the functional unit information
2091     if (instruction_count > 0 || !node_pipeline->mayHaveNoCode())
2092       _bundle_use.add_usage(node_usage);
2093 
2094     // Increment the number of instructions in this bundle
2095     _bundle_instr_count += instruction_count;
2096 
2097     // Remember this node for later
2098     if (n->is_Mach())
2099       _next_node = n;
2100   }
2101 
2102   // It's possible to have a BoxLock in the graph and in the _bbs mapping but
2103   // not in the bb->_nodes array.  This happens for debug-info-only BoxLocks.
2104   // 'Schedule' them (basically ignore in the schedule) but do not insert them
2105   // into the block.  All other scheduled nodes get put in the schedule here.
2106   int op = n->Opcode();
2107   if( (op == Op_Node && n->req() == 0) || // anti-dependence node OR
2108       (op != Op_Node &&         // Not an unused antidepedence node and
2109        // not an unallocated boxlock
2110        (OptoReg::is_valid(_regalloc->get_reg_first(n)) || op != Op_BoxLock)) ) {
2111 
2112     // Push any trailing projections
2113     if( bb->_nodes[bb->_nodes.size()-1] != n ) {
2114       for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
2115         Node *foi = n->fast_out(i);
2116         if( foi->is_Proj() )
2117           _scheduled.push(foi);
2118       }
2119     }
2120 
2121     // Put the instruction in the schedule list
2122     _scheduled.push(n);
2123   }
2124 
2125 #ifndef PRODUCT
2126   if (_cfg->C->trace_opto_output())
2127     dump_available();
2128 #endif
2129 
2130   // Walk all the definitions, decrementing use counts, and
2131   // if a definition has a 0 use count, place it in the available list.
2132   DecrementUseCounts(n,bb);
2133 }
2134 
2135 //------------------------------ComputeUseCount--------------------------------
2136 // This method sets the use count within a basic block.  We will ignore all
2137 // uses outside the current basic block.  As we are doing a backwards walk,
2138 // any node we reach that has a use count of 0 may be scheduled.  This also
2139 // avoids the problem of cyclic references from phi nodes, as long as phi
2140 // nodes are at the front of the basic block.  This method also initializes
2141 // the available list to the set of instructions that have no uses within this
2142 // basic block.
2143 void Scheduling::ComputeUseCount(const Block *bb) {
2144 #ifndef PRODUCT
2145   if (_cfg->C->trace_opto_output())
2146     tty->print("# -> ComputeUseCount\n");
2147 #endif
2148 
2149   // Clear the list of available and scheduled instructions, just in case
2150   _available.clear();
2151   _scheduled.clear();
2152 
2153   // No delay slot specified
2154   _unconditional_delay_slot = NULL;
2155 
2156 #ifdef ASSERT
2157   for( uint i=0; i < bb->_nodes.size(); i++ )
2158     assert( _uses[bb->_nodes[i]->_idx] == 0, "_use array not clean" );
2159 #endif
2160 
2161   // Force the _uses count to never go to zero for unscheduable pieces
2162   // of the block
2163   for( uint k = 0; k < _bb_start; k++ )
2164     _uses[bb->_nodes[k]->_idx] = 1;
2165   for( uint l = _bb_end; l < bb->_nodes.size(); l++ )
2166     _uses[bb->_nodes[l]->_idx] = 1;
2167 
2168   // Iterate backwards over the instructions in the block.  Don't count the
2169   // branch projections at end or the block header instructions.
2170   for( uint j = _bb_end-1; j >= _bb_start; j-- ) {
2171     Node *n = bb->_nodes[j];
2172     if( n->is_Proj() ) continue; // Projections handled another way
2173 
2174     // Account for all uses
2175     for ( uint k = 0; k < n->len(); k++ ) {
2176       Node *inp = n->in(k);
2177       if (!inp) continue;
2178       assert(inp != n, "no cycles allowed" );
2179       if( _bbs[inp->_idx] == bb ) { // Block-local use?
2180         if( inp->is_Proj() )    // Skip through Proj's
2181           inp = inp->in(0);
2182         ++_uses[inp->_idx];     // Count 1 block-local use
2183       }
2184     }
2185 
2186     // If this instruction has a 0 use count, then it is available
2187     if (!_uses[n->_idx]) {
2188       _current_latency[n->_idx] = _bundle_cycle_number;
2189       AddNodeToAvailableList(n);
2190     }
2191 
2192 #ifndef PRODUCT
2193     if (_cfg->C->trace_opto_output()) {
2194       tty->print("#   uses: %3d: ", _uses[n->_idx]);
2195       n->dump();
2196     }
2197 #endif
2198   }
2199 
2200 #ifndef PRODUCT
2201   if (_cfg->C->trace_opto_output())
2202     tty->print("# <- ComputeUseCount\n");
2203 #endif
2204 }
2205 
2206 // This routine performs scheduling on each basic block in reverse order,
2207 // using instruction latencies and taking into account function unit
2208 // availability.
2209 void Scheduling::DoScheduling() {
2210 #ifndef PRODUCT
2211   if (_cfg->C->trace_opto_output())
2212     tty->print("# -> DoScheduling\n");
2213 #endif
2214 
2215   Block *succ_bb = NULL;
2216   Block *bb;
2217 
2218   // Walk over all the basic blocks in reverse order
2219   for( int i=_cfg->_num_blocks-1; i >= 0; succ_bb = bb, i-- ) {
2220     bb = _cfg->_blocks[i];
2221 
2222 #ifndef PRODUCT
2223     if (_cfg->C->trace_opto_output()) {
2224       tty->print("#  Schedule BB#%03d (initial)\n", i);
2225       for (uint j = 0; j < bb->_nodes.size(); j++)
2226         bb->_nodes[j]->dump();
2227     }
2228 #endif
2229 
2230     // On the head node, skip processing
2231     if( bb == _cfg->_broot )
2232       continue;
2233 
2234     // Skip empty, connector blocks
2235     if (bb->is_connector())
2236       continue;
2237 
2238     // If the following block is not the sole successor of
2239     // this one, then reset the pipeline information
2240     if (bb->_num_succs != 1 || bb->non_connector_successor(0) != succ_bb) {
2241 #ifndef PRODUCT
2242       if (_cfg->C->trace_opto_output()) {
2243         tty->print("*** bundle start of next BB, node %d, for %d instructions\n",
2244                    _next_node->_idx, _bundle_instr_count);
2245       }
2246 #endif
2247       step_and_clear();
2248     }
2249 
2250     // Leave untouched the starting instruction, any Phis, a CreateEx node
2251     // or Top.  bb->_nodes[_bb_start] is the first schedulable instruction.
2252     _bb_end = bb->_nodes.size()-1;
2253     for( _bb_start=1; _bb_start <= _bb_end; _bb_start++ ) {
2254       Node *n = bb->_nodes[_bb_start];
2255       // Things not matched, like Phinodes and ProjNodes don't get scheduled.
2256       // Also, MachIdealNodes do not get scheduled
2257       if( !n->is_Mach() ) continue;     // Skip non-machine nodes
2258       MachNode *mach = n->as_Mach();
2259       int iop = mach->ideal_Opcode();
2260       if( iop == Op_CreateEx ) continue; // CreateEx is pinned
2261       if( iop == Op_Con ) continue;      // Do not schedule Top
2262       if( iop == Op_Node &&     // Do not schedule PhiNodes, ProjNodes
2263           mach->pipeline() == MachNode::pipeline_class() &&
2264           !n->is_SpillCopy() )  // Breakpoints, Prolog, etc
2265         continue;
2266       break;                    // Funny loop structure to be sure...
2267     }
2268     // Compute last "interesting" instruction in block - last instruction we
2269     // might schedule.  _bb_end points just after last schedulable inst.  We
2270     // normally schedule conditional branches (despite them being forced last
2271     // in the block), because they have delay slots we can fill.  Calls all
2272     // have their delay slots filled in the template expansions, so we don't
2273     // bother scheduling them.
2274     Node *last = bb->_nodes[_bb_end];
2275     if( last->is_Catch() ||
2276        // Exclude unreachable path case when Halt node is in a separate block.
2277        (_bb_end > 1 && last->is_Mach() && last->as_Mach()->ideal_Opcode() == Op_Halt) ) {
2278       // There must be a prior call.  Skip it.
2279       while( !bb->_nodes[--_bb_end]->is_Call() ) {
2280         assert( bb->_nodes[_bb_end]->is_Proj(), "skipping projections after expected call" );
2281       }
2282     } else if( last->is_MachNullCheck() ) {
2283       // Backup so the last null-checked memory instruction is
2284       // outside the schedulable range. Skip over the nullcheck,
2285       // projection, and the memory nodes.
2286       Node *mem = last->in(1);
2287       do {
2288         _bb_end--;
2289       } while (mem != bb->_nodes[_bb_end]);
2290     } else {
2291       // Set _bb_end to point after last schedulable inst.
2292       _bb_end++;
2293     }
2294 
2295     assert( _bb_start <= _bb_end, "inverted block ends" );
2296 
2297     // Compute the register antidependencies for the basic block
2298     ComputeRegisterAntidependencies(bb);
2299     if (_cfg->C->failing())  return;  // too many D-U pinch points
2300 
2301     // Compute intra-bb latencies for the nodes
2302     ComputeLocalLatenciesForward(bb);
2303 
2304     // Compute the usage within the block, and set the list of all nodes
2305     // in the block that have no uses within the block.
2306     ComputeUseCount(bb);
2307 
2308     // Schedule the remaining instructions in the block
2309     while ( _available.size() > 0 ) {
2310       Node *n = ChooseNodeToBundle();
2311       AddNodeToBundle(n,bb);
2312     }
2313 
2314     assert( _scheduled.size() == _bb_end - _bb_start, "wrong number of instructions" );
2315 #ifdef ASSERT
2316     for( uint l = _bb_start; l < _bb_end; l++ ) {
2317       Node *n = bb->_nodes[l];
2318       uint m;
2319       for( m = 0; m < _bb_end-_bb_start; m++ )
2320         if( _scheduled[m] == n )
2321           break;
2322       assert( m < _bb_end-_bb_start, "instruction missing in schedule" );
2323     }
2324 #endif
2325 
2326     // Now copy the instructions (in reverse order) back to the block
2327     for ( uint k = _bb_start; k < _bb_end; k++ )
2328       bb->_nodes.map(k, _scheduled[_bb_end-k-1]);
2329 
2330 #ifndef PRODUCT
2331     if (_cfg->C->trace_opto_output()) {
2332       tty->print("#  Schedule BB#%03d (final)\n", i);
2333       uint current = 0;
2334       for (uint j = 0; j < bb->_nodes.size(); j++) {
2335         Node *n = bb->_nodes[j];
2336         if( valid_bundle_info(n) ) {
2337           Bundle *bundle = node_bundling(n);
2338           if (bundle->instr_count() > 0 || bundle->flags() > 0) {
2339             tty->print("*** Bundle: ");
2340             bundle->dump();
2341           }
2342           n->dump();
2343         }
2344       }
2345     }
2346 #endif
2347 #ifdef ASSERT
2348   verify_good_schedule(bb,"after block local scheduling");
2349 #endif
2350   }
2351 
2352 #ifndef PRODUCT
2353   if (_cfg->C->trace_opto_output())
2354     tty->print("# <- DoScheduling\n");
2355 #endif
2356 
2357   // Record final node-bundling array location
2358   _regalloc->C->set_node_bundling_base(_node_bundling_base);
2359 
2360 } // end DoScheduling
2361 
2362 //------------------------------verify_good_schedule---------------------------
2363 // Verify that no live-range used in the block is killed in the block by a
2364 // wrong DEF.  This doesn't verify live-ranges that span blocks.
2365 
2366 // Check for edge existence.  Used to avoid adding redundant precedence edges.
2367 static bool edge_from_to( Node *from, Node *to ) {
2368   for( uint i=0; i<from->len(); i++ )
2369     if( from->in(i) == to )
2370       return true;
2371   return false;
2372 }
2373 
2374 #ifdef ASSERT
2375 //------------------------------verify_do_def----------------------------------
2376 void Scheduling::verify_do_def( Node *n, OptoReg::Name def, const char *msg ) {
2377   // Check for bad kills
2378   if( OptoReg::is_valid(def) ) { // Ignore stores & control flow
2379     Node *prior_use = _reg_node[def];
2380     if( prior_use && !edge_from_to(prior_use,n) ) {
2381       tty->print("%s = ",OptoReg::as_VMReg(def)->name());
2382       n->dump();
2383       tty->print_cr("...");
2384       prior_use->dump();
2385       assert_msg(edge_from_to(prior_use,n),msg);
2386     }
2387     _reg_node.map(def,NULL); // Kill live USEs
2388   }
2389 }
2390 
2391 //------------------------------verify_good_schedule---------------------------
2392 void Scheduling::verify_good_schedule( Block *b, const char *msg ) {
2393 
2394   // Zap to something reasonable for the verify code
2395   _reg_node.clear();
2396 
2397   // Walk over the block backwards.  Check to make sure each DEF doesn't
2398   // kill a live value (other than the one it's supposed to).  Add each
2399   // USE to the live set.
2400   for( uint i = b->_nodes.size()-1; i >= _bb_start; i-- ) {
2401     Node *n = b->_nodes[i];
2402     int n_op = n->Opcode();
2403     if( n_op == Op_MachProj && n->ideal_reg() == MachProjNode::fat_proj ) {
2404       // Fat-proj kills a slew of registers
2405       RegMask rm = n->out_RegMask();// Make local copy
2406       while( rm.is_NotEmpty() ) {
2407         OptoReg::Name kill = rm.find_first_elem();
2408         rm.Remove(kill);
2409         verify_do_def( n, kill, msg );
2410       }
2411     } else if( n_op != Op_Node ) { // Avoid brand new antidependence nodes
2412       // Get DEF'd registers the normal way
2413       verify_do_def( n, _regalloc->get_reg_first(n), msg );
2414       verify_do_def( n, _regalloc->get_reg_second(n), msg );
2415     }
2416 
2417     // Now make all USEs live
2418     for( uint i=1; i<n->req(); i++ ) {
2419       Node *def = n->in(i);
2420       assert(def != 0, "input edge required");
2421       OptoReg::Name reg_lo = _regalloc->get_reg_first(def);
2422       OptoReg::Name reg_hi = _regalloc->get_reg_second(def);
2423       if( OptoReg::is_valid(reg_lo) ) {
2424         assert_msg(!_reg_node[reg_lo] || edge_from_to(_reg_node[reg_lo],def), msg );
2425         _reg_node.map(reg_lo,n);
2426       }
2427       if( OptoReg::is_valid(reg_hi) ) {
2428         assert_msg(!_reg_node[reg_hi] || edge_from_to(_reg_node[reg_hi],def), msg );
2429         _reg_node.map(reg_hi,n);
2430       }
2431     }
2432 
2433   }
2434 
2435   // Zap to something reasonable for the Antidependence code
2436   _reg_node.clear();
2437 }
2438 #endif
2439 
2440 // Conditionally add precedence edges.  Avoid putting edges on Projs.
2441 static void add_prec_edge_from_to( Node *from, Node *to ) {
2442   if( from->is_Proj() ) {       // Put precedence edge on Proj's input
2443     assert( from->req() == 1 && (from->len() == 1 || from->in(1)==0), "no precedence edges on projections" );
2444     from = from->in(0);
2445   }
2446   if( from != to &&             // No cycles (for things like LD L0,[L0+4] )
2447       !edge_from_to( from, to ) ) // Avoid duplicate edge
2448     from->add_prec(to);
2449 }
2450 
2451 //------------------------------anti_do_def------------------------------------
2452 void Scheduling::anti_do_def( Block *b, Node *def, OptoReg::Name def_reg, int is_def ) {
2453   if( !OptoReg::is_valid(def_reg) ) // Ignore stores & control flow
2454     return;
2455 
2456   Node *pinch = _reg_node[def_reg]; // Get pinch point
2457   if( !pinch || _bbs[pinch->_idx] != b || // No pinch-point yet?
2458       is_def ) {    // Check for a true def (not a kill)
2459     _reg_node.map(def_reg,def); // Record def/kill as the optimistic pinch-point
2460     return;
2461   }
2462 
2463   Node *kill = def;             // Rename 'def' to more descriptive 'kill'
2464   debug_only( def = (Node*)0xdeadbeef; )
2465 
2466   // After some number of kills there _may_ be a later def
2467   Node *later_def = NULL;
2468 
2469   // Finding a kill requires a real pinch-point.
2470   // Check for not already having a pinch-point.
2471   // Pinch points are Op_Node's.
2472   if( pinch->Opcode() != Op_Node ) { // Or later-def/kill as pinch-point?
2473     later_def = pinch;            // Must be def/kill as optimistic pinch-point
2474     if ( _pinch_free_list.size() > 0) {
2475       pinch = _pinch_free_list.pop();
2476     } else {
2477       pinch = new (_cfg->C, 1) Node(1); // Pinch point to-be
2478     }
2479     if (pinch->_idx >= _regalloc->node_regs_max_index()) {
2480       _cfg->C->record_method_not_compilable("too many D-U pinch points");
2481       return;
2482     }
2483     _bbs.map(pinch->_idx,b);      // Pretend it's valid in this block (lazy init)
2484     _reg_node.map(def_reg,pinch); // Record pinch-point
2485     //_regalloc->set_bad(pinch->_idx); // Already initialized this way.
2486     if( later_def->outcnt() == 0 || later_def->ideal_reg() == MachProjNode::fat_proj ) { // Distinguish def from kill
2487       pinch->init_req(0, _cfg->C->top());     // set not NULL for the next call
2488       add_prec_edge_from_to(later_def,pinch); // Add edge from kill to pinch
2489       later_def = NULL;           // and no later def
2490     }
2491     pinch->set_req(0,later_def);  // Hook later def so we can find it
2492   } else {                        // Else have valid pinch point
2493     if( pinch->in(0) )            // If there is a later-def
2494       later_def = pinch->in(0);   // Get it
2495   }
2496 
2497   // Add output-dependence edge from later def to kill
2498   if( later_def )               // If there is some original def
2499     add_prec_edge_from_to(later_def,kill); // Add edge from def to kill
2500 
2501   // See if current kill is also a use, and so is forced to be the pinch-point.
2502   if( pinch->Opcode() == Op_Node ) {
2503     Node *uses = kill->is_Proj() ? kill->in(0) : kill;
2504     for( uint i=1; i<uses->req(); i++ ) {
2505       if( _regalloc->get_reg_first(uses->in(i)) == def_reg ||
2506           _regalloc->get_reg_second(uses->in(i)) == def_reg ) {
2507         // Yes, found a use/kill pinch-point
2508         pinch->set_req(0,NULL);  //
2509         pinch->replace_by(kill); // Move anti-dep edges up
2510         pinch = kill;
2511         _reg_node.map(def_reg,pinch);
2512         return;
2513       }
2514     }
2515   }
2516 
2517   // Add edge from kill to pinch-point
2518   add_prec_edge_from_to(kill,pinch);
2519 }
2520 
2521 //------------------------------anti_do_use------------------------------------
2522 void Scheduling::anti_do_use( Block *b, Node *use, OptoReg::Name use_reg ) {
2523   if( !OptoReg::is_valid(use_reg) ) // Ignore stores & control flow
2524     return;
2525   Node *pinch = _reg_node[use_reg]; // Get pinch point
2526   // Check for no later def_reg/kill in block
2527   if( pinch && _bbs[pinch->_idx] == b &&
2528       // Use has to be block-local as well
2529       _bbs[use->_idx] == b ) {
2530     if( pinch->Opcode() == Op_Node && // Real pinch-point (not optimistic?)
2531         pinch->req() == 1 ) {   // pinch not yet in block?
2532       pinch->del_req(0);        // yank pointer to later-def, also set flag
2533       // Insert the pinch-point in the block just after the last use
2534       b->_nodes.insert(b->find_node(use)+1,pinch);
2535       _bb_end++;                // Increase size scheduled region in block
2536     }
2537 
2538     add_prec_edge_from_to(pinch,use);
2539   }
2540 }
2541 
2542 //------------------------------ComputeRegisterAntidependences-----------------
2543 // We insert antidependences between the reads and following write of
2544 // allocated registers to prevent illegal code motion. Hopefully, the
2545 // number of added references should be fairly small, especially as we
2546 // are only adding references within the current basic block.
2547 void Scheduling::ComputeRegisterAntidependencies(Block *b) {
2548 
2549 #ifdef ASSERT
2550   verify_good_schedule(b,"before block local scheduling");
2551 #endif
2552 
2553   // A valid schedule, for each register independently, is an endless cycle
2554   // of: a def, then some uses (connected to the def by true dependencies),
2555   // then some kills (defs with no uses), finally the cycle repeats with a new
2556   // def.  The uses are allowed to float relative to each other, as are the
2557   // kills.  No use is allowed to slide past a kill (or def).  This requires
2558   // antidependencies between all uses of a single def and all kills that
2559   // follow, up to the next def.  More edges are redundant, because later defs
2560   // & kills are already serialized with true or antidependencies.  To keep
2561   // the edge count down, we add a 'pinch point' node if there's more than
2562   // one use or more than one kill/def.
2563 
2564   // We add dependencies in one bottom-up pass.
2565 
2566   // For each instruction we handle it's DEFs/KILLs, then it's USEs.
2567 
2568   // For each DEF/KILL, we check to see if there's a prior DEF/KILL for this
2569   // register.  If not, we record the DEF/KILL in _reg_node, the
2570   // register-to-def mapping.  If there is a prior DEF/KILL, we insert a
2571   // "pinch point", a new Node that's in the graph but not in the block.
2572   // We put edges from the prior and current DEF/KILLs to the pinch point.
2573   // We put the pinch point in _reg_node.  If there's already a pinch point
2574   // we merely add an edge from the current DEF/KILL to the pinch point.
2575 
2576   // After doing the DEF/KILLs, we handle USEs.  For each used register, we
2577   // put an edge from the pinch point to the USE.
2578 
2579   // To be expedient, the _reg_node array is pre-allocated for the whole
2580   // compilation.  _reg_node is lazily initialized; it either contains a NULL,
2581   // or a valid def/kill/pinch-point, or a leftover node from some prior
2582   // block.  Leftover node from some prior block is treated like a NULL (no
2583   // prior def, so no anti-dependence needed).  Valid def is distinguished by
2584   // it being in the current block.
2585   bool fat_proj_seen = false;
2586   uint last_safept = _bb_end-1;
2587   Node* end_node         = (_bb_end-1 >= _bb_start) ? b->_nodes[last_safept] : NULL;
2588   Node* last_safept_node = end_node;
2589   for( uint i = _bb_end-1; i >= _bb_start; i-- ) {
2590     Node *n = b->_nodes[i];
2591     int is_def = n->outcnt();   // def if some uses prior to adding precedence edges
2592     if( n->Opcode() == Op_MachProj && n->ideal_reg() == MachProjNode::fat_proj ) {
2593       // Fat-proj kills a slew of registers
2594       // This can add edges to 'n' and obscure whether or not it was a def,
2595       // hence the is_def flag.
2596       fat_proj_seen = true;
2597       RegMask rm = n->out_RegMask();// Make local copy
2598       while( rm.is_NotEmpty() ) {
2599         OptoReg::Name kill = rm.find_first_elem();
2600         rm.Remove(kill);
2601         anti_do_def( b, n, kill, is_def );
2602       }
2603     } else {
2604       // Get DEF'd registers the normal way
2605       anti_do_def( b, n, _regalloc->get_reg_first(n), is_def );
2606       anti_do_def( b, n, _regalloc->get_reg_second(n), is_def );
2607     }
2608 
2609     // Check each register used by this instruction for a following DEF/KILL
2610     // that must occur afterward and requires an anti-dependence edge.
2611     for( uint j=0; j<n->req(); j++ ) {
2612       Node *def = n->in(j);
2613       if( def ) {
2614         assert( def->Opcode() != Op_MachProj || def->ideal_reg() != MachProjNode::fat_proj, "" );
2615         anti_do_use( b, n, _regalloc->get_reg_first(def) );
2616         anti_do_use( b, n, _regalloc->get_reg_second(def) );
2617       }
2618     }
2619     // Do not allow defs of new derived values to float above GC
2620     // points unless the base is definitely available at the GC point.
2621 
2622     Node *m = b->_nodes[i];
2623 
2624     // Add precedence edge from following safepoint to use of derived pointer
2625     if( last_safept_node != end_node &&
2626         m != last_safept_node) {
2627       for (uint k = 1; k < m->req(); k++) {
2628         const Type *t = m->in(k)->bottom_type();
2629         if( t->isa_oop_ptr() &&
2630             t->is_ptr()->offset() != 0 ) {
2631           last_safept_node->add_prec( m );
2632           break;
2633         }
2634       }
2635     }
2636 
2637     if( n->jvms() ) {           // Precedence edge from derived to safept
2638       // Check if last_safept_node was moved by pinch-point insertion in anti_do_use()
2639       if( b->_nodes[last_safept] != last_safept_node ) {
2640         last_safept = b->find_node(last_safept_node);
2641       }
2642       for( uint j=last_safept; j > i; j-- ) {
2643         Node *mach = b->_nodes[j];
2644         if( mach->is_Mach() && mach->as_Mach()->ideal_Opcode() == Op_AddP )
2645           mach->add_prec( n );
2646       }
2647       last_safept = i;
2648       last_safept_node = m;
2649     }
2650   }
2651 
2652   if (fat_proj_seen) {
2653     // Garbage collect pinch nodes that were not consumed.
2654     // They are usually created by a fat kill MachProj for a call.
2655     garbage_collect_pinch_nodes();
2656   }
2657 }
2658 
2659 //------------------------------garbage_collect_pinch_nodes-------------------------------
2660 
2661 // Garbage collect pinch nodes for reuse by other blocks.
2662 //
2663 // The block scheduler's insertion of anti-dependence
2664 // edges creates many pinch nodes when the block contains
2665 // 2 or more Calls.  A pinch node is used to prevent a
2666 // combinatorial explosion of edges.  If a set of kills for a
2667 // register is anti-dependent on a set of uses (or defs), rather
2668 // than adding an edge in the graph between each pair of kill
2669 // and use (or def), a pinch is inserted between them:
2670 //
2671 //            use1   use2  use3
2672 //                \   |   /
2673 //                 \  |  /
2674 //                  pinch
2675 //                 /  |  \
2676 //                /   |   \
2677 //            kill1 kill2 kill3
2678 //
2679 // One pinch node is created per register killed when
2680 // the second call is encountered during a backwards pass
2681 // over the block.  Most of these pinch nodes are never
2682 // wired into the graph because the register is never
2683 // used or def'ed in the block.
2684 //
2685 void Scheduling::garbage_collect_pinch_nodes() {
2686 #ifndef PRODUCT
2687     if (_cfg->C->trace_opto_output()) tty->print("Reclaimed pinch nodes:");
2688 #endif
2689     int trace_cnt = 0;
2690     for (uint k = 0; k < _reg_node.Size(); k++) {
2691       Node* pinch = _reg_node[k];
2692       if (pinch != NULL && pinch->Opcode() == Op_Node &&
2693           // no predecence input edges
2694           (pinch->req() == pinch->len() || pinch->in(pinch->req()) == NULL) ) {
2695         cleanup_pinch(pinch);
2696         _pinch_free_list.push(pinch);
2697         _reg_node.map(k, NULL);
2698 #ifndef PRODUCT
2699         if (_cfg->C->trace_opto_output()) {
2700           trace_cnt++;
2701           if (trace_cnt > 40) {
2702             tty->print("\n");
2703             trace_cnt = 0;
2704           }
2705           tty->print(" %d", pinch->_idx);
2706         }
2707 #endif
2708       }
2709     }
2710 #ifndef PRODUCT
2711     if (_cfg->C->trace_opto_output()) tty->print("\n");
2712 #endif
2713 }
2714 
2715 // Clean up a pinch node for reuse.
2716 void Scheduling::cleanup_pinch( Node *pinch ) {
2717   assert (pinch && pinch->Opcode() == Op_Node && pinch->req() == 1, "just checking");
2718 
2719   for (DUIterator_Last imin, i = pinch->last_outs(imin); i >= imin; ) {
2720     Node* use = pinch->last_out(i);
2721     uint uses_found = 0;
2722     for (uint j = use->req(); j < use->len(); j++) {
2723       if (use->in(j) == pinch) {
2724         use->rm_prec(j);
2725         uses_found++;
2726       }
2727     }
2728     assert(uses_found > 0, "must be a precedence edge");
2729     i -= uses_found;    // we deleted 1 or more copies of this edge
2730   }
2731   // May have a later_def entry
2732   pinch->set_req(0, NULL);
2733 }
2734 
2735 //------------------------------print_statistics-------------------------------
2736 #ifndef PRODUCT
2737 
2738 void Scheduling::dump_available() const {
2739   tty->print("#Availist  ");
2740   for (uint i = 0; i < _available.size(); i++)
2741     tty->print(" N%d/l%d", _available[i]->_idx,_current_latency[_available[i]->_idx]);
2742   tty->cr();
2743 }
2744 
2745 // Print Scheduling Statistics
2746 void Scheduling::print_statistics() {
2747   // Print the size added by nops for bundling
2748   tty->print("Nops added %d bytes to total of %d bytes",
2749     _total_nop_size, _total_method_size);
2750   if (_total_method_size > 0)
2751     tty->print(", for %.2f%%",
2752       ((double)_total_nop_size) / ((double) _total_method_size) * 100.0);
2753   tty->print("\n");
2754 
2755   // Print the number of branch shadows filled
2756   if (Pipeline::_branch_has_delay_slot) {
2757     tty->print("Of %d branches, %d had unconditional delay slots filled",
2758       _total_branches, _total_unconditional_delays);
2759     if (_total_branches > 0)
2760       tty->print(", for %.2f%%",
2761         ((double)_total_unconditional_delays) / ((double)_total_branches) * 100.0);
2762     tty->print("\n");
2763   }
2764 
2765   uint total_instructions = 0, total_bundles = 0;
2766 
2767   for (uint i = 1; i <= Pipeline::_max_instrs_per_cycle; i++) {
2768     uint bundle_count   = _total_instructions_per_bundle[i];
2769     total_instructions += bundle_count * i;
2770     total_bundles      += bundle_count;
2771   }
2772 
2773   if (total_bundles > 0)
2774     tty->print("Average ILP (excluding nops) is %.2f\n",
2775       ((double)total_instructions) / ((double)total_bundles));
2776 }
2777 #endif