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