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