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