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