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