1 /*
   2  * Copyright (c) 1999, 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 "gc/shared/barrierSet.hpp"
  26 #include "gc/shared/c2/barrierSetC2.hpp"
  27 #include "memory/allocation.inline.hpp"
  28 #include "memory/resourceArea.hpp"
  29 #include "opto/addnode.hpp"
  30 #include "opto/callnode.hpp"
  31 #include "opto/castnode.hpp"
  32 #include "opto/connode.hpp"
  33 #include "opto/divnode.hpp"
  34 #include "opto/loopnode.hpp"
  35 #include "opto/matcher.hpp"
  36 #include "opto/movenode.hpp"
  37 #include "opto/mulnode.hpp"
  38 #include "opto/opaquenode.hpp"
  39 #include "opto/rootnode.hpp"
  40 #include "opto/subnode.hpp"
  41 #include "opto/subtypenode.hpp"
  42 #include "opto/superword.hpp"
  43 #include "opto/vectornode.hpp"
  44 #include "utilities/checkedCast.hpp"
  45 #include "utilities/macros.hpp"
  46 
  47 //=============================================================================
  48 //------------------------------split_thru_phi---------------------------------
  49 // Split Node 'n' through merge point if there is enough win.
  50 Node* PhaseIdealLoop::split_thru_phi(Node* n, Node* region, int policy) {
  51   if ((n->Opcode() == Op_ConvI2L && n->bottom_type() != TypeLong::LONG) ||
  52       (n->Opcode() == Op_ConvL2I && n->bottom_type() != TypeInt::INT)) {
  53     // ConvI2L/ConvL2I may have type information on it which is unsafe to push up
  54     // so disable this for now
  55     return nullptr;
  56   }
  57 
  58   // Splitting range check CastIIs through a loop induction Phi can
  59   // cause new Phis to be created that are left unrelated to the loop
  60   // induction Phi and prevent optimizations (vectorization)
  61   if (n->Opcode() == Op_CastII && region->is_CountedLoop() &&
  62       n->in(1) == region->as_CountedLoop()->phi()) {
  63     return nullptr;
  64   }
  65 
  66   if (cannot_split_division(n, region)) {
  67     return nullptr;
  68   }
  69 
  70   SplitThruPhiWins wins(region);
  71   assert(!n->is_CFG(), "");
  72   assert(region->is_Region(), "");
  73 
  74   const Type* type = n->bottom_type();
  75   const TypeOopPtr* t_oop = _igvn.type(n)->isa_oopptr();
  76   Node* phi;
  77   if (t_oop != nullptr && t_oop->is_known_instance_field()) {
  78     int iid    = t_oop->instance_id();
  79     int index  = C->get_alias_index(t_oop);
  80     int offset = t_oop->offset();
  81     phi = new PhiNode(region, type, nullptr, iid, index, offset);
  82   } else {
  83     phi = PhiNode::make_blank(region, n);
  84   }
  85   uint old_unique = C->unique();
  86   for (uint i = 1; i < region->req(); i++) {
  87     Node* x;
  88     Node* the_clone = nullptr;
  89     if (region->in(i) == C->top()) {
  90       x = C->top();             // Dead path?  Use a dead data op
  91     } else {
  92       x = n->clone();           // Else clone up the data op
  93       the_clone = x;            // Remember for possible deletion.
  94       // Alter data node to use pre-phi inputs
  95       if (n->in(0) == region)
  96         x->set_req( 0, region->in(i) );
  97       for (uint j = 1; j < n->req(); j++) {
  98         Node* in = n->in(j);
  99         if (in->is_Phi() && in->in(0) == region)
 100           x->set_req(j, in->in(i)); // Use pre-Phi input for the clone
 101       }
 102     }
 103     // Check for a 'win' on some paths
 104     const Type* t = x->Value(&_igvn);
 105 
 106     bool singleton = t->singleton();
 107 
 108     // A TOP singleton indicates that there are no possible values incoming
 109     // along a particular edge. In most cases, this is OK, and the Phi will
 110     // be eliminated later in an Ideal call. However, we can't allow this to
 111     // happen if the singleton occurs on loop entry, as the elimination of
 112     // the PhiNode may cause the resulting node to migrate back to a previous
 113     // loop iteration.
 114     if (singleton && t == Type::TOP) {
 115       // Is_Loop() == false does not confirm the absence of a loop (e.g., an
 116       // irreducible loop may not be indicated by an affirmative is_Loop());
 117       // therefore, the only top we can split thru a phi is on a backedge of
 118       // a loop.
 119       singleton &= region->is_Loop() && (i != LoopNode::EntryControl);
 120     }
 121 
 122     if (singleton) {
 123       wins.add_win(i);
 124       x = makecon(t);
 125     } else {
 126       // We now call Identity to try to simplify the cloned node.
 127       // Note that some Identity methods call phase->type(this).
 128       // Make sure that the type array is big enough for
 129       // our new node, even though we may throw the node away.
 130       // (Note: This tweaking with igvn only works because x is a new node.)
 131       _igvn.set_type(x, t);
 132       // If x is a TypeNode, capture any more-precise type permanently into Node
 133       // otherwise it will be not updated during igvn->transform since
 134       // igvn->type(x) is set to x->Value() already.
 135       x->raise_bottom_type(t);
 136       Node* y = x->Identity(&_igvn);
 137       if (y != x) {
 138         wins.add_win(i);
 139         x = y;
 140       } else {
 141         y = _igvn.hash_find(x);
 142         if (y == nullptr) {
 143           y = similar_subtype_check(x, region->in(i));
 144         }
 145         if (y) {
 146           wins.add_win(i);
 147           x = y;
 148         } else {
 149           // Else x is a new node we are keeping
 150           // We do not need register_new_node_with_optimizer
 151           // because set_type has already been called.
 152           _igvn._worklist.push(x);
 153         }
 154       }
 155     }
 156 
 157     phi->set_req( i, x );
 158 
 159     if (the_clone == nullptr) {
 160       continue;
 161     }
 162 
 163     if (the_clone != x) {
 164       _igvn.remove_dead_node(the_clone);
 165     } else if (region->is_Loop() && i == LoopNode::LoopBackControl &&
 166                n->is_Load() && can_move_to_inner_loop(n, region->as_Loop(), x)) {
 167       // it is not a win if 'x' moved from an outer to an inner loop
 168       // this edge case can only happen for Load nodes
 169       wins.reset();
 170       break;
 171     }
 172   }
 173   // Too few wins?
 174   if (!wins.profitable(policy)) {
 175     _igvn.remove_dead_node(phi);
 176     return nullptr;
 177   }
 178 
 179   // Record Phi
 180   register_new_node( phi, region );
 181 
 182   for (uint i2 = 1; i2 < phi->req(); i2++) {
 183     Node *x = phi->in(i2);
 184     // If we commoned up the cloned 'x' with another existing Node,
 185     // the existing Node picks up a new use.  We need to make the
 186     // existing Node occur higher up so it dominates its uses.
 187     Node *old_ctrl;
 188     IdealLoopTree *old_loop;
 189 
 190     if (x->is_Con()) {
 191       assert(get_ctrl(x) == C->root(), "constant control is not root");
 192       continue;
 193     }
 194     // The occasional new node
 195     if (x->_idx >= old_unique) {     // Found a new, unplaced node?
 196       old_ctrl = nullptr;
 197       old_loop = nullptr;               // Not in any prior loop
 198     } else {
 199       old_ctrl = get_ctrl(x);
 200       old_loop = get_loop(old_ctrl); // Get prior loop
 201     }
 202     // New late point must dominate new use
 203     Node *new_ctrl = dom_lca(old_ctrl, region->in(i2));
 204     if (new_ctrl == old_ctrl) // Nothing is changed
 205       continue;
 206 
 207     IdealLoopTree *new_loop = get_loop(new_ctrl);
 208 
 209     // Don't move x into a loop if its uses are
 210     // outside of loop. Otherwise x will be cloned
 211     // for each use outside of this loop.
 212     IdealLoopTree *use_loop = get_loop(region);
 213     if (!new_loop->is_member(use_loop) &&
 214         (old_loop == nullptr || !new_loop->is_member(old_loop))) {
 215       // Take early control, later control will be recalculated
 216       // during next iteration of loop optimizations.
 217       new_ctrl = get_early_ctrl(x);
 218       new_loop = get_loop(new_ctrl);
 219     }
 220     // Set new location
 221     set_ctrl(x, new_ctrl);
 222     // If changing loop bodies, see if we need to collect into new body
 223     if (old_loop != new_loop) {
 224       if (old_loop && !old_loop->_child)
 225         old_loop->_body.yank(x);
 226       if (!new_loop->_child)
 227         new_loop->_body.push(x);  // Collect body info
 228     }
 229   }
 230 
 231 #ifndef PRODUCT
 232   if (TraceLoopOpts) {
 233     tty->print_cr("Split %d %s through %d Phi in %d %s",
 234                   n->_idx, n->Name(), phi->_idx, region->_idx, region->Name());
 235   }
 236 #endif // !PRODUCT
 237 
 238   return phi;
 239 }
 240 
 241 // Test whether node 'x' can move into an inner loop relative to node 'n'.
 242 // Note: The test is not exact. Returns true if 'x' COULD end up in an inner loop,
 243 // BUT it can also return true and 'x' is in the outer loop
 244 bool PhaseIdealLoop::can_move_to_inner_loop(Node* n, LoopNode* n_loop, Node* x) {
 245   IdealLoopTree* n_loop_tree = get_loop(n_loop);
 246   IdealLoopTree* x_loop_tree = get_loop(get_early_ctrl(x));
 247   // x_loop_tree should be outer or same loop as n_loop_tree
 248   return !x_loop_tree->is_member(n_loop_tree);
 249 }
 250 
 251 // Subtype checks that carry profile data don't common so look for a replacement by following edges
 252 Node* PhaseIdealLoop::similar_subtype_check(const Node* x, Node* r_in) {
 253   if (x->is_SubTypeCheck()) {
 254     Node* in1 = x->in(1);
 255     for (DUIterator_Fast imax, i = in1->fast_outs(imax); i < imax; i++) {
 256       Node* u = in1->fast_out(i);
 257       if (u != x && u->is_SubTypeCheck() && u->in(1) == x->in(1) && u->in(2) == x->in(2)) {
 258         for (DUIterator_Fast jmax, j = u->fast_outs(jmax); j < jmax; j++) {
 259           Node* bol = u->fast_out(j);
 260           for (DUIterator_Fast kmax, k = bol->fast_outs(kmax); k < kmax; k++) {
 261             Node* iff = bol->fast_out(k);
 262             // Only dominating subtype checks are interesting: otherwise we risk replacing a subtype check by another with
 263             // unrelated profile
 264             if (iff->is_If() && is_dominator(iff, r_in)) {
 265               return u;
 266             }
 267           }
 268         }
 269       }
 270     }
 271   }
 272   return nullptr;
 273 }
 274 
 275 // Return true if 'n' is a Div or Mod node (without zero check If node which was removed earlier) with a loop phi divisor
 276 // of a trip-counted (integer or long) loop with a backedge input that could be zero (include zero in its type range). In
 277 // this case, we cannot split the division to the backedge as it could freely float above the loop exit check resulting in
 278 // a division by zero. This situation is possible because the type of an increment node of an iv phi (trip-counter) could
 279 // include zero while the iv phi does not (see PhiNode::Value() for trip-counted loops where we improve types of iv phis).
 280 // We also need to check other loop phis as they could have been created in the same split-if pass when applying
 281 // PhaseIdealLoop::split_thru_phi() to split nodes through an iv phi.
 282 bool PhaseIdealLoop::cannot_split_division(const Node* n, const Node* region) const {
 283   const Type* zero;
 284   switch (n->Opcode()) {
 285     case Op_DivI:
 286     case Op_ModI:
 287     case Op_UDivI:
 288     case Op_UModI:
 289       zero = TypeInt::ZERO;
 290       break;
 291     case Op_DivL:
 292     case Op_ModL:
 293     case Op_UDivL:
 294     case Op_UModL:
 295       zero = TypeLong::ZERO;
 296       break;
 297     default:
 298       return false;
 299   }
 300 
 301   if (n->in(0) != nullptr) {
 302     // Cannot split through phi if Div or Mod node has a control dependency to a zero check.
 303     return true;
 304   }
 305 
 306   Node* divisor = n->in(2);
 307   return is_divisor_loop_phi(divisor, region) &&
 308          loop_phi_backedge_type_contains_zero(divisor, zero);
 309 }
 310 
 311 bool PhaseIdealLoop::is_divisor_loop_phi(const Node* divisor, const Node* loop) {
 312   return loop->is_Loop() && divisor->is_Phi() && divisor->in(0) == loop;
 313 }
 314 
 315 bool PhaseIdealLoop::loop_phi_backedge_type_contains_zero(const Node* phi_divisor, const Type* zero) const {
 316     return _igvn.type(phi_divisor->in(LoopNode::LoopBackControl))->filter_speculative(zero) != Type::TOP;
 317 }
 318 
 319 //------------------------------dominated_by------------------------------------
 320 // Replace the dominated test with an obvious true or false.  Place it on the
 321 // IGVN worklist for later cleanup.  Move control-dependent data Nodes on the
 322 // live path up to the dominating control.
 323 void PhaseIdealLoop::dominated_by(IfProjNode* prevdom, IfNode* iff, bool flip, bool pin_array_access_nodes) {
 324   if (VerifyLoopOptimizations && PrintOpto) { tty->print_cr("dominating test"); }
 325 
 326   // prevdom is the dominating projection of the dominating test.
 327   assert(iff->Opcode() == Op_If ||
 328          iff->Opcode() == Op_CountedLoopEnd ||
 329          iff->Opcode() == Op_LongCountedLoopEnd ||
 330          iff->Opcode() == Op_RangeCheck ||
 331          iff->Opcode() == Op_ParsePredicate,
 332         "Check this code when new subtype is added");
 333 
 334   int pop = prevdom->Opcode();
 335   assert( pop == Op_IfFalse || pop == Op_IfTrue, "" );
 336   if (flip) {
 337     if (pop == Op_IfTrue)
 338       pop = Op_IfFalse;
 339     else
 340       pop = Op_IfTrue;
 341   }
 342   // 'con' is set to true or false to kill the dominated test.
 343   Node* con = makecon(pop == Op_IfTrue ? TypeInt::ONE : TypeInt::ZERO);
 344   // Hack the dominated test
 345   _igvn.replace_input_of(iff, 1, con);
 346 
 347   // If I don't have a reachable TRUE and FALSE path following the IfNode then
 348   // I can assume this path reaches an infinite loop.  In this case it's not
 349   // important to optimize the data Nodes - either the whole compilation will
 350   // be tossed or this path (and all data Nodes) will go dead.
 351   if (iff->outcnt() != 2) {
 352     return;
 353   }
 354 
 355   // Make control-dependent data Nodes on the live path (path that will remain
 356   // once the dominated IF is removed) become control-dependent on the
 357   // dominating projection.
 358   Node* dp = iff->proj_out_or_null(pop == Op_IfTrue);
 359 
 360   if (dp == nullptr) {
 361     return;
 362   }
 363 
 364   rewire_safe_outputs_to_dominator(dp, prevdom, pin_array_access_nodes);
 365 }
 366 
 367 void PhaseIdealLoop::rewire_safe_outputs_to_dominator(Node* source, Node* dominator, const bool pin_array_access_nodes) {
 368   IdealLoopTree* old_loop = get_loop(source);
 369 
 370   for (DUIterator_Fast imax, i = source->fast_outs(imax); i < imax; i++) {
 371     Node* out = source->fast_out(i); // Control-dependent node
 372     // Do not rewire Div and Mod nodes which could have a zero divisor to avoid skipping their zero check.
 373     if (out->depends_only_on_test() && _igvn.no_dependent_zero_check(out)) {
 374       assert(out->in(0) == source, "must be control dependent on source");
 375       _igvn.replace_input_of(out, 0, dominator);
 376       if (pin_array_access_nodes) {
 377         // Because of Loop Predication, Loads and range check Cast nodes that are control dependent on this range
 378         // check (that is about to be removed) now depend on multiple dominating Hoisted Check Predicates. After the
 379         // removal of this range check, these control dependent nodes end up at the lowest/nearest dominating predicate
 380         // in the graph. To ensure that these Loads/Casts do not float above any of the dominating checks (even when the
 381         // lowest dominating check is later replaced by yet another dominating check), we need to pin them at the lowest
 382         // dominating check.
 383         Node* clone = out->pin_array_access_node();
 384         if (clone != nullptr) {
 385           clone = _igvn.register_new_node_with_optimizer(clone, out);
 386           _igvn.replace_node(out, clone);
 387           out = clone;
 388         }
 389       }
 390       set_early_ctrl(out, false);
 391       IdealLoopTree* new_loop = get_loop(get_ctrl(out));
 392       if (old_loop != new_loop) {
 393         if (!old_loop->_child) {
 394           old_loop->_body.yank(out);
 395         }
 396         if (!new_loop->_child) {
 397           new_loop->_body.push(out);
 398         }
 399       }
 400       --i;
 401       --imax;
 402     }
 403   }
 404 }
 405 
 406 //------------------------------has_local_phi_input----------------------------
 407 // Return TRUE if 'n' has Phi inputs from its local block and no other
 408 // block-local inputs (all non-local-phi inputs come from earlier blocks)
 409 Node *PhaseIdealLoop::has_local_phi_input( Node *n ) {
 410   Node *n_ctrl = get_ctrl(n);
 411   // See if some inputs come from a Phi in this block, or from before
 412   // this block.
 413   uint i;
 414   for( i = 1; i < n->req(); i++ ) {
 415     Node *phi = n->in(i);
 416     if( phi->is_Phi() && phi->in(0) == n_ctrl )
 417       break;
 418   }
 419   if( i >= n->req() )
 420     return nullptr;                // No Phi inputs; nowhere to clone thru
 421 
 422   // Check for inputs created between 'n' and the Phi input.  These
 423   // must split as well; they have already been given the chance
 424   // (courtesy of a post-order visit) and since they did not we must
 425   // recover the 'cost' of splitting them by being very profitable
 426   // when splitting 'n'.  Since this is unlikely we simply give up.
 427   for( i = 1; i < n->req(); i++ ) {
 428     Node *m = n->in(i);
 429     if( get_ctrl(m) == n_ctrl && !m->is_Phi() ) {
 430       // We allow the special case of AddP's with no local inputs.
 431       // This allows us to split-up address expressions.
 432       if (m->is_AddP() &&
 433           get_ctrl(m->in(AddPNode::Base)) != n_ctrl &&
 434           get_ctrl(m->in(AddPNode::Address)) != n_ctrl &&
 435           get_ctrl(m->in(AddPNode::Offset)) != n_ctrl) {
 436         // Move the AddP up to the dominating point. That's fine because control of m's inputs
 437         // must dominate get_ctrl(m) == n_ctrl and we just checked that the input controls are != n_ctrl.
 438         Node* c = find_non_split_ctrl(idom(n_ctrl));
 439         if (c->is_OuterStripMinedLoop()) {
 440           c->as_Loop()->verify_strip_mined(1);
 441           c = c->in(LoopNode::EntryControl);
 442         }
 443         set_ctrl_and_loop(m, c);
 444         continue;
 445       }
 446       return nullptr;
 447     }
 448     assert(n->is_Phi() || m->is_Phi() || is_dominator(get_ctrl(m), n_ctrl), "m has strange control");
 449   }
 450 
 451   return n_ctrl;
 452 }
 453 
 454 // Replace expressions like ((V+I) << 2) with (V<<2 + I<<2).
 455 Node* PhaseIdealLoop::remix_address_expressions_add_left_shift(Node* n, IdealLoopTree* n_loop, Node* n_ctrl, BasicType bt) {
 456   assert(bt == T_INT || bt == T_LONG, "only for integers");
 457   int n_op = n->Opcode();
 458 
 459   if (n_op == Op_LShift(bt)) {
 460     // Scale is loop invariant
 461     Node* scale = n->in(2);
 462     Node* scale_ctrl = get_ctrl(scale);
 463     IdealLoopTree* scale_loop = get_loop(scale_ctrl);
 464     if (n_loop == scale_loop || !scale_loop->is_member(n_loop)) {
 465       return nullptr;
 466     }
 467     const TypeInt* scale_t = scale->bottom_type()->isa_int();
 468     if (scale_t != nullptr && scale_t->is_con() && scale_t->get_con() >= 16) {
 469       return nullptr;              // Dont bother with byte/short masking
 470     }
 471     // Add must vary with loop (else shift would be loop-invariant)
 472     Node* add = n->in(1);
 473     Node* add_ctrl = get_ctrl(add);
 474     IdealLoopTree* add_loop = get_loop(add_ctrl);
 475     if (n_loop != add_loop) {
 476       return nullptr;  // happens w/ evil ZKM loops
 477     }
 478 
 479     // Convert I-V into I+ (0-V); same for V-I
 480     if (add->Opcode() == Op_Sub(bt) &&
 481         _igvn.type(add->in(1)) != TypeInteger::zero(bt)) {
 482       assert(add->Opcode() == Op_SubI || add->Opcode() == Op_SubL, "");
 483       Node* zero = integercon(0, bt);
 484       Node* neg = SubNode::make(zero, add->in(2), bt);
 485       register_new_node_with_ctrl_of(neg, add->in(2));
 486       add = AddNode::make(add->in(1), neg, bt);
 487       register_new_node(add, add_ctrl);
 488     }
 489     if (add->Opcode() != Op_Add(bt)) return nullptr;
 490     assert(add->Opcode() == Op_AddI || add->Opcode() == Op_AddL, "");
 491     // See if one add input is loop invariant
 492     Node* add_var = add->in(1);
 493     Node* add_var_ctrl = get_ctrl(add_var);
 494     IdealLoopTree* add_var_loop = get_loop(add_var_ctrl);
 495     Node* add_invar = add->in(2);
 496     Node* add_invar_ctrl = get_ctrl(add_invar);
 497     IdealLoopTree* add_invar_loop = get_loop(add_invar_ctrl);
 498     if (add_invar_loop == n_loop) {
 499       // Swap to find the invariant part
 500       add_invar = add_var;
 501       add_invar_ctrl = add_var_ctrl;
 502       add_invar_loop = add_var_loop;
 503       add_var = add->in(2);
 504     } else if (add_var_loop != n_loop) { // Else neither input is loop invariant
 505       return nullptr;
 506     }
 507     if (n_loop == add_invar_loop || !add_invar_loop->is_member(n_loop)) {
 508       return nullptr;              // No invariant part of the add?
 509     }
 510 
 511     // Yes!  Reshape address expression!
 512     Node* inv_scale = LShiftNode::make(add_invar, scale, bt);
 513     Node* inv_scale_ctrl =
 514             dom_depth(add_invar_ctrl) > dom_depth(scale_ctrl) ?
 515             add_invar_ctrl : scale_ctrl;
 516     register_new_node(inv_scale, inv_scale_ctrl);
 517     Node* var_scale = LShiftNode::make(add_var, scale, bt);
 518     register_new_node(var_scale, n_ctrl);
 519     Node* var_add = AddNode::make(var_scale, inv_scale, bt);
 520     register_new_node(var_add, n_ctrl);
 521     _igvn.replace_node(n, var_add);
 522     return var_add;
 523   }
 524   return nullptr;
 525 }
 526 
 527 //------------------------------remix_address_expressions----------------------
 528 // Rework addressing expressions to get the most loop-invariant stuff
 529 // moved out.  We'd like to do all associative operators, but it's especially
 530 // important (common) to do address expressions.
 531 Node* PhaseIdealLoop::remix_address_expressions(Node* n) {
 532   if (!has_ctrl(n))  return nullptr;
 533   Node* n_ctrl = get_ctrl(n);
 534   IdealLoopTree* n_loop = get_loop(n_ctrl);
 535 
 536   // See if 'n' mixes loop-varying and loop-invariant inputs and
 537   // itself is loop-varying.
 538 
 539   // Only interested in binary ops (and AddP)
 540   if (n->req() < 3 || n->req() > 4) return nullptr;
 541 
 542   Node* n1_ctrl = get_ctrl(n->in(                    1));
 543   Node* n2_ctrl = get_ctrl(n->in(                    2));
 544   Node* n3_ctrl = get_ctrl(n->in(n->req() == 3 ? 2 : 3));
 545   IdealLoopTree* n1_loop = get_loop(n1_ctrl);
 546   IdealLoopTree* n2_loop = get_loop(n2_ctrl);
 547   IdealLoopTree* n3_loop = get_loop(n3_ctrl);
 548 
 549   // Does one of my inputs spin in a tighter loop than self?
 550   if ((n_loop->is_member(n1_loop) && n_loop != n1_loop) ||
 551       (n_loop->is_member(n2_loop) && n_loop != n2_loop) ||
 552       (n_loop->is_member(n3_loop) && n_loop != n3_loop)) {
 553     return nullptr;                // Leave well enough alone
 554   }
 555 
 556   // Is at least one of my inputs loop-invariant?
 557   if (n1_loop == n_loop &&
 558       n2_loop == n_loop &&
 559       n3_loop == n_loop) {
 560     return nullptr;                // No loop-invariant inputs
 561   }
 562 
 563   Node* res = remix_address_expressions_add_left_shift(n, n_loop, n_ctrl, T_INT);
 564   if (res != nullptr) {
 565     return res;
 566   }
 567   res = remix_address_expressions_add_left_shift(n, n_loop, n_ctrl, T_LONG);
 568   if (res != nullptr) {
 569     return res;
 570   }
 571 
 572   int n_op = n->Opcode();
 573   // Replace (I+V) with (V+I)
 574   if (n_op == Op_AddI ||
 575       n_op == Op_AddL ||
 576       n_op == Op_AddF ||
 577       n_op == Op_AddD ||
 578       n_op == Op_MulI ||
 579       n_op == Op_MulL ||
 580       n_op == Op_MulF ||
 581       n_op == Op_MulD) {
 582     if (n2_loop == n_loop) {
 583       assert(n1_loop != n_loop, "");
 584       n->swap_edges(1, 2);
 585     }
 586   }
 587 
 588   // Replace ((I1 +p V) +p I2) with ((I1 +p I2) +p V),
 589   // but not if I2 is a constant. Skip for irreducible loops.
 590   if (n_op == Op_AddP && n_loop->_head->is_Loop()) {
 591     if (n2_loop == n_loop && n3_loop != n_loop) {
 592       if (n->in(2)->Opcode() == Op_AddP && !n->in(3)->is_Con()) {
 593         Node* n22_ctrl = get_ctrl(n->in(2)->in(2));
 594         Node* n23_ctrl = get_ctrl(n->in(2)->in(3));
 595         IdealLoopTree* n22loop = get_loop(n22_ctrl);
 596         IdealLoopTree* n23_loop = get_loop(n23_ctrl);
 597         if (n22loop != n_loop && n22loop->is_member(n_loop) &&
 598             n23_loop == n_loop) {
 599           Node* add1 = new AddPNode(n->in(1), n->in(2)->in(2), n->in(3));
 600           // Stuff new AddP in the loop preheader
 601           register_new_node(add1, n_loop->_head->as_Loop()->skip_strip_mined(1)->in(LoopNode::EntryControl));
 602           Node* add2 = new AddPNode(n->in(1), add1, n->in(2)->in(3));
 603           register_new_node(add2, n_ctrl);
 604           _igvn.replace_node(n, add2);
 605           return add2;
 606         }
 607       }
 608     }
 609 
 610     // Replace (I1 +p (I2 + V)) with ((I1 +p I2) +p V)
 611     if (n2_loop != n_loop && n3_loop == n_loop) {
 612       if (n->in(3)->Opcode() == Op_AddX) {
 613         Node* V = n->in(3)->in(1);
 614         Node* I = n->in(3)->in(2);
 615         if (is_member(n_loop,get_ctrl(V))) {
 616         } else {
 617           Node *tmp = V; V = I; I = tmp;
 618         }
 619         if (!is_member(n_loop,get_ctrl(I))) {
 620           Node* add1 = new AddPNode(n->in(1), n->in(2), I);
 621           // Stuff new AddP in the loop preheader
 622           register_new_node(add1, n_loop->_head->as_Loop()->skip_strip_mined(1)->in(LoopNode::EntryControl));
 623           Node* add2 = new AddPNode(n->in(1), add1, V);
 624           register_new_node(add2, n_ctrl);
 625           _igvn.replace_node(n, add2);
 626           return add2;
 627         }
 628       }
 629     }
 630   }
 631 
 632   return nullptr;
 633 }
 634 
 635 // Optimize ((in1[2*i] * in2[2*i]) + (in1[2*i+1] * in2[2*i+1]))
 636 Node *PhaseIdealLoop::convert_add_to_muladd(Node* n) {
 637   assert(n->Opcode() == Op_AddI, "sanity");
 638   Node * nn = nullptr;
 639   Node * in1 = n->in(1);
 640   Node * in2 = n->in(2);
 641   if (in1->Opcode() == Op_MulI && in2->Opcode() == Op_MulI) {
 642     IdealLoopTree* loop_n = get_loop(get_ctrl(n));
 643     if (loop_n->is_counted() &&
 644         loop_n->_head->as_Loop()->is_valid_counted_loop(T_INT) &&
 645         Matcher::match_rule_supported(Op_MulAddVS2VI) &&
 646         Matcher::match_rule_supported(Op_MulAddS2I)) {
 647       Node* mul_in1 = in1->in(1);
 648       Node* mul_in2 = in1->in(2);
 649       Node* mul_in3 = in2->in(1);
 650       Node* mul_in4 = in2->in(2);
 651       if (mul_in1->Opcode() == Op_LoadS &&
 652           mul_in2->Opcode() == Op_LoadS &&
 653           mul_in3->Opcode() == Op_LoadS &&
 654           mul_in4->Opcode() == Op_LoadS) {
 655         IdealLoopTree* loop1 = get_loop(get_ctrl(mul_in1));
 656         IdealLoopTree* loop2 = get_loop(get_ctrl(mul_in2));
 657         IdealLoopTree* loop3 = get_loop(get_ctrl(mul_in3));
 658         IdealLoopTree* loop4 = get_loop(get_ctrl(mul_in4));
 659         IdealLoopTree* loop5 = get_loop(get_ctrl(in1));
 660         IdealLoopTree* loop6 = get_loop(get_ctrl(in2));
 661         // All nodes should be in the same counted loop.
 662         if (loop_n == loop1 && loop_n == loop2 && loop_n == loop3 &&
 663             loop_n == loop4 && loop_n == loop5 && loop_n == loop6) {
 664           Node* adr1 = mul_in1->in(MemNode::Address);
 665           Node* adr2 = mul_in2->in(MemNode::Address);
 666           Node* adr3 = mul_in3->in(MemNode::Address);
 667           Node* adr4 = mul_in4->in(MemNode::Address);
 668           if (adr1->is_AddP() && adr2->is_AddP() && adr3->is_AddP() && adr4->is_AddP()) {
 669             if ((adr1->in(AddPNode::Base) == adr3->in(AddPNode::Base)) &&
 670                 (adr2->in(AddPNode::Base) == adr4->in(AddPNode::Base))) {
 671               nn = new MulAddS2INode(mul_in1, mul_in2, mul_in3, mul_in4);
 672               register_new_node_with_ctrl_of(nn, n);
 673               _igvn.replace_node(n, nn);
 674               return nn;
 675             } else if ((adr1->in(AddPNode::Base) == adr4->in(AddPNode::Base)) &&
 676                        (adr2->in(AddPNode::Base) == adr3->in(AddPNode::Base))) {
 677               nn = new MulAddS2INode(mul_in1, mul_in2, mul_in4, mul_in3);
 678               register_new_node_with_ctrl_of(nn, n);
 679               _igvn.replace_node(n, nn);
 680               return nn;
 681             }
 682           }
 683         }
 684       }
 685     }
 686   }
 687   return nn;
 688 }
 689 
 690 //------------------------------conditional_move-------------------------------
 691 // Attempt to replace a Phi with a conditional move.  We have some pretty
 692 // strict profitability requirements.  All Phis at the merge point must
 693 // be converted, so we can remove the control flow.  We need to limit the
 694 // number of c-moves to a small handful.  All code that was in the side-arms
 695 // of the CFG diamond is now speculatively executed.  This code has to be
 696 // "cheap enough".  We are pretty much limited to CFG diamonds that merge
 697 // 1 or 2 items with a total of 1 or 2 ops executed speculatively.
 698 Node *PhaseIdealLoop::conditional_move( Node *region ) {
 699 
 700   assert(region->is_Region(), "sanity check");
 701   if (region->req() != 3) return nullptr;
 702 
 703   // Check for CFG diamond
 704   Node *lp = region->in(1);
 705   Node *rp = region->in(2);
 706   if (!lp || !rp) return nullptr;
 707   Node *lp_c = lp->in(0);
 708   if (lp_c == nullptr || lp_c != rp->in(0) || !lp_c->is_If()) return nullptr;
 709   IfNode *iff = lp_c->as_If();
 710 
 711   // Check for ops pinned in an arm of the diamond.
 712   // Can't remove the control flow in this case
 713   if (lp->outcnt() > 1) return nullptr;
 714   if (rp->outcnt() > 1) return nullptr;
 715 
 716   IdealLoopTree* r_loop = get_loop(region);
 717   assert(r_loop == get_loop(iff), "sanity");
 718   // Always convert to CMOVE if all results are used only outside this loop.
 719   bool used_inside_loop = (r_loop == _ltree_root);
 720 
 721   // Check profitability
 722   int cost = 0;
 723   int phis = 0;
 724   for (DUIterator_Fast imax, i = region->fast_outs(imax); i < imax; i++) {
 725     Node *out = region->fast_out(i);
 726     if (!out->is_Phi()) continue; // Ignore other control edges, etc
 727     phis++;
 728     PhiNode* phi = out->as_Phi();
 729     BasicType bt = phi->type()->basic_type();
 730     switch (bt) {
 731     case T_DOUBLE:
 732     case T_FLOAT:
 733       if (C->use_cmove()) {
 734         continue; //TODO: maybe we want to add some cost
 735       }
 736       cost += Matcher::float_cmove_cost(); // Could be very expensive
 737       break;
 738     case T_LONG: {
 739       cost += Matcher::long_cmove_cost(); // May encodes as 2 CMOV's
 740     }
 741     case T_INT:                 // These all CMOV fine
 742     case T_ADDRESS: {           // (RawPtr)
 743       cost++;
 744       break;
 745     }
 746     case T_NARROWOOP: // Fall through
 747     case T_OBJECT: {            // Base oops are OK, but not derived oops
 748       const TypeOopPtr *tp = phi->type()->make_ptr()->isa_oopptr();
 749       // Derived pointers are Bad (tm): what's the Base (for GC purposes) of a
 750       // CMOVE'd derived pointer?  It's a CMOVE'd derived base.  Thus
 751       // CMOVE'ing a derived pointer requires we also CMOVE the base.  If we
 752       // have a Phi for the base here that we convert to a CMOVE all is well
 753       // and good.  But if the base is dead, we'll not make a CMOVE.  Later
 754       // the allocator will have to produce a base by creating a CMOVE of the
 755       // relevant bases.  This puts the allocator in the business of
 756       // manufacturing expensive instructions, generally a bad plan.
 757       // Just Say No to Conditionally-Moved Derived Pointers.
 758       if (tp && tp->offset() != 0)
 759         return nullptr;
 760       cost++;
 761       break;
 762     }
 763     default:
 764       return nullptr;              // In particular, can't do memory or I/O
 765     }
 766     // Add in cost any speculative ops
 767     for (uint j = 1; j < region->req(); j++) {
 768       Node *proj = region->in(j);
 769       Node *inp = phi->in(j);
 770       if (get_ctrl(inp) == proj) { // Found local op
 771         cost++;
 772         // Check for a chain of dependent ops; these will all become
 773         // speculative in a CMOV.
 774         for (uint k = 1; k < inp->req(); k++)
 775           if (get_ctrl(inp->in(k)) == proj)
 776             cost += ConditionalMoveLimit; // Too much speculative goo
 777       }
 778     }
 779     // See if the Phi is used by a Cmp or Narrow oop Decode/Encode.
 780     // This will likely Split-If, a higher-payoff operation.
 781     for (DUIterator_Fast kmax, k = phi->fast_outs(kmax); k < kmax; k++) {
 782       Node* use = phi->fast_out(k);
 783       if (use->is_Cmp() || use->is_DecodeNarrowPtr() || use->is_EncodeNarrowPtr())
 784         cost += ConditionalMoveLimit;
 785       // Is there a use inside the loop?
 786       // Note: check only basic types since CMoveP is pinned.
 787       if (!used_inside_loop && is_java_primitive(bt)) {
 788         IdealLoopTree* u_loop = get_loop(has_ctrl(use) ? get_ctrl(use) : use);
 789         if (r_loop == u_loop || r_loop->is_member(u_loop)) {
 790           used_inside_loop = true;
 791         }
 792       }
 793     }
 794   }//for
 795   Node* bol = iff->in(1);
 796   assert(!bol->is_OpaqueInitializedAssertionPredicate(), "Initialized Assertion Predicates cannot form a diamond with Halt");
 797   if (bol->is_OpaqueTemplateAssertionPredicate()) {
 798     // Ignore Template Assertion Predicates with OpaqueTemplateAssertionPredicate nodes.
 799     return nullptr;
 800   }
 801   if (bol->is_OpaqueMultiversioning()) {
 802     assert(bol->as_OpaqueMultiversioning()->is_useless(), "Must be useless, i.e. fast main loop has already disappeared.");
 803     // Ignore multiversion_if that just lost its loops. The OpaqueMultiversioning is marked useless,
 804     // and will make the multiversion_if constant fold in the next IGVN round.
 805     return nullptr;
 806   }
 807   if (!bol->is_Bool()) {
 808     assert(false, "Expected Bool, but got %s", NodeClassNames[bol->Opcode()]);
 809     return nullptr;
 810   }
 811   int cmp_op = bol->in(1)->Opcode();
 812   if (cmp_op == Op_SubTypeCheck) { // SubTypeCheck expansion expects an IfNode
 813     return nullptr;
 814   }
 815   // It is expensive to generate flags from a float compare.
 816   // Avoid duplicated float compare.
 817   if (phis > 1 && (cmp_op == Op_CmpF || cmp_op == Op_CmpD)) return nullptr;
 818 
 819   float infrequent_prob = PROB_UNLIKELY_MAG(3);
 820   // Ignore cost and blocks frequency if CMOVE can be moved outside the loop.
 821   if (used_inside_loop) {
 822     if (cost >= ConditionalMoveLimit) return nullptr; // Too much goo
 823 
 824     // BlockLayoutByFrequency optimization moves infrequent branch
 825     // from hot path. No point in CMOV'ing in such case (110 is used
 826     // instead of 100 to take into account not exactness of float value).
 827     if (BlockLayoutByFrequency) {
 828       infrequent_prob = MAX2(infrequent_prob, (float)BlockLayoutMinDiamondPercentage/110.0f);
 829     }
 830   }
 831   // Check for highly predictable branch.  No point in CMOV'ing if
 832   // we are going to predict accurately all the time.
 833   if (C->use_cmove() && (cmp_op == Op_CmpF || cmp_op == Op_CmpD)) {
 834     //keep going
 835   } else if (iff->_prob < infrequent_prob ||
 836       iff->_prob > (1.0f - infrequent_prob))
 837     return nullptr;
 838 
 839   // --------------
 840   // Now replace all Phis with CMOV's
 841   Node *cmov_ctrl = iff->in(0);
 842   uint flip = (lp->Opcode() == Op_IfTrue);
 843   Node_List wq;
 844   while (1) {
 845     PhiNode* phi = nullptr;
 846     for (DUIterator_Fast imax, i = region->fast_outs(imax); i < imax; i++) {
 847       Node *out = region->fast_out(i);
 848       if (out->is_Phi()) {
 849         phi = out->as_Phi();
 850         break;
 851       }
 852     }
 853     if (phi == nullptr || _igvn.type(phi) == Type::TOP || !CMoveNode::supported(_igvn.type(phi))) {
 854       break;
 855     }
 856     // Move speculative ops
 857     wq.push(phi);
 858     while (wq.size() > 0) {
 859       Node *n = wq.pop();
 860       for (uint j = 1; j < n->req(); j++) {
 861         Node* m = n->in(j);
 862         if (m != nullptr && !is_dominator(get_ctrl(m), cmov_ctrl)) {
 863           set_ctrl(m, cmov_ctrl);
 864           wq.push(m);
 865         }
 866       }
 867     }
 868     Node* cmov = CMoveNode::make(iff->in(1), phi->in(1+flip), phi->in(2-flip), _igvn.type(phi));
 869     register_new_node(cmov, cmov_ctrl);
 870     _igvn.replace_node(phi, cmov);
 871 #ifndef PRODUCT
 872     if (TraceLoopOpts) {
 873       tty->print("CMOV  ");
 874       r_loop->dump_head();
 875       if (Verbose) {
 876         bol->in(1)->dump(1);
 877         cmov->dump(1);
 878       }
 879     }
 880     DEBUG_ONLY( if (VerifyLoopOptimizations) { verify(); } );
 881 #endif
 882   }
 883 
 884   // The useless CFG diamond will fold up later; see the optimization in
 885   // RegionNode::Ideal.
 886   _igvn._worklist.push(region);
 887 
 888   return iff->in(1);
 889 }
 890 
 891 static void enqueue_cfg_uses(Node* m, Unique_Node_List& wq) {
 892   for (DUIterator_Fast imax, i = m->fast_outs(imax); i < imax; i++) {
 893     Node* u = m->fast_out(i);
 894     if (u->is_CFG()) {
 895       if (u->is_NeverBranch()) {
 896         u = u->as_NeverBranch()->proj_out(0);
 897         enqueue_cfg_uses(u, wq);
 898       } else {
 899         wq.push(u);
 900       }
 901     }
 902   }
 903 }
 904 
 905 // Try moving a store out of a loop, right before the loop
 906 Node* PhaseIdealLoop::try_move_store_before_loop(Node* n, Node *n_ctrl) {
 907   // Store has to be first in the loop body
 908   IdealLoopTree *n_loop = get_loop(n_ctrl);
 909   if (n->is_Store() && n_loop != _ltree_root &&
 910       n_loop->is_loop() && n_loop->_head->is_Loop() &&
 911       n->in(0) != nullptr) {
 912     Node* address = n->in(MemNode::Address);
 913     Node* value = n->in(MemNode::ValueIn);
 914     Node* mem = n->in(MemNode::Memory);
 915     IdealLoopTree* address_loop = get_loop(get_ctrl(address));
 916     IdealLoopTree* value_loop = get_loop(get_ctrl(value));
 917 
 918     // - address and value must be loop invariant
 919     // - memory must be a memory Phi for the loop
 920     // - Store must be the only store on this memory slice in the
 921     // loop: if there's another store following this one then value
 922     // written at iteration i by the second store could be overwritten
 923     // at iteration i+n by the first store: it's not safe to move the
 924     // first store out of the loop
 925     // - nothing must observe the memory Phi: it guarantees no read
 926     // before the store, we are also guaranteed the store post
 927     // dominates the loop head (ignoring a possible early
 928     // exit). Otherwise there would be extra Phi involved between the
 929     // loop's Phi and the store.
 930     // - there must be no early exit from the loop before the Store
 931     // (such an exit most of the time would be an extra use of the
 932     // memory Phi but sometimes is a bottom memory Phi that takes the
 933     // store as input).
 934 
 935     if (!n_loop->is_member(address_loop) &&
 936         !n_loop->is_member(value_loop) &&
 937         mem->is_Phi() && mem->in(0) == n_loop->_head &&
 938         mem->outcnt() == 1 &&
 939         mem->in(LoopNode::LoopBackControl) == n) {
 940 
 941       assert(n_loop->_tail != nullptr, "need a tail");
 942       assert(is_dominator(n_ctrl, n_loop->_tail), "store control must not be in a branch in the loop");
 943 
 944       // Verify that there's no early exit of the loop before the store.
 945       bool ctrl_ok = false;
 946       {
 947         // Follow control from loop head until n, we exit the loop or
 948         // we reach the tail
 949         ResourceMark rm;
 950         Unique_Node_List wq;
 951         wq.push(n_loop->_head);
 952 
 953         for (uint next = 0; next < wq.size(); ++next) {
 954           Node *m = wq.at(next);
 955           if (m == n->in(0)) {
 956             ctrl_ok = true;
 957             continue;
 958           }
 959           assert(!has_ctrl(m), "should be CFG");
 960           if (!n_loop->is_member(get_loop(m)) || m == n_loop->_tail) {
 961             ctrl_ok = false;
 962             break;
 963           }
 964           enqueue_cfg_uses(m, wq);
 965           if (wq.size() > 10) {
 966             ctrl_ok = false;
 967             break;
 968           }
 969         }
 970       }
 971       if (ctrl_ok) {
 972         // move the Store
 973         _igvn.replace_input_of(mem, LoopNode::LoopBackControl, mem);
 974         _igvn.replace_input_of(n, 0, n_loop->_head->as_Loop()->skip_strip_mined()->in(LoopNode::EntryControl));
 975         _igvn.replace_input_of(n, MemNode::Memory, mem->in(LoopNode::EntryControl));
 976         // Disconnect the phi now. An empty phi can confuse other
 977         // optimizations in this pass of loop opts.
 978         _igvn.replace_node(mem, mem->in(LoopNode::EntryControl));
 979         n_loop->_body.yank(mem);
 980 
 981         set_ctrl_and_loop(n, n->in(0));
 982 
 983         return n;
 984       }
 985     }
 986   }
 987   return nullptr;
 988 }
 989 
 990 // Try moving a store out of a loop, right after the loop
 991 void PhaseIdealLoop::try_move_store_after_loop(Node* n) {
 992   if (n->is_Store() && n->in(0) != nullptr) {
 993     Node *n_ctrl = get_ctrl(n);
 994     IdealLoopTree *n_loop = get_loop(n_ctrl);
 995     // Store must be in a loop
 996     if (n_loop != _ltree_root && !n_loop->_irreducible) {
 997       Node* address = n->in(MemNode::Address);
 998       Node* value = n->in(MemNode::ValueIn);
 999       IdealLoopTree* address_loop = get_loop(get_ctrl(address));
1000       // address must be loop invariant
1001       if (!n_loop->is_member(address_loop)) {
1002         // Store must be last on this memory slice in the loop and
1003         // nothing in the loop must observe it
1004         Node* phi = nullptr;
1005         for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
1006           Node* u = n->fast_out(i);
1007           if (has_ctrl(u)) { // control use?
1008             IdealLoopTree *u_loop = get_loop(get_ctrl(u));
1009             if (!n_loop->is_member(u_loop)) {
1010               continue;
1011             }
1012             if (u->is_Phi() && u->in(0) == n_loop->_head) {
1013               assert(_igvn.type(u) == Type::MEMORY, "bad phi");
1014               // multiple phis on the same slice are possible
1015               if (phi != nullptr) {
1016                 return;
1017               }
1018               phi = u;
1019               continue;
1020             }
1021           }
1022           return;
1023         }
1024         if (phi != nullptr) {
1025           // Nothing in the loop before the store (next iteration)
1026           // must observe the stored value
1027           bool mem_ok = true;
1028           {
1029             ResourceMark rm;
1030             Unique_Node_List wq;
1031             wq.push(phi);
1032             for (uint next = 0; next < wq.size() && mem_ok; ++next) {
1033               Node *m = wq.at(next);
1034               for (DUIterator_Fast imax, i = m->fast_outs(imax); i < imax && mem_ok; i++) {
1035                 Node* u = m->fast_out(i);
1036                 if (u->is_Store() || u->is_Phi()) {
1037                   if (u != n) {
1038                     wq.push(u);
1039                     mem_ok = (wq.size() <= 10);
1040                   }
1041                 } else {
1042                   mem_ok = false;
1043                   break;
1044                 }
1045               }
1046             }
1047           }
1048           if (mem_ok) {
1049             // Move the store out of the loop if the LCA of all
1050             // users (except for the phi) is outside the loop.
1051             Node* hook = new Node(1);
1052             hook->init_req(0, n_ctrl); // Add an input to prevent hook from being dead
1053             _igvn.rehash_node_delayed(phi);
1054             int count = phi->replace_edge(n, hook, &_igvn);
1055             assert(count > 0, "inconsistent phi");
1056 
1057             // Compute latest point this store can go
1058             Node* lca = get_late_ctrl(n, get_ctrl(n));
1059             if (lca->is_OuterStripMinedLoop()) {
1060               lca = lca->in(LoopNode::EntryControl);
1061             }
1062             if (n_loop->is_member(get_loop(lca))) {
1063               // LCA is in the loop - bail out
1064               _igvn.replace_node(hook, n);
1065               return;
1066             }
1067 #ifdef ASSERT
1068             if (n_loop->_head->is_Loop() && n_loop->_head->as_Loop()->is_strip_mined()) {
1069               assert(n_loop->_head->Opcode() == Op_CountedLoop, "outer loop is a strip mined");
1070               n_loop->_head->as_Loop()->verify_strip_mined(1);
1071               Node* outer = n_loop->_head->as_CountedLoop()->outer_loop();
1072               IdealLoopTree* outer_loop = get_loop(outer);
1073               assert(n_loop->_parent == outer_loop, "broken loop tree");
1074               assert(get_loop(lca) == outer_loop, "safepoint in outer loop consume all memory state");
1075             }
1076 #endif
1077             lca = place_outside_loop(lca, n_loop);
1078             assert(!n_loop->is_member(get_loop(lca)), "control must not be back in the loop");
1079             assert(get_loop(lca)->_nest < n_loop->_nest || get_loop(lca)->_head->as_Loop()->is_in_infinite_subgraph(), "must not be moved into inner loop");
1080 
1081             // Move store out of the loop
1082             _igvn.replace_node(hook, n->in(MemNode::Memory));
1083             _igvn.replace_input_of(n, 0, lca);
1084             set_ctrl_and_loop(n, lca);
1085 
1086             // Disconnect the phi now. An empty phi can confuse other
1087             // optimizations in this pass of loop opts..
1088             if (phi->in(LoopNode::LoopBackControl) == phi) {
1089               _igvn.replace_node(phi, phi->in(LoopNode::EntryControl));
1090               n_loop->_body.yank(phi);
1091             }
1092           }
1093         }
1094       }
1095     }
1096   }
1097 }
1098 
1099 //------------------------------split_if_with_blocks_pre-----------------------
1100 // Do the real work in a non-recursive function.  Data nodes want to be
1101 // cloned in the pre-order so they can feed each other nicely.
1102 Node *PhaseIdealLoop::split_if_with_blocks_pre( Node *n ) {
1103   // Cloning these guys is unlikely to win
1104   int n_op = n->Opcode();
1105   if (n_op == Op_MergeMem) {
1106     return n;
1107   }
1108   if (n->is_Proj()) {
1109     return n;
1110   }
1111   // Do not clone-up CmpFXXX variations, as these are always
1112   // followed by a CmpI
1113   if (n->is_Cmp()) {
1114     return n;
1115   }
1116   // Attempt to use a conditional move instead of a phi/branch
1117   if (ConditionalMoveLimit > 0 && n_op == Op_Region) {
1118     Node *cmov = conditional_move( n );
1119     if (cmov) {
1120       return cmov;
1121     }
1122   }
1123   if (n->is_CFG() || n->is_LoadStore()) {
1124     return n;
1125   }
1126   if (n->is_Opaque1()) { // Opaque nodes cannot be mod'd
1127     if (!C->major_progress()) {   // If chance of no more loop opts...
1128       _igvn._worklist.push(n);  // maybe we'll remove them
1129     }
1130     return n;
1131   }
1132 
1133   if (n->is_Con()) {
1134     return n;   // No cloning for Con nodes
1135   }
1136 
1137   Node *n_ctrl = get_ctrl(n);
1138   if (!n_ctrl) {
1139     return n;       // Dead node
1140   }
1141 
1142   Node* res = try_move_store_before_loop(n, n_ctrl);
1143   if (res != nullptr) {
1144     return n;
1145   }
1146 
1147   // Attempt to remix address expressions for loop invariants
1148   Node *m = remix_address_expressions( n );
1149   if( m ) return m;
1150 
1151   if (n_op == Op_AddI) {
1152     Node *nn = convert_add_to_muladd( n );
1153     if ( nn ) return nn;
1154   }
1155 
1156   if (n->is_ConstraintCast()) {
1157     Node* dom_cast = n->as_ConstraintCast()->dominating_cast(&_igvn, this);
1158     // ConstraintCastNode::dominating_cast() uses node control input to determine domination.
1159     // Node control inputs don't necessarily agree with loop control info (due to
1160     // transformations happened in between), thus additional dominance check is needed
1161     // to keep loop info valid.
1162     if (dom_cast != nullptr && is_dominator(get_ctrl(dom_cast), get_ctrl(n))) {
1163       _igvn.replace_node(n, dom_cast);
1164       return dom_cast;
1165     }
1166   }
1167 
1168   // Determine if the Node has inputs from some local Phi.
1169   // Returns the block to clone thru.
1170   Node *n_blk = has_local_phi_input( n );
1171   if( !n_blk ) return n;
1172 
1173   // Do not clone the trip counter through on a CountedLoop
1174   // (messes up the canonical shape).
1175   if (((n_blk->is_CountedLoop() || (n_blk->is_Loop() && n_blk->as_Loop()->is_loop_nest_inner_loop())) && n->Opcode() == Op_AddI) ||
1176       (n_blk->is_LongCountedLoop() && n->Opcode() == Op_AddL)) {
1177     return n;
1178   }
1179   // Pushing a shift through the iv Phi can get in the way of addressing optimizations or range check elimination
1180   if (n_blk->is_BaseCountedLoop() && n->Opcode() == Op_LShift(n_blk->as_BaseCountedLoop()->bt()) &&
1181       n->in(1) == n_blk->as_BaseCountedLoop()->phi()) {
1182     return n;
1183   }
1184 
1185   // Check for having no control input; not pinned.  Allow
1186   // dominating control.
1187   if (n->in(0)) {
1188     Node *dom = idom(n_blk);
1189     if (dom_lca(n->in(0), dom) != n->in(0)) {
1190       return n;
1191     }
1192   }
1193   // Policy: when is it profitable.  You must get more wins than
1194   // policy before it is considered profitable.  Policy is usually 0,
1195   // so 1 win is considered profitable.  Big merges will require big
1196   // cloning, so get a larger policy.
1197   int policy = n_blk->req() >> 2;
1198 
1199   // If the loop is a candidate for range check elimination,
1200   // delay splitting through it's phi until a later loop optimization
1201   if (n_blk->is_BaseCountedLoop()) {
1202     IdealLoopTree *lp = get_loop(n_blk);
1203     if (lp && lp->_rce_candidate) {
1204       return n;
1205     }
1206   }
1207 
1208   if (must_throttle_split_if()) return n;
1209 
1210   // Split 'n' through the merge point if it is profitable
1211   Node *phi = split_thru_phi( n, n_blk, policy );
1212   if (!phi) return n;
1213 
1214   // Found a Phi to split thru!
1215   // Replace 'n' with the new phi
1216   _igvn.replace_node( n, phi );
1217   // Moved a load around the loop, 'en-registering' something.
1218   if (n_blk->is_Loop() && n->is_Load() &&
1219       !phi->in(LoopNode::LoopBackControl)->is_Load())
1220     C->set_major_progress();
1221 
1222   return phi;
1223 }
1224 
1225 static bool merge_point_too_heavy(Compile* C, Node* region) {
1226   // Bail out if the region and its phis have too many users.
1227   int weight = 0;
1228   for (DUIterator_Fast imax, i = region->fast_outs(imax); i < imax; i++) {
1229     weight += region->fast_out(i)->outcnt();
1230   }
1231   int nodes_left = C->max_node_limit() - C->live_nodes();
1232   if (weight * 8 > nodes_left) {
1233     if (PrintOpto) {
1234       tty->print_cr("*** Split-if bails out:  %d nodes, region weight %d", C->unique(), weight);
1235     }
1236     return true;
1237   } else {
1238     return false;
1239   }
1240 }
1241 
1242 static bool merge_point_safe(Node* region) {
1243   // 4799512: Stop split_if_with_blocks from splitting a block with a ConvI2LNode
1244   // having a PhiNode input. This sidesteps the dangerous case where the split
1245   // ConvI2LNode may become TOP if the input Value() does not
1246   // overlap the ConvI2L range, leaving a node which may not dominate its
1247   // uses.
1248   // A better fix for this problem can be found in the BugTraq entry, but
1249   // expediency for Mantis demands this hack.
1250 #ifdef _LP64
1251   for (DUIterator_Fast imax, i = region->fast_outs(imax); i < imax; i++) {
1252     Node* n = region->fast_out(i);
1253     if (n->is_Phi()) {
1254       for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++) {
1255         Node* m = n->fast_out(j);
1256         if (m->Opcode() == Op_ConvI2L)
1257           return false;
1258         if (m->is_CastII()) {
1259           return false;
1260         }
1261       }
1262     }
1263   }
1264 #endif
1265   return true;
1266 }
1267 
1268 
1269 //------------------------------place_outside_loop---------------------------------
1270 // Place some computation outside of this loop on the path to the use passed as argument
1271 Node* PhaseIdealLoop::place_outside_loop(Node* useblock, IdealLoopTree* loop) const {
1272   Node* head = loop->_head;
1273   assert(!loop->is_member(get_loop(useblock)), "must be outside loop");
1274   if (head->is_Loop() && head->as_Loop()->is_strip_mined()) {
1275     loop = loop->_parent;
1276     assert(loop->_head->is_OuterStripMinedLoop(), "malformed strip mined loop");
1277   }
1278 
1279   // Pick control right outside the loop
1280   for (;;) {
1281     Node* dom = idom(useblock);
1282     if (loop->is_member(get_loop(dom))) {
1283       break;
1284     }
1285     useblock = dom;
1286   }
1287   assert(find_non_split_ctrl(useblock) == useblock, "should be non split control");
1288   return useblock;
1289 }
1290 
1291 
1292 bool PhaseIdealLoop::identical_backtoback_ifs(Node *n) {
1293   if (!n->is_If() || n->is_BaseCountedLoopEnd()) {
1294     return false;
1295   }
1296   if (!n->in(0)->is_Region()) {
1297     return false;
1298   }
1299 
1300   Node* region = n->in(0);
1301   Node* dom = idom(region);
1302   if (!dom->is_If() ||  !n->as_If()->same_condition(dom, &_igvn)) {
1303     return false;
1304   }
1305   IfNode* dom_if = dom->as_If();
1306   Node* proj_true = dom_if->proj_out(1);
1307   Node* proj_false = dom_if->proj_out(0);
1308 
1309   for (uint i = 1; i < region->req(); i++) {
1310     if (is_dominator(proj_true, region->in(i))) {
1311       continue;
1312     }
1313     if (is_dominator(proj_false, region->in(i))) {
1314       continue;
1315     }
1316     return false;
1317   }
1318 
1319   return true;
1320 }
1321 
1322 
1323 bool PhaseIdealLoop::can_split_if(Node* n_ctrl) {
1324   if (must_throttle_split_if()) {
1325     return false;
1326   }
1327 
1328   // Do not do 'split-if' if irreducible loops are present.
1329   if (_has_irreducible_loops) {
1330     return false;
1331   }
1332 
1333   if (merge_point_too_heavy(C, n_ctrl)) {
1334     return false;
1335   }
1336 
1337   // Do not do 'split-if' if some paths are dead.  First do dead code
1338   // elimination and then see if its still profitable.
1339   for (uint i = 1; i < n_ctrl->req(); i++) {
1340     if (n_ctrl->in(i) == C->top()) {
1341       return false;
1342     }
1343   }
1344 
1345   // If trying to do a 'Split-If' at the loop head, it is only
1346   // profitable if the cmp folds up on BOTH paths.  Otherwise we
1347   // risk peeling a loop forever.
1348 
1349   // CNC - Disabled for now.  Requires careful handling of loop
1350   // body selection for the cloned code.  Also, make sure we check
1351   // for any input path not being in the same loop as n_ctrl.  For
1352   // irreducible loops we cannot check for 'n_ctrl->is_Loop()'
1353   // because the alternative loop entry points won't be converted
1354   // into LoopNodes.
1355   IdealLoopTree *n_loop = get_loop(n_ctrl);
1356   for (uint j = 1; j < n_ctrl->req(); j++) {
1357     if (get_loop(n_ctrl->in(j)) != n_loop) {
1358       return false;
1359     }
1360   }
1361 
1362   // Check for safety of the merge point.
1363   if (!merge_point_safe(n_ctrl)) {
1364     return false;
1365   }
1366 
1367   return true;
1368 }
1369 
1370 // Detect if the node is the inner strip-mined loop
1371 // Return: null if it's not the case, or the exit of outer strip-mined loop
1372 static Node* is_inner_of_stripmined_loop(const Node* out) {
1373   Node* out_le = nullptr;
1374 
1375   if (out->is_CountedLoopEnd()) {
1376       const CountedLoopNode* loop = out->as_CountedLoopEnd()->loopnode();
1377 
1378       if (loop != nullptr && loop->is_strip_mined()) {
1379         out_le = loop->in(LoopNode::EntryControl)->as_OuterStripMinedLoop()->outer_loop_exit();
1380       }
1381   }
1382 
1383   return out_le;
1384 }
1385 
1386 //------------------------------split_if_with_blocks_post----------------------
1387 // Do the real work in a non-recursive function.  CFG hackery wants to be
1388 // in the post-order, so it can dirty the I-DOM info and not use the dirtied
1389 // info.
1390 void PhaseIdealLoop::split_if_with_blocks_post(Node *n) {
1391 
1392   // Cloning Cmp through Phi's involves the split-if transform.
1393   // FastLock is not used by an If
1394   if (n->is_Cmp() && !n->is_FastLock()) {
1395     Node *n_ctrl = get_ctrl(n);
1396     // Determine if the Node has inputs from some local Phi.
1397     // Returns the block to clone thru.
1398     Node *n_blk = has_local_phi_input(n);
1399     if (n_blk != n_ctrl) {
1400       return;
1401     }
1402 
1403     if (!can_split_if(n_ctrl)) {
1404       return;
1405     }
1406 
1407     if (n->outcnt() != 1) {
1408       return; // Multiple bool's from 1 compare?
1409     }
1410     Node *bol = n->unique_out();
1411     assert(bol->is_Bool(), "expect a bool here");
1412     if (bol->outcnt() != 1) {
1413       return;// Multiple branches from 1 compare?
1414     }
1415     Node *iff = bol->unique_out();
1416 
1417     // Check some safety conditions
1418     if (iff->is_If()) {        // Classic split-if?
1419       if (iff->in(0) != n_ctrl) {
1420         return; // Compare must be in same blk as if
1421       }
1422     } else if (iff->is_CMove()) { // Trying to split-up a CMOVE
1423       // Can't split CMove with different control.
1424       if (get_ctrl(iff) != n_ctrl) {
1425         return;
1426       }
1427       if (get_ctrl(iff->in(2)) == n_ctrl ||
1428           get_ctrl(iff->in(3)) == n_ctrl) {
1429         return;                 // Inputs not yet split-up
1430       }
1431       if (get_loop(n_ctrl) != get_loop(get_ctrl(iff))) {
1432         return;                 // Loop-invar test gates loop-varying CMOVE
1433       }
1434     } else {
1435       return;  // some other kind of node, such as an Allocate
1436     }
1437 
1438     // When is split-if profitable?  Every 'win' on means some control flow
1439     // goes dead, so it's almost always a win.
1440     int policy = 0;
1441     // Split compare 'n' through the merge point if it is profitable
1442     Node *phi = split_thru_phi( n, n_ctrl, policy);
1443     if (!phi) {
1444       return;
1445     }
1446 
1447     // Found a Phi to split thru!
1448     // Replace 'n' with the new phi
1449     _igvn.replace_node(n, phi);
1450 
1451     // Now split the bool up thru the phi
1452     Node *bolphi = split_thru_phi(bol, n_ctrl, -1);
1453     guarantee(bolphi != nullptr, "null boolean phi node");
1454 
1455     _igvn.replace_node(bol, bolphi);
1456     assert(iff->in(1) == bolphi, "");
1457 
1458     if (bolphi->Value(&_igvn)->singleton()) {
1459       return;
1460     }
1461 
1462     // Conditional-move?  Must split up now
1463     if (!iff->is_If()) {
1464       Node *cmovphi = split_thru_phi(iff, n_ctrl, -1);
1465       _igvn.replace_node(iff, cmovphi);
1466       return;
1467     }
1468 
1469     // Now split the IF
1470     C->print_method(PHASE_BEFORE_SPLIT_IF, 4, iff);
1471     if (TraceLoopOpts) {
1472       tty->print_cr("Split-If");
1473     }
1474     do_split_if(iff);
1475     C->print_method(PHASE_AFTER_SPLIT_IF, 4, iff);
1476     return;
1477   }
1478 
1479   // Two identical ifs back to back can be merged
1480   if (try_merge_identical_ifs(n)) {
1481     return;
1482   }
1483 
1484   // Check for an IF ready to split; one that has its
1485   // condition codes input coming from a Phi at the block start.
1486   int n_op = n->Opcode();
1487 
1488   // Check for an IF being dominated by another IF same test
1489   if (n_op == Op_If ||
1490       n_op == Op_RangeCheck) {
1491     Node *bol = n->in(1);
1492     uint max = bol->outcnt();
1493     // Check for same test used more than once?
1494     if (bol->is_Bool() && (max > 1 || bol->in(1)->is_SubTypeCheck())) {
1495       // Search up IDOMs to see if this IF is dominated.
1496       Node* cmp = bol->in(1);
1497       Node *cutoff = cmp->is_SubTypeCheck() ? dom_lca(get_ctrl(cmp->in(1)), get_ctrl(cmp->in(2))) : get_ctrl(bol);
1498 
1499       // Now search up IDOMs till cutoff, looking for a dominating test
1500       Node *prevdom = n;
1501       Node *dom = idom(prevdom);
1502       while (dom != cutoff) {
1503         if (dom->req() > 1 && n->as_If()->same_condition(dom, &_igvn) && prevdom->in(0) == dom &&
1504             safe_for_if_replacement(dom)) {
1505           // It's invalid to move control dependent data nodes in the inner
1506           // strip-mined loop, because:
1507           //  1) break validation of LoopNode::verify_strip_mined()
1508           //  2) move code with side-effect in strip-mined loop
1509           // Move to the exit of outer strip-mined loop in that case.
1510           Node* out_le = is_inner_of_stripmined_loop(dom);
1511           if (out_le != nullptr) {
1512             prevdom = out_le;
1513           }
1514           // Replace the dominated test with an obvious true or false.
1515           // Place it on the IGVN worklist for later cleanup.
1516           C->set_major_progress();
1517           // Split if: pin array accesses that are control dependent on a range check and moved to a regular if,
1518           // to prevent an array load from floating above its range check. There are three cases:
1519           // 1. Move from RangeCheck "a" to RangeCheck "b": don't need to pin. If we ever remove b, then we pin
1520           //    all its array accesses at that point.
1521           // 2. We move from RangeCheck "a" to regular if "b": need to pin. If we ever remove b, then its array
1522           //    accesses would start to float, since we don't pin at that point.
1523           // 3. If we move from regular if: don't pin. All array accesses are already assumed to be pinned.
1524           bool pin_array_access_nodes =  n->Opcode() == Op_RangeCheck &&
1525                                          prevdom->in(0)->Opcode() != Op_RangeCheck;
1526           dominated_by(prevdom->as_IfProj(), n->as_If(), false, pin_array_access_nodes);
1527           DEBUG_ONLY( if (VerifyLoopOptimizations) { verify(); } );
1528           return;
1529         }
1530         prevdom = dom;
1531         dom = idom(prevdom);
1532       }
1533     }
1534   }
1535 
1536   try_sink_out_of_loop(n);
1537   if (C->failing()) {
1538     return;
1539   }
1540 
1541   try_move_store_after_loop(n);
1542 }
1543 
1544 // Transform:
1545 //
1546 // if (some_condition) {
1547 //   // body 1
1548 // } else {
1549 //   // body 2
1550 // }
1551 // if (some_condition) {
1552 //   // body 3
1553 // } else {
1554 //   // body 4
1555 // }
1556 //
1557 // into:
1558 //
1559 //
1560 // if (some_condition) {
1561 //   // body 1
1562 //   // body 3
1563 // } else {
1564 //   // body 2
1565 //   // body 4
1566 // }
1567 bool PhaseIdealLoop::try_merge_identical_ifs(Node* n) {
1568   if (identical_backtoback_ifs(n) && can_split_if(n->in(0))) {
1569     Node *n_ctrl = n->in(0);
1570     IfNode* dom_if = idom(n_ctrl)->as_If();
1571     if (n->in(1) != dom_if->in(1)) {
1572       assert(n->in(1)->in(1)->is_SubTypeCheck() &&
1573              (n->in(1)->in(1)->as_SubTypeCheck()->method() != nullptr ||
1574               dom_if->in(1)->in(1)->as_SubTypeCheck()->method() != nullptr), "only for subtype checks with profile data attached");
1575       _igvn.replace_input_of(n, 1, dom_if->in(1));
1576     }
1577     ProjNode* dom_proj_true = dom_if->proj_out(1);
1578     ProjNode* dom_proj_false = dom_if->proj_out(0);
1579 
1580     // Now split the IF
1581     RegionNode* new_false_region;
1582     RegionNode* new_true_region;
1583     do_split_if(n, &new_false_region, &new_true_region);
1584     assert(new_false_region->req() == new_true_region->req(), "");
1585 #ifdef ASSERT
1586     for (uint i = 1; i < new_false_region->req(); ++i) {
1587       assert(new_false_region->in(i)->in(0) == new_true_region->in(i)->in(0), "unexpected shape following split if");
1588       assert(i == new_false_region->req() - 1 || new_false_region->in(i)->in(0)->in(1) == new_false_region->in(i + 1)->in(0)->in(1), "unexpected shape following split if");
1589     }
1590 #endif
1591     assert(new_false_region->in(1)->in(0)->in(1) == dom_if->in(1), "dominating if and dominated if after split must share test");
1592 
1593     // We now have:
1594     // if (some_condition) {
1595     //   // body 1
1596     //   if (some_condition) {
1597     //     body3: // new_true_region
1598     //     // body3
1599     //   } else {
1600     //     goto body4;
1601     //   }
1602     // } else {
1603     //   // body 2
1604     //  if (some_condition) {
1605     //     goto body3;
1606     //   } else {
1607     //     body4:   // new_false_region
1608     //     // body4;
1609     //   }
1610     // }
1611     //
1612 
1613     // clone pinned nodes thru the resulting regions
1614     push_pinned_nodes_thru_region(dom_if, new_true_region);
1615     push_pinned_nodes_thru_region(dom_if, new_false_region);
1616 
1617     // Optimize out the cloned ifs. Because pinned nodes were cloned, this also allows a CastPP that would be dependent
1618     // on a projection of n to have the dom_if as a control dependency. We don't want the CastPP to end up with an
1619     // unrelated control dependency.
1620     for (uint i = 1; i < new_false_region->req(); i++) {
1621       if (is_dominator(dom_proj_true, new_false_region->in(i))) {
1622         dominated_by(dom_proj_true->as_IfProj(), new_false_region->in(i)->in(0)->as_If());
1623       } else {
1624         assert(is_dominator(dom_proj_false, new_false_region->in(i)), "bad if");
1625         dominated_by(dom_proj_false->as_IfProj(), new_false_region->in(i)->in(0)->as_If());
1626       }
1627     }
1628     return true;
1629   }
1630   return false;
1631 }
1632 
1633 void PhaseIdealLoop::push_pinned_nodes_thru_region(IfNode* dom_if, Node* region) {
1634   for (DUIterator i = region->outs(); region->has_out(i); i++) {
1635     Node* u = region->out(i);
1636     if (!has_ctrl(u) || u->is_Phi() || !u->depends_only_on_test() || !_igvn.no_dependent_zero_check(u)) {
1637       continue;
1638     }
1639     assert(u->in(0) == region, "not a control dependent node?");
1640     uint j = 1;
1641     for (; j < u->req(); ++j) {
1642       Node* in = u->in(j);
1643       if (!is_dominator(ctrl_or_self(in), dom_if)) {
1644         break;
1645       }
1646     }
1647     if (j == u->req()) {
1648       Node *phi = PhiNode::make_blank(region, u);
1649       for (uint k = 1; k < region->req(); ++k) {
1650         Node* clone = u->clone();
1651         clone->set_req(0, region->in(k));
1652         register_new_node(clone, region->in(k));
1653         phi->init_req(k, clone);
1654       }
1655       register_new_node(phi, region);
1656       _igvn.replace_node(u, phi);
1657       --i;
1658     }
1659   }
1660 }
1661 
1662 bool PhaseIdealLoop::safe_for_if_replacement(const Node* dom) const {
1663   if (!dom->is_CountedLoopEnd()) {
1664     return true;
1665   }
1666   CountedLoopEndNode* le = dom->as_CountedLoopEnd();
1667   CountedLoopNode* cl = le->loopnode();
1668   if (cl == nullptr) {
1669     return true;
1670   }
1671   if (!cl->is_main_loop()) {
1672     return true;
1673   }
1674   if (cl->is_canonical_loop_entry() == nullptr) {
1675     return true;
1676   }
1677   // Further unrolling is possible so loop exit condition might change
1678   return false;
1679 }
1680 
1681 // See if a shared loop-varying computation has no loop-varying uses.
1682 // Happens if something is only used for JVM state in uncommon trap exits,
1683 // like various versions of induction variable+offset.  Clone the
1684 // computation per usage to allow it to sink out of the loop.
1685 void PhaseIdealLoop::try_sink_out_of_loop(Node* n) {
1686   bool is_raw_to_oop_cast = n->is_ConstraintCast() &&
1687                             n->in(1)->bottom_type()->isa_rawptr() &&
1688                             !n->bottom_type()->isa_rawptr();
1689 
1690   if (has_ctrl(n) &&
1691       !n->is_Phi() &&
1692       !n->is_Bool() &&
1693       !n->is_Proj() &&
1694       !n->is_MergeMem() &&
1695       !n->is_CMove() &&
1696       !n->is_OpaqueNotNull() &&
1697       !n->is_OpaqueInitializedAssertionPredicate() &&
1698       !n->is_OpaqueTemplateAssertionPredicate() &&
1699       !is_raw_to_oop_cast && // don't extend live ranges of raw oops
1700       (KillPathsReachableByDeadTypeNode || !n->is_Type())
1701       ) {
1702     Node *n_ctrl = get_ctrl(n);
1703     IdealLoopTree *n_loop = get_loop(n_ctrl);
1704 
1705     if (n->in(0) != nullptr) {
1706       IdealLoopTree* loop_ctrl = get_loop(n->in(0));
1707       if (n_loop != loop_ctrl && n_loop->is_member(loop_ctrl)) {
1708         // n has a control input inside a loop but get_ctrl() is member of an outer loop. This could happen, for example,
1709         // for Div nodes inside a loop (control input inside loop) without a use except for an UCT (outside the loop).
1710         // Rewire control of n to right outside of the loop, regardless if its input(s) are later sunk or not.
1711         Node* maybe_pinned_n = n;
1712         Node* outside_ctrl = place_outside_loop(n_ctrl, loop_ctrl);
1713         if (!would_sink_below_pre_loop_exit(loop_ctrl, outside_ctrl)) {
1714           if (n->depends_only_on_test()) {
1715             Node* pinned_clone = n->pin_array_access_node();
1716             if (pinned_clone != nullptr) {
1717               // Pin array access nodes: if this is an array load, it's going to be dependent on a condition that's not a
1718               // range check for that access. If that condition is replaced by an identical dominating one, then an
1719               // unpinned load would risk floating above its range check.
1720               register_new_node(pinned_clone, n_ctrl);
1721               maybe_pinned_n = pinned_clone;
1722               _igvn.replace_node(n, pinned_clone);
1723             }
1724           }
1725           _igvn.replace_input_of(maybe_pinned_n, 0, outside_ctrl);
1726         }
1727       }
1728     }
1729     if (n_loop != _ltree_root && n->outcnt() > 1) {
1730       // Compute early control: needed for anti-dependence analysis. It's also possible that as a result of
1731       // previous transformations in this loop opts round, the node can be hoisted now: early control will tell us.
1732       Node* early_ctrl = compute_early_ctrl(n, n_ctrl);
1733       if (n_loop->is_member(get_loop(early_ctrl)) && // check that this one can't be hoisted now
1734           ctrl_of_all_uses_out_of_loop(n, early_ctrl, n_loop)) { // All uses in outer loops!
1735         if (n->is_Store() || n->is_LoadStore()) {
1736             assert(false, "no node with a side effect");
1737             C->record_failure("no node with a side effect");
1738             return;
1739         }
1740         Node* outer_loop_clone = nullptr;
1741         for (DUIterator_Last jmin, j = n->last_outs(jmin); j >= jmin;) {
1742           Node* u = n->last_out(j); // Clone private computation per use
1743           _igvn.rehash_node_delayed(u);
1744           Node* x = nullptr;
1745           if (n->depends_only_on_test()) {
1746             // Pin array access nodes: if this is an array load, it's going to be dependent on a condition that's not a
1747             // range check for that access. If that condition is replaced by an identical dominating one, then an
1748             // unpinned load would risk floating above its range check.
1749             x = n->pin_array_access_node();
1750           }
1751           if (x == nullptr) {
1752             x = n->clone();
1753           }
1754           Node* x_ctrl = nullptr;
1755           if (u->is_Phi()) {
1756             // Replace all uses of normal nodes.  Replace Phi uses
1757             // individually, so the separate Nodes can sink down
1758             // different paths.
1759             uint k = 1;
1760             while (u->in(k) != n) k++;
1761             u->set_req(k, x);
1762             // x goes next to Phi input path
1763             x_ctrl = u->in(0)->in(k);
1764             // Find control for 'x' next to use but not inside inner loops.
1765             x_ctrl = place_outside_loop(x_ctrl, n_loop);
1766             --j;
1767           } else {              // Normal use
1768             if (has_ctrl(u)) {
1769               x_ctrl = get_ctrl(u);
1770             } else {
1771               x_ctrl = u->in(0);
1772             }
1773             // Find control for 'x' next to use but not inside inner loops.
1774             x_ctrl = place_outside_loop(x_ctrl, n_loop);
1775             // Replace all uses
1776             if (u->is_ConstraintCast() && _igvn.type(n)->higher_equal(u->bottom_type()) && u->in(0) == x_ctrl) {
1777               // If we're sinking a chain of data nodes, we might have inserted a cast to pin the use which is not necessary
1778               // anymore now that we're going to pin n as well
1779               _igvn.replace_node(u, x);
1780               --j;
1781             } else {
1782               int nb = u->replace_edge(n, x, &_igvn);
1783               j -= nb;
1784             }
1785           }
1786 
1787           if (n->is_Load()) {
1788             // For loads, add a control edge to a CFG node outside of the loop
1789             // to force them to not combine and return back inside the loop
1790             // during GVN optimization (4641526).
1791             assert(x_ctrl == get_late_ctrl_with_anti_dep(x->as_Load(), early_ctrl, x_ctrl), "anti-dependences were already checked");
1792 
1793             IdealLoopTree* x_loop = get_loop(x_ctrl);
1794             Node* x_head = x_loop->_head;
1795             if (x_head->is_Loop() && x_head->is_OuterStripMinedLoop()) {
1796               // Do not add duplicate LoadNodes to the outer strip mined loop
1797               if (outer_loop_clone != nullptr) {
1798                 _igvn.replace_node(x, outer_loop_clone);
1799                 continue;
1800               }
1801               outer_loop_clone = x;
1802             }
1803             x->set_req(0, x_ctrl);
1804           } else if (n->in(0) != nullptr){
1805             x->set_req(0, x_ctrl);
1806           }
1807           assert(dom_depth(n_ctrl) <= dom_depth(x_ctrl), "n is later than its clone");
1808           assert(!n_loop->is_member(get_loop(x_ctrl)), "should have moved out of loop");
1809           register_new_node(x, x_ctrl);
1810 
1811           // Chain of AddP nodes: (AddP base (AddP base (AddP base )))
1812           // All AddP nodes must keep the same base after sinking so:
1813           // 1- We don't add a CastPP here until the last one of the chain is sunk: if part of the chain is not sunk,
1814           // their bases remain the same.
1815           // (see 2- below)
1816           assert(!x->is_AddP() || !x->in(AddPNode::Address)->is_AddP() ||
1817                  x->in(AddPNode::Address)->in(AddPNode::Base) == x->in(AddPNode::Base) ||
1818                  !x->in(AddPNode::Address)->in(AddPNode::Base)->eqv_uncast(x->in(AddPNode::Base)), "unexpected AddP shape");
1819           if (x->in(0) == nullptr && !x->is_DecodeNarrowPtr() &&
1820               !(x->is_AddP() && x->in(AddPNode::Address)->is_AddP() && x->in(AddPNode::Address)->in(AddPNode::Base) == x->in(AddPNode::Base))) {
1821             assert(!x->is_Load(), "load should be pinned");
1822             // Use a cast node to pin clone out of loop
1823             Node* cast = nullptr;
1824             for (uint k = 0; k < x->req(); k++) {
1825               Node* in = x->in(k);
1826               if (in != nullptr && n_loop->is_member(get_loop(get_ctrl(in)))) {
1827                 const Type* in_t = _igvn.type(in);
1828                 cast = ConstraintCastNode::make_cast_for_type(x_ctrl, in, in_t,
1829                                                               ConstraintCastNode::UnconditionalDependency, nullptr);
1830               }
1831               if (cast != nullptr) {
1832                 Node* prev = _igvn.hash_find_insert(cast);
1833                 if (prev != nullptr && get_ctrl(prev) == x_ctrl) {
1834                   cast->destruct(&_igvn);
1835                   cast = prev;
1836                 } else {
1837                   register_new_node(cast, x_ctrl);
1838                 }
1839                 x->replace_edge(in, cast);
1840                 // Chain of AddP nodes:
1841                 // 2- A CastPP of the base is only added now that all AddP nodes are sunk
1842                 if (x->is_AddP() && k == AddPNode::Base) {
1843                   update_addp_chain_base(x, n->in(AddPNode::Base), cast);
1844                 }
1845                 break;
1846               }
1847             }
1848             assert(cast != nullptr, "must have added a cast to pin the node");
1849           }
1850         }
1851         _igvn.remove_dead_node(n);
1852       }
1853       _dom_lca_tags_round = 0;
1854     }
1855   }
1856 }
1857 
1858 void PhaseIdealLoop::update_addp_chain_base(Node* x, Node* old_base, Node* new_base) {
1859   ResourceMark rm;
1860   Node_List wq;
1861   wq.push(x);
1862   while (wq.size() != 0) {
1863     Node* n = wq.pop();
1864     for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
1865       Node* u = n->fast_out(i);
1866       if (u->is_AddP() && u->in(AddPNode::Base) == old_base) {
1867         _igvn.replace_input_of(u, AddPNode::Base, new_base);
1868         wq.push(u);
1869       }
1870     }
1871   }
1872 }
1873 
1874 // Compute the early control of a node by following its inputs until we reach
1875 // nodes that are pinned. Then compute the LCA of the control of all pinned nodes.
1876 Node* PhaseIdealLoop::compute_early_ctrl(Node* n, Node* n_ctrl) {
1877   Node* early_ctrl = nullptr;
1878   ResourceMark rm;
1879   Unique_Node_List wq;
1880   wq.push(n);
1881   for (uint i = 0; i < wq.size(); i++) {
1882     Node* m = wq.at(i);
1883     Node* c = nullptr;
1884     if (m->is_CFG()) {
1885       c = m;
1886     } else if (m->pinned()) {
1887       c = m->in(0);
1888     } else {
1889       for (uint j = 0; j < m->req(); j++) {
1890         Node* in = m->in(j);
1891         if (in != nullptr) {
1892           wq.push(in);
1893         }
1894       }
1895     }
1896     if (c != nullptr) {
1897       assert(is_dominator(c, n_ctrl), "control input must dominate current control");
1898       if (early_ctrl == nullptr || is_dominator(early_ctrl, c)) {
1899         early_ctrl = c;
1900       }
1901     }
1902   }
1903   assert(is_dominator(early_ctrl, n_ctrl), "early control must dominate current control");
1904   return early_ctrl;
1905 }
1906 
1907 bool PhaseIdealLoop::ctrl_of_all_uses_out_of_loop(const Node* n, Node* n_ctrl, IdealLoopTree* n_loop) {
1908   for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
1909     Node* u = n->fast_out(i);
1910     if (u->is_Opaque1()) {
1911       return false;  // Found loop limit, bugfix for 4677003
1912     }
1913     // We can't reuse tags in PhaseIdealLoop::dom_lca_for_get_late_ctrl_internal() so make sure calls to
1914     // get_late_ctrl_with_anti_dep() use their own tag
1915     _dom_lca_tags_round++;
1916     assert(_dom_lca_tags_round != 0, "shouldn't wrap around");
1917 
1918     if (u->is_Phi()) {
1919       for (uint j = 1; j < u->req(); ++j) {
1920         if (u->in(j) == n && !ctrl_of_use_out_of_loop(n, n_ctrl, n_loop, u->in(0)->in(j))) {
1921           return false;
1922         }
1923       }
1924     } else {
1925       Node* ctrl = has_ctrl(u) ? get_ctrl(u) : u->in(0);
1926       if (!ctrl_of_use_out_of_loop(n, n_ctrl, n_loop, ctrl)) {
1927         return false;
1928       }
1929     }
1930   }
1931   return true;
1932 }
1933 
1934 // Sinking a node from a pre loop to its main loop pins the node between the pre and main loops. If that node is input
1935 // to a check that's eliminated by range check elimination, it becomes input to an expression that feeds into the exit
1936 // test of the pre loop above the point in the graph where it's pinned. This results in a broken graph. One way to avoid
1937 // it would be to not eliminate the check in the main loop. Instead, we prevent sinking of the node here so better code
1938 // is generated for the main loop.
1939 bool PhaseIdealLoop::would_sink_below_pre_loop_exit(IdealLoopTree* n_loop, Node* ctrl) {
1940   if (n_loop->_head->is_CountedLoop() && n_loop->_head->as_CountedLoop()->is_pre_loop()) {
1941     CountedLoopNode* pre_loop = n_loop->_head->as_CountedLoop();
1942     if (is_dominator(pre_loop->loopexit(), ctrl)) {
1943       return true;
1944     }
1945   }
1946   return false;
1947 }
1948 
1949 bool PhaseIdealLoop::ctrl_of_use_out_of_loop(const Node* n, Node* n_ctrl, IdealLoopTree* n_loop, Node* ctrl) {
1950   if (n->is_Load()) {
1951     ctrl = get_late_ctrl_with_anti_dep(n->as_Load(), n_ctrl, ctrl);
1952   }
1953   IdealLoopTree *u_loop = get_loop(ctrl);
1954   if (u_loop == n_loop) {
1955     return false; // Found loop-varying use
1956   }
1957   if (n_loop->is_member(u_loop)) {
1958     return false; // Found use in inner loop
1959   }
1960   if (would_sink_below_pre_loop_exit(n_loop, ctrl)) {
1961     return false;
1962   }
1963   return true;
1964 }
1965 
1966 //------------------------------split_if_with_blocks---------------------------
1967 // Check for aggressive application of 'split-if' optimization,
1968 // using basic block level info.
1969 void PhaseIdealLoop::split_if_with_blocks(VectorSet &visited, Node_Stack &nstack) {
1970   Node* root = C->root();
1971   visited.set(root->_idx); // first, mark root as visited
1972   // Do pre-visit work for root
1973   Node* n   = split_if_with_blocks_pre(root);
1974   uint  cnt = n->outcnt();
1975   uint  i   = 0;
1976 
1977   while (true) {
1978     // Visit all children
1979     if (i < cnt) {
1980       Node* use = n->raw_out(i);
1981       ++i;
1982       if (use->outcnt() != 0 && !visited.test_set(use->_idx)) {
1983         // Now do pre-visit work for this use
1984         use = split_if_with_blocks_pre(use);
1985         nstack.push(n, i); // Save parent and next use's index.
1986         n   = use;         // Process all children of current use.
1987         cnt = use->outcnt();
1988         i   = 0;
1989       }
1990     }
1991     else {
1992       // All of n's children have been processed, complete post-processing.
1993       if (cnt != 0 && !n->is_Con()) {
1994         assert(has_node(n), "no dead nodes");
1995         split_if_with_blocks_post(n);
1996         if (C->failing()) {
1997           return;
1998         }
1999       }
2000       if (must_throttle_split_if()) {
2001         nstack.clear();
2002       }
2003       if (nstack.is_empty()) {
2004         // Finished all nodes on stack.
2005         break;
2006       }
2007       // Get saved parent node and next use's index. Visit the rest of uses.
2008       n   = nstack.node();
2009       cnt = n->outcnt();
2010       i   = nstack.index();
2011       nstack.pop();
2012     }
2013   }
2014 }
2015 
2016 
2017 //=============================================================================
2018 //
2019 //                   C L O N E   A   L O O P   B O D Y
2020 //
2021 
2022 //------------------------------clone_iff--------------------------------------
2023 // Passed in a Phi merging (recursively) some nearly equivalent Bool/Cmps.
2024 // "Nearly" because all Nodes have been cloned from the original in the loop,
2025 // but the fall-in edges to the Cmp are different.  Clone bool/Cmp pairs
2026 // through the Phi recursively, and return a Bool.
2027 Node* PhaseIdealLoop::clone_iff(PhiNode* phi) {
2028 
2029   // Convert this Phi into a Phi merging Bools
2030   uint i;
2031   for (i = 1; i < phi->req(); i++) {
2032     Node* b = phi->in(i);
2033     if (b->is_Phi()) {
2034       _igvn.replace_input_of(phi, i, clone_iff(b->as_Phi()));
2035     } else {
2036       assert(b->is_Bool() || b->is_OpaqueNotNull() || b->is_OpaqueInitializedAssertionPredicate(),
2037              "bool, non-null check with OpaqueNotNull or Initialized Assertion Predicate with its Opaque node");
2038     }
2039   }
2040   Node* n = phi->in(1);
2041   Node* sample_opaque = nullptr;
2042   Node *sample_bool = nullptr;
2043   if (n->is_OpaqueNotNull() || n->is_OpaqueInitializedAssertionPredicate()) {
2044     sample_opaque = n;
2045     sample_bool = n->in(1);
2046     assert(sample_bool->is_Bool(), "wrong type");
2047   } else {
2048     sample_bool = n;
2049   }
2050   Node *sample_cmp = sample_bool->in(1);
2051 
2052   // Make Phis to merge the Cmp's inputs.
2053   PhiNode *phi1 = new PhiNode(phi->in(0), Type::TOP);
2054   PhiNode *phi2 = new PhiNode(phi->in(0), Type::TOP);
2055   for (i = 1; i < phi->req(); i++) {
2056     Node *n1 = sample_opaque == nullptr ? phi->in(i)->in(1)->in(1) : phi->in(i)->in(1)->in(1)->in(1);
2057     Node *n2 = sample_opaque == nullptr ? phi->in(i)->in(1)->in(2) : phi->in(i)->in(1)->in(1)->in(2);
2058     phi1->set_req(i, n1);
2059     phi2->set_req(i, n2);
2060     phi1->set_type(phi1->type()->meet_speculative(n1->bottom_type()));
2061     phi2->set_type(phi2->type()->meet_speculative(n2->bottom_type()));
2062   }
2063   // See if these Phis have been made before.
2064   // Register with optimizer
2065   Node *hit1 = _igvn.hash_find_insert(phi1);
2066   if (hit1) {                   // Hit, toss just made Phi
2067     _igvn.remove_dead_node(phi1); // Remove new phi
2068     assert(hit1->is_Phi(), "" );
2069     phi1 = (PhiNode*)hit1;      // Use existing phi
2070   } else {                      // Miss
2071     _igvn.register_new_node_with_optimizer(phi1);
2072   }
2073   Node *hit2 = _igvn.hash_find_insert(phi2);
2074   if (hit2) {                   // Hit, toss just made Phi
2075     _igvn.remove_dead_node(phi2); // Remove new phi
2076     assert(hit2->is_Phi(), "" );
2077     phi2 = (PhiNode*)hit2;      // Use existing phi
2078   } else {                      // Miss
2079     _igvn.register_new_node_with_optimizer(phi2);
2080   }
2081   // Register Phis with loop/block info
2082   set_ctrl(phi1, phi->in(0));
2083   set_ctrl(phi2, phi->in(0));
2084   // Make a new Cmp
2085   Node *cmp = sample_cmp->clone();
2086   cmp->set_req(1, phi1);
2087   cmp->set_req(2, phi2);
2088   _igvn.register_new_node_with_optimizer(cmp);
2089   set_ctrl(cmp, phi->in(0));
2090 
2091   // Make a new Bool
2092   Node *b = sample_bool->clone();
2093   b->set_req(1,cmp);
2094   _igvn.register_new_node_with_optimizer(b);
2095   set_ctrl(b, phi->in(0));
2096 
2097   if (sample_opaque != nullptr) {
2098     Node* opaque = sample_opaque->clone();
2099     opaque->set_req(1, b);
2100     _igvn.register_new_node_with_optimizer(opaque);
2101     set_ctrl(opaque, phi->in(0));
2102     return opaque;
2103   }
2104 
2105   assert(b->is_Bool(), "");
2106   return b;
2107 }
2108 
2109 //------------------------------clone_bool-------------------------------------
2110 // Passed in a Phi merging (recursively) some nearly equivalent Bool/Cmps.
2111 // "Nearly" because all Nodes have been cloned from the original in the loop,
2112 // but the fall-in edges to the Cmp are different.  Clone bool/Cmp pairs
2113 // through the Phi recursively, and return a Bool.
2114 CmpNode*PhaseIdealLoop::clone_bool(PhiNode* phi) {
2115   uint i;
2116   // Convert this Phi into a Phi merging Bools
2117   for( i = 1; i < phi->req(); i++ ) {
2118     Node *b = phi->in(i);
2119     if( b->is_Phi() ) {
2120       _igvn.replace_input_of(phi, i, clone_bool(b->as_Phi()));
2121     } else {
2122       assert( b->is_Cmp() || b->is_top(), "inputs are all Cmp or TOP" );
2123     }
2124   }
2125 
2126   Node *sample_cmp = phi->in(1);
2127 
2128   // Make Phis to merge the Cmp's inputs.
2129   PhiNode *phi1 = new PhiNode( phi->in(0), Type::TOP );
2130   PhiNode *phi2 = new PhiNode( phi->in(0), Type::TOP );
2131   for( uint j = 1; j < phi->req(); j++ ) {
2132     Node *cmp_top = phi->in(j); // Inputs are all Cmp or TOP
2133     Node *n1, *n2;
2134     if( cmp_top->is_Cmp() ) {
2135       n1 = cmp_top->in(1);
2136       n2 = cmp_top->in(2);
2137     } else {
2138       n1 = n2 = cmp_top;
2139     }
2140     phi1->set_req( j, n1 );
2141     phi2->set_req( j, n2 );
2142     phi1->set_type(phi1->type()->meet_speculative(n1->bottom_type()));
2143     phi2->set_type(phi2->type()->meet_speculative(n2->bottom_type()));
2144   }
2145 
2146   // See if these Phis have been made before.
2147   // Register with optimizer
2148   Node *hit1 = _igvn.hash_find_insert(phi1);
2149   if( hit1 ) {                  // Hit, toss just made Phi
2150     _igvn.remove_dead_node(phi1); // Remove new phi
2151     assert( hit1->is_Phi(), "" );
2152     phi1 = (PhiNode*)hit1;      // Use existing phi
2153   } else {                      // Miss
2154     _igvn.register_new_node_with_optimizer(phi1);
2155   }
2156   Node *hit2 = _igvn.hash_find_insert(phi2);
2157   if( hit2 ) {                  // Hit, toss just made Phi
2158     _igvn.remove_dead_node(phi2); // Remove new phi
2159     assert( hit2->is_Phi(), "" );
2160     phi2 = (PhiNode*)hit2;      // Use existing phi
2161   } else {                      // Miss
2162     _igvn.register_new_node_with_optimizer(phi2);
2163   }
2164   // Register Phis with loop/block info
2165   set_ctrl(phi1, phi->in(0));
2166   set_ctrl(phi2, phi->in(0));
2167   // Make a new Cmp
2168   Node *cmp = sample_cmp->clone();
2169   cmp->set_req( 1, phi1 );
2170   cmp->set_req( 2, phi2 );
2171   _igvn.register_new_node_with_optimizer(cmp);
2172   set_ctrl(cmp, phi->in(0));
2173 
2174   assert( cmp->is_Cmp(), "" );
2175   return (CmpNode*)cmp;
2176 }
2177 
2178 void PhaseIdealLoop::clone_loop_handle_data_uses(Node* old, Node_List &old_new,
2179                                                  IdealLoopTree* loop, IdealLoopTree* outer_loop,
2180                                                  Node_List*& split_if_set, Node_List*& split_bool_set,
2181                                                  Node_List*& split_cex_set, Node_List& worklist,
2182                                                  uint new_counter, CloneLoopMode mode) {
2183   Node* nnn = old_new[old->_idx];
2184   // Copy uses to a worklist, so I can munge the def-use info
2185   // with impunity.
2186   for (DUIterator_Fast jmax, j = old->fast_outs(jmax); j < jmax; j++)
2187     worklist.push(old->fast_out(j));
2188 
2189   while( worklist.size() ) {
2190     Node *use = worklist.pop();
2191     if (!has_node(use))  continue; // Ignore dead nodes
2192     if (use->in(0) == C->top())  continue;
2193     IdealLoopTree *use_loop = get_loop( has_ctrl(use) ? get_ctrl(use) : use );
2194     // Check for data-use outside of loop - at least one of OLD or USE
2195     // must not be a CFG node.
2196 #ifdef ASSERT
2197     if (loop->_head->as_Loop()->is_strip_mined() && outer_loop->is_member(use_loop) && !loop->is_member(use_loop) && old_new[use->_idx] == nullptr) {
2198       Node* sfpt = loop->_head->as_CountedLoop()->outer_safepoint();
2199       assert(mode != IgnoreStripMined, "incorrect cloning mode");
2200       assert((mode == ControlAroundStripMined && use == sfpt) || !use->is_reachable_from_root(), "missed a node");
2201     }
2202 #endif
2203     if (!loop->is_member(use_loop) && !outer_loop->is_member(use_loop) && (!old->is_CFG() || !use->is_CFG())) {
2204 
2205       // If the Data use is an IF, that means we have an IF outside the
2206       // loop that is switching on a condition that is set inside the
2207       // loop.  Happens if people set a loop-exit flag; then test the flag
2208       // in the loop to break the loop, then test is again outside the
2209       // loop to determine which way the loop exited.
2210       //
2211       // For several uses we need to make sure that there is no phi between,
2212       // the use and the Bool/Cmp. We therefore clone the Bool/Cmp down here
2213       // to avoid such a phi in between.
2214       // For example, it is unexpected that there is a Phi between an
2215       // AllocateArray node and its ValidLengthTest input that could cause
2216       // split if to break.
2217       assert(!use->is_OpaqueTemplateAssertionPredicate(),
2218              "should not clone a Template Assertion Predicate which should be removed once it's useless");
2219       if (use->is_If() || use->is_CMove() || use->is_OpaqueNotNull() || use->is_OpaqueInitializedAssertionPredicate() ||
2220           (use->Opcode() == Op_AllocateArray && use->in(AllocateNode::ValidLengthTest) == old)) {
2221         // Since this code is highly unlikely, we lazily build the worklist
2222         // of such Nodes to go split.
2223         if (!split_if_set) {
2224           split_if_set = new Node_List();
2225         }
2226         split_if_set->push(use);
2227       }
2228       if (use->is_Bool()) {
2229         if (!split_bool_set) {
2230           split_bool_set = new Node_List();
2231         }
2232         split_bool_set->push(use);
2233       }
2234       if (use->Opcode() == Op_CreateEx) {
2235         if (!split_cex_set) {
2236           split_cex_set = new Node_List();
2237         }
2238         split_cex_set->push(use);
2239       }
2240 
2241 
2242       // Get "block" use is in
2243       uint idx = 0;
2244       while( use->in(idx) != old ) idx++;
2245       Node *prev = use->is_CFG() ? use : get_ctrl(use);
2246       assert(!loop->is_member(get_loop(prev)) && !outer_loop->is_member(get_loop(prev)), "" );
2247       Node* cfg = (prev->_idx >= new_counter && prev->is_Region())
2248         ? prev->in(2)
2249         : idom(prev);
2250       if( use->is_Phi() )     // Phi use is in prior block
2251         cfg = prev->in(idx);  // NOT in block of Phi itself
2252       if (cfg->is_top()) {    // Use is dead?
2253         _igvn.replace_input_of(use, idx, C->top());
2254         continue;
2255       }
2256 
2257       // If use is referenced through control edge... (idx == 0)
2258       if (mode == IgnoreStripMined && idx == 0) {
2259         LoopNode *head = loop->_head->as_Loop();
2260         if (head->is_strip_mined() && is_dominator(head->outer_loop_exit(), prev)) {
2261           // That node is outside the inner loop, leave it outside the
2262           // outer loop as well to not confuse verification code.
2263           assert(!loop->_parent->is_member(use_loop), "should be out of the outer loop");
2264           _igvn.replace_input_of(use, 0, head->outer_loop_exit());
2265           continue;
2266         }
2267       }
2268 
2269       while(!outer_loop->is_member(get_loop(cfg))) {
2270         prev = cfg;
2271         cfg = (cfg->_idx >= new_counter && cfg->is_Region()) ? cfg->in(2) : idom(cfg);
2272       }
2273       // If the use occurs after merging several exits from the loop, then
2274       // old value must have dominated all those exits.  Since the same old
2275       // value was used on all those exits we did not need a Phi at this
2276       // merge point.  NOW we do need a Phi here.  Each loop exit value
2277       // is now merged with the peeled body exit; each exit gets its own
2278       // private Phi and those Phis need to be merged here.
2279       Node *phi;
2280       if( prev->is_Region() ) {
2281         if( idx == 0 ) {      // Updating control edge?
2282           phi = prev;         // Just use existing control
2283         } else {              // Else need a new Phi
2284           phi = PhiNode::make( prev, old );
2285           // Now recursively fix up the new uses of old!
2286           for( uint i = 1; i < prev->req(); i++ ) {
2287             worklist.push(phi); // Onto worklist once for each 'old' input
2288           }
2289         }
2290       } else {
2291         // Get new RegionNode merging old and new loop exits
2292         prev = old_new[prev->_idx];
2293         assert( prev, "just made this in step 7" );
2294         if( idx == 0) {      // Updating control edge?
2295           phi = prev;         // Just use existing control
2296         } else {              // Else need a new Phi
2297           // Make a new Phi merging data values properly
2298           phi = PhiNode::make( prev, old );
2299           phi->set_req( 1, nnn );
2300         }
2301       }
2302       // If inserting a new Phi, check for prior hits
2303       if( idx != 0 ) {
2304         Node *hit = _igvn.hash_find_insert(phi);
2305         if( hit == nullptr ) {
2306           _igvn.register_new_node_with_optimizer(phi); // Register new phi
2307         } else {                                      // or
2308           // Remove the new phi from the graph and use the hit
2309           _igvn.remove_dead_node(phi);
2310           phi = hit;                                  // Use existing phi
2311         }
2312         set_ctrl(phi, prev);
2313       }
2314       // Make 'use' use the Phi instead of the old loop body exit value
2315       assert(use->in(idx) == old, "old is still input of use");
2316       // We notify all uses of old, including use, and the indirect uses,
2317       // that may now be optimized because we have replaced old with phi.
2318       _igvn.add_users_to_worklist(old);
2319       if (idx == 0 &&
2320           use->depends_only_on_test()) {
2321         Node* pinned_clone = use->pin_array_access_node();
2322         if (pinned_clone != nullptr) {
2323           // Pin array access nodes: control is updated here to a region. If, after some transformations, only one path
2324           // into the region is left, an array load could become dependent on a condition that's not a range check for
2325           // that access. If that condition is replaced by an identical dominating one, then an unpinned load would risk
2326           // floating above its range check.
2327           pinned_clone->set_req(0, phi);
2328           register_new_node_with_ctrl_of(pinned_clone, use);
2329           _igvn.replace_node(use, pinned_clone);
2330           continue;
2331         }
2332       }
2333       _igvn.replace_input_of(use, idx, phi);
2334       if( use->_idx >= new_counter ) { // If updating new phis
2335         // Not needed for correctness, but prevents a weak assert
2336         // in AddPNode from tripping (when we end up with different
2337         // base & derived Phis that will become the same after
2338         // IGVN does CSE).
2339         Node *hit = _igvn.hash_find_insert(use);
2340         if( hit )             // Go ahead and re-hash for hits.
2341           _igvn.replace_node( use, hit );
2342       }
2343     }
2344   }
2345 }
2346 
2347 static void collect_nodes_in_outer_loop_not_reachable_from_sfpt(Node* n, const IdealLoopTree *loop, const IdealLoopTree* outer_loop,
2348                                                                 const Node_List &old_new, Unique_Node_List& wq, PhaseIdealLoop* phase,
2349                                                                 bool check_old_new) {
2350   for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++) {
2351     Node* u = n->fast_out(j);
2352     assert(check_old_new || old_new[u->_idx] == nullptr, "shouldn't have been cloned");
2353     if (!u->is_CFG() && (!check_old_new || old_new[u->_idx] == nullptr)) {
2354       Node* c = phase->get_ctrl(u);
2355       IdealLoopTree* u_loop = phase->get_loop(c);
2356       assert(!loop->is_member(u_loop) || !loop->_body.contains(u), "can be in outer loop or out of both loops only");
2357       if (!loop->is_member(u_loop)) {
2358         if (outer_loop->is_member(u_loop)) {
2359           wq.push(u);
2360         } else {
2361           // nodes pinned with control in the outer loop but not referenced from the safepoint must be moved out of
2362           // the outer loop too
2363           Node* u_c = u->in(0);
2364           if (u_c != nullptr) {
2365             IdealLoopTree* u_c_loop = phase->get_loop(u_c);
2366             if (outer_loop->is_member(u_c_loop) && !loop->is_member(u_c_loop)) {
2367               wq.push(u);
2368             }
2369           }
2370         }
2371       }
2372     }
2373   }
2374 }
2375 
2376 void PhaseIdealLoop::clone_outer_loop(LoopNode* head, CloneLoopMode mode, IdealLoopTree *loop,
2377                                       IdealLoopTree* outer_loop, int dd, Node_List &old_new,
2378                                       Node_List& extra_data_nodes) {
2379   if (head->is_strip_mined() && mode != IgnoreStripMined) {
2380     CountedLoopNode* cl = head->as_CountedLoop();
2381     Node* l = cl->outer_loop();
2382     Node* tail = cl->outer_loop_tail();
2383     IfNode* le = cl->outer_loop_end();
2384     Node* sfpt = cl->outer_safepoint();
2385     CountedLoopEndNode* cle = cl->loopexit();
2386     CountedLoopNode* new_cl = old_new[cl->_idx]->as_CountedLoop();
2387     CountedLoopEndNode* new_cle = new_cl->as_CountedLoop()->loopexit_or_null();
2388     Node* cle_out = cle->proj_out(false);
2389 
2390     Node* new_sfpt = nullptr;
2391     Node* new_cle_out = cle_out->clone();
2392     old_new.map(cle_out->_idx, new_cle_out);
2393     if (mode == CloneIncludesStripMined) {
2394       // clone outer loop body
2395       Node* new_l = l->clone();
2396       Node* new_tail = tail->clone();
2397       IfNode* new_le = le->clone()->as_If();
2398       new_sfpt = sfpt->clone();
2399 
2400       set_loop(new_l, outer_loop->_parent);
2401       set_idom(new_l, new_l->in(LoopNode::EntryControl), dd);
2402       set_loop(new_cle_out, outer_loop->_parent);
2403       set_idom(new_cle_out, new_cle, dd);
2404       set_loop(new_sfpt, outer_loop->_parent);
2405       set_idom(new_sfpt, new_cle_out, dd);
2406       set_loop(new_le, outer_loop->_parent);
2407       set_idom(new_le, new_sfpt, dd);
2408       set_loop(new_tail, outer_loop->_parent);
2409       set_idom(new_tail, new_le, dd);
2410       set_idom(new_cl, new_l, dd);
2411 
2412       old_new.map(l->_idx, new_l);
2413       old_new.map(tail->_idx, new_tail);
2414       old_new.map(le->_idx, new_le);
2415       old_new.map(sfpt->_idx, new_sfpt);
2416 
2417       new_l->set_req(LoopNode::LoopBackControl, new_tail);
2418       new_l->set_req(0, new_l);
2419       new_tail->set_req(0, new_le);
2420       new_le->set_req(0, new_sfpt);
2421       new_sfpt->set_req(0, new_cle_out);
2422       new_cle_out->set_req(0, new_cle);
2423       new_cl->set_req(LoopNode::EntryControl, new_l);
2424 
2425       _igvn.register_new_node_with_optimizer(new_l);
2426       _igvn.register_new_node_with_optimizer(new_tail);
2427       _igvn.register_new_node_with_optimizer(new_le);
2428     } else {
2429       Node *newhead = old_new[loop->_head->_idx];
2430       newhead->as_Loop()->clear_strip_mined();
2431       _igvn.replace_input_of(newhead, LoopNode::EntryControl, newhead->in(LoopNode::EntryControl)->in(LoopNode::EntryControl));
2432       set_idom(newhead, newhead->in(LoopNode::EntryControl), dd);
2433     }
2434     // Look at data node that were assigned a control in the outer
2435     // loop: they are kept in the outer loop by the safepoint so start
2436     // from the safepoint node's inputs.
2437     IdealLoopTree* outer_loop = get_loop(l);
2438     Node_Stack stack(2);
2439     stack.push(sfpt, 1);
2440     uint new_counter = C->unique();
2441     while (stack.size() > 0) {
2442       Node* n = stack.node();
2443       uint i = stack.index();
2444       while (i < n->req() &&
2445              (n->in(i) == nullptr ||
2446               !has_ctrl(n->in(i)) ||
2447               get_loop(get_ctrl(n->in(i))) != outer_loop ||
2448               (old_new[n->in(i)->_idx] != nullptr && old_new[n->in(i)->_idx]->_idx >= new_counter))) {
2449         i++;
2450       }
2451       if (i < n->req()) {
2452         stack.set_index(i+1);
2453         stack.push(n->in(i), 0);
2454       } else {
2455         assert(old_new[n->_idx] == nullptr || n == sfpt || old_new[n->_idx]->_idx < new_counter, "no clone yet");
2456         Node* m = n == sfpt ? new_sfpt : n->clone();
2457         if (m != nullptr) {
2458           for (uint i = 0; i < n->req(); i++) {
2459             if (m->in(i) != nullptr && old_new[m->in(i)->_idx] != nullptr) {
2460               m->set_req(i, old_new[m->in(i)->_idx]);
2461             }
2462           }
2463         } else {
2464           assert(n == sfpt && mode != CloneIncludesStripMined, "where's the safepoint clone?");
2465         }
2466         if (n != sfpt) {
2467           extra_data_nodes.push(n);
2468           _igvn.register_new_node_with_optimizer(m);
2469           assert(get_ctrl(n) == cle_out, "what other control?");
2470           set_ctrl(m, new_cle_out);
2471           old_new.map(n->_idx, m);
2472         }
2473         stack.pop();
2474       }
2475     }
2476     if (mode == CloneIncludesStripMined) {
2477       _igvn.register_new_node_with_optimizer(new_sfpt);
2478       _igvn.register_new_node_with_optimizer(new_cle_out);
2479     }
2480     // Some other transformation may have pessimistically assigned some
2481     // data nodes to the outer loop. Set their control so they are out
2482     // of the outer loop.
2483     ResourceMark rm;
2484     Unique_Node_List wq;
2485     for (uint i = 0; i < extra_data_nodes.size(); i++) {
2486       Node* old = extra_data_nodes.at(i);
2487       collect_nodes_in_outer_loop_not_reachable_from_sfpt(old, loop, outer_loop, old_new, wq, this, true);
2488     }
2489 
2490     for (uint i = 0; i < loop->_body.size(); i++) {
2491       Node* old = loop->_body.at(i);
2492       collect_nodes_in_outer_loop_not_reachable_from_sfpt(old, loop, outer_loop, old_new, wq, this, true);
2493     }
2494 
2495     Node* inner_out = sfpt->in(0);
2496     if (inner_out->outcnt() > 1) {
2497       collect_nodes_in_outer_loop_not_reachable_from_sfpt(inner_out, loop, outer_loop, old_new, wq, this, true);
2498     }
2499 
2500     Node* new_ctrl = cl->outer_loop_exit();
2501     assert(get_loop(new_ctrl) != outer_loop, "must be out of the loop nest");
2502     for (uint i = 0; i < wq.size(); i++) {
2503       Node* n = wq.at(i);
2504       set_ctrl(n, new_ctrl);
2505       if (n->in(0) != nullptr) {
2506         _igvn.replace_input_of(n, 0, new_ctrl);
2507       }
2508       collect_nodes_in_outer_loop_not_reachable_from_sfpt(n, loop, outer_loop, old_new, wq, this, false);
2509     }
2510   } else {
2511     Node *newhead = old_new[loop->_head->_idx];
2512     set_idom(newhead, newhead->in(LoopNode::EntryControl), dd);
2513   }
2514 }
2515 
2516 //------------------------------clone_loop-------------------------------------
2517 //
2518 //                   C L O N E   A   L O O P   B O D Y
2519 //
2520 // This is the basic building block of the loop optimizations.  It clones an
2521 // entire loop body.  It makes an old_new loop body mapping; with this mapping
2522 // you can find the new-loop equivalent to an old-loop node.  All new-loop
2523 // nodes are exactly equal to their old-loop counterparts, all edges are the
2524 // same.  All exits from the old-loop now have a RegionNode that merges the
2525 // equivalent new-loop path.  This is true even for the normal "loop-exit"
2526 // condition.  All uses of loop-invariant old-loop values now come from (one
2527 // or more) Phis that merge their new-loop equivalents.
2528 //
2529 // This operation leaves the graph in an illegal state: there are two valid
2530 // control edges coming from the loop pre-header to both loop bodies.  I'll
2531 // definitely have to hack the graph after running this transform.
2532 //
2533 // From this building block I will further edit edges to perform loop peeling
2534 // or loop unrolling or iteration splitting (Range-Check-Elimination), etc.
2535 //
2536 // Parameter side_by_size_idom:
2537 //   When side_by_size_idom is null, the dominator tree is constructed for
2538 //      the clone loop to dominate the original.  Used in construction of
2539 //      pre-main-post loop sequence.
2540 //   When nonnull, the clone and original are side-by-side, both are
2541 //      dominated by the side_by_side_idom node.  Used in construction of
2542 //      unswitched loops.
2543 void PhaseIdealLoop::clone_loop( IdealLoopTree *loop, Node_List &old_new, int dd,
2544                                 CloneLoopMode mode, Node* side_by_side_idom) {
2545 
2546   LoopNode* head = loop->_head->as_Loop();
2547   head->verify_strip_mined(1);
2548 
2549   if (C->do_vector_loop() && PrintOpto) {
2550     const char* mname = C->method()->name()->as_quoted_ascii();
2551     if (mname != nullptr) {
2552       tty->print("PhaseIdealLoop::clone_loop: for vectorize method %s\n", mname);
2553     }
2554   }
2555 
2556   CloneMap& cm = C->clone_map();
2557   if (C->do_vector_loop()) {
2558     cm.set_clone_idx(cm.max_gen()+1);
2559 #ifndef PRODUCT
2560     if (PrintOpto) {
2561       tty->print_cr("PhaseIdealLoop::clone_loop: _clone_idx %d", cm.clone_idx());
2562       loop->dump_head();
2563     }
2564 #endif
2565   }
2566 
2567   // Step 1: Clone the loop body.  Make the old->new mapping.
2568   clone_loop_body(loop->_body, old_new, &cm);
2569 
2570   IdealLoopTree* outer_loop = (head->is_strip_mined() && mode != IgnoreStripMined) ? get_loop(head->as_CountedLoop()->outer_loop()) : loop;
2571 
2572   // Step 2: Fix the edges in the new body.  If the old input is outside the
2573   // loop use it.  If the old input is INside the loop, use the corresponding
2574   // new node instead.
2575   fix_body_edges(loop->_body, loop, old_new, dd, outer_loop->_parent, false);
2576 
2577   Node_List extra_data_nodes; // data nodes in the outer strip mined loop
2578   clone_outer_loop(head, mode, loop, outer_loop, dd, old_new, extra_data_nodes);
2579 
2580   // Step 3: Now fix control uses.  Loop varying control uses have already
2581   // been fixed up (as part of all input edges in Step 2).  Loop invariant
2582   // control uses must be either an IfFalse or an IfTrue.  Make a merge
2583   // point to merge the old and new IfFalse/IfTrue nodes; make the use
2584   // refer to this.
2585   Node_List worklist;
2586   uint new_counter = C->unique();
2587   fix_ctrl_uses(loop->_body, loop, old_new, mode, side_by_side_idom, &cm, worklist);
2588 
2589   // Step 4: If loop-invariant use is not control, it must be dominated by a
2590   // loop exit IfFalse/IfTrue.  Find "proper" loop exit.  Make a Region
2591   // there if needed.  Make a Phi there merging old and new used values.
2592   Node_List *split_if_set = nullptr;
2593   Node_List *split_bool_set = nullptr;
2594   Node_List *split_cex_set = nullptr;
2595   fix_data_uses(loop->_body, loop, mode, outer_loop, new_counter, old_new, worklist, split_if_set, split_bool_set, split_cex_set);
2596 
2597   for (uint i = 0; i < extra_data_nodes.size(); i++) {
2598     Node* old = extra_data_nodes.at(i);
2599     clone_loop_handle_data_uses(old, old_new, loop, outer_loop, split_if_set,
2600                                 split_bool_set, split_cex_set, worklist, new_counter,
2601                                 mode);
2602   }
2603 
2604   // Check for IFs that need splitting/cloning.  Happens if an IF outside of
2605   // the loop uses a condition set in the loop.  The original IF probably
2606   // takes control from one or more OLD Regions (which in turn get from NEW
2607   // Regions).  In any case, there will be a set of Phis for each merge point
2608   // from the IF up to where the original BOOL def exists the loop.
2609   finish_clone_loop(split_if_set, split_bool_set, split_cex_set);
2610 
2611 }
2612 
2613 void PhaseIdealLoop::finish_clone_loop(Node_List* split_if_set, Node_List* split_bool_set, Node_List* split_cex_set) {
2614   if (split_if_set) {
2615     while (split_if_set->size()) {
2616       Node *iff = split_if_set->pop();
2617       uint input = iff->Opcode() == Op_AllocateArray ? AllocateNode::ValidLengthTest : 1;
2618       if (iff->in(input)->is_Phi()) {
2619         Node *b = clone_iff(iff->in(input)->as_Phi());
2620         _igvn.replace_input_of(iff, input, b);
2621       }
2622     }
2623   }
2624   if (split_bool_set) {
2625     while (split_bool_set->size()) {
2626       Node *b = split_bool_set->pop();
2627       Node *phi = b->in(1);
2628       assert(phi->is_Phi(), "");
2629       CmpNode *cmp = clone_bool((PhiNode*) phi);
2630       _igvn.replace_input_of(b, 1, cmp);
2631     }
2632   }
2633   if (split_cex_set) {
2634     while (split_cex_set->size()) {
2635       Node *b = split_cex_set->pop();
2636       assert(b->in(0)->is_Region(), "");
2637       assert(b->in(1)->is_Phi(), "");
2638       assert(b->in(0)->in(0) == b->in(1)->in(0), "");
2639       split_up(b, b->in(0), nullptr);
2640     }
2641   }
2642 }
2643 
2644 void PhaseIdealLoop::fix_data_uses(Node_List& body, IdealLoopTree* loop, CloneLoopMode mode, IdealLoopTree* outer_loop,
2645                                    uint new_counter, Node_List &old_new, Node_List &worklist, Node_List*& split_if_set,
2646                                    Node_List*& split_bool_set, Node_List*& split_cex_set) {
2647   for(uint i = 0; i < body.size(); i++ ) {
2648     Node* old = body.at(i);
2649     clone_loop_handle_data_uses(old, old_new, loop, outer_loop, split_if_set,
2650                                 split_bool_set, split_cex_set, worklist, new_counter,
2651                                 mode);
2652   }
2653 }
2654 
2655 void PhaseIdealLoop::fix_ctrl_uses(const Node_List& body, const IdealLoopTree* loop, Node_List &old_new, CloneLoopMode mode,
2656                                    Node* side_by_side_idom, CloneMap* cm, Node_List &worklist) {
2657   LoopNode* head = loop->_head->as_Loop();
2658   for(uint i = 0; i < body.size(); i++ ) {
2659     Node* old = body.at(i);
2660     if( !old->is_CFG() ) continue;
2661 
2662     // Copy uses to a worklist, so I can munge the def-use info
2663     // with impunity.
2664     for (DUIterator_Fast jmax, j = old->fast_outs(jmax); j < jmax; j++) {
2665       worklist.push(old->fast_out(j));
2666     }
2667 
2668     while (worklist.size()) {  // Visit all uses
2669       Node *use = worklist.pop();
2670       if (!has_node(use))  continue; // Ignore dead nodes
2671       IdealLoopTree *use_loop = get_loop(has_ctrl(use) ? get_ctrl(use) : use );
2672       if (!loop->is_member(use_loop) && use->is_CFG()) {
2673         // Both OLD and USE are CFG nodes here.
2674         assert(use->is_Proj(), "" );
2675         Node* nnn = old_new[old->_idx];
2676 
2677         Node* newuse = nullptr;
2678         if (head->is_strip_mined() && mode != IgnoreStripMined) {
2679           CountedLoopNode* cl = head->as_CountedLoop();
2680           CountedLoopEndNode* cle = cl->loopexit();
2681           Node* cle_out = cle->proj_out_or_null(false);
2682           if (use == cle_out) {
2683             IfNode* le = cl->outer_loop_end();
2684             use = le->proj_out(false);
2685             use_loop = get_loop(use);
2686             if (mode == CloneIncludesStripMined) {
2687               nnn = old_new[le->_idx];
2688             } else {
2689               newuse = old_new[cle_out->_idx];
2690             }
2691           }
2692         }
2693         if (newuse == nullptr) {
2694           newuse = use->clone();
2695         }
2696 
2697         // Clone the loop exit control projection
2698         if (C->do_vector_loop() && cm != nullptr) {
2699           cm->verify_insert_and_clone(use, newuse, cm->clone_idx());
2700         }
2701         newuse->set_req(0,nnn);
2702         _igvn.register_new_node_with_optimizer(newuse);
2703         set_loop(newuse, use_loop);
2704         set_idom(newuse, nnn, dom_depth(nnn) + 1 );
2705 
2706         // We need a Region to merge the exit from the peeled body and the
2707         // exit from the old loop body.
2708         RegionNode *r = new RegionNode(3);
2709         uint dd_r = MIN2(dom_depth(newuse), dom_depth(use));
2710         assert(dd_r >= dom_depth(dom_lca(newuse, use)), "" );
2711 
2712         // The original user of 'use' uses 'r' instead.
2713         for (DUIterator_Last lmin, l = use->last_outs(lmin); l >= lmin;) {
2714           Node* useuse = use->last_out(l);
2715           _igvn.rehash_node_delayed(useuse);
2716           uint uses_found = 0;
2717           if (useuse->in(0) == use) {
2718             useuse->set_req(0, r);
2719             uses_found++;
2720             if (useuse->is_CFG()) {
2721               // This is not a dom_depth > dd_r because when new
2722               // control flow is constructed by a loop opt, a node and
2723               // its dominator can end up at the same dom_depth
2724               assert(dom_depth(useuse) >= dd_r, "");
2725               set_idom(useuse, r, dom_depth(useuse));
2726             }
2727           }
2728           for (uint k = 1; k < useuse->req(); k++) {
2729             if( useuse->in(k) == use ) {
2730               useuse->set_req(k, r);
2731               uses_found++;
2732               if (useuse->is_Loop() && k == LoopNode::EntryControl) {
2733                 // This is not a dom_depth > dd_r because when new
2734                 // control flow is constructed by a loop opt, a node
2735                 // and its dominator can end up at the same dom_depth
2736                 assert(dom_depth(useuse) >= dd_r , "");
2737                 set_idom(useuse, r, dom_depth(useuse));
2738               }
2739             }
2740           }
2741           l -= uses_found;    // we deleted 1 or more copies of this edge
2742         }
2743 
2744         assert(use->is_Proj(), "loop exit should be projection");
2745         // lazy_replace() below moves all nodes that are:
2746         // - control dependent on the loop exit or
2747         // - have control set to the loop exit
2748         // below the post-loop merge point. lazy_replace() takes a dead control as first input. To make it
2749         // possible to use it, the loop exit projection is cloned and becomes the new exit projection. The initial one
2750         // becomes dead and is "replaced" by the region.
2751         Node* use_clone = use->clone();
2752         register_control(use_clone, use_loop, idom(use), dom_depth(use));
2753         // Now finish up 'r'
2754         r->set_req(1, newuse);
2755         r->set_req(2, use_clone);
2756         _igvn.register_new_node_with_optimizer(r);
2757         set_loop(r, use_loop);
2758         set_idom(r, (side_by_side_idom == nullptr) ? newuse->in(0) : side_by_side_idom, dd_r);
2759         lazy_replace(use, r);
2760         // Map the (cloned) old use to the new merge point
2761         old_new.map(use_clone->_idx, r);
2762       } // End of if a loop-exit test
2763     }
2764   }
2765 }
2766 
2767 void PhaseIdealLoop::fix_body_edges(const Node_List &body, IdealLoopTree* loop, const Node_List &old_new, int dd,
2768                                     IdealLoopTree* parent, bool partial) {
2769   for(uint i = 0; i < body.size(); i++ ) {
2770     Node *old = body.at(i);
2771     Node *nnn = old_new[old->_idx];
2772     // Fix CFG/Loop controlling the new node
2773     if (has_ctrl(old)) {
2774       set_ctrl(nnn, old_new[get_ctrl(old)->_idx]);
2775     } else {
2776       set_loop(nnn, parent);
2777       if (old->outcnt() > 0) {
2778         Node* dom = idom(old);
2779         if (old_new[dom->_idx] != nullptr) {
2780           dom = old_new[dom->_idx];
2781           set_idom(nnn, dom, dd );
2782         }
2783       }
2784     }
2785     // Correct edges to the new node
2786     for (uint j = 0; j < nnn->req(); j++) {
2787         Node *n = nnn->in(j);
2788         if (n != nullptr) {
2789           IdealLoopTree *old_in_loop = get_loop(has_ctrl(n) ? get_ctrl(n) : n);
2790           if (loop->is_member(old_in_loop)) {
2791             if (old_new[n->_idx] != nullptr) {
2792               nnn->set_req(j, old_new[n->_idx]);
2793             } else {
2794               assert(!body.contains(n), "");
2795               assert(partial, "node not cloned");
2796             }
2797           }
2798         }
2799     }
2800     _igvn.hash_find_insert(nnn);
2801   }
2802 }
2803 
2804 void PhaseIdealLoop::clone_loop_body(const Node_List& body, Node_List &old_new, CloneMap* cm) {
2805   for (uint i = 0; i < body.size(); i++) {
2806     Node* old = body.at(i);
2807     Node* nnn = old->clone();
2808     old_new.map(old->_idx, nnn);
2809     if (C->do_vector_loop() && cm != nullptr) {
2810       cm->verify_insert_and_clone(old, nnn, cm->clone_idx());
2811     }
2812     _igvn.register_new_node_with_optimizer(nnn);
2813   }
2814 }
2815 
2816 
2817 //---------------------- stride_of_possible_iv -------------------------------------
2818 // Looks for an iff/bool/comp with one operand of the compare
2819 // being a cycle involving an add and a phi,
2820 // with an optional truncation (left-shift followed by a right-shift)
2821 // of the add. Returns zero if not an iv.
2822 int PhaseIdealLoop::stride_of_possible_iv(Node* iff) {
2823   Node* trunc1 = nullptr;
2824   Node* trunc2 = nullptr;
2825   const TypeInteger* ttype = nullptr;
2826   if (!iff->is_If() || iff->in(1) == nullptr || !iff->in(1)->is_Bool()) {
2827     return 0;
2828   }
2829   BoolNode* bl = iff->in(1)->as_Bool();
2830   Node* cmp = bl->in(1);
2831   if (!cmp || (cmp->Opcode() != Op_CmpI && cmp->Opcode() != Op_CmpU)) {
2832     return 0;
2833   }
2834   // Must have an invariant operand
2835   if (is_member(get_loop(iff), get_ctrl(cmp->in(2)))) {
2836     return 0;
2837   }
2838   Node* add2 = nullptr;
2839   Node* cmp1 = cmp->in(1);
2840   if (cmp1->is_Phi()) {
2841     // (If (Bool (CmpX phi:(Phi ...(Optional-trunc(AddI phi add2))) )))
2842     Node* phi = cmp1;
2843     for (uint i = 1; i < phi->req(); i++) {
2844       Node* in = phi->in(i);
2845       Node* add = CountedLoopNode::match_incr_with_optional_truncation(in,
2846                                 &trunc1, &trunc2, &ttype, T_INT);
2847       if (add && add->in(1) == phi) {
2848         add2 = add->in(2);
2849         break;
2850       }
2851     }
2852   } else {
2853     // (If (Bool (CmpX addtrunc:(Optional-trunc((AddI (Phi ...addtrunc...) add2)) )))
2854     Node* addtrunc = cmp1;
2855     Node* add = CountedLoopNode::match_incr_with_optional_truncation(addtrunc,
2856                                 &trunc1, &trunc2, &ttype, T_INT);
2857     if (add && add->in(1)->is_Phi()) {
2858       Node* phi = add->in(1);
2859       for (uint i = 1; i < phi->req(); i++) {
2860         if (phi->in(i) == addtrunc) {
2861           add2 = add->in(2);
2862           break;
2863         }
2864       }
2865     }
2866   }
2867   if (add2 != nullptr) {
2868     const TypeInt* add2t = _igvn.type(add2)->is_int();
2869     if (add2t->is_con()) {
2870       return add2t->get_con();
2871     }
2872   }
2873   return 0;
2874 }
2875 
2876 
2877 //---------------------- stay_in_loop -------------------------------------
2878 // Return the (unique) control output node that's in the loop (if it exists.)
2879 Node* PhaseIdealLoop::stay_in_loop( Node* n, IdealLoopTree *loop) {
2880   Node* unique = nullptr;
2881   if (!n) return nullptr;
2882   for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
2883     Node* use = n->fast_out(i);
2884     if (!has_ctrl(use) && loop->is_member(get_loop(use))) {
2885       if (unique != nullptr) {
2886         return nullptr;
2887       }
2888       unique = use;
2889     }
2890   }
2891   return unique;
2892 }
2893 
2894 //------------------------------ register_node -------------------------------------
2895 // Utility to register node "n" with PhaseIdealLoop
2896 void PhaseIdealLoop::register_node(Node* n, IdealLoopTree* loop, Node* pred, uint ddepth) {
2897   _igvn.register_new_node_with_optimizer(n);
2898   loop->_body.push(n);
2899   if (n->is_CFG()) {
2900     set_loop(n, loop);
2901     set_idom(n, pred, ddepth);
2902   } else {
2903     set_ctrl(n, pred);
2904   }
2905 }
2906 
2907 //------------------------------ proj_clone -------------------------------------
2908 // Utility to create an if-projection
2909 ProjNode* PhaseIdealLoop::proj_clone(ProjNode* p, IfNode* iff) {
2910   ProjNode* c = p->clone()->as_Proj();
2911   c->set_req(0, iff);
2912   return c;
2913 }
2914 
2915 //------------------------------ short_circuit_if -------------------------------------
2916 // Force the iff control output to be the live_proj
2917 Node* PhaseIdealLoop::short_circuit_if(IfNode* iff, ProjNode* live_proj) {
2918   guarantee(live_proj != nullptr, "null projection");
2919   int proj_con = live_proj->_con;
2920   assert(proj_con == 0 || proj_con == 1, "false or true projection");
2921   Node* con = intcon(proj_con);
2922   if (iff) {
2923     iff->set_req(1, con);
2924   }
2925   return con;
2926 }
2927 
2928 //------------------------------ insert_if_before_proj -------------------------------------
2929 // Insert a new if before an if projection (* - new node)
2930 //
2931 // before
2932 //           if(test)
2933 //           /     \
2934 //          v       v
2935 //    other-proj   proj (arg)
2936 //
2937 // after
2938 //           if(test)
2939 //           /     \
2940 //          /       v
2941 //         |      * proj-clone
2942 //         v          |
2943 //    other-proj      v
2944 //                * new_if(relop(cmp[IU](left,right)))
2945 //                  /  \
2946 //                 v    v
2947 //         * new-proj  proj
2948 //         (returned)
2949 //
2950 ProjNode* PhaseIdealLoop::insert_if_before_proj(Node* left, bool Signed, BoolTest::mask relop, Node* right, ProjNode* proj) {
2951   IfNode* iff = proj->in(0)->as_If();
2952   IdealLoopTree *loop = get_loop(proj);
2953   ProjNode *other_proj = iff->proj_out(!proj->is_IfTrue())->as_Proj();
2954   uint ddepth = dom_depth(proj);
2955 
2956   _igvn.rehash_node_delayed(iff);
2957   _igvn.rehash_node_delayed(proj);
2958 
2959   proj->set_req(0, nullptr);  // temporary disconnect
2960   ProjNode* proj2 = proj_clone(proj, iff);
2961   register_node(proj2, loop, iff, ddepth);
2962 
2963   Node* cmp = Signed ? (Node*) new CmpINode(left, right) : (Node*) new CmpUNode(left, right);
2964   register_node(cmp, loop, proj2, ddepth);
2965 
2966   BoolNode* bol = new BoolNode(cmp, relop);
2967   register_node(bol, loop, proj2, ddepth);
2968 
2969   int opcode = iff->Opcode();
2970   assert(opcode == Op_If || opcode == Op_RangeCheck, "unexpected opcode");
2971   IfNode* new_if = IfNode::make_with_same_profile(iff, proj2, bol);
2972   register_node(new_if, loop, proj2, ddepth);
2973 
2974   proj->set_req(0, new_if); // reattach
2975   set_idom(proj, new_if, ddepth);
2976 
2977   ProjNode* new_exit = proj_clone(other_proj, new_if)->as_Proj();
2978   guarantee(new_exit != nullptr, "null exit node");
2979   register_node(new_exit, get_loop(other_proj), new_if, ddepth);
2980 
2981   return new_exit;
2982 }
2983 
2984 //------------------------------ insert_region_before_proj -------------------------------------
2985 // Insert a region before an if projection (* - new node)
2986 //
2987 // before
2988 //           if(test)
2989 //          /      |
2990 //         v       |
2991 //       proj      v
2992 //               other-proj
2993 //
2994 // after
2995 //           if(test)
2996 //          /      |
2997 //         v       |
2998 // * proj-clone    v
2999 //         |     other-proj
3000 //         v
3001 // * new-region
3002 //         |
3003 //         v
3004 // *      dum_if
3005 //       /     \
3006 //      v       \
3007 // * dum-proj    v
3008 //              proj
3009 //
3010 RegionNode* PhaseIdealLoop::insert_region_before_proj(ProjNode* proj) {
3011   IfNode* iff = proj->in(0)->as_If();
3012   IdealLoopTree *loop = get_loop(proj);
3013   ProjNode *other_proj = iff->proj_out(!proj->is_IfTrue())->as_Proj();
3014   uint ddepth = dom_depth(proj);
3015 
3016   _igvn.rehash_node_delayed(iff);
3017   _igvn.rehash_node_delayed(proj);
3018 
3019   proj->set_req(0, nullptr);  // temporary disconnect
3020   ProjNode* proj2 = proj_clone(proj, iff);
3021   register_node(proj2, loop, iff, ddepth);
3022 
3023   RegionNode* reg = new RegionNode(2);
3024   reg->set_req(1, proj2);
3025   register_node(reg, loop, iff, ddepth);
3026 
3027   IfNode* dum_if = new IfNode(reg, short_circuit_if(nullptr, proj), iff->_prob, iff->_fcnt);
3028   register_node(dum_if, loop, reg, ddepth);
3029 
3030   proj->set_req(0, dum_if); // reattach
3031   set_idom(proj, dum_if, ddepth);
3032 
3033   ProjNode* dum_proj = proj_clone(other_proj, dum_if);
3034   register_node(dum_proj, loop, dum_if, ddepth);
3035 
3036   return reg;
3037 }
3038 
3039 // Idea
3040 // ----
3041 // Partial Peeling tries to rotate the loop in such a way that it can later be turned into a counted loop. Counted loops
3042 // require a signed loop exit test. When calling this method, we've only found a suitable unsigned test to partial peel
3043 // with. Therefore, we try to split off a signed loop exit test from the unsigned test such that it can be used as new
3044 // loop exit while keeping the unsigned test unchanged and preserving the same behavior as if we've used the unsigned
3045 // test alone instead:
3046 //
3047 // Before Partial Peeling:
3048 //   Loop:
3049 //     <peeled section>
3050 //     Split off signed loop exit test
3051 //     <-- CUT HERE -->
3052 //     Unchanged unsigned loop exit test
3053 //     <rest of unpeeled section>
3054 //     goto Loop
3055 //
3056 // After Partial Peeling:
3057 //   <cloned peeled section>
3058 //   Cloned split off signed loop exit test
3059 //   Loop:
3060 //     Unchanged unsigned loop exit test
3061 //     <rest of unpeeled section>
3062 //     <peeled section>
3063 //     Split off signed loop exit test
3064 //     goto Loop
3065 //
3066 // Details
3067 // -------
3068 // Before:
3069 //          if (i <u limit)    Unsigned loop exit condition
3070 //         /       |
3071 //        v        v
3072 //   exit-proj   stay-in-loop-proj
3073 //
3074 // Split off a signed loop exit test (i.e. with CmpI) from an unsigned loop exit test (i.e. with CmpU) and insert it
3075 // before the CmpU on the stay-in-loop path and keep both tests:
3076 //
3077 //          if (i <u limit)    Signed loop exit test
3078 //        /        |
3079 //       /  if (i <u limit)    Unsigned loop exit test
3080 //      /  /       |
3081 //     v  v        v
3082 //  exit-region  stay-in-loop-proj
3083 //
3084 // Implementation
3085 // --------------
3086 // We need to make sure that the new signed loop exit test is properly inserted into the graph such that the unsigned
3087 // loop exit test still dominates the same set of control nodes, the ctrl() relation from data nodes to both loop
3088 // exit tests is preserved, and their loop nesting is correct.
3089 //
3090 // To achieve that, we clone the unsigned loop exit test completely (leave it unchanged), insert the signed loop exit
3091 // test above it and kill the original unsigned loop exit test by setting it's condition to a constant
3092 // (i.e. stay-in-loop-const in graph below) such that IGVN can fold it later:
3093 //
3094 //           if (stay-in-loop-const)  Killed original unsigned loop exit test
3095 //          /       |
3096 //         /        v
3097 //        /  if (i <  limit)          Split off signed loop exit test
3098 //       /  /       |
3099 //      /  /        v
3100 //     /  /  if (i <u limit)          Cloned unsigned loop exit test
3101 //    /  /   /      |
3102 //   v  v  v        |
3103 //  exit-region     |
3104 //        |         |
3105 //    dummy-if      |
3106 //     /  |         |
3107 // dead   |         |
3108 //        v         v
3109 //   exit-proj   stay-in-loop-proj
3110 //
3111 // Note: The dummy-if is inserted to create a region to merge the loop exits between the original to be killed unsigned
3112 //       loop exit test and its exit projection while keeping the exit projection (also see insert_region_before_proj()).
3113 //
3114 // Requirements
3115 // ------------
3116 // Note that we can only split off a signed loop exit test from the unsigned loop exit test when the behavior is exactly
3117 // the same as before with only a single unsigned test. This is only possible if certain requirements are met.
3118 // Otherwise, we need to bail out (see comments in the code below).
3119 IfNode* PhaseIdealLoop::insert_cmpi_loop_exit(IfNode* if_cmpu, IdealLoopTree* loop) {
3120   const bool Signed   = true;
3121   const bool Unsigned = false;
3122 
3123   BoolNode* bol = if_cmpu->in(1)->as_Bool();
3124   if (bol->_test._test != BoolTest::lt) {
3125     return nullptr;
3126   }
3127   CmpNode* cmpu = bol->in(1)->as_Cmp();
3128   assert(cmpu->Opcode() == Op_CmpU, "must be unsigned comparison");
3129 
3130   int stride = stride_of_possible_iv(if_cmpu);
3131   if (stride == 0) {
3132     return nullptr;
3133   }
3134 
3135   Node* lp_proj = stay_in_loop(if_cmpu, loop);
3136   guarantee(lp_proj != nullptr, "null loop node");
3137 
3138   ProjNode* lp_continue = lp_proj->as_Proj();
3139   ProjNode* lp_exit     = if_cmpu->proj_out(!lp_continue->is_IfTrue())->as_Proj();
3140   if (!lp_exit->is_IfFalse()) {
3141     // The loop exit condition is (i <u limit) ==> (i >= 0 && i < limit).
3142     // We therefore can't add a single exit condition.
3143     return nullptr;
3144   }
3145   // The unsigned loop exit condition is
3146   //   !(i <u  limit)
3147   // =   i >=u limit
3148   //
3149   // First, we note that for any x for which
3150   //   0 <= x <= INT_MAX
3151   // we can convert x to an unsigned int and still get the same guarantee:
3152   //   0 <=  (uint) x <=  INT_MAX = (uint) INT_MAX
3153   //   0 <=u (uint) x <=u INT_MAX = (uint) INT_MAX   (LEMMA)
3154   //
3155   // With that in mind, if
3156   //   limit >= 0             (COND)
3157   // then the unsigned loop exit condition
3158   //   i >=u limit            (ULE)
3159   // is equivalent to
3160   //   i < 0 || i >= limit    (SLE-full)
3161   // because either i is negative and therefore always greater than MAX_INT when converting to unsigned
3162   //   (uint) i >=u MAX_INT >= limit >= 0
3163   // or otherwise
3164   //   i >= limit >= 0
3165   // holds due to (LEMMA).
3166   //
3167   // For completeness, a counterexample with limit < 0:
3168   // Assume i = -3 and limit = -2:
3169   //   i  < 0
3170   //   -2 < 0
3171   // is true and thus also "i < 0 || i >= limit". But
3172   //   i  >=u limit
3173   //   -3 >=u -2
3174   // is false.
3175   Node* limit = cmpu->in(2);
3176   const TypeInt* type_limit = _igvn.type(limit)->is_int();
3177   if (type_limit->_lo < 0) {
3178     return nullptr;
3179   }
3180 
3181   // We prove below that we can extract a single signed loop exit condition from (SLE-full), depending on the stride:
3182   //   stride < 0:
3183   //     i < 0        (SLE = SLE-negative)
3184   //   stride > 0:
3185   //     i >= limit   (SLE = SLE-positive)
3186   // such that we have the following graph before Partial Peeling with stride > 0 (similar for stride < 0):
3187   //
3188   // Loop:
3189   //   <peeled section>
3190   //   i >= limit    (SLE-positive)
3191   //   <-- CUT HERE -->
3192   //   i >=u limit   (ULE)
3193   //   <rest of unpeeled section>
3194   //   goto Loop
3195   //
3196   // We exit the loop if:
3197   //   (SLE) is true OR (ULE) is true
3198   // However, if (SLE) is true then (ULE) also needs to be true to ensure the exact same behavior. Otherwise, we wrongly
3199   // exit a loop that should not have been exited if we did not apply Partial Peeling. More formally, we need to ensure:
3200   //   (SLE) IMPLIES (ULE)
3201   // This indeed holds when (COND) is given:
3202   // - stride > 0:
3203   //       i >=  limit             // (SLE = SLE-positive)
3204   //       i >=  limit >= 0        // (COND)
3205   //       i >=u limit >= 0        // (LEMMA)
3206   //     which is the unsigned loop exit condition (ULE).
3207   // - stride < 0:
3208   //       i        <  0           // (SLE = SLE-negative)
3209   //       (uint) i >u MAX_INT     // (NEG) all negative values are greater than MAX_INT when converted to unsigned
3210   //       MAX_INT >= limit >= 0   // (COND)
3211   //       MAX_INT >=u limit >= 0  // (LEMMA)
3212   //     and thus from (NEG) and (LEMMA):
3213   //       i >=u limit
3214   //     which is the unsigned loop exit condition (ULE).
3215   //
3216   //
3217   // After Partial Peeling, we have the following structure for stride > 0 (similar for stride < 0):
3218   //   <cloned peeled section>
3219   //   i >= limit (SLE-positive)
3220   //   Loop:
3221   //     i >=u limit (ULE)
3222   //     <rest of unpeeled section>
3223   //     <peeled section>
3224   //     i >= limit (SLE-positive)
3225   //     goto Loop
3226   Node* rhs_cmpi;
3227   if (stride > 0) {
3228     rhs_cmpi = limit; // For i >= limit
3229   } else {
3230     rhs_cmpi = makecon(TypeInt::ZERO); // For i < 0
3231   }
3232   // Create a new region on the exit path
3233   RegionNode* reg = insert_region_before_proj(lp_exit);
3234   guarantee(reg != nullptr, "null region node");
3235 
3236   // Clone the if-cmpu-true-false using a signed compare
3237   BoolTest::mask rel_i = stride > 0 ? bol->_test._test : BoolTest::ge;
3238   ProjNode* cmpi_exit = insert_if_before_proj(cmpu->in(1), Signed, rel_i, rhs_cmpi, lp_continue);
3239   reg->add_req(cmpi_exit);
3240 
3241   // Clone the if-cmpu-true-false
3242   BoolTest::mask rel_u = bol->_test._test;
3243   ProjNode* cmpu_exit = insert_if_before_proj(cmpu->in(1), Unsigned, rel_u, cmpu->in(2), lp_continue);
3244   reg->add_req(cmpu_exit);
3245 
3246   // Force original if to stay in loop.
3247   short_circuit_if(if_cmpu, lp_continue);
3248 
3249   return cmpi_exit->in(0)->as_If();
3250 }
3251 
3252 //------------------------------ remove_cmpi_loop_exit -------------------------------------
3253 // Remove a previously inserted signed compare loop exit.
3254 void PhaseIdealLoop::remove_cmpi_loop_exit(IfNode* if_cmp, IdealLoopTree *loop) {
3255   Node* lp_proj = stay_in_loop(if_cmp, loop);
3256   assert(if_cmp->in(1)->in(1)->Opcode() == Op_CmpI &&
3257          stay_in_loop(lp_proj, loop)->is_If() &&
3258          stay_in_loop(lp_proj, loop)->in(1)->in(1)->Opcode() == Op_CmpU, "inserted cmpi before cmpu");
3259   Node* con = makecon(lp_proj->is_IfTrue() ? TypeInt::ONE : TypeInt::ZERO);
3260   if_cmp->set_req(1, con);
3261 }
3262 
3263 //------------------------------ scheduled_nodelist -------------------------------------
3264 // Create a post order schedule of nodes that are in the
3265 // "member" set.  The list is returned in "sched".
3266 // The first node in "sched" is the loop head, followed by
3267 // nodes which have no inputs in the "member" set, and then
3268 // followed by the nodes that have an immediate input dependence
3269 // on a node in "sched".
3270 void PhaseIdealLoop::scheduled_nodelist( IdealLoopTree *loop, VectorSet& member, Node_List &sched ) {
3271 
3272   assert(member.test(loop->_head->_idx), "loop head must be in member set");
3273   VectorSet visited;
3274   Node_Stack nstack(loop->_body.size());
3275 
3276   Node* n  = loop->_head;  // top of stack is cached in "n"
3277   uint idx = 0;
3278   visited.set(n->_idx);
3279 
3280   // Initially push all with no inputs from within member set
3281   for(uint i = 0; i < loop->_body.size(); i++ ) {
3282     Node *elt = loop->_body.at(i);
3283     if (member.test(elt->_idx)) {
3284       bool found = false;
3285       for (uint j = 0; j < elt->req(); j++) {
3286         Node* def = elt->in(j);
3287         if (def && member.test(def->_idx) && def != elt) {
3288           found = true;
3289           break;
3290         }
3291       }
3292       if (!found && elt != loop->_head) {
3293         nstack.push(n, idx);
3294         n = elt;
3295         assert(!visited.test(n->_idx), "not seen yet");
3296         visited.set(n->_idx);
3297       }
3298     }
3299   }
3300 
3301   // traverse out's that are in the member set
3302   while (true) {
3303     if (idx < n->outcnt()) {
3304       Node* use = n->raw_out(idx);
3305       idx++;
3306       if (!visited.test_set(use->_idx)) {
3307         if (member.test(use->_idx)) {
3308           nstack.push(n, idx);
3309           n = use;
3310           idx = 0;
3311         }
3312       }
3313     } else {
3314       // All outputs processed
3315       sched.push(n);
3316       if (nstack.is_empty()) break;
3317       n   = nstack.node();
3318       idx = nstack.index();
3319       nstack.pop();
3320     }
3321   }
3322 }
3323 
3324 
3325 //------------------------------ has_use_in_set -------------------------------------
3326 // Has a use in the vector set
3327 bool PhaseIdealLoop::has_use_in_set( Node* n, VectorSet& vset ) {
3328   for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++) {
3329     Node* use = n->fast_out(j);
3330     if (vset.test(use->_idx)) {
3331       return true;
3332     }
3333   }
3334   return false;
3335 }
3336 
3337 
3338 //------------------------------ has_use_internal_to_set -------------------------------------
3339 // Has use internal to the vector set (ie. not in a phi at the loop head)
3340 bool PhaseIdealLoop::has_use_internal_to_set( Node* n, VectorSet& vset, IdealLoopTree *loop ) {
3341   Node* head  = loop->_head;
3342   for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++) {
3343     Node* use = n->fast_out(j);
3344     if (vset.test(use->_idx) && !(use->is_Phi() && use->in(0) == head)) {
3345       return true;
3346     }
3347   }
3348   return false;
3349 }
3350 
3351 
3352 //------------------------------ clone_for_use_outside_loop -------------------------------------
3353 // clone "n" for uses that are outside of loop
3354 int PhaseIdealLoop::clone_for_use_outside_loop( IdealLoopTree *loop, Node* n, Node_List& worklist ) {
3355   int cloned = 0;
3356   assert(worklist.size() == 0, "should be empty");
3357   for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++) {
3358     Node* use = n->fast_out(j);
3359     if( !loop->is_member(get_loop(has_ctrl(use) ? get_ctrl(use) : use)) ) {
3360       worklist.push(use);
3361     }
3362   }
3363 
3364   if (C->check_node_count(worklist.size() + NodeLimitFudgeFactor,
3365                           "Too many clones required in clone_for_use_outside_loop in partial peeling")) {
3366     return -1;
3367   }
3368 
3369   while( worklist.size() ) {
3370     Node *use = worklist.pop();
3371     if (!has_node(use) || use->in(0) == C->top()) continue;
3372     uint j;
3373     for (j = 0; j < use->req(); j++) {
3374       if (use->in(j) == n) break;
3375     }
3376     assert(j < use->req(), "must be there");
3377 
3378     // clone "n" and insert it between the inputs of "n" and the use outside the loop
3379     Node* n_clone = n->clone();
3380     _igvn.replace_input_of(use, j, n_clone);
3381     cloned++;
3382     Node* use_c;
3383     if (!use->is_Phi()) {
3384       use_c = has_ctrl(use) ? get_ctrl(use) : use->in(0);
3385     } else {
3386       // Use in a phi is considered a use in the associated predecessor block
3387       use_c = use->in(0)->in(j);
3388     }
3389     set_ctrl(n_clone, use_c);
3390     assert(!loop->is_member(get_loop(use_c)), "should be outside loop");
3391     get_loop(use_c)->_body.push(n_clone);
3392     _igvn.register_new_node_with_optimizer(n_clone);
3393 #ifndef PRODUCT
3394     if (TracePartialPeeling) {
3395       tty->print_cr("loop exit cloning old: %d new: %d newbb: %d", n->_idx, n_clone->_idx, get_ctrl(n_clone)->_idx);
3396     }
3397 #endif
3398   }
3399   return cloned;
3400 }
3401 
3402 
3403 //------------------------------ clone_for_special_use_inside_loop -------------------------------------
3404 // clone "n" for special uses that are in the not_peeled region.
3405 // If these def-uses occur in separate blocks, the code generator
3406 // marks the method as not compilable.  For example, if a "BoolNode"
3407 // is in a different basic block than the "IfNode" that uses it, then
3408 // the compilation is aborted in the code generator.
3409 void PhaseIdealLoop::clone_for_special_use_inside_loop( IdealLoopTree *loop, Node* n,
3410                                                         VectorSet& not_peel, Node_List& sink_list, Node_List& worklist ) {
3411   if (n->is_Phi() || n->is_Load()) {
3412     return;
3413   }
3414   assert(worklist.size() == 0, "should be empty");
3415   for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++) {
3416     Node* use = n->fast_out(j);
3417     if ( not_peel.test(use->_idx) &&
3418          (use->is_If() || use->is_CMove() || use->is_Bool() || use->is_OpaqueInitializedAssertionPredicate()) &&
3419          use->in(1) == n)  {
3420       worklist.push(use);
3421     }
3422   }
3423   if (worklist.size() > 0) {
3424     // clone "n" and insert it between inputs of "n" and the use
3425     Node* n_clone = n->clone();
3426     loop->_body.push(n_clone);
3427     _igvn.register_new_node_with_optimizer(n_clone);
3428     set_ctrl(n_clone, get_ctrl(n));
3429     sink_list.push(n_clone);
3430     not_peel.set(n_clone->_idx);
3431 #ifndef PRODUCT
3432     if (TracePartialPeeling) {
3433       tty->print_cr("special not_peeled cloning old: %d new: %d", n->_idx, n_clone->_idx);
3434     }
3435 #endif
3436     while( worklist.size() ) {
3437       Node *use = worklist.pop();
3438       _igvn.rehash_node_delayed(use);
3439       for (uint j = 1; j < use->req(); j++) {
3440         if (use->in(j) == n) {
3441           use->set_req(j, n_clone);
3442         }
3443       }
3444     }
3445   }
3446 }
3447 
3448 
3449 //------------------------------ insert_phi_for_loop -------------------------------------
3450 // Insert phi(lp_entry_val, back_edge_val) at use->in(idx) for loop lp if phi does not already exist
3451 void PhaseIdealLoop::insert_phi_for_loop( Node* use, uint idx, Node* lp_entry_val, Node* back_edge_val, LoopNode* lp ) {
3452   Node *phi = PhiNode::make(lp, back_edge_val);
3453   phi->set_req(LoopNode::EntryControl, lp_entry_val);
3454   // Use existing phi if it already exists
3455   Node *hit = _igvn.hash_find_insert(phi);
3456   if( hit == nullptr ) {
3457     _igvn.register_new_node_with_optimizer(phi);
3458     set_ctrl(phi, lp);
3459   } else {
3460     // Remove the new phi from the graph and use the hit
3461     _igvn.remove_dead_node(phi);
3462     phi = hit;
3463   }
3464   _igvn.replace_input_of(use, idx, phi);
3465 }
3466 
3467 #ifdef ASSERT
3468 //------------------------------ is_valid_loop_partition -------------------------------------
3469 // Validate the loop partition sets: peel and not_peel
3470 bool PhaseIdealLoop::is_valid_loop_partition( IdealLoopTree *loop, VectorSet& peel, Node_List& peel_list,
3471                                               VectorSet& not_peel ) {
3472   uint i;
3473   // Check that peel_list entries are in the peel set
3474   for (i = 0; i < peel_list.size(); i++) {
3475     if (!peel.test(peel_list.at(i)->_idx)) {
3476       return false;
3477     }
3478   }
3479   // Check at loop members are in one of peel set or not_peel set
3480   for (i = 0; i < loop->_body.size(); i++ ) {
3481     Node *def  = loop->_body.at(i);
3482     uint di = def->_idx;
3483     // Check that peel set elements are in peel_list
3484     if (peel.test(di)) {
3485       if (not_peel.test(di)) {
3486         return false;
3487       }
3488       // Must be in peel_list also
3489       bool found = false;
3490       for (uint j = 0; j < peel_list.size(); j++) {
3491         if (peel_list.at(j)->_idx == di) {
3492           found = true;
3493           break;
3494         }
3495       }
3496       if (!found) {
3497         return false;
3498       }
3499     } else if (not_peel.test(di)) {
3500       if (peel.test(di)) {
3501         return false;
3502       }
3503     } else {
3504       return false;
3505     }
3506   }
3507   return true;
3508 }
3509 
3510 //------------------------------ is_valid_clone_loop_exit_use -------------------------------------
3511 // Ensure a use outside of loop is of the right form
3512 bool PhaseIdealLoop::is_valid_clone_loop_exit_use( IdealLoopTree *loop, Node* use, uint exit_idx) {
3513   Node *use_c = has_ctrl(use) ? get_ctrl(use) : use;
3514   return (use->is_Phi() &&
3515           use_c->is_Region() && use_c->req() == 3 &&
3516           (use_c->in(exit_idx)->Opcode() == Op_IfTrue ||
3517            use_c->in(exit_idx)->Opcode() == Op_IfFalse ||
3518            use_c->in(exit_idx)->Opcode() == Op_JumpProj) &&
3519           loop->is_member( get_loop( use_c->in(exit_idx)->in(0) ) ) );
3520 }
3521 
3522 //------------------------------ is_valid_clone_loop_form -------------------------------------
3523 // Ensure that all uses outside of loop are of the right form
3524 bool PhaseIdealLoop::is_valid_clone_loop_form( IdealLoopTree *loop, Node_List& peel_list,
3525                                                uint orig_exit_idx, uint clone_exit_idx) {
3526   uint len = peel_list.size();
3527   for (uint i = 0; i < len; i++) {
3528     Node *def = peel_list.at(i);
3529 
3530     for (DUIterator_Fast jmax, j = def->fast_outs(jmax); j < jmax; j++) {
3531       Node *use = def->fast_out(j);
3532       Node *use_c = has_ctrl(use) ? get_ctrl(use) : use;
3533       if (!loop->is_member(get_loop(use_c))) {
3534         // use is not in the loop, check for correct structure
3535         if (use->in(0) == def) {
3536           // Okay
3537         } else if (!is_valid_clone_loop_exit_use(loop, use, orig_exit_idx)) {
3538           return false;
3539         }
3540       }
3541     }
3542   }
3543   return true;
3544 }
3545 #endif
3546 
3547 //------------------------------ partial_peel -------------------------------------
3548 // Partially peel (aka loop rotation) the top portion of a loop (called
3549 // the peel section below) by cloning it and placing one copy just before
3550 // the new loop head and the other copy at the bottom of the new loop.
3551 //
3552 //    before                       after                where it came from
3553 //
3554 //    stmt1                        stmt1
3555 //  loop:                          stmt2                     clone
3556 //    stmt2                        if condA goto exitA       clone
3557 //    if condA goto exitA        new_loop:                   new
3558 //    stmt3                        stmt3                     clone
3559 //    if !condB goto loop          if condB goto exitB       clone
3560 //  exitB:                         stmt2                     orig
3561 //    stmt4                        if !condA goto new_loop   orig
3562 //  exitA:                         goto exitA
3563 //                               exitB:
3564 //                                 stmt4
3565 //                               exitA:
3566 //
3567 // Step 1: find the cut point: an exit test on probable
3568 //         induction variable.
3569 // Step 2: schedule (with cloning) operations in the peel
3570 //         section that can be executed after the cut into
3571 //         the section that is not peeled.  This may need
3572 //         to clone operations into exit blocks.  For
3573 //         instance, a reference to A[i] in the not-peel
3574 //         section and a reference to B[i] in an exit block
3575 //         may cause a left-shift of i by 2 to be placed
3576 //         in the peel block.  This step will clone the left
3577 //         shift into the exit block and sink the left shift
3578 //         from the peel to the not-peel section.
3579 // Step 3: clone the loop, retarget the control, and insert
3580 //         phis for values that are live across the new loop
3581 //         head.  This is very dependent on the graph structure
3582 //         from clone_loop.  It creates region nodes for
3583 //         exit control and associated phi nodes for values
3584 //         flow out of the loop through that exit.  The region
3585 //         node is dominated by the clone's control projection.
3586 //         So the clone's peel section is placed before the
3587 //         new loop head, and the clone's not-peel section is
3588 //         forms the top part of the new loop.  The original
3589 //         peel section forms the tail of the new loop.
3590 // Step 4: update the dominator tree and recompute the
3591 //         dominator depth.
3592 //
3593 //                   orig
3594 //
3595 //                   stmt1
3596 //                     |
3597 //                     v
3598 //                 predicates
3599 //                     |
3600 //                     v
3601 //                   loop<----+
3602 //                     |      |
3603 //                   stmt2    |
3604 //                     |      |
3605 //                     v      |
3606 //                    ifA     |
3607 //                   / |      |
3608 //                  v  v      |
3609 //               false true   ^  <-- last_peel
3610 //               /     |      |
3611 //              /   ===|==cut |
3612 //             /     stmt3    |  <-- first_not_peel
3613 //            /        |      |
3614 //            |        v      |
3615 //            v       ifB     |
3616 //          exitA:   / \      |
3617 //                  /   \     |
3618 //                 v     v    |
3619 //               false true   |
3620 //               /       \    |
3621 //              /         ----+
3622 //             |
3623 //             v
3624 //           exitB:
3625 //           stmt4
3626 //
3627 //
3628 //            after clone loop
3629 //
3630 //                   stmt1
3631 //                     |
3632 //                     v
3633 //                predicates
3634 //                 /       \
3635 //        clone   /         \   orig
3636 //               /           \
3637 //              /             \
3638 //             v               v
3639 //   +---->loop                loop<----+
3640 //   |      |                    |      |
3641 //   |    stmt2                stmt2    |
3642 //   |      |                    |      |
3643 //   |      v                    v      |
3644 //   |      ifA                 ifA     |
3645 //   |      | \                / |      |
3646 //   |      v  v              v  v      |
3647 //   ^    true  false      false true   ^  <-- last_peel
3648 //   |      |   ^   \       /    |      |
3649 //   | cut==|==  \   \     /  ===|==cut |
3650 //   |    stmt3   \   \   /    stmt3    |  <-- first_not_peel
3651 //   |      |    dom   | |       |      |
3652 //   |      v      \  1v v2      v      |
3653 //   |      ifB     regionA     ifB     |
3654 //   |      / \        |       / \      |
3655 //   |     /   \       v      /   \     |
3656 //   |    v     v    exitA:  v     v    |
3657 //   |    true  false      false true   |
3658 //   |    /     ^   \      /       \    |
3659 //   +----       \   \    /         ----+
3660 //               dom  \  /
3661 //                 \  1v v2
3662 //                  regionB
3663 //                     |
3664 //                     v
3665 //                   exitB:
3666 //                   stmt4
3667 //
3668 //
3669 //           after partial peel
3670 //
3671 //                  stmt1
3672 //                     |
3673 //                     v
3674 //                predicates
3675 //                 /
3676 //        clone   /             orig
3677 //               /          TOP
3678 //              /             \
3679 //             v               v
3680 //    TOP->loop                loop----+
3681 //          |                    |      |
3682 //        stmt2                stmt2    |
3683 //          |                    |      |
3684 //          v                    v      |
3685 //          ifA                 ifA     |
3686 //          | \                / |      |
3687 //          v  v              v  v      |
3688 //        true  false      false true   |     <-- last_peel
3689 //          |   ^   \       /    +------|---+
3690 //  +->newloop   \   \     /  === ==cut |   |
3691 //  |     stmt3   \   \   /     TOP     |   |
3692 //  |       |    dom   | |      stmt3   |   | <-- first_not_peel
3693 //  |       v      \  1v v2      v      |   |
3694 //  |       ifB     regionA     ifB     ^   v
3695 //  |       / \        |       / \      |   |
3696 //  |      /   \       v      /   \     |   |
3697 //  |     v     v    exitA:  v     v    |   |
3698 //  |     true  false      false true   |   |
3699 //  |     /     ^   \      /       \    |   |
3700 //  |    |       \   \    /         v   |   |
3701 //  |    |       dom  \  /         TOP  |   |
3702 //  |    |         \  1v v2             |   |
3703 //  ^    v          regionB             |   |
3704 //  |    |             |                |   |
3705 //  |    |             v                ^   v
3706 //  |    |           exitB:             |   |
3707 //  |    |           stmt4              |   |
3708 //  |    +------------>-----------------+   |
3709 //  |                                       |
3710 //  +-----------------<---------------------+
3711 //
3712 //
3713 //              final graph
3714 //
3715 //                  stmt1
3716 //                    |
3717 //                    v
3718 //                predicates
3719 //                    |
3720 //                    v
3721 //                  stmt2 clone
3722 //                    |
3723 //                    v
3724 //         ........> ifA clone
3725 //         :        / |
3726 //        dom      /  |
3727 //         :      v   v
3728 //         :  false   true
3729 //         :  |       |
3730 //         :  |       v
3731 //         :  |    newloop<-----+
3732 //         :  |        |        |
3733 //         :  |     stmt3 clone |
3734 //         :  |        |        |
3735 //         :  |        v        |
3736 //         :  |       ifB       |
3737 //         :  |      / \        |
3738 //         :  |     v   v       |
3739 //         :  |  false true     |
3740 //         :  |   |     |       |
3741 //         :  |   v    stmt2    |
3742 //         :  | exitB:  |       |
3743 //         :  | stmt4   v       |
3744 //         :  |       ifA orig  |
3745 //         :  |      /  \       |
3746 //         :  |     /    \      |
3747 //         :  |    v     v      |
3748 //         :  |  false  true    |
3749 //         :  |  /        \     |
3750 //         :  v  v         -----+
3751 //          RegionA
3752 //             |
3753 //             v
3754 //           exitA
3755 //
3756 bool PhaseIdealLoop::partial_peel( IdealLoopTree *loop, Node_List &old_new ) {
3757 
3758   assert(!loop->_head->is_CountedLoop(), "Non-counted loop only");
3759   if (!loop->_head->is_Loop()) {
3760     return false;
3761   }
3762   LoopNode *head = loop->_head->as_Loop();
3763 
3764   if (head->is_partial_peel_loop() || head->partial_peel_has_failed()) {
3765     return false;
3766   }
3767 
3768   // Check for complex exit control
3769   for (uint ii = 0; ii < loop->_body.size(); ii++) {
3770     Node *n = loop->_body.at(ii);
3771     int opc = n->Opcode();
3772     if (n->is_Call()        ||
3773         opc == Op_Catch     ||
3774         opc == Op_CatchProj ||
3775         opc == Op_Jump      ||
3776         opc == Op_JumpProj) {
3777 #ifndef PRODUCT
3778       if (TracePartialPeeling) {
3779         tty->print_cr("\nExit control too complex: lp: %d", head->_idx);
3780       }
3781 #endif
3782       return false;
3783     }
3784   }
3785 
3786   int dd = dom_depth(head);
3787 
3788   // Step 1: find cut point
3789 
3790   // Walk up dominators to loop head looking for first loop exit
3791   // which is executed on every path thru loop.
3792   IfNode *peel_if = nullptr;
3793   IfNode *peel_if_cmpu = nullptr;
3794 
3795   Node *iff = loop->tail();
3796   while (iff != head) {
3797     if (iff->is_If()) {
3798       Node *ctrl = get_ctrl(iff->in(1));
3799       if (ctrl->is_top()) return false; // Dead test on live IF.
3800       // If loop-varying exit-test, check for induction variable
3801       if (loop->is_member(get_loop(ctrl)) &&
3802           loop->is_loop_exit(iff) &&
3803           is_possible_iv_test(iff)) {
3804         Node* cmp = iff->in(1)->in(1);
3805         if (cmp->Opcode() == Op_CmpI) {
3806           peel_if = iff->as_If();
3807         } else {
3808           assert(cmp->Opcode() == Op_CmpU, "must be CmpI or CmpU");
3809           peel_if_cmpu = iff->as_If();
3810         }
3811       }
3812     }
3813     iff = idom(iff);
3814   }
3815 
3816   // Prefer signed compare over unsigned compare.
3817   IfNode* new_peel_if = nullptr;
3818   if (peel_if == nullptr) {
3819     if (!PartialPeelAtUnsignedTests || peel_if_cmpu == nullptr) {
3820       return false;   // No peel point found
3821     }
3822     new_peel_if = insert_cmpi_loop_exit(peel_if_cmpu, loop);
3823     if (new_peel_if == nullptr) {
3824       return false;   // No peel point found
3825     }
3826     peel_if = new_peel_if;
3827   }
3828   Node* last_peel        = stay_in_loop(peel_if, loop);
3829   Node* first_not_peeled = stay_in_loop(last_peel, loop);
3830   if (first_not_peeled == nullptr || first_not_peeled == head) {
3831     return false;
3832   }
3833 
3834 #ifndef PRODUCT
3835   if (TraceLoopOpts) {
3836     tty->print("PartialPeel  ");
3837     loop->dump_head();
3838   }
3839 
3840   if (TracePartialPeeling) {
3841     tty->print_cr("before partial peel one iteration");
3842     Node_List wl;
3843     Node* t = head->in(2);
3844     while (true) {
3845       wl.push(t);
3846       if (t == head) break;
3847       t = idom(t);
3848     }
3849     while (wl.size() > 0) {
3850       Node* tt = wl.pop();
3851       tt->dump();
3852       if (tt == last_peel) tty->print_cr("-- cut --");
3853     }
3854   }
3855 #endif
3856 
3857   C->print_method(PHASE_BEFORE_PARTIAL_PEELING, 4, head);
3858 
3859   VectorSet peel;
3860   VectorSet not_peel;
3861   Node_List peel_list;
3862   Node_List worklist;
3863   Node_List sink_list;
3864 
3865   uint estimate = loop->est_loop_clone_sz(1);
3866   if (exceeding_node_budget(estimate)) {
3867     return false;
3868   }
3869 
3870   // Set of cfg nodes to peel are those that are executable from
3871   // the head through last_peel.
3872   assert(worklist.size() == 0, "should be empty");
3873   worklist.push(head);
3874   peel.set(head->_idx);
3875   while (worklist.size() > 0) {
3876     Node *n = worklist.pop();
3877     if (n != last_peel) {
3878       for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++) {
3879         Node* use = n->fast_out(j);
3880         if (use->is_CFG() &&
3881             loop->is_member(get_loop(use)) &&
3882             !peel.test_set(use->_idx)) {
3883           worklist.push(use);
3884         }
3885       }
3886     }
3887   }
3888 
3889   // Set of non-cfg nodes to peel are those that are control
3890   // dependent on the cfg nodes.
3891   for (uint i = 0; i < loop->_body.size(); i++) {
3892     Node *n = loop->_body.at(i);
3893     Node *n_c = has_ctrl(n) ? get_ctrl(n) : n;
3894     if (peel.test(n_c->_idx)) {
3895       peel.set(n->_idx);
3896     } else {
3897       not_peel.set(n->_idx);
3898     }
3899   }
3900 
3901   // Step 2: move operations from the peeled section down into the
3902   //         not-peeled section
3903 
3904   // Get a post order schedule of nodes in the peel region
3905   // Result in right-most operand.
3906   scheduled_nodelist(loop, peel, peel_list);
3907 
3908   assert(is_valid_loop_partition(loop, peel, peel_list, not_peel), "bad partition");
3909 
3910   // For future check for too many new phis
3911   uint old_phi_cnt = 0;
3912   for (DUIterator_Fast jmax, j = head->fast_outs(jmax); j < jmax; j++) {
3913     Node* use = head->fast_out(j);
3914     if (use->is_Phi()) old_phi_cnt++;
3915   }
3916 
3917 #ifndef PRODUCT
3918   if (TracePartialPeeling) {
3919     tty->print_cr("\npeeled list");
3920   }
3921 #endif
3922 
3923   // Evacuate nodes in peel region into the not_peeled region if possible
3924   bool too_many_clones = false;
3925   uint new_phi_cnt = 0;
3926   uint cloned_for_outside_use = 0;
3927   for (uint i = 0; i < peel_list.size();) {
3928     Node* n = peel_list.at(i);
3929 #ifndef PRODUCT
3930   if (TracePartialPeeling) n->dump();
3931 #endif
3932     bool incr = true;
3933     if (!n->is_CFG()) {
3934       if (has_use_in_set(n, not_peel)) {
3935         // If not used internal to the peeled region,
3936         // move "n" from peeled to not_peeled region.
3937         if (!has_use_internal_to_set(n, peel, loop)) {
3938           // if not pinned and not a load (which maybe anti-dependent on a store)
3939           // and not a CMove (Matcher expects only bool->cmove).
3940           if (n->in(0) == nullptr && !n->is_Load() && !n->is_CMove()) {
3941             int new_clones = clone_for_use_outside_loop(loop, n, worklist);
3942             if (C->failing()) return false;
3943             if (new_clones == -1) {
3944               too_many_clones = true;
3945               break;
3946             }
3947             cloned_for_outside_use += new_clones;
3948             sink_list.push(n);
3949             peel.remove(n->_idx);
3950             not_peel.set(n->_idx);
3951             peel_list.remove(i);
3952             incr = false;
3953 #ifndef PRODUCT
3954             if (TracePartialPeeling) {
3955               tty->print_cr("sink to not_peeled region: %d newbb: %d",
3956                             n->_idx, get_ctrl(n)->_idx);
3957             }
3958 #endif
3959           }
3960         } else {
3961           // Otherwise check for special def-use cases that span
3962           // the peel/not_peel boundary such as bool->if
3963           clone_for_special_use_inside_loop(loop, n, not_peel, sink_list, worklist);
3964           new_phi_cnt++;
3965         }
3966       }
3967     }
3968     if (incr) i++;
3969   }
3970 
3971   estimate += cloned_for_outside_use + new_phi_cnt;
3972   bool exceed_node_budget = !may_require_nodes(estimate);
3973   bool exceed_phi_limit = new_phi_cnt > old_phi_cnt + PartialPeelNewPhiDelta;
3974 
3975   if (too_many_clones || exceed_node_budget || exceed_phi_limit) {
3976 #ifndef PRODUCT
3977     if (TracePartialPeeling && exceed_phi_limit) {
3978       tty->print_cr("\nToo many new phis: %d  old %d new cmpi: %c",
3979                     new_phi_cnt, old_phi_cnt, new_peel_if != nullptr?'T':'F');
3980     }
3981 #endif
3982     if (new_peel_if != nullptr) {
3983       remove_cmpi_loop_exit(new_peel_if, loop);
3984     }
3985     // Inhibit more partial peeling on this loop
3986     assert(!head->is_partial_peel_loop(), "not partial peeled");
3987     head->mark_partial_peel_failed();
3988     if (cloned_for_outside_use > 0) {
3989       // Terminate this round of loop opts because
3990       // the graph outside this loop was changed.
3991       C->set_major_progress();
3992       return true;
3993     }
3994     return false;
3995   }
3996 
3997   // Step 3: clone loop, retarget control, and insert new phis
3998 
3999   // Create new loop head for new phis and to hang
4000   // the nodes being moved (sinked) from the peel region.
4001   LoopNode* new_head = new LoopNode(last_peel, last_peel);
4002   new_head->set_unswitch_count(head->unswitch_count()); // Preserve
4003   _igvn.register_new_node_with_optimizer(new_head);
4004   assert(first_not_peeled->in(0) == last_peel, "last_peel <- first_not_peeled");
4005   _igvn.replace_input_of(first_not_peeled, 0, new_head);
4006   set_loop(new_head, loop);
4007   loop->_body.push(new_head);
4008   not_peel.set(new_head->_idx);
4009   set_idom(new_head, last_peel, dom_depth(first_not_peeled));
4010   set_idom(first_not_peeled, new_head, dom_depth(first_not_peeled));
4011 
4012   while (sink_list.size() > 0) {
4013     Node* n = sink_list.pop();
4014     set_ctrl(n, new_head);
4015   }
4016 
4017   assert(is_valid_loop_partition(loop, peel, peel_list, not_peel), "bad partition");
4018 
4019   clone_loop(loop, old_new, dd, IgnoreStripMined);
4020 
4021   const uint clone_exit_idx = 1;
4022   const uint orig_exit_idx  = 2;
4023   assert(is_valid_clone_loop_form(loop, peel_list, orig_exit_idx, clone_exit_idx), "bad clone loop");
4024 
4025   Node* head_clone             = old_new[head->_idx];
4026   LoopNode* new_head_clone     = old_new[new_head->_idx]->as_Loop();
4027   Node* orig_tail_clone        = head_clone->in(2);
4028 
4029   // Add phi if "def" node is in peel set and "use" is not
4030 
4031   for (uint i = 0; i < peel_list.size(); i++) {
4032     Node *def  = peel_list.at(i);
4033     if (!def->is_CFG()) {
4034       for (DUIterator_Fast jmax, j = def->fast_outs(jmax); j < jmax; j++) {
4035         Node *use = def->fast_out(j);
4036         if (has_node(use) && use->in(0) != C->top() &&
4037             (!peel.test(use->_idx) ||
4038              (use->is_Phi() && use->in(0) == head)) ) {
4039           worklist.push(use);
4040         }
4041       }
4042       while( worklist.size() ) {
4043         Node *use = worklist.pop();
4044         for (uint j = 1; j < use->req(); j++) {
4045           Node* n = use->in(j);
4046           if (n == def) {
4047 
4048             // "def" is in peel set, "use" is not in peel set
4049             // or "use" is in the entry boundary (a phi) of the peel set
4050 
4051             Node* use_c = has_ctrl(use) ? get_ctrl(use) : use;
4052 
4053             if ( loop->is_member(get_loop( use_c )) ) {
4054               // use is in loop
4055               if (old_new[use->_idx] != nullptr) { // null for dead code
4056                 Node* use_clone = old_new[use->_idx];
4057                 _igvn.replace_input_of(use, j, C->top());
4058                 insert_phi_for_loop( use_clone, j, old_new[def->_idx], def, new_head_clone );
4059               }
4060             } else {
4061               assert(is_valid_clone_loop_exit_use(loop, use, orig_exit_idx), "clone loop format");
4062               // use is not in the loop, check if the live range includes the cut
4063               Node* lp_if = use_c->in(orig_exit_idx)->in(0);
4064               if (not_peel.test(lp_if->_idx)) {
4065                 assert(j == orig_exit_idx, "use from original loop");
4066                 insert_phi_for_loop( use, clone_exit_idx, old_new[def->_idx], def, new_head_clone );
4067               }
4068             }
4069           }
4070         }
4071       }
4072     }
4073   }
4074 
4075   // Step 3b: retarget control
4076 
4077   // Redirect control to the new loop head if a cloned node in
4078   // the not_peeled region has control that points into the peeled region.
4079   // This necessary because the cloned peeled region will be outside
4080   // the loop.
4081   //                            from    to
4082   //          cloned-peeled    <---+
4083   //    new_head_clone:            |    <--+
4084   //          cloned-not_peeled  in(0)    in(0)
4085   //          orig-peeled
4086 
4087   for (uint i = 0; i < loop->_body.size(); i++) {
4088     Node *n = loop->_body.at(i);
4089     if (!n->is_CFG()           && n->in(0) != nullptr        &&
4090         not_peel.test(n->_idx) && peel.test(n->in(0)->_idx)) {
4091       Node* n_clone = old_new[n->_idx];
4092       if (n_clone->depends_only_on_test()) {
4093         // Pin array access nodes: control is updated here to the loop head. If, after some transformations, the
4094         // backedge is removed, an array load could become dependent on a condition that's not a range check for that
4095         // access. If that condition is replaced by an identical dominating one, then an unpinned load would risk
4096         // floating above its range check.
4097         Node* pinned_clone = n_clone->pin_array_access_node();
4098         if (pinned_clone != nullptr) {
4099           register_new_node_with_ctrl_of(pinned_clone, n_clone);
4100           old_new.map(n->_idx, pinned_clone);
4101           _igvn.replace_node(n_clone, pinned_clone);
4102           n_clone = pinned_clone;
4103         }
4104       }
4105       _igvn.replace_input_of(n_clone, 0, new_head_clone);
4106     }
4107   }
4108 
4109   // Backedge of the surviving new_head (the clone) is original last_peel
4110   _igvn.replace_input_of(new_head_clone, LoopNode::LoopBackControl, last_peel);
4111 
4112   // Cut first node in original not_peel set
4113   _igvn.rehash_node_delayed(new_head);                     // Multiple edge updates:
4114   new_head->set_req(LoopNode::EntryControl,    C->top());  //   use rehash_node_delayed / set_req instead of
4115   new_head->set_req(LoopNode::LoopBackControl, C->top());  //   multiple replace_input_of calls
4116 
4117   // Copy head_clone back-branch info to original head
4118   // and remove original head's loop entry and
4119   // clone head's back-branch
4120   _igvn.rehash_node_delayed(head); // Multiple edge updates
4121   head->set_req(LoopNode::EntryControl,    head_clone->in(LoopNode::LoopBackControl));
4122   head->set_req(LoopNode::LoopBackControl, C->top());
4123   _igvn.replace_input_of(head_clone, LoopNode::LoopBackControl, C->top());
4124 
4125   // Similarly modify the phis
4126   for (DUIterator_Fast kmax, k = head->fast_outs(kmax); k < kmax; k++) {
4127     Node* use = head->fast_out(k);
4128     if (use->is_Phi() && use->outcnt() > 0) {
4129       Node* use_clone = old_new[use->_idx];
4130       _igvn.rehash_node_delayed(use); // Multiple edge updates
4131       use->set_req(LoopNode::EntryControl,    use_clone->in(LoopNode::LoopBackControl));
4132       use->set_req(LoopNode::LoopBackControl, C->top());
4133       _igvn.replace_input_of(use_clone, LoopNode::LoopBackControl, C->top());
4134     }
4135   }
4136 
4137   // Step 4: update dominator tree and dominator depth
4138 
4139   set_idom(head, orig_tail_clone, dd);
4140   recompute_dom_depth();
4141 
4142   // Inhibit more partial peeling on this loop
4143   new_head_clone->set_partial_peel_loop();
4144   C->set_major_progress();
4145   loop->record_for_igvn();
4146 
4147 #ifndef PRODUCT
4148   if (TracePartialPeeling) {
4149     tty->print_cr("\nafter partial peel one iteration");
4150     Node_List wl;
4151     Node* t = last_peel;
4152     while (true) {
4153       wl.push(t);
4154       if (t == head_clone) break;
4155       t = idom(t);
4156     }
4157     while (wl.size() > 0) {
4158       Node* tt = wl.pop();
4159       if (tt == head) tty->print_cr("orig head");
4160       else if (tt == new_head_clone) tty->print_cr("new head");
4161       else if (tt == head_clone) tty->print_cr("clone head");
4162       tt->dump();
4163     }
4164   }
4165 #endif
4166 
4167   C->print_method(PHASE_AFTER_PARTIAL_PEELING, 4, new_head_clone);
4168 
4169   return true;
4170 }
4171 
4172 // Transform:
4173 //
4174 // loop<-----------------+
4175 //  |                    |
4176 // stmt1 stmt2 .. stmtn  |
4177 //  |     |        |     |
4178 //  \     |       /      |
4179 //    v   v     v        |
4180 //       region          |
4181 //         |             |
4182 //     shared_stmt       |
4183 //         |             |
4184 //         v             |
4185 //         if            |
4186 //         / \           |
4187 //        |   -----------+
4188 //        v
4189 //
4190 // into:
4191 //
4192 //    loop<-------------------+
4193 //     |                      |
4194 //     v                      |
4195 // +->loop                    |
4196 // |   |                      |
4197 // |  stmt1 stmt2 .. stmtn    |
4198 // |   |     |        |       |
4199 // |   |      \       /       |
4200 // |   |       v     v        |
4201 // |   |        region1       |
4202 // |   |           |          |
4203 // |  shared_stmt shared_stmt |
4204 // |   |           |          |
4205 // |   v           v          |
4206 // |   if          if         |
4207 // |   /\          / \        |
4208 // +--   |         |   -------+
4209 //       \         /
4210 //        v       v
4211 //         region2
4212 //
4213 // (region2 is shown to merge mirrored projections of the loop exit
4214 // ifs to make the diagram clearer but they really merge the same
4215 // projection)
4216 //
4217 // Conditions for this transformation to trigger:
4218 // - the path through stmt1 is frequent enough
4219 // - the inner loop will be turned into a counted loop after transformation
4220 bool PhaseIdealLoop::duplicate_loop_backedge(IdealLoopTree *loop, Node_List &old_new) {
4221   if (!DuplicateBackedge) {
4222     return false;
4223   }
4224   assert(!loop->_head->is_CountedLoop() || StressDuplicateBackedge, "Non-counted loop only");
4225   if (!loop->_head->is_Loop()) {
4226     return false;
4227   }
4228 
4229   uint estimate = loop->est_loop_clone_sz(1);
4230   if (exceeding_node_budget(estimate)) {
4231     return false;
4232   }
4233 
4234   LoopNode *head = loop->_head->as_Loop();
4235 
4236   Node* region = nullptr;
4237   IfNode* exit_test = nullptr;
4238   uint inner;
4239   float f;
4240   if (StressDuplicateBackedge) {
4241     if (head->is_strip_mined()) {
4242       return false;
4243     }
4244     Node* c = head->in(LoopNode::LoopBackControl);
4245 
4246     while (c != head) {
4247       if (c->is_Region()) {
4248         region = c;
4249       }
4250       c = idom(c);
4251     }
4252 
4253     if (region == nullptr) {
4254       return false;
4255     }
4256 
4257     inner = 1;
4258   } else {
4259     // Is the shape of the loop that of a counted loop...
4260     Node* back_control = loop_exit_control(head, loop);
4261     if (back_control == nullptr) {
4262       return false;
4263     }
4264 
4265     BoolTest::mask bt = BoolTest::illegal;
4266     float cl_prob = 0;
4267     Node* incr = nullptr;
4268     Node* limit = nullptr;
4269     Node* cmp = loop_exit_test(back_control, loop, incr, limit, bt, cl_prob);
4270     if (cmp == nullptr || cmp->Opcode() != Op_CmpI) {
4271       return false;
4272     }
4273 
4274     // With an extra phi for the candidate iv?
4275     // Or the region node is the loop head
4276     if (!incr->is_Phi() || incr->in(0) == head) {
4277       return false;
4278     }
4279 
4280     PathFrequency pf(head, this);
4281     region = incr->in(0);
4282 
4283     // Go over all paths for the extra phi's region and see if that
4284     // path is frequent enough and would match the expected iv shape
4285     // if the extra phi is removed
4286     inner = 0;
4287     for (uint i = 1; i < incr->req(); ++i) {
4288       Node* in = incr->in(i);
4289       Node* trunc1 = nullptr;
4290       Node* trunc2 = nullptr;
4291       const TypeInteger* iv_trunc_t = nullptr;
4292       Node* orig_in = in;
4293       if (!(in = CountedLoopNode::match_incr_with_optional_truncation(in, &trunc1, &trunc2, &iv_trunc_t, T_INT))) {
4294         continue;
4295       }
4296       assert(in->Opcode() == Op_AddI, "wrong increment code");
4297       Node* xphi = nullptr;
4298       Node* stride = loop_iv_stride(in, xphi);
4299 
4300       if (stride == nullptr) {
4301         continue;
4302       }
4303 
4304       PhiNode* phi = loop_iv_phi(xphi, nullptr, head);
4305       if (phi == nullptr ||
4306           (trunc1 == nullptr && phi->in(LoopNode::LoopBackControl) != incr) ||
4307           (trunc1 != nullptr && phi->in(LoopNode::LoopBackControl) != trunc1)) {
4308         return false;
4309       }
4310 
4311       f = pf.to(region->in(i));
4312       if (f > 0.5) {
4313         inner = i;
4314         break;
4315       }
4316     }
4317 
4318     if (inner == 0) {
4319       return false;
4320     }
4321 
4322     exit_test = back_control->in(0)->as_If();
4323   }
4324 
4325   if (idom(region)->is_Catch()) {
4326     return false;
4327   }
4328 
4329   // Collect all control nodes that need to be cloned (shared_stmt in the diagram)
4330   Unique_Node_List wq;
4331   wq.push(head->in(LoopNode::LoopBackControl));
4332   for (uint i = 0; i < wq.size(); i++) {
4333     Node* c = wq.at(i);
4334     assert(get_loop(c) == loop, "not in the right loop?");
4335     if (c->is_Region()) {
4336       if (c != region) {
4337         for (uint j = 1; j < c->req(); ++j) {
4338           wq.push(c->in(j));
4339         }
4340       }
4341     } else {
4342       wq.push(c->in(0));
4343     }
4344     assert(!is_strict_dominator(c, region), "shouldn't go above region");
4345   }
4346 
4347   Node* region_dom = idom(region);
4348 
4349   // Can't do the transformation if this would cause a membar pair to
4350   // be split
4351   for (uint i = 0; i < wq.size(); i++) {
4352     Node* c = wq.at(i);
4353     if (c->is_MemBar() && (c->as_MemBar()->trailing_store() || c->as_MemBar()->trailing_load_store())) {
4354       assert(c->as_MemBar()->leading_membar()->trailing_membar() == c, "bad membar pair");
4355       if (!wq.member(c->as_MemBar()->leading_membar())) {
4356         return false;
4357       }
4358     }
4359   }
4360   C->print_method(PHASE_BEFORE_DUPLICATE_LOOP_BACKEDGE, 4, head);
4361 
4362   // Collect data nodes that need to be clones as well
4363   int dd = dom_depth(head);
4364 
4365   for (uint i = 0; i < loop->_body.size(); ++i) {
4366     Node* n = loop->_body.at(i);
4367     if (has_ctrl(n)) {
4368       Node* c = get_ctrl(n);
4369       if (wq.member(c)) {
4370         wq.push(n);
4371       }
4372     } else {
4373       set_idom(n, idom(n), dd);
4374     }
4375   }
4376 
4377   // clone shared_stmt
4378   clone_loop_body(wq, old_new, nullptr);
4379 
4380   Node* region_clone = old_new[region->_idx];
4381   region_clone->set_req(inner, C->top());
4382   set_idom(region, region->in(inner), dd);
4383 
4384   // Prepare the outer loop
4385   Node* outer_head = new LoopNode(head->in(LoopNode::EntryControl), old_new[head->in(LoopNode::LoopBackControl)->_idx]);
4386   register_control(outer_head, loop->_parent, outer_head->in(LoopNode::EntryControl));
4387   _igvn.replace_input_of(head, LoopNode::EntryControl, outer_head);
4388   set_idom(head, outer_head, dd);
4389 
4390   fix_body_edges(wq, loop, old_new, dd, loop->_parent, true);
4391 
4392   // Make one of the shared_stmt copies only reachable from stmt1, the
4393   // other only from stmt2..stmtn.
4394   Node* dom = nullptr;
4395   for (uint i = 1; i < region->req(); ++i) {
4396     if (i != inner) {
4397       _igvn.replace_input_of(region, i, C->top());
4398     }
4399     Node* in = region_clone->in(i);
4400     if (in->is_top()) {
4401       continue;
4402     }
4403     if (dom == nullptr) {
4404       dom = in;
4405     } else {
4406       dom = dom_lca(dom, in);
4407     }
4408   }
4409 
4410   set_idom(region_clone, dom, dd);
4411 
4412   // Set up the outer loop
4413   for (uint i = 0; i < head->outcnt(); i++) {
4414     Node* u = head->raw_out(i);
4415     if (u->is_Phi()) {
4416       Node* outer_phi = u->clone();
4417       outer_phi->set_req(0, outer_head);
4418       Node* backedge = old_new[u->in(LoopNode::LoopBackControl)->_idx];
4419       if (backedge == nullptr) {
4420         backedge = u->in(LoopNode::LoopBackControl);
4421       }
4422       outer_phi->set_req(LoopNode::LoopBackControl, backedge);
4423       register_new_node(outer_phi, outer_head);
4424       _igvn.replace_input_of(u, LoopNode::EntryControl, outer_phi);
4425     }
4426   }
4427 
4428   // create control and data nodes for out of loop uses (including region2)
4429   Node_List worklist;
4430   uint new_counter = C->unique();
4431   fix_ctrl_uses(wq, loop, old_new, ControlAroundStripMined, outer_head, nullptr, worklist);
4432 
4433   Node_List *split_if_set = nullptr;
4434   Node_List *split_bool_set = nullptr;
4435   Node_List *split_cex_set = nullptr;
4436   fix_data_uses(wq, loop, ControlAroundStripMined, loop->skip_strip_mined(), new_counter, old_new, worklist,
4437                 split_if_set, split_bool_set, split_cex_set);
4438 
4439   finish_clone_loop(split_if_set, split_bool_set, split_cex_set);
4440 
4441   if (exit_test != nullptr) {
4442     float cnt = exit_test->_fcnt;
4443     if (cnt != COUNT_UNKNOWN) {
4444       exit_test->_fcnt = cnt * f;
4445       old_new[exit_test->_idx]->as_If()->_fcnt = cnt * (1 - f);
4446     }
4447   }
4448 
4449   C->set_major_progress();
4450 
4451   C->print_method(PHASE_AFTER_DUPLICATE_LOOP_BACKEDGE, 4, outer_head);
4452 
4453   return true;
4454 }
4455 
4456 // AutoVectorize the loop: replace scalar ops with vector ops.
4457 PhaseIdealLoop::AutoVectorizeStatus
4458 PhaseIdealLoop::auto_vectorize(IdealLoopTree* lpt, VSharedData &vshared) {
4459   // Counted loop only
4460   if (!lpt->is_counted()) {
4461     return AutoVectorizeStatus::Impossible;
4462   }
4463 
4464   // Main-loop only
4465   CountedLoopNode* cl = lpt->_head->as_CountedLoop();
4466   if (!cl->is_main_loop()) {
4467     return AutoVectorizeStatus::Impossible;
4468   }
4469 
4470   VLoop vloop(lpt, false);
4471   if (!vloop.check_preconditions()) {
4472     return AutoVectorizeStatus::TriedAndFailed;
4473   }
4474 
4475   // Ensure the shared data is cleared before each use
4476   vshared.clear();
4477 
4478   const VLoopAnalyzer vloop_analyzer(vloop, vshared);
4479   if (!vloop_analyzer.success()) {
4480     return AutoVectorizeStatus::TriedAndFailed;
4481   }
4482 
4483   SuperWord sw(vloop_analyzer);
4484   if (!sw.transform_loop()) {
4485     return AutoVectorizeStatus::TriedAndFailed;
4486   }
4487 
4488   return AutoVectorizeStatus::Success;
4489 }
4490 
4491 // Just before insert_pre_post_loops, we can multiversion the loop:
4492 //
4493 //              multiversion_if
4494 //               |       |
4495 //         fast_loop   slow_loop
4496 //
4497 // In the fast_loop we can make speculative assumptions, and put the
4498 // conditions into the multiversion_if. If the conditions hold at runtime,
4499 // we enter the fast_loop, if the conditions fail, we take the slow_loop
4500 // instead which does not make any of the speculative assumptions.
4501 //
4502 // Note: we only multiversion the loop if the loop does not have any
4503 //       auto vectorization check Predicate. If we have that predicate,
4504 //       then we can simply add the speculative assumption checks to
4505 //       that Predicate. This means we do not need to duplicate the
4506 //       loop - we have a smaller graph and save compile time. Should
4507 //       the conditions ever fail, then we deopt / trap at the Predicate
4508 //       and recompile without that Predicate. At that point we will
4509 //       multiversion the loop, so that we can still have speculative
4510 //       runtime checks.
4511 //
4512 // We perform the multiversioning when the loop is still in its single
4513 // iteration form, even before we insert pre and post loops. This makes
4514 // the cloning much simpler. However, this means that both the fast
4515 // and the slow loop have to be optimized independently (adding pre
4516 // and post loops, unrolling the main loop, auto-vectorize etc.). And
4517 // we may end up not needing any speculative assumptions in the fast_loop
4518 // and then rejecting the slow_loop by constant folding the multiversion_if.
4519 //
4520 // Therefore, we "delay" the optimization of the slow_loop until we add
4521 // at least one speculative assumption for the fast_loop. If we never
4522 // add such a speculative runtime check, the OpaqueMultiversioningNode
4523 // of the multiversion_if constant folds to true after loop opts, and the
4524 // multiversion_if folds away the "delayed" slow_loop. If we add any
4525 // speculative assumption, then we notify the OpaqueMultiversioningNode
4526 // with "notify_slow_loop_that_it_can_resume_optimizations".
4527 //
4528 // Note: new runtime checks can be added to the multiversion_if with
4529 //       PhaseIdealLoop::create_new_if_for_multiversion
4530 void PhaseIdealLoop::maybe_multiversion_for_auto_vectorization_runtime_checks(IdealLoopTree* lpt, Node_List& old_new) {
4531   CountedLoopNode* cl = lpt->_head->as_CountedLoop();
4532   LoopNode* outer_loop = cl->skip_strip_mined();
4533   Node* entry = outer_loop->in(LoopNode::EntryControl);
4534 
4535   // Check we have multiversioning enabled, and are not already multiversioned.
4536   if (!LoopMultiversioning || cl->is_multiversion()) { return; }
4537 
4538   // Check that we do not have a parse-predicate where we can add the runtime checks
4539   // during auto-vectorization.
4540   const Predicates predicates(entry);
4541   const PredicateBlock* predicate_block = predicates.auto_vectorization_check_block();
4542   if (predicate_block->has_parse_predicate()) { return; }
4543 
4544   // Check node budget.
4545   uint estimate = lpt->est_loop_clone_sz(2);
4546   if (!may_require_nodes(estimate)) { return; }
4547 
4548   do_multiversioning(lpt, old_new);
4549 }
4550 
4551 // Returns true if the Reduction node is unordered.
4552 static bool is_unordered_reduction(Node* n) {
4553   return n->is_Reduction() && !n->as_Reduction()->requires_strict_order();
4554 }
4555 
4556 // Having ReductionNodes in the loop is expensive. They need to recursively
4557 // fold together the vector values, for every vectorized loop iteration. If
4558 // we encounter the following pattern, we can vector accumulate the values
4559 // inside the loop, and only have a single UnorderedReduction after the loop.
4560 //
4561 // Note: UnorderedReduction represents a ReductionNode which does not require
4562 // calculating in strict order.
4563 //
4564 // CountedLoop     init
4565 //          |        |
4566 //          +------+ | +-----------------------+
4567 //                 | | |                       |
4568 //                PhiNode (s)                  |
4569 //                  |                          |
4570 //                  |          Vector          |
4571 //                  |            |             |
4572 //               UnorderedReduction (first_ur) |
4573 //                  |                          |
4574 //                 ...         Vector          |
4575 //                  |            |             |
4576 //               UnorderedReduction (last_ur)  |
4577 //                       |                     |
4578 //                       +---------------------+
4579 //
4580 // We patch the graph to look like this:
4581 //
4582 // CountedLoop   identity_vector
4583 //         |         |
4584 //         +-------+ | +---------------+
4585 //                 | | |               |
4586 //                PhiNode (v)          |
4587 //                   |                 |
4588 //                   |         Vector  |
4589 //                   |           |     |
4590 //                 VectorAccumulator   |
4591 //                   |                 |
4592 //                  ...        Vector  |
4593 //                   |           |     |
4594 //      init       VectorAccumulator   |
4595 //        |          |     |           |
4596 //     UnorderedReduction  +-----------+
4597 //
4598 // We turned the scalar (s) Phi into a vectorized one (v). In the loop, we
4599 // use vector_accumulators, which do the same reductions, but only element
4600 // wise. This is a single operation per vector_accumulator, rather than many
4601 // for a UnorderedReduction. We can then reduce the last vector_accumulator
4602 // after the loop, and also reduce the init value into it.
4603 //
4604 // We can not do this with all reductions. Some reductions do not allow the
4605 // reordering of operations (for example float addition/multiplication require
4606 // strict order).
4607 void PhaseIdealLoop::move_unordered_reduction_out_of_loop(IdealLoopTree* loop) {
4608   assert(!C->major_progress() && loop->is_counted() && loop->is_innermost(), "sanity");
4609 
4610   // Find all Phi nodes with an unordered Reduction on backedge.
4611   CountedLoopNode* cl = loop->_head->as_CountedLoop();
4612   for (DUIterator_Fast jmax, j = cl->fast_outs(jmax); j < jmax; j++) {
4613     Node* phi = cl->fast_out(j);
4614     // We have a phi with a single use, and an unordered Reduction on the backedge.
4615     if (!phi->is_Phi() || phi->outcnt() != 1 || !is_unordered_reduction(phi->in(2))) {
4616       continue;
4617     }
4618 
4619     ReductionNode* last_ur = phi->in(2)->as_Reduction();
4620     assert(!last_ur->requires_strict_order(), "must be");
4621 
4622     // Determine types
4623     const TypeVect* vec_t = last_ur->vect_type();
4624     uint vector_length    = vec_t->length();
4625     BasicType bt          = vec_t->element_basic_type();
4626 
4627     // Convert opcode from vector-reduction -> scalar -> normal-vector-op
4628     const int sopc        = VectorNode::scalar_opcode(last_ur->Opcode(), bt);
4629     const int vopc        = VectorNode::opcode(sopc, bt);
4630     if (!Matcher::match_rule_supported_vector(vopc, vector_length, bt)) {
4631         DEBUG_ONLY( last_ur->dump(); )
4632         assert(false, "do not have normal vector op for this reduction");
4633         continue; // not implemented -> fails
4634     }
4635 
4636     // Traverse up the chain of unordered Reductions, checking that it loops back to
4637     // the phi. Check that all unordered Reductions only have a single use, except for
4638     // the last (last_ur), which only has phi as a use in the loop, and all other uses
4639     // are outside the loop.
4640     ReductionNode* current = last_ur;
4641     ReductionNode* first_ur = nullptr;
4642     while (true) {
4643       assert(!current->requires_strict_order(), "sanity");
4644 
4645       // Expect no ctrl and a vector_input from within the loop.
4646       Node* ctrl = current->in(0);
4647       Node* vector_input = current->in(2);
4648       if (ctrl != nullptr || get_ctrl(vector_input) != cl) {
4649         DEBUG_ONLY( current->dump(1); )
4650         assert(false, "reduction has ctrl or bad vector_input");
4651         break; // Chain traversal fails.
4652       }
4653 
4654       assert(current->vect_type() != nullptr, "must have vector type");
4655       if (current->vect_type() != last_ur->vect_type()) {
4656         // Reductions do not have the same vector type (length and element type).
4657         break; // Chain traversal fails.
4658       }
4659 
4660       // Expect single use of an unordered Reduction, except for last_ur.
4661       if (current == last_ur) {
4662         // Expect all uses to be outside the loop, except phi.
4663         for (DUIterator_Fast kmax, k = current->fast_outs(kmax); k < kmax; k++) {
4664           Node* use = current->fast_out(k);
4665           if (use != phi && ctrl_or_self(use) == cl) {
4666             DEBUG_ONLY( current->dump(-1); )
4667             assert(false, "reduction has use inside loop");
4668             // Should not be allowed by SuperWord::mark_reductions
4669             return; // bail out of optimization
4670           }
4671         }
4672       } else {
4673         if (current->outcnt() != 1) {
4674           break; // Chain traversal fails.
4675         }
4676       }
4677 
4678       // Expect another unordered Reduction or phi as the scalar input.
4679       Node* scalar_input = current->in(1);
4680       if (is_unordered_reduction(scalar_input) &&
4681           scalar_input->Opcode() == current->Opcode()) {
4682         // Move up the unordered Reduction chain.
4683         current = scalar_input->as_Reduction();
4684         assert(!current->requires_strict_order(), "must be");
4685       } else if (scalar_input == phi) {
4686         // Chain terminates at phi.
4687         first_ur = current;
4688         current = nullptr;
4689         break; // Success.
4690       } else {
4691         // scalar_input is neither phi nor a matching reduction
4692         // Can for example be scalar reduction when we have
4693         // partial vectorization.
4694         break; // Chain traversal fails.
4695       }
4696     }
4697     if (current != nullptr) {
4698       // Chain traversal was not successful.
4699       continue;
4700     }
4701     assert(first_ur != nullptr, "must have successfully terminated chain traversal");
4702 
4703     Node* identity_scalar = ReductionNode::make_identity_con_scalar(_igvn, sopc, bt);
4704     set_root_as_ctrl(identity_scalar);
4705     VectorNode* identity_vector = VectorNode::scalar2vector(identity_scalar, vector_length, bt);
4706     register_new_node(identity_vector, C->root());
4707     assert(vec_t == identity_vector->vect_type(), "matching vector type");
4708     VectorNode::trace_new_vector(identity_vector, "Unordered Reduction");
4709 
4710     // Turn the scalar phi into a vector phi.
4711     _igvn.rehash_node_delayed(phi);
4712     Node* init = phi->in(1); // Remember init before replacing it.
4713     phi->set_req_X(1, identity_vector, &_igvn);
4714     phi->as_Type()->set_type(vec_t);
4715     _igvn.set_type(phi, vec_t);
4716 
4717     // Traverse down the chain of unordered Reductions, and replace them with vector_accumulators.
4718     current = first_ur;
4719     while (true) {
4720       // Create vector_accumulator to replace current.
4721       Node* last_vector_accumulator = current->in(1);
4722       Node* vector_input            = current->in(2);
4723       VectorNode* vector_accumulator = VectorNode::make(vopc, last_vector_accumulator, vector_input, vec_t);
4724       register_new_node(vector_accumulator, cl);
4725       _igvn.replace_node(current, vector_accumulator);
4726       VectorNode::trace_new_vector(vector_accumulator, "Unordered Reduction");
4727       if (current == last_ur) {
4728         break;
4729       }
4730       current = vector_accumulator->unique_out()->as_Reduction();
4731       assert(!current->requires_strict_order(), "must be");
4732     }
4733 
4734     // Create post-loop reduction.
4735     Node* last_accumulator = phi->in(2);
4736     Node* post_loop_reduction = ReductionNode::make(sopc, nullptr, init, last_accumulator, bt);
4737 
4738     // Take over uses of last_accumulator that are not in the loop.
4739     for (DUIterator i = last_accumulator->outs(); last_accumulator->has_out(i); i++) {
4740       Node* use = last_accumulator->out(i);
4741       if (use != phi && use != post_loop_reduction) {
4742         assert(ctrl_or_self(use) != cl, "use must be outside loop");
4743         use->replace_edge(last_accumulator, post_loop_reduction,  &_igvn);
4744         --i;
4745       }
4746     }
4747     register_new_node(post_loop_reduction, get_late_ctrl(post_loop_reduction, cl));
4748     VectorNode::trace_new_vector(post_loop_reduction, "Unordered Reduction");
4749 
4750     assert(last_accumulator->outcnt() == 2, "last_accumulator has 2 uses: phi and post_loop_reduction");
4751     assert(post_loop_reduction->outcnt() > 0, "should have taken over all non loop uses of last_accumulator");
4752     assert(phi->outcnt() == 1, "accumulator is the only use of phi");
4753   }
4754 }
4755 
4756 void DataNodeGraph::clone_data_nodes(Node* new_ctrl) {
4757   for (uint i = 0; i < _data_nodes.size(); i++) {
4758     clone(_data_nodes[i], new_ctrl);
4759   }
4760 }
4761 
4762 // Clone the given node and set it up properly. Set 'new_ctrl' as ctrl.
4763 void DataNodeGraph::clone(Node* node, Node* new_ctrl) {
4764   Node* clone = node->clone();
4765   _phase->igvn().register_new_node_with_optimizer(clone);
4766   _orig_to_new.put(node, clone);
4767   _phase->set_ctrl(clone, new_ctrl);
4768   if (node->is_CastII()) {
4769     clone->set_req(0, new_ctrl);
4770   }
4771 }
4772 
4773 // Rewire the data inputs of all (unprocessed) cloned nodes, whose inputs are still pointing to the same inputs as their
4774 // corresponding orig nodes, to the newly cloned inputs to create a separate cloned graph.
4775 void DataNodeGraph::rewire_clones_to_cloned_inputs() {
4776   _orig_to_new.iterate_all([&](Node* node, Node* clone) {
4777     for (uint i = 1; i < node->req(); i++) {
4778       Node** cloned_input = _orig_to_new.get(node->in(i));
4779       if (cloned_input != nullptr) {
4780         // Input was also cloned -> rewire clone to the cloned input.
4781         _phase->igvn().replace_input_of(clone, i, *cloned_input);
4782       }
4783     }
4784   });
4785 }
4786 
4787 // Clone all non-OpaqueLoop* nodes and apply the provided transformation strategy for OpaqueLoop* nodes.
4788 // Set 'new_ctrl' as ctrl for all cloned non-OpaqueLoop* nodes.
4789 void DataNodeGraph::clone_data_nodes_and_transform_opaque_loop_nodes(
4790     const TransformStrategyForOpaqueLoopNodes& transform_strategy,
4791     Node* new_ctrl) {
4792   for (uint i = 0; i < _data_nodes.size(); i++) {
4793     Node* data_node = _data_nodes[i];
4794     if (data_node->is_Opaque1()) {
4795       transform_opaque_node(transform_strategy, data_node);
4796     } else {
4797       clone(data_node, new_ctrl);
4798     }
4799   }
4800 }
4801 
4802 void DataNodeGraph::transform_opaque_node(const TransformStrategyForOpaqueLoopNodes& transform_strategy, Node* node) {
4803   Node* transformed_node;
4804   if (node->is_OpaqueLoopInit()) {
4805     transformed_node = transform_strategy.transform_opaque_init(node->as_OpaqueLoopInit());
4806   } else {
4807     assert(node->is_OpaqueLoopStride(), "must be OpaqueLoopStrideNode");
4808     transformed_node = transform_strategy.transform_opaque_stride(node->as_OpaqueLoopStride());
4809   }
4810   // Add an orig->new mapping to correctly update the inputs of the copied graph in rewire_clones_to_cloned_inputs().
4811   _orig_to_new.put(node, transformed_node);
4812 }