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