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