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