1 /*
   2  * Copyright (c) 1998, 2025, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "asm/macroAssembler.inline.hpp"
  26 #include "gc/shared/gc_globals.hpp"
  27 #include "memory/allocation.inline.hpp"
  28 #include "oops/compressedOops.hpp"
  29 #include "opto/ad.hpp"
  30 #include "opto/block.hpp"
  31 #include "opto/c2compiler.hpp"
  32 #include "opto/callnode.hpp"
  33 #include "opto/cfgnode.hpp"
  34 #include "opto/machnode.hpp"
  35 #include "opto/runtime.hpp"
  36 #include "opto/chaitin.hpp"
  37 #include "runtime/os.inline.hpp"
  38 #include "runtime/sharedRuntime.hpp"
  39 
  40 // Optimization - Graph Style
  41 
  42 // Check whether val is not-null-decoded compressed oop,
  43 // i.e. will grab into the base of the heap if it represents null.
  44 static bool accesses_heap_base_zone(Node *val) {
  45   if (CompressedOops::base() != nullptr) { // Implies UseCompressedOops.
  46     if (val && val->is_Mach()) {
  47       if (val->as_Mach()->ideal_Opcode() == Op_DecodeN) {
  48         // This assumes all Decodes with TypePtr::NotNull are matched to nodes that
  49         // decode null to point to the heap base (Decode_NN).
  50         if (val->bottom_type()->is_oopptr()->ptr() == TypePtr::NotNull) {
  51           return true;
  52         }
  53       }
  54       // Must recognize load operation with Decode matched in memory operand.
  55       // We should not reach here except for PPC/AIX, as os::zero_page_read_protected()
  56       // returns true everywhere else. On PPC, no such memory operands
  57       // exist, therefore we did not yet implement a check for such operands.
  58       NOT_AIX(Unimplemented());
  59     }
  60   }
  61   return false;
  62 }
  63 
  64 static bool needs_explicit_null_check_for_read(Node *val) {
  65   // On some OSes (AIX) the page at address 0 is only write protected.
  66   // If so, only Store operations will trap.
  67   if (os::zero_page_read_protected()) {
  68     return false;  // Implicit null check will work.
  69   }
  70   // Also a read accessing the base of a heap-based compressed heap will trap.
  71   if (accesses_heap_base_zone(val) &&         // Hits the base zone page.
  72       CompressedOops::use_implicit_null_checks()) { // Base zone page is protected.
  73     return false;
  74   }
  75 
  76   return true;
  77 }
  78 
  79 //------------------------------implicit_null_check----------------------------
  80 // Detect implicit-null-check opportunities.  Basically, find null checks
  81 // with suitable memory ops nearby.  Use the memory op to do the null check.
  82 // I can generate a memory op if there is not one nearby.
  83 // The proj is the control projection for the not-null case.
  84 // The val is the pointer being checked for nullness or
  85 // decodeHeapOop_not_null node if it did not fold into address.
  86 void PhaseCFG::implicit_null_check(Block* block, Node *proj, Node *val, int allowed_reasons) {
  87   // Assume if null check need for 0 offset then always needed
  88   // Intel solaris doesn't support any null checks yet and no
  89   // mechanism exists (yet) to set the switches at an os_cpu level
  90   if( !ImplicitNullChecks || MacroAssembler::needs_explicit_null_check(0)) return;
  91 
  92   // Make sure the ptr-is-null path appears to be uncommon!
  93   float f = block->end()->as_MachIf()->_prob;
  94   if( proj->Opcode() == Op_IfTrue ) f = 1.0f - f;
  95   if( f > PROB_UNLIKELY_MAG(4) ) return;
  96 
  97   uint bidx = 0;                // Capture index of value into memop
  98   bool was_store;               // Memory op is a store op
  99 
 100   // Get the successor block for if the test ptr is non-null
 101   Block* not_null_block;  // this one goes with the proj
 102   Block* null_block;
 103   if (block->get_node(block->number_of_nodes()-1) == proj) {
 104     null_block     = block->_succs[0];
 105     not_null_block = block->_succs[1];
 106   } else {
 107     assert(block->get_node(block->number_of_nodes()-2) == proj, "proj is one or the other");
 108     not_null_block = block->_succs[0];
 109     null_block     = block->_succs[1];
 110   }
 111   while (null_block->is_Empty() == Block::empty_with_goto) {
 112     null_block     = null_block->_succs[0];
 113   }
 114 
 115   // Search the exception block for an uncommon trap.
 116   // (See Parse::do_if and Parse::do_ifnull for the reason
 117   // we need an uncommon trap.  Briefly, we need a way to
 118   // detect failure of this optimization, as in 6366351.)
 119   {
 120     bool found_trap = false;
 121     for (uint i1 = 0; i1 < null_block->number_of_nodes(); i1++) {
 122       Node* nn = null_block->get_node(i1);
 123       if (nn->is_MachCall() &&
 124           nn->as_MachCall()->entry_point() == OptoRuntime::uncommon_trap_blob()->entry_point()) {
 125         const Type* trtype = nn->in(TypeFunc::Parms)->bottom_type();
 126         if (trtype->isa_int() && trtype->is_int()->is_con()) {
 127           jint tr_con = trtype->is_int()->get_con();
 128           Deoptimization::DeoptReason reason = Deoptimization::trap_request_reason(tr_con);
 129           Deoptimization::DeoptAction action = Deoptimization::trap_request_action(tr_con);
 130           assert((int)reason < (int)BitsPerInt, "recode bit map");
 131           if (is_set_nth_bit(allowed_reasons, (int) reason)
 132               && action != Deoptimization::Action_none) {
 133             // This uncommon trap is sure to recompile, eventually.
 134             // When that happens, C->too_many_traps will prevent
 135             // this transformation from happening again.
 136             found_trap = true;
 137           }
 138         }
 139         break;
 140       }
 141     }
 142     if (!found_trap) {
 143       // We did not find an uncommon trap.
 144       return;
 145     }
 146   }
 147 
 148   // Check for decodeHeapOop_not_null node which did not fold into address
 149   bool is_decoden = ((intptr_t)val) & 1;
 150   val = (Node*)(((intptr_t)val) & ~1);
 151 
 152   assert(!is_decoden ||
 153          ((val->in(0) == nullptr) && val->is_Mach() &&
 154           (val->as_Mach()->ideal_Opcode() == Op_DecodeN)), "sanity");
 155 
 156   // Search the successor block for a load or store who's base value is also
 157   // the tested value.  There may be several.
 158   MachNode *best = nullptr;        // Best found so far
 159   for (DUIterator i = val->outs(); val->has_out(i); i++) {
 160     Node *m = val->out(i);
 161     if( !m->is_Mach() ) continue;
 162     MachNode *mach = m->as_Mach();
 163     if (mach->barrier_data() != 0) {
 164       // Using memory accesses with barriers to perform implicit null checks is
 165       // not supported. These operations might expand into multiple assembly
 166       // instructions during code emission, including new memory accesses (e.g.
 167       // in G1's pre-barrier), which would invalidate the implicit null
 168       // exception table.
 169       continue;
 170     }
 171     was_store = false;
 172     int iop = mach->ideal_Opcode();
 173     switch( iop ) {
 174     case Op_LoadB:
 175     case Op_LoadUB:
 176     case Op_LoadUS:
 177     case Op_LoadD:
 178     case Op_LoadF:
 179     case Op_LoadI:
 180     case Op_LoadL:
 181     case Op_LoadP:
 182     case Op_LoadN:
 183     case Op_LoadS:
 184     case Op_LoadKlass:
 185     case Op_LoadNKlass:
 186     case Op_LoadRange:
 187     case Op_LoadD_unaligned:
 188     case Op_LoadL_unaligned:
 189       assert(mach->in(2) == val, "should be address");
 190       break;
 191     case Op_StoreB:
 192     case Op_StoreC:
 193     case Op_StoreD:
 194     case Op_StoreF:
 195     case Op_StoreI:
 196     case Op_StoreL:
 197     case Op_StoreLSpecial:
 198     case Op_StoreP:
 199     case Op_StoreN:
 200     case Op_StoreNKlass:
 201       was_store = true;         // Memory op is a store op
 202       // Stores will have their address in slot 2 (memory in slot 1).
 203       // If the value being nul-checked is in another slot, it means we
 204       // are storing the checked value, which does NOT check the value!
 205       if( mach->in(2) != val ) continue;
 206       break;                    // Found a memory op?
 207     case Op_StrComp:
 208     case Op_StrEquals:
 209     case Op_StrIndexOf:
 210     case Op_StrIndexOfChar:
 211     case Op_AryEq:
 212     case Op_VectorizedHashCode:
 213     case Op_StrInflatedCopy:
 214     case Op_StrCompressedCopy:
 215     case Op_EncodeISOArray:
 216     case Op_CountPositives:
 217       // Not a legit memory op for implicit null check regardless of
 218       // embedded loads
 219       continue;
 220     default:                    // Also check for embedded loads
 221       if( !mach->needs_anti_dependence_check() )
 222         continue;               // Not an memory op; skip it
 223       if( must_clone[iop] ) {
 224         // Do not move nodes which produce flags because
 225         // RA will try to clone it to place near branch and
 226         // it will cause recompilation, see clone_node().
 227         continue;
 228       }
 229       {
 230         // Check that value is used in memory address in
 231         // instructions with embedded load (CmpP val1,(val2+off)).
 232         Node* base;
 233         Node* index;
 234         const MachOper* oper = mach->memory_inputs(base, index);
 235         if (oper == nullptr || oper == (MachOper*)-1) {
 236           continue;             // Not an memory op; skip it
 237         }
 238         if (val == base ||
 239             (val == index && val->bottom_type()->isa_narrowoop())) {
 240           break;                // Found it
 241         } else {
 242           continue;             // Skip it
 243         }
 244       }
 245       break;
 246     }
 247 
 248     // On some OSes (AIX) the page at address 0 is only write protected.
 249     // If so, only Store operations will trap.
 250     // But a read accessing the base of a heap-based compressed heap will trap.
 251     if (!was_store && needs_explicit_null_check_for_read(val)) {
 252       continue;
 253     }
 254 
 255     // Check that node's control edge is not-null block's head or dominates it,
 256     // otherwise we can't hoist it because there are other control dependencies.
 257     Node* ctrl = mach->in(0);
 258     if (ctrl != nullptr && !(ctrl == not_null_block->head() ||
 259         get_block_for_node(ctrl)->dominates(not_null_block))) {
 260       continue;
 261     }
 262 
 263     // check if the offset is not too high for implicit exception
 264     {
 265       intptr_t offset = 0;
 266       const TypePtr *adr_type = nullptr;  // Do not need this return value here
 267       const Node* base = mach->get_base_and_disp(offset, adr_type);
 268       if (base == nullptr || base == NodeSentinel) {
 269         // Narrow oop address doesn't have base, only index.
 270         // Give up if offset is beyond page size or if heap base is not protected.
 271         if (val->bottom_type()->isa_narrowoop() &&
 272             (MacroAssembler::needs_explicit_null_check(offset) ||
 273              !CompressedOops::use_implicit_null_checks()))
 274           continue;
 275         // cannot reason about it; is probably not implicit null exception
 276       } else {
 277         const TypePtr* tptr;
 278         if ((UseCompressedOops && CompressedOops::shift() == 0) ||
 279             (UseCompressedClassPointers && CompressedKlassPointers::shift() == 0)) {
 280           // 32-bits narrow oop can be the base of address expressions
 281           tptr = base->get_ptr_type();
 282         } else {
 283           // only regular oops are expected here
 284           tptr = base->bottom_type()->is_ptr();
 285         }
 286         // Give up if offset is not a compile-time constant.
 287         if (offset == Type::OffsetBot || tptr->offset() == Type::OffsetBot)
 288           continue;
 289         offset += tptr->offset(); // correct if base is offsetted
 290         // Give up if reference is beyond page size.
 291         if (MacroAssembler::needs_explicit_null_check(offset))
 292           continue;
 293         // Give up if base is a decode node and the heap base is not protected.
 294         if (base->is_Mach() && base->as_Mach()->ideal_Opcode() == Op_DecodeN &&
 295             !CompressedOops::use_implicit_null_checks())
 296           continue;
 297       }
 298     }
 299 
 300     // Check ctrl input to see if the null-check dominates the memory op
 301     Block *cb = get_block_for_node(mach);
 302     cb = cb->_idom;             // Always hoist at least 1 block
 303     if( !was_store ) {          // Stores can be hoisted only one block
 304       while( cb->_dom_depth > (block->_dom_depth + 1))
 305         cb = cb->_idom;         // Hoist loads as far as we want
 306       // The non-null-block should dominate the memory op, too. Live
 307       // range spilling will insert a spill in the non-null-block if it is
 308       // needs to spill the memory op for an implicit null check.
 309       if (cb->_dom_depth == (block->_dom_depth + 1)) {
 310         if (cb != not_null_block) continue;
 311         cb = cb->_idom;
 312       }
 313     }
 314     if( cb != block ) continue;
 315 
 316     // Found a memory user; see if it can be hoisted to check-block
 317     uint vidx = 0;              // Capture index of value into memop
 318     uint j;
 319     for( j = mach->req()-1; j > 0; j-- ) {
 320       if( mach->in(j) == val ) {
 321         vidx = j;
 322         // Ignore DecodeN val which could be hoisted to where needed.
 323         if( is_decoden ) continue;
 324       }
 325       // Block of memory-op input
 326       Block* inb = get_block_for_node(mach->in(j));
 327       if (mach->in(j)->is_Con() && mach->in(j)->req() == 1 && inb == get_block_for_node(mach)) {
 328         // Ignore constant loads scheduled in the same block (we can simply hoist them as well)
 329         continue;
 330       }
 331       Block *b = block;          // Start from nul check
 332       while( b != inb && b->_dom_depth > inb->_dom_depth )
 333         b = b->_idom;           // search upwards for input
 334       // See if input dominates null check
 335       if( b != inb )
 336         break;
 337     }
 338     if( j > 0 )
 339       continue;
 340     Block *mb = get_block_for_node(mach);
 341     // Hoisting stores requires more checks for the anti-dependence case.
 342     // Give up hoisting if we have to move the store past any load.
 343     if (was_store) {
 344        // Make sure control does not do a merge (would have to check allpaths)
 345        if (mb->num_preds() != 2) {
 346          continue;
 347        }
 348        // mach is a store, hence block is the immediate dominator of mb.
 349        // Due to the null-check shape of block (where its successors cannot re-join),
 350        // block must be the direct predecessor of mb.
 351        assert(get_block_for_node(mb->pred(1)) == block, "Unexpected predecessor block");
 352        uint k;
 353        uint num_nodes = mb->number_of_nodes();
 354        for (k = 1; k < num_nodes; k++) {
 355          Node *n = mb->get_node(k);
 356          if (n->needs_anti_dependence_check() &&
 357              n->in(LoadNode::Memory) == mach->in(StoreNode::Memory)) {
 358            break;              // Found anti-dependent load
 359          }
 360        }
 361        if (k < num_nodes) {
 362          continue;             // Found anti-dependent load
 363        }
 364     }
 365 
 366     // Make sure this memory op is not already being used for a NullCheck
 367     Node *e = mb->end();
 368     if( e->is_MachNullCheck() && e->in(1) == mach )
 369       continue;                 // Already being used as a null check
 370 
 371     // Found a candidate!  Pick one with least dom depth - the highest
 372     // in the dom tree should be closest to the null check.
 373     if (best == nullptr || get_block_for_node(mach)->_dom_depth < get_block_for_node(best)->_dom_depth) {
 374       best = mach;
 375       bidx = vidx;
 376     }
 377   }
 378   // No candidate!
 379   if (best == nullptr) {
 380     return;
 381   }
 382 
 383   // ---- Found an implicit null check
 384 #ifndef PRODUCT
 385   extern uint implicit_null_checks;
 386   implicit_null_checks++;
 387 #endif
 388 
 389   if( is_decoden ) {
 390     // Check if we need to hoist decodeHeapOop_not_null first.
 391     Block *valb = get_block_for_node(val);
 392     if( block != valb && block->_dom_depth < valb->_dom_depth ) {
 393       // Hoist it up to the end of the test block together with its inputs if they exist.
 394       for (uint i = 2; i < val->req(); i++) {
 395         // DecodeN has 2 regular inputs + optional MachTemp or load Base inputs.
 396         Node *temp = val->in(i);
 397         Block *tempb = get_block_for_node(temp);
 398         if (!tempb->dominates(block)) {
 399           assert(block->dominates(tempb), "sanity check: temp node placement");
 400           // We only expect nodes without further inputs, like MachTemp or load Base.
 401           assert(temp->req() == 0 || (temp->req() == 1 && temp->in(0) == (Node*)C->root()),
 402                  "need for recursive hoisting not expected");
 403           tempb->find_remove(temp);
 404           block->add_inst(temp);
 405           map_node_to_block(temp, block);
 406         }
 407       }
 408       valb->find_remove(val);
 409       block->add_inst(val);
 410       map_node_to_block(val, block);
 411       // DecodeN on x86 may kill flags. Check for flag-killing projections
 412       // that also need to be hoisted.
 413       for (DUIterator_Fast jmax, j = val->fast_outs(jmax); j < jmax; j++) {
 414         Node* n = val->fast_out(j);
 415         if( n->is_MachProj() ) {
 416           get_block_for_node(n)->find_remove(n);
 417           block->add_inst(n);
 418           map_node_to_block(n, block);
 419         }
 420       }
 421     }
 422   }
 423 
 424   // Hoist constant load inputs as well.
 425   for (uint i = 1; i < best->req(); ++i) {
 426     Node* n = best->in(i);
 427     if (n->is_Con() && get_block_for_node(n) == get_block_for_node(best)) {
 428       get_block_for_node(n)->find_remove(n);
 429       block->add_inst(n);
 430       map_node_to_block(n, block);
 431       // Constant loads may kill flags (for example, when XORing a register).
 432       // Check for flag-killing projections that also need to be hoisted.
 433       for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++) {
 434         Node* proj = n->fast_out(j);
 435         if (proj->is_MachProj()) {
 436           get_block_for_node(proj)->find_remove(proj);
 437           block->add_inst(proj);
 438           map_node_to_block(proj, block);
 439         }
 440       }
 441     }
 442   }
 443 
 444   // Hoist the memory candidate up to the end of the test block.
 445   Block *old_block = get_block_for_node(best);
 446   old_block->find_remove(best);
 447   block->add_inst(best);
 448   map_node_to_block(best, block);
 449 
 450   // Move the control dependence if it is pinned to not-null block.
 451   // Don't change it in other cases: null or dominating control.
 452   Node* ctrl = best->in(0);
 453   if (ctrl != nullptr && get_block_for_node(ctrl) == not_null_block) {
 454     // Set it to control edge of null check.
 455     best->set_req(0, proj->in(0)->in(0));
 456   }
 457 
 458   // Check for flag-killing projections that also need to be hoisted
 459   // Should be DU safe because no edge updates.
 460   for (DUIterator_Fast jmax, j = best->fast_outs(jmax); j < jmax; j++) {
 461     Node* n = best->fast_out(j);
 462     if( n->is_MachProj() ) {
 463       get_block_for_node(n)->find_remove(n);
 464       block->add_inst(n);
 465       map_node_to_block(n, block);
 466     }
 467   }
 468 
 469   // proj==Op_True --> ne test; proj==Op_False --> eq test.
 470   // One of two graph shapes got matched:
 471   //   (IfTrue  (If (Bool NE (CmpP ptr null))))
 472   //   (IfFalse (If (Bool EQ (CmpP ptr null))))
 473   // null checks are always branch-if-eq.  If we see a IfTrue projection
 474   // then we are replacing a 'ne' test with a 'eq' null check test.
 475   // We need to flip the projections to keep the same semantics.
 476   if( proj->Opcode() == Op_IfTrue ) {
 477     // Swap order of projections in basic block to swap branch targets
 478     Node *tmp1 = block->get_node(block->end_idx()+1);
 479     Node *tmp2 = block->get_node(block->end_idx()+2);
 480     block->map_node(tmp2, block->end_idx()+1);
 481     block->map_node(tmp1, block->end_idx()+2);
 482     Node *tmp = new Node(C->top()); // Use not null input
 483     tmp1->replace_by(tmp);
 484     tmp2->replace_by(tmp1);
 485     tmp->replace_by(tmp2);
 486     tmp->destruct(nullptr);
 487   }
 488 
 489   // Remove the existing null check; use a new implicit null check instead.
 490   // Since schedule-local needs precise def-use info, we need to correct
 491   // it as well.
 492   Node *old_tst = proj->in(0);
 493   MachNode *nul_chk = new MachNullCheckNode(old_tst->in(0),best,bidx);
 494   block->map_node(nul_chk, block->end_idx());
 495   map_node_to_block(nul_chk, block);
 496   // Redirect users of old_test to nul_chk
 497   for (DUIterator_Last i2min, i2 = old_tst->last_outs(i2min); i2 >= i2min; --i2)
 498     old_tst->last_out(i2)->set_req(0, nul_chk);
 499   // Clean-up any dead code
 500   for (uint i3 = 0; i3 < old_tst->req(); i3++) {
 501     Node* in = old_tst->in(i3);
 502     old_tst->set_req(i3, nullptr);
 503     if (in->outcnt() == 0) {
 504       // Remove dead input node
 505       in->disconnect_inputs(C);
 506       block->find_remove(in);
 507     }
 508   }
 509 
 510   latency_from_uses(nul_chk);
 511   latency_from_uses(best);
 512 
 513   // insert anti-dependences to defs in this block
 514   if (! best->needs_anti_dependence_check()) {
 515     for (uint k = 1; k < block->number_of_nodes(); k++) {
 516       Node *n = block->get_node(k);
 517       if (n->needs_anti_dependence_check() &&
 518           n->in(LoadNode::Memory) == best->in(StoreNode::Memory)) {
 519         // Found anti-dependent load
 520         insert_anti_dependences(block, n);
 521         if (C->failing()) {
 522           return;
 523         }
 524       }
 525     }
 526   }
 527 }
 528 
 529 
 530 //------------------------------select-----------------------------------------
 531 // Select a nice fellow from the worklist to schedule next. If there is only one
 532 // choice, then use it. CreateEx nodes that are initially ready must start their
 533 // blocks and are given the highest priority, by being placed at the beginning
 534 // of the worklist. Next after initially-ready CreateEx nodes are projections,
 535 // which must follow their parents, and CreateEx nodes with local input
 536 // dependencies. Next are constants and CheckCastPP nodes. There are a number of
 537 // other special cases, for instructions that consume condition codes, et al.
 538 // These are chosen immediately. Some instructions are required to immediately
 539 // precede the last instruction in the block, and these are taken last. Of the
 540 // remaining cases (most), choose the instruction with the greatest latency
 541 // (that is, the most number of pseudo-cycles required to the end of the
 542 // routine). If there is a tie, choose the instruction with the most inputs.
 543 Node* PhaseCFG::select(
 544   Block* block,
 545   Node_List &worklist,
 546   GrowableArray<int> &ready_cnt,
 547   VectorSet &next_call,
 548   uint sched_slot,
 549   intptr_t* recalc_pressure_nodes) {
 550 
 551   // If only a single entry on the stack, use it
 552   uint cnt = worklist.size();
 553   if (cnt == 1) {
 554     Node *n = worklist[0];
 555     worklist.map(0,worklist.pop());
 556     return n;
 557   }
 558 
 559   uint choice  = 0; // Bigger is most important
 560   uint latency = 0; // Bigger is scheduled first
 561   uint score   = 0; // Bigger is better
 562   int idx = -1;     // Index in worklist
 563   int cand_cnt = 0; // Candidate count
 564   bool block_size_threshold_ok = (recalc_pressure_nodes != nullptr) && (block->number_of_nodes() > 10);
 565 
 566   for( uint i=0; i<cnt; i++ ) { // Inspect entire worklist
 567     // Order in worklist is used to break ties.
 568     // See caller for how this is used to delay scheduling
 569     // of induction variable increments to after the other
 570     // uses of the phi are scheduled.
 571     Node *n = worklist[i];      // Get Node on worklist
 572 
 573     int iop = n->is_Mach() ? n->as_Mach()->ideal_Opcode() : 0;
 574     if (iop == Op_CreateEx || n->is_Proj()) {
 575       // CreateEx nodes that are initially ready must start the block (after Phi
 576       // and Parm nodes which are pre-scheduled) and get top priority. This is
 577       // currently enforced by placing them at the beginning of the initial
 578       // worklist and selecting them eagerly here. After these, projections and
 579       // other CreateEx nodes are selected with equal priority.
 580       worklist.map(i,worklist.pop());
 581       return n;
 582     }
 583 
 584     if (n->Opcode() == Op_Con || iop == Op_CheckCastPP) {
 585       // Constants and CheckCastPP nodes have higher priority than the rest of
 586       // the nodes tested below. Record as current winner, but keep looking for
 587       // higher-priority nodes in the worklist.
 588       choice  = 4;
 589       // Latency and score are only used to break ties among low-priority nodes.
 590       latency = 0;
 591       score   = 0;
 592       idx     = i;
 593       continue;
 594     }
 595 
 596     // Final call in a block must be adjacent to 'catch'
 597     Node *e = block->end();
 598     if( e->is_Catch() && e->in(0)->in(0) == n )
 599       continue;
 600 
 601     // Memory op for an implicit null check has to be at the end of the block
 602     if( e->is_MachNullCheck() && e->in(1) == n )
 603       continue;
 604 
 605     // Schedule IV increment last.
 606     if (e->is_Mach() && e->as_Mach()->ideal_Opcode() == Op_CountedLoopEnd) {
 607       // Cmp might be matched into CountedLoopEnd node.
 608       Node *cmp = (e->in(1)->ideal_reg() == Op_RegFlags) ? e->in(1) : e;
 609       if (cmp->req() > 1 && cmp->in(1) == n && n->is_iteratively_computed()) {
 610         continue;
 611       }
 612     }
 613 
 614     uint n_choice = 2;
 615 
 616     // See if this instruction is consumed by a branch. If so, then (as the
 617     // branch is the last instruction in the basic block) force it to the
 618     // end of the basic block
 619     if ( must_clone[iop] ) {
 620       // See if any use is a branch
 621       bool found_machif = false;
 622 
 623       for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++) {
 624         Node* use = n->fast_out(j);
 625 
 626         // The use is a conditional branch, make them adjacent
 627         if (use->is_MachIf() && get_block_for_node(use) == block) {
 628           found_machif = true;
 629           break;
 630         }
 631 
 632         // More than this instruction pending for successor to be ready,
 633         // don't choose this if other opportunities are ready
 634         if (ready_cnt.at(use->_idx) > 1)
 635           n_choice = 1;
 636       }
 637 
 638       // loop terminated, prefer not to use this instruction
 639       if (found_machif)
 640         continue;
 641     }
 642 
 643     // See if this has a predecessor that is "must_clone", i.e. sets the
 644     // condition code. If so, choose this first
 645     for (uint j = 0; j < n->req() ; j++) {
 646       Node *inn = n->in(j);
 647       if (inn) {
 648         if (inn->is_Mach() && must_clone[inn->as_Mach()->ideal_Opcode()] ) {
 649           n_choice = 3;
 650           break;
 651         }
 652       }
 653     }
 654 
 655     // MachTemps should be scheduled last so they are near their uses
 656     if (n->is_MachTemp()) {
 657       n_choice = 1;
 658     }
 659 
 660     uint n_latency = get_latency_for_node(n);
 661     uint n_score = n->req();   // Many inputs get high score to break ties
 662 
 663     if (OptoRegScheduling && block_size_threshold_ok) {
 664       if (recalc_pressure_nodes[n->_idx] == 0x7fff7fff) {
 665         _regalloc->_scratch_int_pressure.init(_regalloc->_sched_int_pressure.high_pressure_limit());
 666         _regalloc->_scratch_float_pressure.init(_regalloc->_sched_float_pressure.high_pressure_limit());
 667         // simulate the notion that we just picked this node to schedule
 668         n->add_flag(Node::Flag_is_scheduled);
 669         // now calculate its effect upon the graph if we did
 670         adjust_register_pressure(n, block, recalc_pressure_nodes, false);
 671         // return its state for finalize in case somebody else wins
 672         n->remove_flag(Node::Flag_is_scheduled);
 673         // now save the two final pressure components of register pressure, limiting pressure calcs to short size
 674         short int_pressure = (short)_regalloc->_scratch_int_pressure.current_pressure();
 675         short float_pressure = (short)_regalloc->_scratch_float_pressure.current_pressure();
 676         recalc_pressure_nodes[n->_idx] = int_pressure;
 677         recalc_pressure_nodes[n->_idx] |= (float_pressure << 16);
 678       }
 679 
 680       if (_scheduling_for_pressure) {
 681         latency = n_latency;
 682         if (n_choice != 3) {
 683           // Now evaluate each register pressure component based on threshold in the score.
 684           // In general the defining register type will dominate the score, ergo we will not see register pressure grow on both banks
 685           // on a single instruction, but we might see it shrink on both banks.
 686           // For each use of register that has a register class that is over the high pressure limit, we build n_score up for
 687           // live ranges that terminate on this instruction.
 688           if (_regalloc->_sched_int_pressure.current_pressure() > _regalloc->_sched_int_pressure.high_pressure_limit()) {
 689             short int_pressure = (short)recalc_pressure_nodes[n->_idx];
 690             n_score = (int_pressure < 0) ? ((score + n_score) - int_pressure) : (int_pressure > 0) ? 1 : n_score;
 691           }
 692           if (_regalloc->_sched_float_pressure.current_pressure() > _regalloc->_sched_float_pressure.high_pressure_limit()) {
 693             short float_pressure = (short)(recalc_pressure_nodes[n->_idx] >> 16);
 694             n_score = (float_pressure < 0) ? ((score + n_score) - float_pressure) : (float_pressure > 0) ? 1 : n_score;
 695           }
 696         } else {
 697           // make sure we choose these candidates
 698           score = 0;
 699         }
 700       }
 701     }
 702 
 703     // Keep best latency found
 704     cand_cnt++;
 705     if (choice < n_choice ||
 706         (choice == n_choice &&
 707          ((StressLCM && C->randomized_select(cand_cnt)) ||
 708           (!StressLCM &&
 709            (latency < n_latency ||
 710             (latency == n_latency &&
 711              (score < n_score))))))) {
 712       choice  = n_choice;
 713       latency = n_latency;
 714       score   = n_score;
 715       idx     = i;               // Also keep index in worklist
 716     }
 717   } // End of for all ready nodes in worklist
 718 
 719   guarantee(idx >= 0, "index should be set");
 720   Node *n = worklist[(uint)idx];      // Get the winner
 721 
 722   worklist.map((uint)idx, worklist.pop());     // Compress worklist
 723   return n;
 724 }
 725 
 726 //-------------------------adjust_register_pressure----------------------------
 727 void PhaseCFG::adjust_register_pressure(Node* n, Block* block, intptr_t* recalc_pressure_nodes, bool finalize_mode) {
 728   PhaseLive* liveinfo = _regalloc->get_live();
 729   IndexSet* liveout = liveinfo->live(block);
 730   // first adjust the register pressure for the sources
 731   for (uint i = 1; i < n->req(); i++) {
 732     bool lrg_ends = false;
 733     Node *src_n = n->in(i);
 734     if (src_n == nullptr) continue;
 735     if (!src_n->is_Mach()) continue;
 736     uint src = _regalloc->_lrg_map.find(src_n);
 737     if (src == 0) continue;
 738     LRG& lrg_src = _regalloc->lrgs(src);
 739     // detect if the live range ends or not
 740     if (liveout->member(src) == false) {
 741       lrg_ends = true;
 742       for (DUIterator_Fast jmax, j = src_n->fast_outs(jmax); j < jmax; j++) {
 743         Node* m = src_n->fast_out(j); // Get user
 744         if (m == n) continue;
 745         if (!m->is_Mach()) continue;
 746         MachNode *mach = m->as_Mach();
 747         bool src_matches = false;
 748         int iop = mach->ideal_Opcode();
 749 
 750         switch (iop) {
 751         case Op_StoreB:
 752         case Op_StoreC:
 753         case Op_StoreD:
 754         case Op_StoreF:
 755         case Op_StoreI:
 756         case Op_StoreL:
 757         case Op_StoreLSpecial:
 758         case Op_StoreP:
 759         case Op_StoreN:
 760         case Op_StoreVector:
 761         case Op_StoreVectorMasked:
 762         case Op_StoreVectorScatter:
 763         case Op_StoreVectorScatterMasked:
 764         case Op_StoreNKlass:
 765           for (uint k = 1; k < m->req(); k++) {
 766             Node *in = m->in(k);
 767             if (in == src_n) {
 768               src_matches = true;
 769               break;
 770             }
 771           }
 772           break;
 773 
 774         default:
 775           src_matches = true;
 776           break;
 777         }
 778 
 779         // If we have a store as our use, ignore the non source operands
 780         if (src_matches == false) continue;
 781 
 782         // Mark every unscheduled use which is not n with a recalculation
 783         if ((get_block_for_node(m) == block) && (!m->is_scheduled())) {
 784           if (finalize_mode && !m->is_Phi()) {
 785             recalc_pressure_nodes[m->_idx] = 0x7fff7fff;
 786           }
 787           lrg_ends = false;
 788         }
 789       }
 790     }
 791     // if none, this live range ends and we can adjust register pressure
 792     if (lrg_ends) {
 793       if (finalize_mode) {
 794         _regalloc->lower_pressure(block, 0, lrg_src, nullptr, _regalloc->_sched_int_pressure, _regalloc->_sched_float_pressure);
 795       } else {
 796         _regalloc->lower_pressure(block, 0, lrg_src, nullptr, _regalloc->_scratch_int_pressure, _regalloc->_scratch_float_pressure);
 797       }
 798     }
 799   }
 800 
 801   // now add the register pressure from the dest and evaluate which heuristic we should use:
 802   // 1.) The default, latency scheduling
 803   // 2.) Register pressure scheduling based on the high pressure limit threshold for int or float register stacks
 804   uint dst = _regalloc->_lrg_map.find(n);
 805   if (dst != 0) {
 806     LRG& lrg_dst = _regalloc->lrgs(dst);
 807     if (finalize_mode) {
 808       _regalloc->raise_pressure(block, lrg_dst, _regalloc->_sched_int_pressure, _regalloc->_sched_float_pressure);
 809       // check to see if we fall over the register pressure cliff here
 810       if (_regalloc->_sched_int_pressure.current_pressure() > _regalloc->_sched_int_pressure.high_pressure_limit()) {
 811         _scheduling_for_pressure = true;
 812       } else if (_regalloc->_sched_float_pressure.current_pressure() > _regalloc->_sched_float_pressure.high_pressure_limit()) {
 813         _scheduling_for_pressure = true;
 814       } else {
 815         // restore latency scheduling mode
 816         _scheduling_for_pressure = false;
 817       }
 818     } else {
 819       _regalloc->raise_pressure(block, lrg_dst, _regalloc->_scratch_int_pressure, _regalloc->_scratch_float_pressure);
 820     }
 821   }
 822 }
 823 
 824 //------------------------------set_next_call----------------------------------
 825 void PhaseCFG::set_next_call(Block* block, Node* n, VectorSet& next_call) {
 826   if( next_call.test_set(n->_idx) ) return;
 827   for( uint i=0; i<n->len(); i++ ) {
 828     Node *m = n->in(i);
 829     if( !m ) continue;  // must see all nodes in block that precede call
 830     if (get_block_for_node(m) == block) {
 831       set_next_call(block, m, next_call);
 832     }
 833   }
 834 }
 835 
 836 //------------------------------needed_for_next_call---------------------------
 837 // Set the flag 'next_call' for each Node that is needed for the next call to
 838 // be scheduled.  This flag lets me bias scheduling so Nodes needed for the
 839 // next subroutine call get priority - basically it moves things NOT needed
 840 // for the next call till after the call.  This prevents me from trying to
 841 // carry lots of stuff live across a call.
 842 void PhaseCFG::needed_for_next_call(Block* block, Node* this_call, VectorSet& next_call) {
 843   // Find the next control-defining Node in this block
 844   Node* call = nullptr;
 845   for (DUIterator_Fast imax, i = this_call->fast_outs(imax); i < imax; i++) {
 846     Node* m = this_call->fast_out(i);
 847     if (get_block_for_node(m) == block && // Local-block user
 848         m != this_call &&       // Not self-start node
 849         m->is_MachCall()) {
 850       call = m;
 851       break;
 852     }
 853   }
 854   if (call == nullptr)  return;    // No next call (e.g., block end is near)
 855   // Set next-call for all inputs to this call
 856   set_next_call(block, call, next_call);
 857 }
 858 
 859 //------------------------------add_call_kills-------------------------------------
 860 // helper function that adds caller save registers to MachProjNode
 861 static void add_call_kills(MachProjNode *proj, RegMask& regs, const char* save_policy, bool exclude_soe) {
 862   // Fill in the kill mask for the call
 863   for( OptoReg::Name r = OptoReg::Name(0); r < _last_Mach_Reg; r=OptoReg::add(r,1) ) {
 864     if( !regs.Member(r) ) {     // Not already defined by the call
 865       // Save-on-call register?
 866       if ((save_policy[r] == 'C') ||
 867           (save_policy[r] == 'A') ||
 868           ((save_policy[r] == 'E') && exclude_soe)) {
 869         proj->_rout.Insert(r);
 870       }
 871     }
 872   }
 873 }
 874 
 875 
 876 //------------------------------sched_call-------------------------------------
 877 uint PhaseCFG::sched_call(Block* block, uint node_cnt, Node_List& worklist, GrowableArray<int>& ready_cnt, MachCallNode* mcall, VectorSet& next_call) {
 878   RegMask regs;
 879 
 880   // Schedule all the users of the call right now.  All the users are
 881   // projection Nodes, so they must be scheduled next to the call.
 882   // Collect all the defined registers.
 883   for (DUIterator_Fast imax, i = mcall->fast_outs(imax); i < imax; i++) {
 884     Node* n = mcall->fast_out(i);
 885     assert( n->is_MachProj(), "" );
 886     int n_cnt = ready_cnt.at(n->_idx)-1;
 887     ready_cnt.at_put(n->_idx, n_cnt);
 888     assert( n_cnt == 0, "" );
 889     // Schedule next to call
 890     block->map_node(n, node_cnt++);
 891     // Collect defined registers
 892     regs.OR(n->out_RegMask());
 893     // Check for scheduling the next control-definer
 894     if( n->bottom_type() == Type::CONTROL )
 895       // Warm up next pile of heuristic bits
 896       needed_for_next_call(block, n, next_call);
 897 
 898     // Children of projections are now all ready
 899     for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++) {
 900       Node* m = n->fast_out(j); // Get user
 901       if(get_block_for_node(m) != block) {
 902         continue;
 903       }
 904       if( m->is_Phi() ) continue;
 905       int m_cnt = ready_cnt.at(m->_idx) - 1;
 906       ready_cnt.at_put(m->_idx, m_cnt);
 907       if( m_cnt == 0 )
 908         worklist.push(m);
 909     }
 910 
 911   }
 912 
 913   // Act as if the call defines the Frame Pointer.
 914   // Certainly the FP is alive and well after the call.
 915   regs.Insert(_matcher.c_frame_pointer());
 916 
 917   // Set all registers killed and not already defined by the call.
 918   uint r_cnt = mcall->tf()->range_cc()->cnt();
 919   int op = mcall->ideal_Opcode();
 920   MachProjNode *proj = new MachProjNode( mcall, r_cnt+1, RegMask::Empty, MachProjNode::fat_proj );
 921   map_node_to_block(proj, block);
 922   block->insert_node(proj, node_cnt++);
 923 
 924   // Select the right register save policy.
 925   const char *save_policy = nullptr;
 926   switch (op) {
 927     case Op_CallRuntime:
 928     case Op_CallLeaf:
 929     case Op_CallLeafNoFP:
 930     case Op_CallLeafVector:
 931       // Calling C code so use C calling convention
 932       save_policy = _matcher._c_reg_save_policy;
 933       break;
 934 
 935     case Op_CallStaticJava:
 936     case Op_CallDynamicJava:
 937       // Calling Java code so use Java calling convention
 938       save_policy = _matcher._register_save_policy;
 939       break;
 940 
 941     default:
 942       ShouldNotReachHere();
 943   }
 944 
 945   // When using CallRuntime mark SOE registers as killed by the call
 946   // so values that could show up in the RegisterMap aren't live in a
 947   // callee saved register since the register wouldn't know where to
 948   // find them.  CallLeaf and CallLeafNoFP are ok because they can't
 949   // have debug info on them.  Strictly speaking this only needs to be
 950   // done for oops since idealreg2debugmask takes care of debug info
 951   // references but there no way to handle oops differently than other
 952   // pointers as far as the kill mask goes.
 953   bool exclude_soe = op == Op_CallRuntime;
 954 
 955   // If the call is a MethodHandle invoke, we need to exclude the
 956   // register which is used to save the SP value over MH invokes from
 957   // the mask.  Otherwise this register could be used for
 958   // deoptimization information.
 959   if (op == Op_CallStaticJava) {
 960     MachCallStaticJavaNode* mcallstaticjava = (MachCallStaticJavaNode*) mcall;
 961     if (mcallstaticjava->_method_handle_invoke)
 962       proj->_rout.OR(Matcher::method_handle_invoke_SP_save_mask());
 963   }
 964 
 965   add_call_kills(proj, regs, save_policy, exclude_soe);
 966 
 967   return node_cnt;
 968 }
 969 
 970 
 971 //------------------------------schedule_local---------------------------------
 972 // Topological sort within a block.  Someday become a real scheduler.
 973 bool PhaseCFG::schedule_local(Block* block, GrowableArray<int>& ready_cnt, VectorSet& next_call, intptr_t *recalc_pressure_nodes) {
 974   // Already "sorted" are the block start Node (as the first entry), and
 975   // the block-ending Node and any trailing control projections.  We leave
 976   // these alone.  PhiNodes and ParmNodes are made to follow the block start
 977   // Node.  Everything else gets topo-sorted.
 978 
 979 #ifndef PRODUCT
 980     if (trace_opto_pipelining()) {
 981       tty->print_cr("# --- schedule_local B%d, before: ---", block->_pre_order);
 982       for (uint i = 0;i < block->number_of_nodes(); i++) {
 983         tty->print("# ");
 984         block->get_node(i)->dump();
 985       }
 986       tty->print_cr("#");
 987     }
 988 #endif
 989 
 990   // RootNode is already sorted
 991   if (block->number_of_nodes() == 1) {
 992     return true;
 993   }
 994 
 995   bool block_size_threshold_ok = (recalc_pressure_nodes != nullptr) && (block->number_of_nodes() > 10);
 996 
 997   // We track the uses of local definitions as input dependences so that
 998   // we know when a given instruction is available to be scheduled.
 999   uint i;
1000   if (OptoRegScheduling && block_size_threshold_ok) {
1001     for (i = 1; i < block->number_of_nodes(); i++) { // setup nodes for pressure calc
1002       Node *n = block->get_node(i);
1003       n->remove_flag(Node::Flag_is_scheduled);
1004       if (!n->is_Phi()) {
1005         recalc_pressure_nodes[n->_idx] = 0x7fff7fff;
1006       }
1007     }
1008   }
1009 
1010   // Move PhiNodes and ParmNodes from 1 to cnt up to the start
1011   uint node_cnt = block->end_idx();
1012   uint phi_cnt = 1;
1013   for( i = 1; i<node_cnt; i++ ) { // Scan for Phi
1014     Node *n = block->get_node(i);
1015     if( n->is_Phi() ||          // Found a PhiNode or ParmNode
1016         (n->is_Proj()  && n->in(0) == block->head()) ) {
1017       // Move guy at 'phi_cnt' to the end; makes a hole at phi_cnt
1018       block->map_node(block->get_node(phi_cnt), i);
1019       block->map_node(n, phi_cnt++);  // swap Phi/Parm up front
1020       if (OptoRegScheduling && block_size_threshold_ok) {
1021         // mark n as scheduled
1022         n->add_flag(Node::Flag_is_scheduled);
1023       }
1024     } else {                    // All others
1025       // Count block-local inputs to 'n'
1026       uint cnt = n->len();      // Input count
1027       uint local = 0;
1028       for( uint j=0; j<cnt; j++ ) {
1029         Node *m = n->in(j);
1030         if( m && get_block_for_node(m) == block && !m->is_top() )
1031           local++;              // One more block-local input
1032       }
1033       ready_cnt.at_put(n->_idx, local); // Count em up
1034       // A few node types require changing a required edge to a precedence edge
1035       // before allocation.
1036       if( n->is_Mach() && n->req() > TypeFunc::Parms &&
1037           (n->as_Mach()->ideal_Opcode() == Op_MemBarAcquire ||
1038            n->as_Mach()->ideal_Opcode() == Op_MemBarVolatile) ) {
1039         // MemBarAcquire could be created without Precedent edge.
1040         // del_req() replaces the specified edge with the last input edge
1041         // and then removes the last edge. If the specified edge > number of
1042         // edges the last edge will be moved outside of the input edges array
1043         // and the edge will be lost. This is why this code should be
1044         // executed only when Precedent (== TypeFunc::Parms) edge is present.
1045         Node *x = n->in(TypeFunc::Parms);
1046         if (x != nullptr && get_block_for_node(x) == block && n->find_prec_edge(x) != -1) {
1047           // Old edge to node within same block will get removed, but no precedence
1048           // edge will get added because it already exists. Update ready count.
1049           int cnt = ready_cnt.at(n->_idx);
1050           assert(cnt > 1, "MemBar node %d must not get ready here", n->_idx);
1051           ready_cnt.at_put(n->_idx, cnt-1);
1052         }
1053         n->del_req(TypeFunc::Parms);
1054         n->add_prec(x);
1055       }
1056     }
1057   }
1058   for(uint i2=i; i2< block->number_of_nodes(); i2++ ) // Trailing guys get zapped count
1059     ready_cnt.at_put(block->get_node(i2)->_idx, 0);
1060 
1061   // All the prescheduled guys do not hold back internal nodes
1062   uint i3;
1063   for (i3 = 0; i3 < phi_cnt; i3++) {  // For all pre-scheduled
1064     Node *n = block->get_node(i3);       // Get pre-scheduled
1065     for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++) {
1066       Node* m = n->fast_out(j);
1067       if (get_block_for_node(m) == block) { // Local-block user
1068         int m_cnt = ready_cnt.at(m->_idx)-1;
1069         if (OptoRegScheduling && block_size_threshold_ok) {
1070           // mark m as scheduled
1071           if (m_cnt < 0) {
1072             m->add_flag(Node::Flag_is_scheduled);
1073           }
1074         }
1075         ready_cnt.at_put(m->_idx, m_cnt);   // Fix ready count
1076       }
1077     }
1078   }
1079 
1080   Node_List delay;
1081   // Make a worklist
1082   Node_List worklist;
1083   for(uint i4=i3; i4<node_cnt; i4++ ) {    // Put ready guys on worklist
1084     Node *m = block->get_node(i4);
1085     if( !ready_cnt.at(m->_idx) ) {   // Zero ready count?
1086       if (m->is_iteratively_computed()) {
1087         // Push induction variable increments last to allow other uses
1088         // of the phi to be scheduled first. The select() method breaks
1089         // ties in scheduling by worklist order.
1090         delay.push(m);
1091       } else if (m->is_Mach() && m->as_Mach()->ideal_Opcode() == Op_CreateEx) {
1092         // Place CreateEx nodes that are initially ready at the beginning of the
1093         // worklist so they are selected first and scheduled at the block start.
1094         worklist.insert(0, m);
1095       } else {
1096         worklist.push(m);         // Then on to worklist!
1097       }
1098     }
1099   }
1100   while (delay.size()) {
1101     Node* d = delay.pop();
1102     worklist.push(d);
1103   }
1104 
1105   if (OptoRegScheduling && block_size_threshold_ok) {
1106     // To stage register pressure calculations we need to examine the live set variables
1107     // breaking them up by register class to compartmentalize the calculations.
1108     _regalloc->_sched_int_pressure.init(Matcher::int_pressure_limit());
1109     _regalloc->_sched_float_pressure.init(Matcher::float_pressure_limit());
1110     _regalloc->_scratch_int_pressure.init(Matcher::int_pressure_limit());
1111     _regalloc->_scratch_float_pressure.init(Matcher::float_pressure_limit());
1112 
1113     _regalloc->compute_entry_block_pressure(block);
1114   }
1115 
1116   // Warm up the 'next_call' heuristic bits
1117   needed_for_next_call(block, block->head(), next_call);
1118 
1119 #ifndef PRODUCT
1120     if (trace_opto_pipelining()) {
1121       for (uint j=0; j< block->number_of_nodes(); j++) {
1122         Node     *n = block->get_node(j);
1123         int     idx = n->_idx;
1124         tty->print("#   ready cnt:%3d  ", ready_cnt.at(idx));
1125         tty->print("latency:%3d  ", get_latency_for_node(n));
1126         tty->print("%4d: %s\n", idx, n->Name());
1127       }
1128     }
1129 #endif
1130 
1131   uint max_idx = (uint)ready_cnt.length();
1132   // Pull from worklist and schedule
1133   while( worklist.size() ) {    // Worklist is not ready
1134 
1135 #ifndef PRODUCT
1136     if (trace_opto_pipelining()) {
1137       tty->print("#   ready list:");
1138       for( uint i=0; i<worklist.size(); i++ ) { // Inspect entire worklist
1139         Node *n = worklist[i];      // Get Node on worklist
1140         tty->print(" %d", n->_idx);
1141       }
1142       tty->cr();
1143     }
1144 #endif
1145 
1146     // Select and pop a ready guy from worklist
1147     Node* n = select(block, worklist, ready_cnt, next_call, phi_cnt, recalc_pressure_nodes);
1148     block->map_node(n, phi_cnt++);    // Schedule him next
1149 
1150     if (OptoRegScheduling && block_size_threshold_ok) {
1151       n->add_flag(Node::Flag_is_scheduled);
1152 
1153       // Now adjust the resister pressure with the node we selected
1154       if (!n->is_Phi()) {
1155         adjust_register_pressure(n, block, recalc_pressure_nodes, true);
1156       }
1157     }
1158 
1159 #ifndef PRODUCT
1160     if (trace_opto_pipelining()) {
1161       tty->print("#    select %d: %s", n->_idx, n->Name());
1162       tty->print(", latency:%d", get_latency_for_node(n));
1163       n->dump();
1164       if (Verbose) {
1165         tty->print("#   ready list:");
1166         for( uint i=0; i<worklist.size(); i++ ) { // Inspect entire worklist
1167           Node *n = worklist[i];      // Get Node on worklist
1168           tty->print(" %d", n->_idx);
1169         }
1170         tty->cr();
1171       }
1172     }
1173 
1174 #endif
1175     if( n->is_MachCall() ) {
1176       MachCallNode *mcall = n->as_MachCall();
1177       phi_cnt = sched_call(block, phi_cnt, worklist, ready_cnt, mcall, next_call);
1178       continue;
1179     }
1180 
1181     if (n->is_Mach() && n->as_Mach()->has_call()) {
1182       RegMask regs;
1183       regs.Insert(_matcher.c_frame_pointer());
1184       regs.OR(n->out_RegMask());
1185 
1186       MachProjNode *proj = new MachProjNode( n, 1, RegMask::Empty, MachProjNode::fat_proj );
1187       map_node_to_block(proj, block);
1188       block->insert_node(proj, phi_cnt++);
1189 
1190       add_call_kills(proj, regs, _matcher._c_reg_save_policy, false);
1191     }
1192 
1193     // Children are now all ready
1194     for (DUIterator_Fast i5max, i5 = n->fast_outs(i5max); i5 < i5max; i5++) {
1195       Node* m = n->fast_out(i5); // Get user
1196       if (get_block_for_node(m) != block) {
1197         continue;
1198       }
1199       if( m->is_Phi() ) continue;
1200       if (m->_idx >= max_idx) { // new node, skip it
1201         assert(m->is_MachProj() && n->is_Mach() && n->as_Mach()->has_call(), "unexpected node types");
1202         continue;
1203       }
1204       int m_cnt = ready_cnt.at(m->_idx) - 1;
1205       ready_cnt.at_put(m->_idx, m_cnt);
1206       if( m_cnt == 0 )
1207         worklist.push(m);
1208     }
1209   }
1210 
1211   if( phi_cnt != block->end_idx() ) {
1212     // did not schedule all.  Retry, Bailout, or Die
1213     if (C->subsume_loads() == true && !C->failing()) {
1214       // Retry with subsume_loads == false
1215       // If this is the first failure, the sentinel string will "stick"
1216       // to the Compile object, and the C2Compiler will see it and retry.
1217       C->record_failure(C2Compiler::retry_no_subsuming_loads());
1218     } else {
1219       assert(C->failure_is_artificial(), "graph should be schedulable");
1220     }
1221     // assert( phi_cnt == end_idx(), "did not schedule all" );
1222     return false;
1223   }
1224 
1225   if (OptoRegScheduling && block_size_threshold_ok) {
1226     _regalloc->compute_exit_block_pressure(block);
1227     block->_reg_pressure = _regalloc->_sched_int_pressure.final_pressure();
1228     block->_freg_pressure = _regalloc->_sched_float_pressure.final_pressure();
1229   }
1230 
1231 #ifndef PRODUCT
1232   if (trace_opto_pipelining()) {
1233     tty->print_cr("#");
1234     tty->print_cr("# after schedule_local");
1235     for (uint i = 0;i < block->number_of_nodes();i++) {
1236       tty->print("# ");
1237       block->get_node(i)->dump();
1238     }
1239     tty->print_cr("# ");
1240 
1241     if (OptoRegScheduling && block_size_threshold_ok) {
1242       tty->print_cr("# pressure info : %d", block->_pre_order);
1243       _regalloc->print_pressure_info(_regalloc->_sched_int_pressure, "int register info");
1244       _regalloc->print_pressure_info(_regalloc->_sched_float_pressure, "float register info");
1245     }
1246     tty->cr();
1247   }
1248 #endif
1249 
1250   return true;
1251 }
1252 
1253 //--------------------------catch_cleanup_fix_all_inputs-----------------------
1254 static void catch_cleanup_fix_all_inputs(Node *use, Node *old_def, Node *new_def) {
1255   for (uint l = 0; l < use->len(); l++) {
1256     if (use->in(l) == old_def) {
1257       if (l < use->req()) {
1258         use->set_req(l, new_def);
1259       } else {
1260         use->rm_prec(l);
1261         use->add_prec(new_def);
1262         l--;
1263       }
1264     }
1265   }
1266 }
1267 
1268 //------------------------------catch_cleanup_find_cloned_def------------------
1269 Node* PhaseCFG::catch_cleanup_find_cloned_def(Block *use_blk, Node *def, Block *def_blk, int n_clone_idx) {
1270   assert( use_blk != def_blk, "Inter-block cleanup only");
1271 
1272   // The use is some block below the Catch.  Find and return the clone of the def
1273   // that dominates the use. If there is no clone in a dominating block, then
1274   // create a phi for the def in a dominating block.
1275 
1276   // Find which successor block dominates this use.  The successor
1277   // blocks must all be single-entry (from the Catch only; I will have
1278   // split blocks to make this so), hence they all dominate.
1279   while( use_blk->_dom_depth > def_blk->_dom_depth+1 )
1280     use_blk = use_blk->_idom;
1281 
1282   // Find the successor
1283   Node *fixup = nullptr;
1284 
1285   uint j;
1286   for( j = 0; j < def_blk->_num_succs; j++ )
1287     if( use_blk == def_blk->_succs[j] )
1288       break;
1289 
1290   if( j == def_blk->_num_succs ) {
1291     // Block at same level in dom-tree is not a successor.  It needs a
1292     // PhiNode, the PhiNode uses from the def and IT's uses need fixup.
1293     Node_Array inputs;
1294     for(uint k = 1; k < use_blk->num_preds(); k++) {
1295       Block* block = get_block_for_node(use_blk->pred(k));
1296       inputs.map(k, catch_cleanup_find_cloned_def(block, def, def_blk, n_clone_idx));
1297     }
1298 
1299     // Check to see if the use_blk already has an identical phi inserted.
1300     // If it exists, it will be at the first position since all uses of a
1301     // def are processed together.
1302     Node *phi = use_blk->get_node(1);
1303     if( phi->is_Phi() ) {
1304       fixup = phi;
1305       for (uint k = 1; k < use_blk->num_preds(); k++) {
1306         if (phi->in(k) != inputs[k]) {
1307           // Not a match
1308           fixup = nullptr;
1309           break;
1310         }
1311       }
1312     }
1313 
1314     // If an existing PhiNode was not found, make a new one.
1315     if (fixup == nullptr) {
1316       Node *new_phi = PhiNode::make(use_blk->head(), def);
1317       use_blk->insert_node(new_phi, 1);
1318       map_node_to_block(new_phi, use_blk);
1319       for (uint k = 1; k < use_blk->num_preds(); k++) {
1320         new_phi->set_req(k, inputs[k]);
1321       }
1322       fixup = new_phi;
1323     }
1324 
1325   } else {
1326     // Found the use just below the Catch.  Make it use the clone.
1327     fixup = use_blk->get_node(n_clone_idx);
1328   }
1329 
1330   return fixup;
1331 }
1332 
1333 //--------------------------catch_cleanup_intra_block--------------------------
1334 // Fix all input edges in use that reference "def".  The use is in the same
1335 // block as the def and both have been cloned in each successor block.
1336 static void catch_cleanup_intra_block(Node *use, Node *def, Block *blk, int beg, int n_clone_idx) {
1337 
1338   // Both the use and def have been cloned. For each successor block,
1339   // get the clone of the use, and make its input the clone of the def
1340   // found in that block.
1341 
1342   uint use_idx = blk->find_node(use);
1343   uint offset_idx = use_idx - beg;
1344   for( uint k = 0; k < blk->_num_succs; k++ ) {
1345     // Get clone in each successor block
1346     Block *sb = blk->_succs[k];
1347     Node *clone = sb->get_node(offset_idx+1);
1348     assert( clone->Opcode() == use->Opcode(), "" );
1349 
1350     // Make use-clone reference the def-clone
1351     catch_cleanup_fix_all_inputs(clone, def, sb->get_node(n_clone_idx));
1352   }
1353 }
1354 
1355 //------------------------------catch_cleanup_inter_block---------------------
1356 // Fix all input edges in use that reference "def".  The use is in a different
1357 // block than the def.
1358 void PhaseCFG::catch_cleanup_inter_block(Node *use, Block *use_blk, Node *def, Block *def_blk, int n_clone_idx) {
1359   if( !use_blk ) return;        // Can happen if the use is a precedence edge
1360 
1361   Node *new_def = catch_cleanup_find_cloned_def(use_blk, def, def_blk, n_clone_idx);
1362   catch_cleanup_fix_all_inputs(use, def, new_def);
1363 }
1364 
1365 //------------------------------call_catch_cleanup-----------------------------
1366 // If we inserted any instructions between a Call and his CatchNode,
1367 // clone the instructions on all paths below the Catch.
1368 void PhaseCFG::call_catch_cleanup(Block* block) {
1369 
1370   // End of region to clone
1371   uint end = block->end_idx();
1372   if( !block->get_node(end)->is_Catch() ) return;
1373   // Start of region to clone
1374   uint beg = end;
1375   while(!block->get_node(beg-1)->is_MachProj() ||
1376         !block->get_node(beg-1)->in(0)->is_MachCall() ) {
1377     beg--;
1378     assert(beg > 0,"Catch cleanup walking beyond block boundary");
1379   }
1380   // Range of inserted instructions is [beg, end)
1381   if( beg == end ) return;
1382 
1383   // Clone along all Catch output paths.  Clone area between the 'beg' and
1384   // 'end' indices.
1385   for( uint i = 0; i < block->_num_succs; i++ ) {
1386     Block *sb = block->_succs[i];
1387     // Clone the entire area; ignoring the edge fixup for now.
1388     for( uint j = end; j > beg; j-- ) {
1389       Node *clone = block->get_node(j-1)->clone();
1390       sb->insert_node(clone, 1);
1391       map_node_to_block(clone, sb);
1392       if (clone->needs_anti_dependence_check()) {
1393         insert_anti_dependences(sb, clone);
1394         if (C->failing()) {
1395           return;
1396         }
1397       }
1398     }
1399   }
1400 
1401 
1402   // Fixup edges.  Check the def-use info per cloned Node
1403   for(uint i2 = beg; i2 < end; i2++ ) {
1404     uint n_clone_idx = i2-beg+1; // Index of clone of n in each successor block
1405     Node *n = block->get_node(i2);        // Node that got cloned
1406     // Need DU safe iterator because of edge manipulation in calls.
1407     Unique_Node_List* out = new Unique_Node_List();
1408     for (DUIterator_Fast j1max, j1 = n->fast_outs(j1max); j1 < j1max; j1++) {
1409       out->push(n->fast_out(j1));
1410     }
1411     uint max = out->size();
1412     for (uint j = 0; j < max; j++) {// For all users
1413       Node *use = out->pop();
1414       Block *buse = get_block_for_node(use);
1415       if( use->is_Phi() ) {
1416         for( uint k = 1; k < use->req(); k++ )
1417           if( use->in(k) == n ) {
1418             Block* b = get_block_for_node(buse->pred(k));
1419             Node *fixup = catch_cleanup_find_cloned_def(b, n, block, n_clone_idx);
1420             use->set_req(k, fixup);
1421           }
1422       } else {
1423         if (block == buse) {
1424           catch_cleanup_intra_block(use, n, block, beg, n_clone_idx);
1425         } else {
1426           catch_cleanup_inter_block(use, buse, n, block, n_clone_idx);
1427         }
1428       }
1429     } // End for all users
1430 
1431   } // End of for all Nodes in cloned area
1432 
1433   // Remove the now-dead cloned ops
1434   for(uint i3 = beg; i3 < end; i3++ ) {
1435     block->get_node(beg)->disconnect_inputs(C);
1436     block->remove_node(beg);
1437   }
1438 
1439   // If the successor blocks have a CreateEx node, move it back to the top
1440   for (uint i4 = 0; i4 < block->_num_succs; i4++) {
1441     Block *sb = block->_succs[i4];
1442     uint new_cnt = end - beg;
1443     // Remove any newly created, but dead, nodes by traversing their schedule
1444     // backwards. Here, a dead node is a node whose only outputs (if any) are
1445     // unused projections.
1446     for (uint j = new_cnt; j > 0; j--) {
1447       Node *n = sb->get_node(j);
1448       // Individual projections are examined together with all siblings when
1449       // their parent is visited.
1450       if (n->is_Proj()) {
1451         continue;
1452       }
1453       bool dead = true;
1454       for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
1455         Node* out = n->fast_out(i);
1456         // n is live if it has a non-projection output or a used projection.
1457         if (!out->is_Proj() || out->outcnt() > 0) {
1458           dead = false;
1459           break;
1460         }
1461       }
1462       if (dead) {
1463         // n's only outputs (if any) are unused projections scheduled next to n
1464         // (see PhaseCFG::select()). Remove these projections backwards.
1465         for (uint k = j + n->outcnt(); k > j; k--) {
1466           Node* proj = sb->get_node(k);
1467           assert(proj->is_Proj() && proj->in(0) == n,
1468                  "projection should correspond to dead node");
1469           proj->disconnect_inputs(C);
1470           sb->remove_node(k);
1471           new_cnt--;
1472         }
1473         // Now remove the node itself.
1474         n->disconnect_inputs(C);
1475         sb->remove_node(j);
1476         new_cnt--;
1477       }
1478     }
1479     // If any newly created nodes remain, move the CreateEx node to the top
1480     if (new_cnt > 0) {
1481       Node *cex = sb->get_node(1+new_cnt);
1482       if( cex->is_Mach() && cex->as_Mach()->ideal_Opcode() == Op_CreateEx ) {
1483         sb->remove_node(1+new_cnt);
1484         sb->insert_node(cex, 1);
1485       }
1486     }
1487   }
1488 }