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