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