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