1 /*
   2  * Copyright (c) 2000, 2010, 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 "compiler/compileLog.hpp"
  27 #include "memory/allocation.inline.hpp"
  28 #include "opto/addnode.hpp"
  29 #include "opto/callnode.hpp"
  30 #include "opto/connode.hpp"
  31 #include "opto/divnode.hpp"
  32 #include "opto/loopnode.hpp"
  33 #include "opto/mulnode.hpp"
  34 #include "opto/rootnode.hpp"
  35 #include "opto/runtime.hpp"
  36 #include "opto/subnode.hpp"
  37 
  38 //------------------------------is_loop_exit-----------------------------------
  39 // Given an IfNode, return the loop-exiting projection or NULL if both
  40 // arms remain in the loop.
  41 Node *IdealLoopTree::is_loop_exit(Node *iff) const {
  42   if( iff->outcnt() != 2 ) return NULL; // Ignore partially dead tests
  43   PhaseIdealLoop *phase = _phase;
  44   // Test is an IfNode, has 2 projections.  If BOTH are in the loop
  45   // we need loop unswitching instead of peeling.
  46   if( !is_member(phase->get_loop( iff->raw_out(0) )) )
  47     return iff->raw_out(0);
  48   if( !is_member(phase->get_loop( iff->raw_out(1) )) )
  49     return iff->raw_out(1);
  50   return NULL;
  51 }
  52 
  53 
  54 //=============================================================================
  55 
  56 
  57 //------------------------------record_for_igvn----------------------------
  58 // Put loop body on igvn work list
  59 void IdealLoopTree::record_for_igvn() {
  60   for( uint i = 0; i < _body.size(); i++ ) {
  61     Node *n = _body.at(i);
  62     _phase->_igvn._worklist.push(n);
  63   }
  64 }
  65 
  66 //------------------------------compute_profile_trip_cnt----------------------------
  67 // Compute loop trip count from profile data as
  68 //    (backedge_count + loop_exit_count) / loop_exit_count
  69 void IdealLoopTree::compute_profile_trip_cnt( PhaseIdealLoop *phase ) {
  70   if (!_head->is_CountedLoop()) {
  71     return;
  72   }
  73   CountedLoopNode* head = _head->as_CountedLoop();
  74   if (head->profile_trip_cnt() != COUNT_UNKNOWN) {
  75     return; // Already computed
  76   }
  77   float trip_cnt = (float)max_jint; // default is big
  78 
  79   Node* back = head->in(LoopNode::LoopBackControl);
  80   while (back != head) {
  81     if ((back->Opcode() == Op_IfTrue || back->Opcode() == Op_IfFalse) &&
  82         back->in(0) &&
  83         back->in(0)->is_If() &&
  84         back->in(0)->as_If()->_fcnt != COUNT_UNKNOWN &&
  85         back->in(0)->as_If()->_prob != PROB_UNKNOWN) {
  86       break;
  87     }
  88     back = phase->idom(back);
  89   }
  90   if (back != head) {
  91     assert((back->Opcode() == Op_IfTrue || back->Opcode() == Op_IfFalse) &&
  92            back->in(0), "if-projection exists");
  93     IfNode* back_if = back->in(0)->as_If();
  94     float loop_back_cnt = back_if->_fcnt * back_if->_prob;
  95 
  96     // Now compute a loop exit count
  97     float loop_exit_cnt = 0.0f;
  98     for( uint i = 0; i < _body.size(); i++ ) {
  99       Node *n = _body[i];
 100       if( n->is_If() ) {
 101         IfNode *iff = n->as_If();
 102         if( iff->_fcnt != COUNT_UNKNOWN && iff->_prob != PROB_UNKNOWN ) {
 103           Node *exit = is_loop_exit(iff);
 104           if( exit ) {
 105             float exit_prob = iff->_prob;
 106             if (exit->Opcode() == Op_IfFalse) exit_prob = 1.0 - exit_prob;
 107             if (exit_prob > PROB_MIN) {
 108               float exit_cnt = iff->_fcnt * exit_prob;
 109               loop_exit_cnt += exit_cnt;
 110             }
 111           }
 112         }
 113       }
 114     }
 115     if (loop_exit_cnt > 0.0f) {
 116       trip_cnt = (loop_back_cnt + loop_exit_cnt) / loop_exit_cnt;
 117     } else {
 118       // No exit count so use
 119       trip_cnt = loop_back_cnt;
 120     }
 121   }
 122 #ifndef PRODUCT
 123   if (TraceProfileTripCount) {
 124     tty->print_cr("compute_profile_trip_cnt  lp: %d cnt: %f\n", head->_idx, trip_cnt);
 125   }
 126 #endif
 127   head->set_profile_trip_cnt(trip_cnt);
 128 }
 129 
 130 //---------------------is_invariant_addition-----------------------------
 131 // Return nonzero index of invariant operand for an Add or Sub
 132 // of (nonconstant) invariant and variant values. Helper for reassociate_invariants.
 133 int IdealLoopTree::is_invariant_addition(Node* n, PhaseIdealLoop *phase) {
 134   int op = n->Opcode();
 135   if (op == Op_AddI || op == Op_SubI) {
 136     bool in1_invar = this->is_invariant(n->in(1));
 137     bool in2_invar = this->is_invariant(n->in(2));
 138     if (in1_invar && !in2_invar) return 1;
 139     if (!in1_invar && in2_invar) return 2;
 140   }
 141   return 0;
 142 }
 143 
 144 //---------------------reassociate_add_sub-----------------------------
 145 // Reassociate invariant add and subtract expressions:
 146 //
 147 // inv1 + (x + inv2)  =>  ( inv1 + inv2) + x
 148 // (x + inv2) + inv1  =>  ( inv1 + inv2) + x
 149 // inv1 + (x - inv2)  =>  ( inv1 - inv2) + x
 150 // inv1 - (inv2 - x)  =>  ( inv1 - inv2) + x
 151 // (x + inv2) - inv1  =>  (-inv1 + inv2) + x
 152 // (x - inv2) + inv1  =>  ( inv1 - inv2) + x
 153 // (x - inv2) - inv1  =>  (-inv1 - inv2) + x
 154 // inv1 + (inv2 - x)  =>  ( inv1 + inv2) - x
 155 // inv1 - (x - inv2)  =>  ( inv1 + inv2) - x
 156 // (inv2 - x) + inv1  =>  ( inv1 + inv2) - x
 157 // (inv2 - x) - inv1  =>  (-inv1 + inv2) - x
 158 // inv1 - (x + inv2)  =>  ( inv1 - inv2) - x
 159 //
 160 Node* IdealLoopTree::reassociate_add_sub(Node* n1, PhaseIdealLoop *phase) {
 161   if (!n1->is_Add() && !n1->is_Sub() || n1->outcnt() == 0) return NULL;
 162   if (is_invariant(n1)) return NULL;
 163   int inv1_idx = is_invariant_addition(n1, phase);
 164   if (!inv1_idx) return NULL;
 165   // Don't mess with add of constant (igvn moves them to expression tree root.)
 166   if (n1->is_Add() && n1->in(2)->is_Con()) return NULL;
 167   Node* inv1 = n1->in(inv1_idx);
 168   Node* n2 = n1->in(3 - inv1_idx);
 169   int inv2_idx = is_invariant_addition(n2, phase);
 170   if (!inv2_idx) return NULL;
 171   Node* x    = n2->in(3 - inv2_idx);
 172   Node* inv2 = n2->in(inv2_idx);
 173 
 174   bool neg_x    = n2->is_Sub() && inv2_idx == 1;
 175   bool neg_inv2 = n2->is_Sub() && inv2_idx == 2;
 176   bool neg_inv1 = n1->is_Sub() && inv1_idx == 2;
 177   if (n1->is_Sub() && inv1_idx == 1) {
 178     neg_x    = !neg_x;
 179     neg_inv2 = !neg_inv2;
 180   }
 181   Node* inv1_c = phase->get_ctrl(inv1);
 182   Node* inv2_c = phase->get_ctrl(inv2);
 183   Node* n_inv1;
 184   if (neg_inv1) {
 185     Node *zero = phase->_igvn.intcon(0);
 186     phase->set_ctrl(zero, phase->C->root());
 187     n_inv1 = new (phase->C, 3) SubINode(zero, inv1);
 188     phase->register_new_node(n_inv1, inv1_c);
 189   } else {
 190     n_inv1 = inv1;
 191   }
 192   Node* inv;
 193   if (neg_inv2) {
 194     inv = new (phase->C, 3) SubINode(n_inv1, inv2);
 195   } else {
 196     inv = new (phase->C, 3) AddINode(n_inv1, inv2);
 197   }
 198   phase->register_new_node(inv, phase->get_early_ctrl(inv));
 199 
 200   Node* addx;
 201   if (neg_x) {
 202     addx = new (phase->C, 3) SubINode(inv, x);
 203   } else {
 204     addx = new (phase->C, 3) AddINode(x, inv);
 205   }
 206   phase->register_new_node(addx, phase->get_ctrl(x));
 207   phase->_igvn.replace_node(n1, addx);
 208   assert(phase->get_loop(phase->get_ctrl(n1)) == this, "");
 209   _body.yank(n1);
 210   return addx;
 211 }
 212 
 213 //---------------------reassociate_invariants-----------------------------
 214 // Reassociate invariant expressions:
 215 void IdealLoopTree::reassociate_invariants(PhaseIdealLoop *phase) {
 216   for (int i = _body.size() - 1; i >= 0; i--) {
 217     Node *n = _body.at(i);
 218     for (int j = 0; j < 5; j++) {
 219       Node* nn = reassociate_add_sub(n, phase);
 220       if (nn == NULL) break;
 221       n = nn; // again
 222     };
 223   }
 224 }
 225 
 226 //------------------------------policy_peeling---------------------------------
 227 // Return TRUE or FALSE if the loop should be peeled or not.  Peel if we can
 228 // make some loop-invariant test (usually a null-check) happen before the loop.
 229 bool IdealLoopTree::policy_peeling( PhaseIdealLoop *phase ) const {
 230   Node *test = ((IdealLoopTree*)this)->tail();
 231   int  body_size = ((IdealLoopTree*)this)->_body.size();
 232   int  uniq      = phase->C->unique();
 233   // Peeling does loop cloning which can result in O(N^2) node construction
 234   if( body_size > 255 /* Prevent overflow for large body_size */
 235       || (body_size * body_size + uniq > MaxNodeLimit) ) {
 236     return false;           // too large to safely clone
 237   }
 238   while( test != _head ) {      // Scan till run off top of loop
 239     if( test->is_If() ) {       // Test?
 240       Node *ctrl = phase->get_ctrl(test->in(1));
 241       if (ctrl->is_top())
 242         return false;           // Found dead test on live IF?  No peeling!
 243       // Standard IF only has one input value to check for loop invariance
 244       assert( test->Opcode() == Op_If || test->Opcode() == Op_CountedLoopEnd, "Check this code when new subtype is added");
 245       // Condition is not a member of this loop?
 246       if( !is_member(phase->get_loop(ctrl)) &&
 247           is_loop_exit(test) )
 248         return true;            // Found reason to peel!
 249     }
 250     // Walk up dominators to loop _head looking for test which is
 251     // executed on every path thru loop.
 252     test = phase->idom(test);
 253   }
 254   return false;
 255 }
 256 
 257 //------------------------------peeled_dom_test_elim---------------------------
 258 // If we got the effect of peeling, either by actually peeling or by making
 259 // a pre-loop which must execute at least once, we can remove all
 260 // loop-invariant dominated tests in the main body.
 261 void PhaseIdealLoop::peeled_dom_test_elim( IdealLoopTree *loop, Node_List &old_new ) {
 262   bool progress = true;
 263   while( progress ) {
 264     progress = false;           // Reset for next iteration
 265     Node *prev = loop->_head->in(LoopNode::LoopBackControl);//loop->tail();
 266     Node *test = prev->in(0);
 267     while( test != loop->_head ) { // Scan till run off top of loop
 268 
 269       int p_op = prev->Opcode();
 270       if( (p_op == Op_IfFalse || p_op == Op_IfTrue) &&
 271           test->is_If() &&      // Test?
 272           !test->in(1)->is_Con() && // And not already obvious?
 273           // Condition is not a member of this loop?
 274           !loop->is_member(get_loop(get_ctrl(test->in(1))))){
 275         // Walk loop body looking for instances of this test
 276         for( uint i = 0; i < loop->_body.size(); i++ ) {
 277           Node *n = loop->_body.at(i);
 278           if( n->is_If() && n->in(1) == test->in(1) /*&& n != loop->tail()->in(0)*/ ) {
 279             // IfNode was dominated by version in peeled loop body
 280             progress = true;
 281             dominated_by( old_new[prev->_idx], n );
 282           }
 283         }
 284       }
 285       prev = test;
 286       test = idom(test);
 287     } // End of scan tests in loop
 288 
 289   } // End of while( progress )
 290 }
 291 
 292 //------------------------------do_peeling-------------------------------------
 293 // Peel the first iteration of the given loop.
 294 // Step 1: Clone the loop body.  The clone becomes the peeled iteration.
 295 //         The pre-loop illegally has 2 control users (old & new loops).
 296 // Step 2: Make the old-loop fall-in edges point to the peeled iteration.
 297 //         Do this by making the old-loop fall-in edges act as if they came
 298 //         around the loopback from the prior iteration (follow the old-loop
 299 //         backedges) and then map to the new peeled iteration.  This leaves
 300 //         the pre-loop with only 1 user (the new peeled iteration), but the
 301 //         peeled-loop backedge has 2 users.
 302 // Step 3: Cut the backedge on the clone (so its not a loop) and remove the
 303 //         extra backedge user.
 304 void PhaseIdealLoop::do_peeling( IdealLoopTree *loop, Node_List &old_new ) {
 305 
 306   C->set_major_progress();
 307   // Peeling a 'main' loop in a pre/main/post situation obfuscates the
 308   // 'pre' loop from the main and the 'pre' can no longer have it's
 309   // iterations adjusted.  Therefore, we need to declare this loop as
 310   // no longer a 'main' loop; it will need new pre and post loops before
 311   // we can do further RCE.
 312 #ifndef PRODUCT
 313   if (TraceLoopOpts) {
 314     tty->print("Peel         ");
 315     loop->dump_head();
 316   }
 317 #endif
 318   Node *h = loop->_head;
 319   if (h->is_CountedLoop()) {
 320     CountedLoopNode *cl = h->as_CountedLoop();
 321     assert(cl->trip_count() > 0, "peeling a fully unrolled loop");
 322     cl->set_trip_count(cl->trip_count() - 1);
 323     if (cl->is_main_loop()) {
 324       cl->set_normal_loop();
 325 #ifndef PRODUCT
 326       if (PrintOpto && VerifyLoopOptimizations) {
 327         tty->print("Peeling a 'main' loop; resetting to 'normal' ");
 328         loop->dump_head();
 329       }
 330 #endif
 331     }
 332   }
 333 
 334   // Step 1: Clone the loop body.  The clone becomes the peeled iteration.
 335   //         The pre-loop illegally has 2 control users (old & new loops).
 336   clone_loop( loop, old_new, dom_depth(loop->_head) );
 337 
 338 
 339   // Step 2: Make the old-loop fall-in edges point to the peeled iteration.
 340   //         Do this by making the old-loop fall-in edges act as if they came
 341   //         around the loopback from the prior iteration (follow the old-loop
 342   //         backedges) and then map to the new peeled iteration.  This leaves
 343   //         the pre-loop with only 1 user (the new peeled iteration), but the
 344   //         peeled-loop backedge has 2 users.
 345   for (DUIterator_Fast jmax, j = loop->_head->fast_outs(jmax); j < jmax; j++) {
 346     Node* old = loop->_head->fast_out(j);
 347     if( old->in(0) == loop->_head && old->req() == 3 &&
 348         (old->is_Loop() || old->is_Phi()) ) {
 349       Node *new_exit_value = old_new[old->in(LoopNode::LoopBackControl)->_idx];
 350       if( !new_exit_value )     // Backedge value is ALSO loop invariant?
 351         // Then loop body backedge value remains the same.
 352         new_exit_value = old->in(LoopNode::LoopBackControl);
 353       _igvn.hash_delete(old);
 354       old->set_req(LoopNode::EntryControl, new_exit_value);
 355     }
 356   }
 357 
 358 
 359   // Step 3: Cut the backedge on the clone (so its not a loop) and remove the
 360   //         extra backedge user.
 361   Node *nnn = old_new[loop->_head->_idx];
 362   _igvn.hash_delete(nnn);
 363   nnn->set_req(LoopNode::LoopBackControl, C->top());
 364   for (DUIterator_Fast j2max, j2 = nnn->fast_outs(j2max); j2 < j2max; j2++) {
 365     Node* use = nnn->fast_out(j2);
 366     if( use->in(0) == nnn && use->req() == 3 && use->is_Phi() ) {
 367       _igvn.hash_delete(use);
 368       use->set_req(LoopNode::LoopBackControl, C->top());
 369     }
 370   }
 371 
 372 
 373   // Step 4: Correct dom-depth info.  Set to loop-head depth.
 374   int dd = dom_depth(loop->_head);
 375   set_idom(loop->_head, loop->_head->in(1), dd);
 376   for (uint j3 = 0; j3 < loop->_body.size(); j3++) {
 377     Node *old = loop->_body.at(j3);
 378     Node *nnn = old_new[old->_idx];
 379     if (!has_ctrl(nnn))
 380       set_idom(nnn, idom(nnn), dd-1);
 381     // While we're at it, remove any SafePoints from the peeled code
 382     if( old->Opcode() == Op_SafePoint ) {
 383       Node *nnn = old_new[old->_idx];
 384       lazy_replace(nnn,nnn->in(TypeFunc::Control));
 385     }
 386   }
 387 
 388   // Now force out all loop-invariant dominating tests.  The optimizer
 389   // finds some, but we _know_ they are all useless.
 390   peeled_dom_test_elim(loop,old_new);
 391 
 392   loop->record_for_igvn();
 393 }
 394 
 395 //------------------------------policy_maximally_unroll------------------------
 396 // Return exact loop trip count, or 0 if not maximally unrolling
 397 bool IdealLoopTree::policy_maximally_unroll( PhaseIdealLoop *phase ) const {
 398   CountedLoopNode *cl = _head->as_CountedLoop();
 399   assert(cl->is_normal_loop(), "");
 400 
 401   Node *init_n = cl->init_trip();
 402   Node *limit_n = cl->limit();
 403 
 404   // Non-constant bounds
 405   if (init_n   == NULL || !init_n->is_Con()  ||
 406       limit_n  == NULL || !limit_n->is_Con() ||
 407       // protect against stride not being a constant
 408       !cl->stride_is_con()) {
 409     return false;
 410   }
 411   int init   = init_n->get_int();
 412   int limit  = limit_n->get_int();
 413   int span   = limit - init;
 414   int stride = cl->stride_con();
 415 
 416   if (init >= limit || stride > span) {
 417     // return a false (no maximally unroll) and the regular unroll/peel
 418     // route will make a small mess which CCP will fold away.
 419     return false;
 420   }
 421   uint trip_count = span/stride;   // trip_count can be greater than 2 Gig.
 422   assert( (int)trip_count*stride == span, "must divide evenly" );
 423 
 424   // Real policy: if we maximally unroll, does it get too big?
 425   // Allow the unrolled mess to get larger than standard loop
 426   // size.  After all, it will no longer be a loop.
 427   uint body_size    = _body.size();
 428   uint unroll_limit = (uint)LoopUnrollLimit * 4;
 429   assert( (intx)unroll_limit == LoopUnrollLimit * 4, "LoopUnrollLimit must fit in 32bits");
 430   cl->set_trip_count(trip_count);
 431   if (trip_count > unroll_limit || body_size > unroll_limit) {
 432     return false;
 433   }
 434 
 435   // Do not unroll a loop with String intrinsics code.
 436   // String intrinsics are large and have loops.
 437   for (uint k = 0; k < _body.size(); k++) {
 438     Node* n = _body.at(k);
 439     switch (n->Opcode()) {
 440       case Op_StrComp:
 441       case Op_StrEquals:
 442       case Op_StrIndexOf:
 443       case Op_AryEq: {
 444         return false;
 445       }
 446     } // switch
 447   }
 448 
 449   if (body_size <= unroll_limit) {
 450     uint new_body_size = body_size * trip_count;
 451     if (new_body_size <= unroll_limit &&
 452         body_size == new_body_size / trip_count &&
 453         // Unrolling can result in a large amount of node construction
 454         new_body_size < MaxNodeLimit - phase->C->unique()) {
 455       return true;    // maximally unroll
 456     }
 457   }
 458 
 459   return false;               // Do not maximally unroll
 460 }
 461 
 462 
 463 //------------------------------policy_unroll----------------------------------
 464 // Return TRUE or FALSE if the loop should be unrolled or not.  Unroll if
 465 // the loop is a CountedLoop and the body is small enough.
 466 bool IdealLoopTree::policy_unroll( PhaseIdealLoop *phase ) const {
 467 
 468   CountedLoopNode *cl = _head->as_CountedLoop();
 469   assert(cl->is_normal_loop() || cl->is_main_loop(), "");
 470 
 471   // protect against stride not being a constant
 472   if (!cl->stride_is_con()) return false;
 473 
 474   // protect against over-unrolling
 475   if (cl->trip_count() <= 1) return false;
 476 
 477   int future_unroll_ct = cl->unrolled_count() * 2;
 478 
 479   // Don't unroll if the next round of unrolling would push us
 480   // over the expected trip count of the loop.  One is subtracted
 481   // from the expected trip count because the pre-loop normally
 482   // executes 1 iteration.
 483   if (UnrollLimitForProfileCheck > 0 &&
 484       cl->profile_trip_cnt() != COUNT_UNKNOWN &&
 485       future_unroll_ct        > UnrollLimitForProfileCheck &&
 486       (float)future_unroll_ct > cl->profile_trip_cnt() - 1.0) {
 487     return false;
 488   }
 489 
 490   // When unroll count is greater than LoopUnrollMin, don't unroll if:
 491   //   the residual iterations are more than 10% of the trip count
 492   //   and rounds of "unroll,optimize" are not making significant progress
 493   //   Progress defined as current size less than 20% larger than previous size.
 494   if (UseSuperWord && cl->node_count_before_unroll() > 0 &&
 495       future_unroll_ct > LoopUnrollMin &&
 496       (future_unroll_ct - 1) * 10.0 > cl->profile_trip_cnt() &&
 497       1.2 * cl->node_count_before_unroll() < (double)_body.size()) {
 498     return false;
 499   }
 500 
 501   Node *init_n = cl->init_trip();
 502   Node *limit_n = cl->limit();
 503   // Non-constant bounds.
 504   // Protect against over-unrolling when init or/and limit are not constant
 505   // (so that trip_count's init value is maxint) but iv range is known.
 506   if (init_n   == NULL || !init_n->is_Con()  ||
 507       limit_n  == NULL || !limit_n->is_Con()) {
 508     Node* phi = cl->phi();
 509     if (phi != NULL) {
 510       assert(phi->is_Phi() && phi->in(0) == _head, "Counted loop should have iv phi.");
 511       const TypeInt* iv_type = phase->_igvn.type(phi)->is_int();
 512       int next_stride = cl->stride_con() * 2; // stride after this unroll
 513       if (next_stride > 0) {
 514         if (iv_type->_lo + next_stride <= iv_type->_lo || // overflow
 515             iv_type->_lo + next_stride >  iv_type->_hi) {
 516           return false;  // over-unrolling
 517         }
 518       } else if (next_stride < 0) {
 519         if (iv_type->_hi + next_stride >= iv_type->_hi || // overflow
 520             iv_type->_hi + next_stride <  iv_type->_lo) {
 521           return false;  // over-unrolling
 522         }
 523       }
 524     }
 525   }
 526 
 527   // Adjust body_size to determine if we unroll or not
 528   uint body_size = _body.size();
 529   // Key test to unroll CaffeineMark's Logic test
 530   int xors_in_loop = 0;
 531   // Also count ModL, DivL and MulL which expand mightly
 532   for (uint k = 0; k < _body.size(); k++) {
 533     Node* n = _body.at(k);
 534     switch (n->Opcode()) {
 535       case Op_XorI: xors_in_loop++; break; // CaffeineMark's Logic test
 536       case Op_ModL: body_size += 30; break;
 537       case Op_DivL: body_size += 30; break;
 538       case Op_MulL: body_size += 10; break;
 539       case Op_StrComp:
 540       case Op_StrEquals:
 541       case Op_StrIndexOf:
 542       case Op_AryEq: {
 543         // Do not unroll a loop with String intrinsics code.
 544         // String intrinsics are large and have loops.
 545         return false;
 546       }
 547     } // switch
 548   }
 549 
 550   // Check for being too big
 551   if (body_size > (uint)LoopUnrollLimit) {
 552     if (xors_in_loop >= 4 && body_size < (uint)LoopUnrollLimit*4) return true;
 553     // Normal case: loop too big
 554     return false;
 555   }
 556 
 557   // Check for stride being a small enough constant
 558   if (abs(cl->stride_con()) > (1<<3)) return false;
 559 
 560   // Unroll once!  (Each trip will soon do double iterations)
 561   return true;
 562 }
 563 
 564 //------------------------------policy_align-----------------------------------
 565 // Return TRUE or FALSE if the loop should be cache-line aligned.  Gather the
 566 // expression that does the alignment.  Note that only one array base can be
 567 // aligned in a loop (unless the VM guarantees mutual alignment).  Note that
 568 // if we vectorize short memory ops into longer memory ops, we may want to
 569 // increase alignment.
 570 bool IdealLoopTree::policy_align( PhaseIdealLoop *phase ) const {
 571   return false;
 572 }
 573 
 574 //------------------------------policy_range_check-----------------------------
 575 // Return TRUE or FALSE if the loop should be range-check-eliminated.
 576 // Actually we do iteration-splitting, a more powerful form of RCE.
 577 bool IdealLoopTree::policy_range_check( PhaseIdealLoop *phase ) const {
 578   if( !RangeCheckElimination ) return false;
 579 
 580   CountedLoopNode *cl = _head->as_CountedLoop();
 581   // If we unrolled with no intention of doing RCE and we later
 582   // changed our minds, we got no pre-loop.  Either we need to
 583   // make a new pre-loop, or we gotta disallow RCE.
 584   if( cl->is_main_no_pre_loop() ) return false; // Disallowed for now.
 585   Node *trip_counter = cl->phi();
 586 
 587   // Check loop body for tests of trip-counter plus loop-invariant vs
 588   // loop-invariant.
 589   for( uint i = 0; i < _body.size(); i++ ) {
 590     Node *iff = _body[i];
 591     if( iff->Opcode() == Op_If ) { // Test?
 592 
 593       // Comparing trip+off vs limit
 594       Node *bol = iff->in(1);
 595       if( bol->req() != 2 ) continue; // dead constant test
 596       if (!bol->is_Bool()) {
 597         assert(UseLoopPredicate && bol->Opcode() == Op_Conv2B, "predicate check only");
 598         continue;
 599       }
 600       Node *cmp = bol->in(1);
 601 
 602       Node *rc_exp = cmp->in(1);
 603       Node *limit = cmp->in(2);
 604 
 605       Node *limit_c = phase->get_ctrl(limit);
 606       if( limit_c == phase->C->top() )
 607         return false;           // Found dead test on live IF?  No RCE!
 608       if( is_member(phase->get_loop(limit_c) ) ) {
 609         // Compare might have operands swapped; commute them
 610         rc_exp = cmp->in(2);
 611         limit  = cmp->in(1);
 612         limit_c = phase->get_ctrl(limit);
 613         if( is_member(phase->get_loop(limit_c) ) )
 614           continue;             // Both inputs are loop varying; cannot RCE
 615       }
 616 
 617       if (!phase->is_scaled_iv_plus_offset(rc_exp, trip_counter, NULL, NULL)) {
 618         continue;
 619       }
 620       // Yeah!  Found a test like 'trip+off vs limit'
 621       // Test is an IfNode, has 2 projections.  If BOTH are in the loop
 622       // we need loop unswitching instead of iteration splitting.
 623       if( is_loop_exit(iff) )
 624         return true;            // Found reason to split iterations
 625     } // End of is IF
 626   }
 627 
 628   return false;
 629 }
 630 
 631 //------------------------------policy_peel_only-------------------------------
 632 // Return TRUE or FALSE if the loop should NEVER be RCE'd or aligned.  Useful
 633 // for unrolling loops with NO array accesses.
 634 bool IdealLoopTree::policy_peel_only( PhaseIdealLoop *phase ) const {
 635 
 636   for( uint i = 0; i < _body.size(); i++ )
 637     if( _body[i]->is_Mem() )
 638       return false;
 639 
 640   // No memory accesses at all!
 641   return true;
 642 }
 643 
 644 //------------------------------clone_up_backedge_goo--------------------------
 645 // If Node n lives in the back_ctrl block and cannot float, we clone a private
 646 // version of n in preheader_ctrl block and return that, otherwise return n.
 647 Node *PhaseIdealLoop::clone_up_backedge_goo( Node *back_ctrl, Node *preheader_ctrl, Node *n ) {
 648   if( get_ctrl(n) != back_ctrl ) return n;
 649 
 650   Node *x = NULL;               // If required, a clone of 'n'
 651   // Check for 'n' being pinned in the backedge.
 652   if( n->in(0) && n->in(0) == back_ctrl ) {
 653     x = n->clone();             // Clone a copy of 'n' to preheader
 654     x->set_req( 0, preheader_ctrl ); // Fix x's control input to preheader
 655   }
 656 
 657   // Recursive fixup any other input edges into x.
 658   // If there are no changes we can just return 'n', otherwise
 659   // we need to clone a private copy and change it.
 660   for( uint i = 1; i < n->req(); i++ ) {
 661     Node *g = clone_up_backedge_goo( back_ctrl, preheader_ctrl, n->in(i) );
 662     if( g != n->in(i) ) {
 663       if( !x )
 664         x = n->clone();
 665       x->set_req(i, g);
 666     }
 667   }
 668   if( x ) {                     // x can legally float to pre-header location
 669     register_new_node( x, preheader_ctrl );
 670     return x;
 671   } else {                      // raise n to cover LCA of uses
 672     set_ctrl( n, find_non_split_ctrl(back_ctrl->in(0)) );
 673   }
 674   return n;
 675 }
 676 
 677 //------------------------------insert_pre_post_loops--------------------------
 678 // Insert pre and post loops.  If peel_only is set, the pre-loop can not have
 679 // more iterations added.  It acts as a 'peel' only, no lower-bound RCE, no
 680 // alignment.  Useful to unroll loops that do no array accesses.
 681 void PhaseIdealLoop::insert_pre_post_loops( IdealLoopTree *loop, Node_List &old_new, bool peel_only ) {
 682 
 683 #ifndef PRODUCT
 684   if (TraceLoopOpts) {
 685     if (peel_only)
 686       tty->print("PeelMainPost ");
 687     else
 688       tty->print("PreMainPost  ");
 689     loop->dump_head();
 690   }
 691 #endif
 692   C->set_major_progress();
 693 
 694   // Find common pieces of the loop being guarded with pre & post loops
 695   CountedLoopNode *main_head = loop->_head->as_CountedLoop();
 696   assert( main_head->is_normal_loop(), "" );
 697   CountedLoopEndNode *main_end = main_head->loopexit();
 698   assert( main_end->outcnt() == 2, "1 true, 1 false path only" );
 699   uint dd_main_head = dom_depth(main_head);
 700   uint max = main_head->outcnt();
 701 
 702   Node *pre_header= main_head->in(LoopNode::EntryControl);
 703   Node *init      = main_head->init_trip();
 704   Node *incr      = main_end ->incr();
 705   Node *limit     = main_end ->limit();
 706   Node *stride    = main_end ->stride();
 707   Node *cmp       = main_end ->cmp_node();
 708   BoolTest::mask b_test = main_end->test_trip();
 709 
 710   // Need only 1 user of 'bol' because I will be hacking the loop bounds.
 711   Node *bol = main_end->in(CountedLoopEndNode::TestValue);
 712   if( bol->outcnt() != 1 ) {
 713     bol = bol->clone();
 714     register_new_node(bol,main_end->in(CountedLoopEndNode::TestControl));
 715     _igvn.hash_delete(main_end);
 716     main_end->set_req(CountedLoopEndNode::TestValue, bol);
 717   }
 718   // Need only 1 user of 'cmp' because I will be hacking the loop bounds.
 719   if( cmp->outcnt() != 1 ) {
 720     cmp = cmp->clone();
 721     register_new_node(cmp,main_end->in(CountedLoopEndNode::TestControl));
 722     _igvn.hash_delete(bol);
 723     bol->set_req(1, cmp);
 724   }
 725 
 726   //------------------------------
 727   // Step A: Create Post-Loop.
 728   Node* main_exit = main_end->proj_out(false);
 729   assert( main_exit->Opcode() == Op_IfFalse, "" );
 730   int dd_main_exit = dom_depth(main_exit);
 731 
 732   // Step A1: Clone the loop body.  The clone becomes the post-loop.  The main
 733   // loop pre-header illegally has 2 control users (old & new loops).
 734   clone_loop( loop, old_new, dd_main_exit );
 735   assert( old_new[main_end ->_idx]->Opcode() == Op_CountedLoopEnd, "" );
 736   CountedLoopNode *post_head = old_new[main_head->_idx]->as_CountedLoop();
 737   post_head->set_post_loop(main_head);
 738 
 739   // Reduce the post-loop trip count.
 740   CountedLoopEndNode* post_end = old_new[main_end ->_idx]->as_CountedLoopEnd();
 741   post_end->_prob = PROB_FAIR;
 742 
 743   // Build the main-loop normal exit.
 744   IfFalseNode *new_main_exit = new (C, 1) IfFalseNode(main_end);
 745   _igvn.register_new_node_with_optimizer( new_main_exit );
 746   set_idom(new_main_exit, main_end, dd_main_exit );
 747   set_loop(new_main_exit, loop->_parent);
 748 
 749   // Step A2: Build a zero-trip guard for the post-loop.  After leaving the
 750   // main-loop, the post-loop may not execute at all.  We 'opaque' the incr
 751   // (the main-loop trip-counter exit value) because we will be changing
 752   // the exit value (via unrolling) so we cannot constant-fold away the zero
 753   // trip guard until all unrolling is done.
 754   Node *zer_opaq = new (C, 2) Opaque1Node(C, incr);
 755   Node *zer_cmp  = new (C, 3) CmpINode( zer_opaq, limit );
 756   Node *zer_bol  = new (C, 2) BoolNode( zer_cmp, b_test );
 757   register_new_node( zer_opaq, new_main_exit );
 758   register_new_node( zer_cmp , new_main_exit );
 759   register_new_node( zer_bol , new_main_exit );
 760 
 761   // Build the IfNode
 762   IfNode *zer_iff = new (C, 2) IfNode( new_main_exit, zer_bol, PROB_FAIR, COUNT_UNKNOWN );
 763   _igvn.register_new_node_with_optimizer( zer_iff );
 764   set_idom(zer_iff, new_main_exit, dd_main_exit);
 765   set_loop(zer_iff, loop->_parent);
 766 
 767   // Plug in the false-path, taken if we need to skip post-loop
 768   _igvn.hash_delete( main_exit );
 769   main_exit->set_req(0, zer_iff);
 770   _igvn._worklist.push(main_exit);
 771   set_idom(main_exit, zer_iff, dd_main_exit);
 772   set_idom(main_exit->unique_out(), zer_iff, dd_main_exit);
 773   // Make the true-path, must enter the post loop
 774   Node *zer_taken = new (C, 1) IfTrueNode( zer_iff );
 775   _igvn.register_new_node_with_optimizer( zer_taken );
 776   set_idom(zer_taken, zer_iff, dd_main_exit);
 777   set_loop(zer_taken, loop->_parent);
 778   // Plug in the true path
 779   _igvn.hash_delete( post_head );
 780   post_head->set_req(LoopNode::EntryControl, zer_taken);
 781   set_idom(post_head, zer_taken, dd_main_exit);
 782 
 783   // Step A3: Make the fall-in values to the post-loop come from the
 784   // fall-out values of the main-loop.
 785   for (DUIterator_Fast imax, i = main_head->fast_outs(imax); i < imax; i++) {
 786     Node* main_phi = main_head->fast_out(i);
 787     if( main_phi->is_Phi() && main_phi->in(0) == main_head && main_phi->outcnt() >0 ) {
 788       Node *post_phi = old_new[main_phi->_idx];
 789       Node *fallmain  = clone_up_backedge_goo(main_head->back_control(),
 790                                               post_head->init_control(),
 791                                               main_phi->in(LoopNode::LoopBackControl));
 792       _igvn.hash_delete(post_phi);
 793       post_phi->set_req( LoopNode::EntryControl, fallmain );
 794     }
 795   }
 796 
 797   // Update local caches for next stanza
 798   main_exit = new_main_exit;
 799 
 800 
 801   //------------------------------
 802   // Step B: Create Pre-Loop.
 803 
 804   // Step B1: Clone the loop body.  The clone becomes the pre-loop.  The main
 805   // loop pre-header illegally has 2 control users (old & new loops).
 806   clone_loop( loop, old_new, dd_main_head );
 807   CountedLoopNode*    pre_head = old_new[main_head->_idx]->as_CountedLoop();
 808   CountedLoopEndNode* pre_end  = old_new[main_end ->_idx]->as_CountedLoopEnd();
 809   pre_head->set_pre_loop(main_head);
 810   Node *pre_incr = old_new[incr->_idx];
 811 
 812   // Reduce the pre-loop trip count.
 813   pre_end->_prob = PROB_FAIR;
 814 
 815   // Find the pre-loop normal exit.
 816   Node* pre_exit = pre_end->proj_out(false);
 817   assert( pre_exit->Opcode() == Op_IfFalse, "" );
 818   IfFalseNode *new_pre_exit = new (C, 1) IfFalseNode(pre_end);
 819   _igvn.register_new_node_with_optimizer( new_pre_exit );
 820   set_idom(new_pre_exit, pre_end, dd_main_head);
 821   set_loop(new_pre_exit, loop->_parent);
 822 
 823   // Step B2: Build a zero-trip guard for the main-loop.  After leaving the
 824   // pre-loop, the main-loop may not execute at all.  Later in life this
 825   // zero-trip guard will become the minimum-trip guard when we unroll
 826   // the main-loop.
 827   Node *min_opaq = new (C, 2) Opaque1Node(C, limit);
 828   Node *min_cmp  = new (C, 3) CmpINode( pre_incr, min_opaq );
 829   Node *min_bol  = new (C, 2) BoolNode( min_cmp, b_test );
 830   register_new_node( min_opaq, new_pre_exit );
 831   register_new_node( min_cmp , new_pre_exit );
 832   register_new_node( min_bol , new_pre_exit );
 833 
 834   // Build the IfNode (assume the main-loop is executed always).
 835   IfNode *min_iff = new (C, 2) IfNode( new_pre_exit, min_bol, PROB_ALWAYS, COUNT_UNKNOWN );
 836   _igvn.register_new_node_with_optimizer( min_iff );
 837   set_idom(min_iff, new_pre_exit, dd_main_head);
 838   set_loop(min_iff, loop->_parent);
 839 
 840   // Plug in the false-path, taken if we need to skip main-loop
 841   _igvn.hash_delete( pre_exit );
 842   pre_exit->set_req(0, min_iff);
 843   set_idom(pre_exit, min_iff, dd_main_head);
 844   set_idom(pre_exit->unique_out(), min_iff, dd_main_head);
 845   // Make the true-path, must enter the main loop
 846   Node *min_taken = new (C, 1) IfTrueNode( min_iff );
 847   _igvn.register_new_node_with_optimizer( min_taken );
 848   set_idom(min_taken, min_iff, dd_main_head);
 849   set_loop(min_taken, loop->_parent);
 850   // Plug in the true path
 851   _igvn.hash_delete( main_head );
 852   main_head->set_req(LoopNode::EntryControl, min_taken);
 853   set_idom(main_head, min_taken, dd_main_head);
 854 
 855   // Step B3: Make the fall-in values to the main-loop come from the
 856   // fall-out values of the pre-loop.
 857   for (DUIterator_Fast i2max, i2 = main_head->fast_outs(i2max); i2 < i2max; i2++) {
 858     Node* main_phi = main_head->fast_out(i2);
 859     if( main_phi->is_Phi() && main_phi->in(0) == main_head && main_phi->outcnt() > 0 ) {
 860       Node *pre_phi = old_new[main_phi->_idx];
 861       Node *fallpre  = clone_up_backedge_goo(pre_head->back_control(),
 862                                              main_head->init_control(),
 863                                              pre_phi->in(LoopNode::LoopBackControl));
 864       _igvn.hash_delete(main_phi);
 865       main_phi->set_req( LoopNode::EntryControl, fallpre );
 866     }
 867   }
 868 
 869   // Step B4: Shorten the pre-loop to run only 1 iteration (for now).
 870   // RCE and alignment may change this later.
 871   Node *cmp_end = pre_end->cmp_node();
 872   assert( cmp_end->in(2) == limit, "" );
 873   Node *pre_limit = new (C, 3) AddINode( init, stride );
 874 
 875   // Save the original loop limit in this Opaque1 node for
 876   // use by range check elimination.
 877   Node *pre_opaq  = new (C, 3) Opaque1Node(C, pre_limit, limit);
 878 
 879   register_new_node( pre_limit, pre_head->in(0) );
 880   register_new_node( pre_opaq , pre_head->in(0) );
 881 
 882   // Since no other users of pre-loop compare, I can hack limit directly
 883   assert( cmp_end->outcnt() == 1, "no other users" );
 884   _igvn.hash_delete(cmp_end);
 885   cmp_end->set_req(2, peel_only ? pre_limit : pre_opaq);
 886 
 887   // Special case for not-equal loop bounds:
 888   // Change pre loop test, main loop test, and the
 889   // main loop guard test to use lt or gt depending on stride
 890   // direction:
 891   // positive stride use <
 892   // negative stride use >
 893 
 894   if (pre_end->in(CountedLoopEndNode::TestValue)->as_Bool()->_test._test == BoolTest::ne) {
 895 
 896     BoolTest::mask new_test = (main_end->stride_con() > 0) ? BoolTest::lt : BoolTest::gt;
 897     // Modify pre loop end condition
 898     Node* pre_bol = pre_end->in(CountedLoopEndNode::TestValue)->as_Bool();
 899     BoolNode* new_bol0 = new (C, 2) BoolNode(pre_bol->in(1), new_test);
 900     register_new_node( new_bol0, pre_head->in(0) );
 901     _igvn.hash_delete(pre_end);
 902     pre_end->set_req(CountedLoopEndNode::TestValue, new_bol0);
 903     // Modify main loop guard condition
 904     assert(min_iff->in(CountedLoopEndNode::TestValue) == min_bol, "guard okay");
 905     BoolNode* new_bol1 = new (C, 2) BoolNode(min_bol->in(1), new_test);
 906     register_new_node( new_bol1, new_pre_exit );
 907     _igvn.hash_delete(min_iff);
 908     min_iff->set_req(CountedLoopEndNode::TestValue, new_bol1);
 909     // Modify main loop end condition
 910     BoolNode* main_bol = main_end->in(CountedLoopEndNode::TestValue)->as_Bool();
 911     BoolNode* new_bol2 = new (C, 2) BoolNode(main_bol->in(1), new_test);
 912     register_new_node( new_bol2, main_end->in(CountedLoopEndNode::TestControl) );
 913     _igvn.hash_delete(main_end);
 914     main_end->set_req(CountedLoopEndNode::TestValue, new_bol2);
 915   }
 916 
 917   // Flag main loop
 918   main_head->set_main_loop();
 919   if( peel_only ) main_head->set_main_no_pre_loop();
 920 
 921   // It's difficult to be precise about the trip-counts
 922   // for the pre/post loops.  They are usually very short,
 923   // so guess that 4 trips is a reasonable value.
 924   post_head->set_profile_trip_cnt(4.0);
 925   pre_head->set_profile_trip_cnt(4.0);
 926 
 927   // Now force out all loop-invariant dominating tests.  The optimizer
 928   // finds some, but we _know_ they are all useless.
 929   peeled_dom_test_elim(loop,old_new);
 930 }
 931 
 932 //------------------------------is_invariant-----------------------------
 933 // Return true if n is invariant
 934 bool IdealLoopTree::is_invariant(Node* n) const {
 935   Node *n_c = _phase->has_ctrl(n) ? _phase->get_ctrl(n) : n;
 936   if (n_c->is_top()) return false;
 937   return !is_member(_phase->get_loop(n_c));
 938 }
 939 
 940 
 941 //------------------------------do_unroll--------------------------------------
 942 // Unroll the loop body one step - make each trip do 2 iterations.
 943 void PhaseIdealLoop::do_unroll( IdealLoopTree *loop, Node_List &old_new, bool adjust_min_trip ) {
 944   assert(LoopUnrollLimit, "");
 945   CountedLoopNode *loop_head = loop->_head->as_CountedLoop();
 946   CountedLoopEndNode *loop_end = loop_head->loopexit();
 947   assert(loop_end, "");
 948 #ifndef PRODUCT
 949   if (PrintOpto && VerifyLoopOptimizations) {
 950     tty->print("Unrolling ");
 951     loop->dump_head();
 952   } else if (TraceLoopOpts) {
 953     tty->print("Unroll     %d ", loop_head->unrolled_count()*2);
 954     loop->dump_head();
 955   }
 956 #endif
 957 
 958   // Remember loop node count before unrolling to detect
 959   // if rounds of unroll,optimize are making progress
 960   loop_head->set_node_count_before_unroll(loop->_body.size());
 961 
 962   Node *ctrl  = loop_head->in(LoopNode::EntryControl);
 963   Node *limit = loop_head->limit();
 964   Node *init  = loop_head->init_trip();
 965   Node *stride = loop_head->stride();
 966 
 967   Node *opaq = NULL;
 968   if( adjust_min_trip ) {       // If not maximally unrolling, need adjustment
 969     assert( loop_head->is_main_loop(), "" );
 970     assert( ctrl->Opcode() == Op_IfTrue || ctrl->Opcode() == Op_IfFalse, "" );
 971     Node *iff = ctrl->in(0);
 972     assert( iff->Opcode() == Op_If, "" );
 973     Node *bol = iff->in(1);
 974     assert( bol->Opcode() == Op_Bool, "" );
 975     Node *cmp = bol->in(1);
 976     assert( cmp->Opcode() == Op_CmpI, "" );
 977     opaq = cmp->in(2);
 978     // Occasionally it's possible for a pre-loop Opaque1 node to be
 979     // optimized away and then another round of loop opts attempted.
 980     // We can not optimize this particular loop in that case.
 981     if( opaq->Opcode() != Op_Opaque1 )
 982       return;                   // Cannot find pre-loop!  Bail out!
 983   }
 984 
 985   C->set_major_progress();
 986 
 987   // Adjust max trip count. The trip count is intentionally rounded
 988   // down here (e.g. 15-> 7-> 3-> 1) because if we unwittingly over-unroll,
 989   // the main, unrolled, part of the loop will never execute as it is protected
 990   // by the min-trip test.  See bug 4834191 for a case where we over-unrolled
 991   // and later determined that part of the unrolled loop was dead.
 992   loop_head->set_trip_count(loop_head->trip_count() / 2);
 993 
 994   // Double the count of original iterations in the unrolled loop body.
 995   loop_head->double_unrolled_count();
 996 
 997   // -----------
 998   // Step 2: Cut back the trip counter for an unroll amount of 2.
 999   // Loop will normally trip (limit - init)/stride_con.  Since it's a
1000   // CountedLoop this is exact (stride divides limit-init exactly).
1001   // We are going to double the loop body, so we want to knock off any
1002   // odd iteration: (trip_cnt & ~1).  Then back compute a new limit.
1003   Node *span = new (C, 3) SubINode( limit, init );
1004   register_new_node( span, ctrl );
1005   Node *trip = new (C, 3) DivINode( 0, span, stride );
1006   register_new_node( trip, ctrl );
1007   Node *mtwo = _igvn.intcon(-2);
1008   set_ctrl(mtwo, C->root());
1009   Node *rond = new (C, 3) AndINode( trip, mtwo );
1010   register_new_node( rond, ctrl );
1011   Node *spn2 = new (C, 3) MulINode( rond, stride );
1012   register_new_node( spn2, ctrl );
1013   Node *lim2 = new (C, 3) AddINode( spn2, init );
1014   register_new_node( lim2, ctrl );
1015 
1016   // Hammer in the new limit
1017   Node *ctrl2 = loop_end->in(0);
1018   Node *cmp2 = new (C, 3) CmpINode( loop_head->incr(), lim2 );
1019   register_new_node( cmp2, ctrl2 );
1020   Node *bol2 = new (C, 2) BoolNode( cmp2, loop_end->test_trip() );
1021   register_new_node( bol2, ctrl2 );
1022   _igvn.hash_delete(loop_end);
1023   loop_end->set_req(CountedLoopEndNode::TestValue, bol2);
1024 
1025   // Step 3: Find the min-trip test guaranteed before a 'main' loop.
1026   // Make it a 1-trip test (means at least 2 trips).
1027   if( adjust_min_trip ) {
1028     // Guard test uses an 'opaque' node which is not shared.  Hence I
1029     // can edit it's inputs directly.  Hammer in the new limit for the
1030     // minimum-trip guard.
1031     assert( opaq->outcnt() == 1, "" );
1032     _igvn.hash_delete(opaq);
1033     opaq->set_req(1, lim2);
1034   }
1035 
1036   // ---------
1037   // Step 4: Clone the loop body.  Move it inside the loop.  This loop body
1038   // represents the odd iterations; since the loop trips an even number of
1039   // times its backedge is never taken.  Kill the backedge.
1040   uint dd = dom_depth(loop_head);
1041   clone_loop( loop, old_new, dd );
1042 
1043   // Make backedges of the clone equal to backedges of the original.
1044   // Make the fall-in from the original come from the fall-out of the clone.
1045   for (DUIterator_Fast jmax, j = loop_head->fast_outs(jmax); j < jmax; j++) {
1046     Node* phi = loop_head->fast_out(j);
1047     if( phi->is_Phi() && phi->in(0) == loop_head && phi->outcnt() > 0 ) {
1048       Node *newphi = old_new[phi->_idx];
1049       _igvn.hash_delete( phi );
1050       _igvn.hash_delete( newphi );
1051 
1052       phi   ->set_req(LoopNode::   EntryControl, newphi->in(LoopNode::LoopBackControl));
1053       newphi->set_req(LoopNode::LoopBackControl, phi   ->in(LoopNode::LoopBackControl));
1054       phi   ->set_req(LoopNode::LoopBackControl, C->top());
1055     }
1056   }
1057   Node *clone_head = old_new[loop_head->_idx];
1058   _igvn.hash_delete( clone_head );
1059   loop_head ->set_req(LoopNode::   EntryControl, clone_head->in(LoopNode::LoopBackControl));
1060   clone_head->set_req(LoopNode::LoopBackControl, loop_head ->in(LoopNode::LoopBackControl));
1061   loop_head ->set_req(LoopNode::LoopBackControl, C->top());
1062   loop->_head = clone_head;     // New loop header
1063 
1064   set_idom(loop_head,  loop_head ->in(LoopNode::EntryControl), dd);
1065   set_idom(clone_head, clone_head->in(LoopNode::EntryControl), dd);
1066 
1067   // Kill the clone's backedge
1068   Node *newcle = old_new[loop_end->_idx];
1069   _igvn.hash_delete( newcle );
1070   Node *one = _igvn.intcon(1);
1071   set_ctrl(one, C->root());
1072   newcle->set_req(1, one);
1073   // Force clone into same loop body
1074   uint max = loop->_body.size();
1075   for( uint k = 0; k < max; k++ ) {
1076     Node *old = loop->_body.at(k);
1077     Node *nnn = old_new[old->_idx];
1078     loop->_body.push(nnn);
1079     if (!has_ctrl(old))
1080       set_loop(nnn, loop);
1081   }
1082 
1083   loop->record_for_igvn();
1084 }
1085 
1086 //------------------------------do_maximally_unroll----------------------------
1087 
1088 void PhaseIdealLoop::do_maximally_unroll( IdealLoopTree *loop, Node_List &old_new ) {
1089   CountedLoopNode *cl = loop->_head->as_CountedLoop();
1090   assert(cl->trip_count() > 0, "");
1091 #ifndef PRODUCT
1092   if (TraceLoopOpts) {
1093     tty->print("MaxUnroll  %d ", cl->trip_count());
1094     loop->dump_head();
1095   }
1096 #endif
1097 
1098   // If loop is tripping an odd number of times, peel odd iteration
1099   if ((cl->trip_count() & 1) == 1) {
1100     do_peeling(loop, old_new);
1101   }
1102 
1103   // Now its tripping an even number of times remaining.  Double loop body.
1104   // Do not adjust pre-guards; they are not needed and do not exist.
1105   if (cl->trip_count() > 0) {
1106     do_unroll(loop, old_new, false);
1107   }
1108 }
1109 
1110 //------------------------------dominates_backedge---------------------------------
1111 // Returns true if ctrl is executed on every complete iteration
1112 bool IdealLoopTree::dominates_backedge(Node* ctrl) {
1113   assert(ctrl->is_CFG(), "must be control");
1114   Node* backedge = _head->as_Loop()->in(LoopNode::LoopBackControl);
1115   return _phase->dom_lca_internal(ctrl, backedge) == ctrl;
1116 }
1117 
1118 //------------------------------add_constraint---------------------------------
1119 // Constrain the main loop iterations so the condition:
1120 //    scale_con * I + offset  <  limit
1121 // always holds true.  That is, either increase the number of iterations in
1122 // the pre-loop or the post-loop until the condition holds true in the main
1123 // loop.  Stride, scale, offset and limit are all loop invariant.  Further,
1124 // stride and scale are constants (offset and limit often are).
1125 void PhaseIdealLoop::add_constraint( int stride_con, int scale_con, Node *offset, Node *limit, Node *pre_ctrl, Node **pre_limit, Node **main_limit ) {
1126 
1127   // Compute "I :: (limit-offset)/scale_con"
1128   Node *con = new (C, 3) SubINode( limit, offset );
1129   register_new_node( con, pre_ctrl );
1130   Node *scale = _igvn.intcon(scale_con);
1131   set_ctrl(scale, C->root());
1132   Node *X = new (C, 3) DivINode( 0, con, scale );
1133   register_new_node( X, pre_ctrl );
1134 
1135   // For positive stride, the pre-loop limit always uses a MAX function
1136   // and the main loop a MIN function.  For negative stride these are
1137   // reversed.
1138 
1139   // Also for positive stride*scale the affine function is increasing, so the
1140   // pre-loop must check for underflow and the post-loop for overflow.
1141   // Negative stride*scale reverses this; pre-loop checks for overflow and
1142   // post-loop for underflow.
1143   if( stride_con*scale_con > 0 ) {
1144     // Compute I < (limit-offset)/scale_con
1145     // Adjust main-loop last iteration to be MIN/MAX(main_loop,X)
1146     *main_limit = (stride_con > 0)
1147       ? (Node*)(new (C, 3) MinINode( *main_limit, X ))
1148       : (Node*)(new (C, 3) MaxINode( *main_limit, X ));
1149     register_new_node( *main_limit, pre_ctrl );
1150 
1151   } else {
1152     // Compute (limit-offset)/scale_con + SGN(-scale_con) <= I
1153     // Add the negation of the main-loop constraint to the pre-loop.
1154     // See footnote [++] below for a derivation of the limit expression.
1155     Node *incr = _igvn.intcon(scale_con > 0 ? -1 : 1);
1156     set_ctrl(incr, C->root());
1157     Node *adj = new (C, 3) AddINode( X, incr );
1158     register_new_node( adj, pre_ctrl );
1159     *pre_limit = (scale_con > 0)
1160       ? (Node*)new (C, 3) MinINode( *pre_limit, adj )
1161       : (Node*)new (C, 3) MaxINode( *pre_limit, adj );
1162     register_new_node( *pre_limit, pre_ctrl );
1163 
1164 //   [++] Here's the algebra that justifies the pre-loop limit expression:
1165 //
1166 //   NOT( scale_con * I + offset  <  limit )
1167 //      ==
1168 //   scale_con * I + offset  >=  limit
1169 //      ==
1170 //   SGN(scale_con) * I  >=  (limit-offset)/|scale_con|
1171 //      ==
1172 //   (limit-offset)/|scale_con|   <=  I * SGN(scale_con)
1173 //      ==
1174 //   (limit-offset)/|scale_con|-1  <  I * SGN(scale_con)
1175 //      ==
1176 //   ( if (scale_con > 0) /*common case*/
1177 //       (limit-offset)/scale_con - 1  <  I
1178 //     else
1179 //       (limit-offset)/scale_con + 1  >  I
1180 //    )
1181 //   ( if (scale_con > 0) /*common case*/
1182 //       (limit-offset)/scale_con + SGN(-scale_con)  <  I
1183 //     else
1184 //       (limit-offset)/scale_con + SGN(-scale_con)  >  I
1185   }
1186 }
1187 
1188 
1189 //------------------------------is_scaled_iv---------------------------------
1190 // Return true if exp is a constant times an induction var
1191 bool PhaseIdealLoop::is_scaled_iv(Node* exp, Node* iv, int* p_scale) {
1192   if (exp == iv) {
1193     if (p_scale != NULL) {
1194       *p_scale = 1;
1195     }
1196     return true;
1197   }
1198   int opc = exp->Opcode();
1199   if (opc == Op_MulI) {
1200     if (exp->in(1) == iv && exp->in(2)->is_Con()) {
1201       if (p_scale != NULL) {
1202         *p_scale = exp->in(2)->get_int();
1203       }
1204       return true;
1205     }
1206     if (exp->in(2) == iv && exp->in(1)->is_Con()) {
1207       if (p_scale != NULL) {
1208         *p_scale = exp->in(1)->get_int();
1209       }
1210       return true;
1211     }
1212   } else if (opc == Op_LShiftI) {
1213     if (exp->in(1) == iv && exp->in(2)->is_Con()) {
1214       if (p_scale != NULL) {
1215         *p_scale = 1 << exp->in(2)->get_int();
1216       }
1217       return true;
1218     }
1219   }
1220   return false;
1221 }
1222 
1223 //-----------------------------is_scaled_iv_plus_offset------------------------------
1224 // Return true if exp is a simple induction variable expression: k1*iv + (invar + k2)
1225 bool PhaseIdealLoop::is_scaled_iv_plus_offset(Node* exp, Node* iv, int* p_scale, Node** p_offset, int depth) {
1226   if (is_scaled_iv(exp, iv, p_scale)) {
1227     if (p_offset != NULL) {
1228       Node *zero = _igvn.intcon(0);
1229       set_ctrl(zero, C->root());
1230       *p_offset = zero;
1231     }
1232     return true;
1233   }
1234   int opc = exp->Opcode();
1235   if (opc == Op_AddI) {
1236     if (is_scaled_iv(exp->in(1), iv, p_scale)) {
1237       if (p_offset != NULL) {
1238         *p_offset = exp->in(2);
1239       }
1240       return true;
1241     }
1242     if (exp->in(2)->is_Con()) {
1243       Node* offset2 = NULL;
1244       if (depth < 2 &&
1245           is_scaled_iv_plus_offset(exp->in(1), iv, p_scale,
1246                                    p_offset != NULL ? &offset2 : NULL, depth+1)) {
1247         if (p_offset != NULL) {
1248           Node *ctrl_off2 = get_ctrl(offset2);
1249           Node* offset = new (C, 3) AddINode(offset2, exp->in(2));
1250           register_new_node(offset, ctrl_off2);
1251           *p_offset = offset;
1252         }
1253         return true;
1254       }
1255     }
1256   } else if (opc == Op_SubI) {
1257     if (is_scaled_iv(exp->in(1), iv, p_scale)) {
1258       if (p_offset != NULL) {
1259         Node *zero = _igvn.intcon(0);
1260         set_ctrl(zero, C->root());
1261         Node *ctrl_off = get_ctrl(exp->in(2));
1262         Node* offset = new (C, 3) SubINode(zero, exp->in(2));
1263         register_new_node(offset, ctrl_off);
1264         *p_offset = offset;
1265       }
1266       return true;
1267     }
1268     if (is_scaled_iv(exp->in(2), iv, p_scale)) {
1269       if (p_offset != NULL) {
1270         *p_scale *= -1;
1271         *p_offset = exp->in(1);
1272       }
1273       return true;
1274     }
1275   }
1276   return false;
1277 }
1278 
1279 //------------------------------do_range_check---------------------------------
1280 // Eliminate range-checks and other trip-counter vs loop-invariant tests.
1281 void PhaseIdealLoop::do_range_check( IdealLoopTree *loop, Node_List &old_new ) {
1282 #ifndef PRODUCT
1283   if (PrintOpto && VerifyLoopOptimizations) {
1284     tty->print("Range Check Elimination ");
1285     loop->dump_head();
1286   } else if (TraceLoopOpts) {
1287     tty->print("RangeCheck   ");
1288     loop->dump_head();
1289   }
1290 #endif
1291   assert(RangeCheckElimination, "");
1292   CountedLoopNode *cl = loop->_head->as_CountedLoop();
1293   assert(cl->is_main_loop(), "");
1294 
1295   // protect against stride not being a constant
1296   if (!cl->stride_is_con())
1297     return;
1298 
1299   // Find the trip counter; we are iteration splitting based on it
1300   Node *trip_counter = cl->phi();
1301   // Find the main loop limit; we will trim it's iterations
1302   // to not ever trip end tests
1303   Node *main_limit = cl->limit();
1304 
1305   // Need to find the main-loop zero-trip guard
1306   Node *ctrl  = cl->in(LoopNode::EntryControl);
1307   assert(ctrl->Opcode() == Op_IfTrue || ctrl->Opcode() == Op_IfFalse, "");
1308   Node *iffm = ctrl->in(0);
1309   assert(iffm->Opcode() == Op_If, "");
1310   Node *bolzm = iffm->in(1);
1311   assert(bolzm->Opcode() == Op_Bool, "");
1312   Node *cmpzm = bolzm->in(1);
1313   assert(cmpzm->is_Cmp(), "");
1314   Node *opqzm = cmpzm->in(2);
1315   // Can not optimize a loop if pre-loop Opaque1 node is optimized
1316   // away and then another round of loop opts attempted.
1317   if (opqzm->Opcode() != Op_Opaque1)
1318     return;
1319   assert(opqzm->in(1) == main_limit, "do not understand situation");
1320 
1321   // Find the pre-loop limit; we will expand it's iterations to
1322   // not ever trip low tests.
1323   Node *p_f = iffm->in(0);
1324   assert(p_f->Opcode() == Op_IfFalse, "");
1325   CountedLoopEndNode *pre_end = p_f->in(0)->as_CountedLoopEnd();
1326   assert(pre_end->loopnode()->is_pre_loop(), "");
1327   Node *pre_opaq1 = pre_end->limit();
1328   // Occasionally it's possible for a pre-loop Opaque1 node to be
1329   // optimized away and then another round of loop opts attempted.
1330   // We can not optimize this particular loop in that case.
1331   if (pre_opaq1->Opcode() != Op_Opaque1)
1332     return;
1333   Opaque1Node *pre_opaq = (Opaque1Node*)pre_opaq1;
1334   Node *pre_limit = pre_opaq->in(1);
1335 
1336   // Where do we put new limit calculations
1337   Node *pre_ctrl = pre_end->loopnode()->in(LoopNode::EntryControl);
1338 
1339   // Ensure the original loop limit is available from the
1340   // pre-loop Opaque1 node.
1341   Node *orig_limit = pre_opaq->original_loop_limit();
1342   if (orig_limit == NULL || _igvn.type(orig_limit) == Type::TOP)
1343     return;
1344 
1345   // Must know if its a count-up or count-down loop
1346 
1347   int stride_con = cl->stride_con();
1348   Node *zero = _igvn.intcon(0);
1349   Node *one  = _igvn.intcon(1);
1350   set_ctrl(zero, C->root());
1351   set_ctrl(one,  C->root());
1352 
1353   // Range checks that do not dominate the loop backedge (ie.
1354   // conditionally executed) can lengthen the pre loop limit beyond
1355   // the original loop limit. To prevent this, the pre limit is
1356   // (for stride > 0) MINed with the original loop limit (MAXed
1357   // stride < 0) when some range_check (rc) is conditionally
1358   // executed.
1359   bool conditional_rc = false;
1360 
1361   // Check loop body for tests of trip-counter plus loop-invariant vs
1362   // loop-invariant.
1363   for( uint i = 0; i < loop->_body.size(); i++ ) {
1364     Node *iff = loop->_body[i];
1365     if( iff->Opcode() == Op_If ) { // Test?
1366 
1367       // Test is an IfNode, has 2 projections.  If BOTH are in the loop
1368       // we need loop unswitching instead of iteration splitting.
1369       Node *exit = loop->is_loop_exit(iff);
1370       if( !exit ) continue;
1371       int flip = (exit->Opcode() == Op_IfTrue) ? 1 : 0;
1372 
1373       // Get boolean condition to test
1374       Node *i1 = iff->in(1);
1375       if( !i1->is_Bool() ) continue;
1376       BoolNode *bol = i1->as_Bool();
1377       BoolTest b_test = bol->_test;
1378       // Flip sense of test if exit condition is flipped
1379       if( flip )
1380         b_test = b_test.negate();
1381 
1382       // Get compare
1383       Node *cmp = bol->in(1);
1384 
1385       // Look for trip_counter + offset vs limit
1386       Node *rc_exp = cmp->in(1);
1387       Node *limit  = cmp->in(2);
1388       jint scale_con= 1;        // Assume trip counter not scaled
1389 
1390       Node *limit_c = get_ctrl(limit);
1391       if( loop->is_member(get_loop(limit_c) ) ) {
1392         // Compare might have operands swapped; commute them
1393         b_test = b_test.commute();
1394         rc_exp = cmp->in(2);
1395         limit  = cmp->in(1);
1396         limit_c = get_ctrl(limit);
1397         if( loop->is_member(get_loop(limit_c) ) )
1398           continue;             // Both inputs are loop varying; cannot RCE
1399       }
1400       // Here we know 'limit' is loop invariant
1401 
1402       // 'limit' maybe pinned below the zero trip test (probably from a
1403       // previous round of rce), in which case, it can't be used in the
1404       // zero trip test expression which must occur before the zero test's if.
1405       if( limit_c == ctrl ) {
1406         continue;  // Don't rce this check but continue looking for other candidates.
1407       }
1408 
1409       // Check for scaled induction variable plus an offset
1410       Node *offset = NULL;
1411 
1412       if (!is_scaled_iv_plus_offset(rc_exp, trip_counter, &scale_con, &offset)) {
1413         continue;
1414       }
1415 
1416       Node *offset_c = get_ctrl(offset);
1417       if( loop->is_member( get_loop(offset_c) ) )
1418         continue;               // Offset is not really loop invariant
1419       // Here we know 'offset' is loop invariant.
1420 
1421       // As above for the 'limit', the 'offset' maybe pinned below the
1422       // zero trip test.
1423       if( offset_c == ctrl ) {
1424         continue; // Don't rce this check but continue looking for other candidates.
1425       }
1426 
1427       // At this point we have the expression as:
1428       //   scale_con * trip_counter + offset :: limit
1429       // where scale_con, offset and limit are loop invariant.  Trip_counter
1430       // monotonically increases by stride_con, a constant.  Both (or either)
1431       // stride_con and scale_con can be negative which will flip about the
1432       // sense of the test.
1433 
1434       // Adjust pre and main loop limits to guard the correct iteration set
1435       if( cmp->Opcode() == Op_CmpU ) {// Unsigned compare is really 2 tests
1436         if( b_test._test == BoolTest::lt ) { // Range checks always use lt
1437           // The overflow limit: scale*I+offset < limit
1438           add_constraint( stride_con, scale_con, offset, limit, pre_ctrl, &pre_limit, &main_limit );
1439           // The underflow limit: 0 <= scale*I+offset.
1440           // Some math yields: -scale*I-(offset+1) < 0
1441           Node *plus_one = new (C, 3) AddINode( offset, one );
1442           register_new_node( plus_one, pre_ctrl );
1443           Node *neg_offset = new (C, 3) SubINode( zero, plus_one );
1444           register_new_node( neg_offset, pre_ctrl );
1445           add_constraint( stride_con, -scale_con, neg_offset, zero, pre_ctrl, &pre_limit, &main_limit );
1446           if (!conditional_rc) {
1447             conditional_rc = !loop->dominates_backedge(iff);
1448           }
1449         } else {
1450 #ifndef PRODUCT
1451           if( PrintOpto )
1452             tty->print_cr("missed RCE opportunity");
1453 #endif
1454           continue;             // In release mode, ignore it
1455         }
1456       } else {                  // Otherwise work on normal compares
1457         switch( b_test._test ) {
1458         case BoolTest::ge:      // Convert X >= Y to -X <= -Y
1459           scale_con = -scale_con;
1460           offset = new (C, 3) SubINode( zero, offset );
1461           register_new_node( offset, pre_ctrl );
1462           limit  = new (C, 3) SubINode( zero, limit  );
1463           register_new_node( limit, pre_ctrl );
1464           // Fall into LE case
1465         case BoolTest::le:      // Convert X <= Y to X < Y+1
1466           limit = new (C, 3) AddINode( limit, one );
1467           register_new_node( limit, pre_ctrl );
1468           // Fall into LT case
1469         case BoolTest::lt:
1470           add_constraint( stride_con, scale_con, offset, limit, pre_ctrl, &pre_limit, &main_limit );
1471           if (!conditional_rc) {
1472             conditional_rc = !loop->dominates_backedge(iff);
1473           }
1474           break;
1475         default:
1476 #ifndef PRODUCT
1477           if( PrintOpto )
1478             tty->print_cr("missed RCE opportunity");
1479 #endif
1480           continue;             // Unhandled case
1481         }
1482       }
1483 
1484       // Kill the eliminated test
1485       C->set_major_progress();
1486       Node *kill_con = _igvn.intcon( 1-flip );
1487       set_ctrl(kill_con, C->root());
1488       _igvn.hash_delete(iff);
1489       iff->set_req(1, kill_con);
1490       _igvn._worklist.push(iff);
1491       // Find surviving projection
1492       assert(iff->is_If(), "");
1493       ProjNode* dp = ((IfNode*)iff)->proj_out(1-flip);
1494       // Find loads off the surviving projection; remove their control edge
1495       for (DUIterator_Fast imax, i = dp->fast_outs(imax); i < imax; i++) {
1496         Node* cd = dp->fast_out(i); // Control-dependent node
1497         if( cd->is_Load() ) {   // Loads can now float around in the loop
1498           _igvn.hash_delete(cd);
1499           // Allow the load to float around in the loop, or before it
1500           // but NOT before the pre-loop.
1501           cd->set_req(0, ctrl);   // ctrl, not NULL
1502           _igvn._worklist.push(cd);
1503           --i;
1504           --imax;
1505         }
1506       }
1507 
1508     } // End of is IF
1509 
1510   }
1511 
1512   // Update loop limits
1513   if (conditional_rc) {
1514     pre_limit = (stride_con > 0) ? (Node*)new (C,3) MinINode(pre_limit, orig_limit)
1515                                  : (Node*)new (C,3) MaxINode(pre_limit, orig_limit);
1516     register_new_node(pre_limit, pre_ctrl);
1517   }
1518   _igvn.hash_delete(pre_opaq);
1519   pre_opaq->set_req(1, pre_limit);
1520 
1521   // Note:: we are making the main loop limit no longer precise;
1522   // need to round up based on stride.
1523   if( stride_con != 1 && stride_con != -1 ) { // Cutout for common case
1524     // "Standard" round-up logic:  ([main_limit-init+(y-1)]/y)*y+init
1525     // Hopefully, compiler will optimize for powers of 2.
1526     Node *ctrl = get_ctrl(main_limit);
1527     Node *stride = cl->stride();
1528     Node *init = cl->init_trip();
1529     Node *span = new (C, 3) SubINode(main_limit,init);
1530     register_new_node(span,ctrl);
1531     Node *rndup = _igvn.intcon(stride_con + ((stride_con>0)?-1:1));
1532     Node *add = new (C, 3) AddINode(span,rndup);
1533     register_new_node(add,ctrl);
1534     Node *div = new (C, 3) DivINode(0,add,stride);
1535     register_new_node(div,ctrl);
1536     Node *mul = new (C, 3) MulINode(div,stride);
1537     register_new_node(mul,ctrl);
1538     Node *newlim = new (C, 3) AddINode(mul,init);
1539     register_new_node(newlim,ctrl);
1540     main_limit = newlim;
1541   }
1542 
1543   Node *main_cle = cl->loopexit();
1544   Node *main_bol = main_cle->in(1);
1545   // Hacking loop bounds; need private copies of exit test
1546   if( main_bol->outcnt() > 1 ) {// BoolNode shared?
1547     _igvn.hash_delete(main_cle);
1548     main_bol = main_bol->clone();// Clone a private BoolNode
1549     register_new_node( main_bol, main_cle->in(0) );
1550     main_cle->set_req(1,main_bol);
1551   }
1552   Node *main_cmp = main_bol->in(1);
1553   if( main_cmp->outcnt() > 1 ) { // CmpNode shared?
1554     _igvn.hash_delete(main_bol);
1555     main_cmp = main_cmp->clone();// Clone a private CmpNode
1556     register_new_node( main_cmp, main_cle->in(0) );
1557     main_bol->set_req(1,main_cmp);
1558   }
1559   // Hack the now-private loop bounds
1560   _igvn.hash_delete(main_cmp);
1561   main_cmp->set_req(2, main_limit);
1562   _igvn._worklist.push(main_cmp);
1563   // The OpaqueNode is unshared by design
1564   _igvn.hash_delete(opqzm);
1565   assert( opqzm->outcnt() == 1, "cannot hack shared node" );
1566   opqzm->set_req(1,main_limit);
1567   _igvn._worklist.push(opqzm);
1568 }
1569 
1570 //------------------------------DCE_loop_body----------------------------------
1571 // Remove simplistic dead code from loop body
1572 void IdealLoopTree::DCE_loop_body() {
1573   for( uint i = 0; i < _body.size(); i++ )
1574     if( _body.at(i)->outcnt() == 0 )
1575       _body.map( i--, _body.pop() );
1576 }
1577 
1578 
1579 //------------------------------adjust_loop_exit_prob--------------------------
1580 // Look for loop-exit tests with the 50/50 (or worse) guesses from the parsing stage.
1581 // Replace with a 1-in-10 exit guess.
1582 void IdealLoopTree::adjust_loop_exit_prob( PhaseIdealLoop *phase ) {
1583   Node *test = tail();
1584   while( test != _head ) {
1585     uint top = test->Opcode();
1586     if( top == Op_IfTrue || top == Op_IfFalse ) {
1587       int test_con = ((ProjNode*)test)->_con;
1588       assert(top == (uint)(test_con? Op_IfTrue: Op_IfFalse), "sanity");
1589       IfNode *iff = test->in(0)->as_If();
1590       if( iff->outcnt() == 2 ) {        // Ignore dead tests
1591         Node *bol = iff->in(1);
1592         if( bol && bol->req() > 1 && bol->in(1) &&
1593             ((bol->in(1)->Opcode() == Op_StorePConditional ) ||
1594              (bol->in(1)->Opcode() == Op_StoreIConditional ) ||
1595              (bol->in(1)->Opcode() == Op_StoreLConditional ) ||
1596              (bol->in(1)->Opcode() == Op_CompareAndSwapI ) ||
1597              (bol->in(1)->Opcode() == Op_CompareAndSwapL ) ||
1598              (bol->in(1)->Opcode() == Op_CompareAndSwapP ) ||
1599              (bol->in(1)->Opcode() == Op_CompareAndSwapN )))
1600           return;               // Allocation loops RARELY take backedge
1601         // Find the OTHER exit path from the IF
1602         Node* ex = iff->proj_out(1-test_con);
1603         float p = iff->_prob;
1604         if( !phase->is_member( this, ex ) && iff->_fcnt == COUNT_UNKNOWN ) {
1605           if( top == Op_IfTrue ) {
1606             if( p < (PROB_FAIR + PROB_UNLIKELY_MAG(3))) {
1607               iff->_prob = PROB_STATIC_FREQUENT;
1608             }
1609           } else {
1610             if( p > (PROB_FAIR - PROB_UNLIKELY_MAG(3))) {
1611               iff->_prob = PROB_STATIC_INFREQUENT;
1612             }
1613           }
1614         }
1615       }
1616     }
1617     test = phase->idom(test);
1618   }
1619 }
1620 
1621 
1622 //------------------------------policy_do_remove_empty_loop--------------------
1623 // Micro-benchmark spamming.  Policy is to always remove empty loops.
1624 // The 'DO' part is to replace the trip counter with the value it will
1625 // have on the last iteration.  This will break the loop.
1626 bool IdealLoopTree::policy_do_remove_empty_loop( PhaseIdealLoop *phase ) {
1627   // Minimum size must be empty loop
1628   if (_body.size() > 7/*number of nodes in an empty loop*/)
1629     return false;
1630 
1631   if (!_head->is_CountedLoop())
1632     return false;     // Dead loop
1633   CountedLoopNode *cl = _head->as_CountedLoop();
1634   if (!cl->loopexit())
1635     return false; // Malformed loop
1636   if (!phase->is_member(this, phase->get_ctrl(cl->loopexit()->in(CountedLoopEndNode::TestValue))))
1637     return false;             // Infinite loop
1638 
1639 #ifdef ASSERT
1640   // Ensure only one phi which is the iv.
1641   Node* iv = NULL;
1642   for (DUIterator_Fast imax, i = cl->fast_outs(imax); i < imax; i++) {
1643     Node* n = cl->fast_out(i);
1644     if (n->Opcode() == Op_Phi) {
1645       assert(iv == NULL, "Too many phis" );
1646       iv = n;
1647     }
1648   }
1649   assert(iv == cl->phi(), "Wrong phi" );
1650 #endif
1651 
1652   // main and post loops have explicitly created zero trip guard
1653   bool needs_guard = !cl->is_main_loop() && !cl->is_post_loop();
1654   if (needs_guard) {
1655     // Check for an obvious zero trip guard.
1656     Node* inctrl = cl->in(LoopNode::EntryControl);
1657     if (inctrl->Opcode() == Op_IfTrue) {
1658       // The test should look like just the backedge of a CountedLoop
1659       Node* iff = inctrl->in(0);
1660       if (iff->is_If()) {
1661         Node* bol = iff->in(1);
1662         if (bol->is_Bool() && bol->as_Bool()->_test._test == cl->loopexit()->test_trip()) {
1663           Node* cmp = bol->in(1);
1664           if (cmp->is_Cmp() && cmp->in(1) == cl->init_trip() && cmp->in(2) == cl->limit()) {
1665             needs_guard = false;
1666           }
1667         }
1668       }
1669     }
1670   }
1671 
1672 #ifndef PRODUCT
1673   if (PrintOpto) {
1674     tty->print("Removing empty loop with%s zero trip guard", needs_guard ? "out" : "");
1675     this->dump_head();
1676   } else if (TraceLoopOpts) {
1677     tty->print("Empty with%s zero trip guard   ", needs_guard ? "out" : "");
1678     this->dump_head();
1679   }
1680 #endif
1681 
1682   if (needs_guard) {
1683     // Peel the loop to ensure there's a zero trip guard
1684     Node_List old_new;
1685     phase->do_peeling(this, old_new);
1686   }
1687 
1688   // Replace the phi at loop head with the final value of the last
1689   // iteration.  Then the CountedLoopEnd will collapse (backedge never
1690   // taken) and all loop-invariant uses of the exit values will be correct.
1691   Node *phi = cl->phi();
1692   Node *final = new (phase->C, 3) SubINode( cl->limit(), cl->stride() );
1693   phase->register_new_node(final,cl->in(LoopNode::EntryControl));
1694   phase->_igvn.replace_node(phi,final);
1695   phase->C->set_major_progress();
1696   return true;
1697 }
1698 
1699 
1700 //=============================================================================
1701 //------------------------------iteration_split_impl---------------------------
1702 bool IdealLoopTree::iteration_split_impl( PhaseIdealLoop *phase, Node_List &old_new ) {
1703   // Check and remove empty loops (spam micro-benchmarks)
1704   if( policy_do_remove_empty_loop(phase) )
1705     return true;  // Here we removed an empty loop
1706 
1707   bool should_peel = policy_peeling(phase); // Should we peel?
1708 
1709   bool should_unswitch = policy_unswitching(phase);
1710 
1711   // Non-counted loops may be peeled; exactly 1 iteration is peeled.
1712   // This removes loop-invariant tests (usually null checks).
1713   if( !_head->is_CountedLoop() ) { // Non-counted loop
1714     if (PartialPeelLoop && phase->partial_peel(this, old_new)) {
1715       // Partial peel succeeded so terminate this round of loop opts
1716       return false;
1717     }
1718     if( should_peel ) {            // Should we peel?
1719 #ifndef PRODUCT
1720       if (PrintOpto) tty->print_cr("should_peel");
1721 #endif
1722       phase->do_peeling(this,old_new);
1723     } else if( should_unswitch ) {
1724       phase->do_unswitching(this, old_new);
1725     }
1726     return true;
1727   }
1728   CountedLoopNode *cl = _head->as_CountedLoop();
1729 
1730   if( !cl->loopexit() ) return true; // Ignore various kinds of broken loops
1731 
1732   // Do nothing special to pre- and post- loops
1733   if( cl->is_pre_loop() || cl->is_post_loop() ) return true;
1734 
1735   // Compute loop trip count from profile data
1736   compute_profile_trip_cnt(phase);
1737 
1738   // Before attempting fancy unrolling, RCE or alignment, see if we want
1739   // to completely unroll this loop or do loop unswitching.
1740   if( cl->is_normal_loop() ) {
1741     if (should_unswitch) {
1742       phase->do_unswitching(this, old_new);
1743       return true;
1744     }
1745     bool should_maximally_unroll =  policy_maximally_unroll(phase);
1746     if( should_maximally_unroll ) {
1747       // Here we did some unrolling and peeling.  Eventually we will
1748       // completely unroll this loop and it will no longer be a loop.
1749       phase->do_maximally_unroll(this,old_new);
1750       return true;
1751     }
1752   }
1753 
1754 
1755   // Counted loops may be peeled, may need some iterations run up
1756   // front for RCE, and may want to align loop refs to a cache
1757   // line.  Thus we clone a full loop up front whose trip count is
1758   // at least 1 (if peeling), but may be several more.
1759 
1760   // The main loop will start cache-line aligned with at least 1
1761   // iteration of the unrolled body (zero-trip test required) and
1762   // will have some range checks removed.
1763 
1764   // A post-loop will finish any odd iterations (leftover after
1765   // unrolling), plus any needed for RCE purposes.
1766 
1767   bool should_unroll = policy_unroll(phase);
1768 
1769   bool should_rce = policy_range_check(phase);
1770 
1771   bool should_align = policy_align(phase);
1772 
1773   // If not RCE'ing (iteration splitting) or Aligning, then we do not
1774   // need a pre-loop.  We may still need to peel an initial iteration but
1775   // we will not be needing an unknown number of pre-iterations.
1776   //
1777   // Basically, if may_rce_align reports FALSE first time through,
1778   // we will not be able to later do RCE or Aligning on this loop.
1779   bool may_rce_align = !policy_peel_only(phase) || should_rce || should_align;
1780 
1781   // If we have any of these conditions (RCE, alignment, unrolling) met, then
1782   // we switch to the pre-/main-/post-loop model.  This model also covers
1783   // peeling.
1784   if( should_rce || should_align || should_unroll ) {
1785     if( cl->is_normal_loop() )  // Convert to 'pre/main/post' loops
1786       phase->insert_pre_post_loops(this,old_new, !may_rce_align);
1787 
1788     // Adjust the pre- and main-loop limits to let the pre and post loops run
1789     // with full checks, but the main-loop with no checks.  Remove said
1790     // checks from the main body.
1791     if( should_rce )
1792       phase->do_range_check(this,old_new);
1793 
1794     // Double loop body for unrolling.  Adjust the minimum-trip test (will do
1795     // twice as many iterations as before) and the main body limit (only do
1796     // an even number of trips).  If we are peeling, we might enable some RCE
1797     // and we'd rather unroll the post-RCE'd loop SO... do not unroll if
1798     // peeling.
1799       if( should_unroll && !should_peel )
1800         phase->do_unroll(this,old_new, true);
1801 
1802     // Adjust the pre-loop limits to align the main body
1803     // iterations.
1804     if( should_align )
1805       Unimplemented();
1806 
1807   } else {                      // Else we have an unchanged counted loop
1808     if( should_peel )           // Might want to peel but do nothing else
1809       phase->do_peeling(this,old_new);
1810   }
1811   return true;
1812 }
1813 
1814 
1815 //=============================================================================
1816 //------------------------------iteration_split--------------------------------
1817 bool IdealLoopTree::iteration_split( PhaseIdealLoop *phase, Node_List &old_new ) {
1818   // Recursively iteration split nested loops
1819   if (_child && !_child->iteration_split(phase, old_new))
1820     return false;
1821 
1822   // Clean out prior deadwood
1823   DCE_loop_body();
1824 
1825 
1826   // Look for loop-exit tests with my 50/50 guesses from the Parsing stage.
1827   // Replace with a 1-in-10 exit guess.
1828   if (_parent /*not the root loop*/ &&
1829       !_irreducible &&
1830       // Also ignore the occasional dead backedge
1831       !tail()->is_top()) {
1832     adjust_loop_exit_prob(phase);
1833   }
1834 
1835   // Gate unrolling, RCE and peeling efforts.
1836   if (!_child &&                // If not an inner loop, do not split
1837       !_irreducible &&
1838       _allow_optimizations &&
1839       !tail()->is_top()) {     // Also ignore the occasional dead backedge
1840     if (!_has_call) {
1841         if (!iteration_split_impl(phase, old_new)) {
1842           return false;
1843         }
1844     } else if (policy_unswitching(phase)) {
1845       phase->do_unswitching(this, old_new);
1846     }
1847   }
1848 
1849   // Minor offset re-organization to remove loop-fallout uses of
1850   // trip counter when there was no major reshaping.
1851   phase->reorg_offsets(this);
1852 
1853   if (_next && !_next->iteration_split(phase, old_new))
1854     return false;
1855   return true;
1856 }
1857 
1858 //-------------------------------is_uncommon_trap_proj----------------------------
1859 // Return true if proj is the form of "proj->[region->..]call_uct"
1860 bool PhaseIdealLoop::is_uncommon_trap_proj(ProjNode* proj, Deoptimization::DeoptReason reason) {
1861   int path_limit = 10;
1862   assert(proj, "invalid argument");
1863   Node* out = proj;
1864   for (int ct = 0; ct < path_limit; ct++) {
1865     out = out->unique_ctrl_out();
1866     if (out == NULL || out->is_Root() || out->is_Start())
1867       return false;
1868     if (out->is_CallStaticJava()) {
1869       int req = out->as_CallStaticJava()->uncommon_trap_request();
1870       if (req != 0) {
1871         Deoptimization::DeoptReason trap_reason = Deoptimization::trap_request_reason(req);
1872         if (trap_reason == reason || reason == Deoptimization::Reason_none) {
1873            return true;
1874         }
1875       }
1876       return false; // don't do further after call
1877     }
1878   }
1879   return false;
1880 }
1881 
1882 //-------------------------------is_uncommon_trap_if_pattern-------------------------
1883 // Return true  for "if(test)-> proj -> ...
1884 //                          |
1885 //                          V
1886 //                      other_proj->[region->..]call_uct"
1887 //
1888 // "must_reason_predicate" means the uct reason must be Reason_predicate
1889 bool PhaseIdealLoop::is_uncommon_trap_if_pattern(ProjNode *proj, Deoptimization::DeoptReason reason) {
1890   Node *in0 = proj->in(0);
1891   if (!in0->is_If()) return false;
1892   // Variation of a dead If node.
1893   if (in0->outcnt() < 2)  return false;
1894   IfNode* iff = in0->as_If();
1895 
1896   // we need "If(Conv2B(Opaque1(...)))" pattern for reason_predicate
1897   if (reason != Deoptimization::Reason_none) {
1898     if (iff->in(1)->Opcode() != Op_Conv2B ||
1899        iff->in(1)->in(1)->Opcode() != Op_Opaque1) {
1900       return false;
1901     }
1902   }
1903 
1904   ProjNode* other_proj = iff->proj_out(1-proj->_con)->as_Proj();
1905   return is_uncommon_trap_proj(other_proj, reason);
1906 }
1907 
1908 //-------------------------------register_control-------------------------
1909 void PhaseIdealLoop::register_control(Node* n, IdealLoopTree *loop, Node* pred) {
1910   assert(n->is_CFG(), "must be control node");
1911   _igvn.register_new_node_with_optimizer(n);
1912   loop->_body.push(n);
1913   set_loop(n, loop);
1914   // When called from beautify_loops() idom is not constructed yet.
1915   if (_idom != NULL) {
1916     set_idom(n, pred, dom_depth(pred));
1917   }
1918 }
1919 
1920 //------------------------------create_new_if_for_predicate------------------------
1921 // create a new if above the uct_if_pattern for the predicate to be promoted.
1922 //
1923 //          before                                after
1924 //        ----------                           ----------
1925 //           ctrl                                 ctrl
1926 //            |                                     |
1927 //            |                                     |
1928 //            v                                     v
1929 //           iff                                 new_iff
1930 //          /    \                                /      \
1931 //         /      \                              /        \
1932 //        v        v                            v          v
1933 //  uncommon_proj cont_proj                   if_uct     if_cont
1934 // \      |        |                           |          |
1935 //  \     |        |                           |          |
1936 //   v    v        v                           |          v
1937 //     rgn       loop                          |         iff
1938 //      |                                      |        /     \
1939 //      |                                      |       /       \
1940 //      v                                      |      v         v
1941 // uncommon_trap                               | uncommon_proj cont_proj
1942 //                                           \  \    |           |
1943 //                                            \  \   |           |
1944 //                                             v  v  v           v
1945 //                                               rgn           loop
1946 //                                                |
1947 //                                                |
1948 //                                                v
1949 //                                           uncommon_trap
1950 //
1951 //
1952 // We will create a region to guard the uct call if there is no one there.
1953 // The true projecttion (if_cont) of the new_iff is returned.
1954 // This code is also used to clone predicates to clonned loops.
1955 ProjNode* PhaseIdealLoop::create_new_if_for_predicate(ProjNode* cont_proj, Node* new_entry,
1956                                                       Deoptimization::DeoptReason reason) {
1957   assert(is_uncommon_trap_if_pattern(cont_proj, reason), "must be a uct if pattern!");
1958   IfNode* iff = cont_proj->in(0)->as_If();
1959 
1960   ProjNode *uncommon_proj = iff->proj_out(1 - cont_proj->_con);
1961   Node     *rgn   = uncommon_proj->unique_ctrl_out();
1962   assert(rgn->is_Region() || rgn->is_Call(), "must be a region or call uct");
1963 
1964   if (!rgn->is_Region()) { // create a region to guard the call
1965     assert(rgn->is_Call(), "must be call uct");
1966     CallNode* call = rgn->as_Call();
1967     IdealLoopTree* loop = get_loop(call);
1968     rgn = new (C, 1) RegionNode(1);
1969     rgn->add_req(uncommon_proj);
1970     register_control(rgn, loop, uncommon_proj);
1971     _igvn.hash_delete(call);
1972     call->set_req(0, rgn);
1973     // When called from beautify_loops() idom is not constructed yet.
1974     if (_idom != NULL) {
1975       set_idom(call, rgn, dom_depth(rgn));
1976     }
1977   }
1978 
1979   Node* entry = iff->in(0);
1980   if (new_entry != NULL) {
1981     // Clonning the predicate to new location.
1982     entry = new_entry;
1983   }
1984   // Create new_iff
1985   IdealLoopTree* lp = get_loop(entry);
1986   IfNode *new_iff = new (C, 2) IfNode(entry, NULL, iff->_prob, iff->_fcnt);
1987   register_control(new_iff, lp, entry);
1988   Node *if_cont = new (C, 1) IfTrueNode(new_iff);
1989   Node *if_uct  = new (C, 1) IfFalseNode(new_iff);
1990   if (cont_proj->is_IfFalse()) {
1991     // Swap
1992     Node* tmp = if_uct; if_uct = if_cont; if_cont = tmp;
1993   }
1994   register_control(if_cont, lp, new_iff);
1995   register_control(if_uct, get_loop(rgn), new_iff);
1996 
1997   // if_uct to rgn
1998   _igvn.hash_delete(rgn);
1999   rgn->add_req(if_uct);
2000   // When called from beautify_loops() idom is not constructed yet.
2001   if (_idom != NULL) {
2002     Node* ridom = idom(rgn);
2003     Node* nrdom = dom_lca(ridom, new_iff);
2004     set_idom(rgn, nrdom, dom_depth(rgn));
2005   }
2006   // rgn must have no phis
2007   assert(!rgn->as_Region()->has_phi(), "region must have no phis");
2008 
2009   if (new_entry == NULL) {
2010     // Attach if_cont to iff
2011     _igvn.hash_delete(iff);
2012     iff->set_req(0, if_cont);
2013     if (_idom != NULL) {
2014       set_idom(iff, if_cont, dom_depth(iff));
2015     }
2016   }
2017   return if_cont->as_Proj();
2018 }
2019 
2020 //--------------------------find_predicate_insertion_point-------------------
2021 // Find a good location to insert a predicate
2022 ProjNode* PhaseIdealLoop::find_predicate_insertion_point(Node* start_c, Deoptimization::DeoptReason reason) {
2023   if (start_c == NULL || !start_c->is_Proj())
2024     return NULL;
2025   if (is_uncommon_trap_if_pattern(start_c->as_Proj(), reason)) {
2026     return start_c->as_Proj();
2027   }
2028   return NULL;
2029 }
2030 
2031 //--------------------------find_predicate------------------------------------
2032 // Find a predicate
2033 Node* PhaseIdealLoop::find_predicate(Node* entry) {
2034   Node* predicate = NULL;
2035   if (UseLoopPredicate) {
2036     predicate = find_predicate_insertion_point(entry, Deoptimization::Reason_predicate);
2037     if (predicate != NULL) { // right pattern that can be used by loop predication
2038       assert(entry->in(0)->in(1)->in(1)->Opcode()==Op_Opaque1, "must be");
2039       return entry;
2040     }
2041   }
2042   return NULL;
2043 }
2044 
2045 //------------------------------Invariance-----------------------------------
2046 // Helper class for loop_predication_impl to compute invariance on the fly and
2047 // clone invariants.
2048 class Invariance : public StackObj {
2049   VectorSet _visited, _invariant;
2050   Node_Stack _stack;
2051   VectorSet _clone_visited;
2052   Node_List _old_new; // map of old to new (clone)
2053   IdealLoopTree* _lpt;
2054   PhaseIdealLoop* _phase;
2055 
2056   // Helper function to set up the invariance for invariance computation
2057   // If n is a known invariant, set up directly. Otherwise, look up the
2058   // the possibility to push n onto the stack for further processing.
2059   void visit(Node* use, Node* n) {
2060     if (_lpt->is_invariant(n)) { // known invariant
2061       _invariant.set(n->_idx);
2062     } else if (!n->is_CFG()) {
2063       Node *n_ctrl = _phase->ctrl_or_self(n);
2064       Node *u_ctrl = _phase->ctrl_or_self(use); // self if use is a CFG
2065       if (_phase->is_dominator(n_ctrl, u_ctrl)) {
2066         _stack.push(n, n->in(0) == NULL ? 1 : 0);
2067       }
2068     }
2069   }
2070 
2071   // Compute invariance for "the_node" and (possibly) all its inputs recursively
2072   // on the fly
2073   void compute_invariance(Node* n) {
2074     assert(_visited.test(n->_idx), "must be");
2075     visit(n, n);
2076     while (_stack.is_nonempty()) {
2077       Node*  n = _stack.node();
2078       uint idx = _stack.index();
2079       if (idx == n->req()) { // all inputs are processed
2080         _stack.pop();
2081         // n is invariant if it's inputs are all invariant
2082         bool all_inputs_invariant = true;
2083         for (uint i = 0; i < n->req(); i++) {
2084           Node* in = n->in(i);
2085           if (in == NULL) continue;
2086           assert(_visited.test(in->_idx), "must have visited input");
2087           if (!_invariant.test(in->_idx)) { // bad guy
2088             all_inputs_invariant = false;
2089             break;
2090           }
2091         }
2092         if (all_inputs_invariant) {
2093           _invariant.set(n->_idx); // I am a invariant too
2094         }
2095       } else { // process next input
2096         _stack.set_index(idx + 1);
2097         Node* m = n->in(idx);
2098         if (m != NULL && !_visited.test_set(m->_idx)) {
2099           visit(n, m);
2100         }
2101       }
2102     }
2103   }
2104 
2105   // Helper function to set up _old_new map for clone_nodes.
2106   // If n is a known invariant, set up directly ("clone" of n == n).
2107   // Otherwise, push n onto the stack for real cloning.
2108   void clone_visit(Node* n) {
2109     assert(_invariant.test(n->_idx), "must be invariant");
2110     if (_lpt->is_invariant(n)) { // known invariant
2111       _old_new.map(n->_idx, n);
2112     } else{ // to be cloned
2113       assert (!n->is_CFG(), "should not see CFG here");
2114       _stack.push(n, n->in(0) == NULL ? 1 : 0);
2115     }
2116   }
2117 
2118   // Clone "n" and (possibly) all its inputs recursively
2119   void clone_nodes(Node* n, Node* ctrl) {
2120     clone_visit(n);
2121     while (_stack.is_nonempty()) {
2122       Node*  n = _stack.node();
2123       uint idx = _stack.index();
2124       if (idx == n->req()) { // all inputs processed, clone n!
2125         _stack.pop();
2126         // clone invariant node
2127         Node* n_cl = n->clone();
2128         _old_new.map(n->_idx, n_cl);
2129         _phase->register_new_node(n_cl, ctrl);
2130         for (uint i = 0; i < n->req(); i++) {
2131           Node* in = n_cl->in(i);
2132           if (in == NULL) continue;
2133           n_cl->set_req(i, _old_new[in->_idx]);
2134         }
2135       } else { // process next input
2136         _stack.set_index(idx + 1);
2137         Node* m = n->in(idx);
2138         if (m != NULL && !_clone_visited.test_set(m->_idx)) {
2139           clone_visit(m); // visit the input
2140         }
2141       }
2142     }
2143   }
2144 
2145  public:
2146   Invariance(Arena* area, IdealLoopTree* lpt) :
2147     _lpt(lpt), _phase(lpt->_phase),
2148     _visited(area), _invariant(area), _stack(area, 10 /* guess */),
2149     _clone_visited(area), _old_new(area)
2150   {}
2151 
2152   // Map old to n for invariance computation and clone
2153   void map_ctrl(Node* old, Node* n) {
2154     assert(old->is_CFG() && n->is_CFG(), "must be");
2155     _old_new.map(old->_idx, n); // "clone" of old is n
2156     _invariant.set(old->_idx);  // old is invariant
2157     _clone_visited.set(old->_idx);
2158   }
2159 
2160   // Driver function to compute invariance
2161   bool is_invariant(Node* n) {
2162     if (!_visited.test_set(n->_idx))
2163       compute_invariance(n);
2164     return (_invariant.test(n->_idx) != 0);
2165   }
2166 
2167   // Driver function to clone invariant
2168   Node* clone(Node* n, Node* ctrl) {
2169     assert(ctrl->is_CFG(), "must be");
2170     assert(_invariant.test(n->_idx), "must be an invariant");
2171     if (!_clone_visited.test(n->_idx))
2172       clone_nodes(n, ctrl);
2173     return _old_new[n->_idx];
2174   }
2175 };
2176 
2177 //------------------------------is_range_check_if -----------------------------------
2178 // Returns true if the predicate of iff is in "scale*iv + offset u< load_range(ptr)" format
2179 // Note: this function is particularly designed for loop predication. We require load_range
2180 //       and offset to be loop invariant computed on the fly by "invar"
2181 bool IdealLoopTree::is_range_check_if(IfNode *iff, PhaseIdealLoop *phase, Invariance& invar) const {
2182   if (!is_loop_exit(iff)) {
2183     return false;
2184   }
2185   if (!iff->in(1)->is_Bool()) {
2186     return false;
2187   }
2188   const BoolNode *bol = iff->in(1)->as_Bool();
2189   if (bol->_test._test != BoolTest::lt) {
2190     return false;
2191   }
2192   if (!bol->in(1)->is_Cmp()) {
2193     return false;
2194   }
2195   const CmpNode *cmp = bol->in(1)->as_Cmp();
2196   if (cmp->Opcode() != Op_CmpU ) {
2197     return false;
2198   }
2199   Node* range = cmp->in(2);
2200   if (range->Opcode() != Op_LoadRange) {
2201     const TypeInt* tint = phase->_igvn.type(range)->isa_int();
2202     if (!OptimizeFill || tint == NULL || tint->empty() || tint->_lo < 0) {
2203       // Allow predication on positive values that aren't LoadRanges.
2204       // This allows optimization of loops where the length of the
2205       // array is a known value and doesn't need to be loaded back
2206       // from the array.
2207       return false;
2208     }
2209   }
2210   if (!invar.is_invariant(range)) {
2211     return false;
2212   }
2213   Node *iv     = _head->as_CountedLoop()->phi();
2214   int   scale  = 0;
2215   Node *offset = NULL;
2216   if (!phase->is_scaled_iv_plus_offset(cmp->in(1), iv, &scale, &offset)) {
2217     return false;
2218   }
2219   if(offset && !invar.is_invariant(offset)) { // offset must be invariant
2220     return false;
2221   }
2222   return true;
2223 }
2224 
2225 //------------------------------rc_predicate-----------------------------------
2226 // Create a range check predicate
2227 //
2228 // for (i = init; i < limit; i += stride) {
2229 //    a[scale*i+offset]
2230 // }
2231 //
2232 // Compute max(scale*i + offset) for init <= i < limit and build the predicate
2233 // as "max(scale*i + offset) u< a.length".
2234 //
2235 // There are two cases for max(scale*i + offset):
2236 // (1) stride*scale > 0
2237 //   max(scale*i + offset) = scale*(limit-stride) + offset
2238 // (2) stride*scale < 0
2239 //   max(scale*i + offset) = scale*init + offset
2240 BoolNode* PhaseIdealLoop::rc_predicate(Node* ctrl,
2241                                        int scale, Node* offset,
2242                                        Node* init, Node* limit, Node* stride,
2243                                        Node* range, bool upper) {
2244   DEBUG_ONLY(ttyLocker ttyl);
2245   if (TraceLoopPredicate) tty->print("rc_predicate ");
2246 
2247   Node* max_idx_expr  = init;
2248   int stride_con = stride->get_int();
2249   if ((stride_con > 0) == (scale > 0) == upper) {
2250     max_idx_expr = new (C, 3) SubINode(limit, stride);
2251     register_new_node(max_idx_expr, ctrl);
2252     if (TraceLoopPredicate) tty->print("(limit - stride) ");
2253   } else {
2254     if (TraceLoopPredicate) tty->print("init ");
2255   }
2256 
2257   if (scale != 1) {
2258     ConNode* con_scale = _igvn.intcon(scale);
2259     max_idx_expr = new (C, 3) MulINode(max_idx_expr, con_scale);
2260     register_new_node(max_idx_expr, ctrl);
2261     if (TraceLoopPredicate) tty->print("* %d ", scale);
2262   }
2263 
2264   if (offset && (!offset->is_Con() || offset->get_int() != 0)){
2265     max_idx_expr = new (C, 3) AddINode(max_idx_expr, offset);
2266     register_new_node(max_idx_expr, ctrl);
2267     if (TraceLoopPredicate)
2268       if (offset->is_Con()) tty->print("+ %d ", offset->get_int());
2269       else tty->print("+ offset ");
2270   }
2271 
2272   CmpUNode* cmp = new (C, 3) CmpUNode(max_idx_expr, range);
2273   register_new_node(cmp, ctrl);
2274   BoolNode* bol = new (C, 2) BoolNode(cmp, BoolTest::lt);
2275   register_new_node(bol, ctrl);
2276 
2277   if (TraceLoopPredicate) tty->print_cr("<u range");
2278   return bol;
2279 }
2280 
2281 //------------------------------ loop_predication_impl--------------------------
2282 // Insert loop predicates for null checks and range checks
2283 bool PhaseIdealLoop::loop_predication_impl(IdealLoopTree *loop) {
2284   if (!UseLoopPredicate) return false;
2285 
2286   if (!loop->_head->is_Loop()) {
2287     // Could be a simple region when irreducible loops are present.
2288     return false;
2289   }
2290 
2291   if (loop->_head->unique_ctrl_out()->Opcode() == Op_NeverBranch) {
2292     // do nothing for infinite loops
2293     return false;
2294   }
2295 
2296   CountedLoopNode *cl = NULL;
2297   if (loop->_head->is_CountedLoop()) {
2298     cl = loop->_head->as_CountedLoop();
2299     // do nothing for iteration-splitted loops
2300     if (!cl->is_normal_loop()) return false;
2301   }
2302 
2303   LoopNode *lpn  = loop->_head->as_Loop();
2304   Node* entry = lpn->in(LoopNode::EntryControl);
2305 
2306   ProjNode *predicate_proj = find_predicate_insertion_point(entry, Deoptimization::Reason_predicate);
2307   if (!predicate_proj) {
2308 #ifndef PRODUCT
2309     if (TraceLoopPredicate) {
2310       tty->print("missing predicate:");
2311       loop->dump_head();
2312       lpn->dump(1);
2313     }
2314 #endif
2315     return false;
2316   }
2317   ConNode* zero = _igvn.intcon(0);
2318   set_ctrl(zero, C->root());
2319 
2320   ResourceArea *area = Thread::current()->resource_area();
2321   Invariance invar(area, loop);
2322 
2323   // Create list of if-projs such that a newer proj dominates all older
2324   // projs in the list, and they all dominate loop->tail()
2325   Node_List if_proj_list(area);
2326   LoopNode *head  = loop->_head->as_Loop();
2327   Node *current_proj = loop->tail(); //start from tail
2328   while ( current_proj != head ) {
2329     if (loop == get_loop(current_proj) && // still in the loop ?
2330         current_proj->is_Proj()        && // is a projection  ?
2331         current_proj->in(0)->Opcode() == Op_If) { // is a if projection ?
2332       if_proj_list.push(current_proj);
2333     }
2334     current_proj = idom(current_proj);
2335   }
2336 
2337   bool hoisted = false; // true if at least one proj is promoted
2338   while (if_proj_list.size() > 0) {
2339     // Following are changed to nonnull when a predicate can be hoisted
2340     ProjNode* new_predicate_proj = NULL;
2341 
2342     ProjNode* proj = if_proj_list.pop()->as_Proj();
2343     IfNode*   iff  = proj->in(0)->as_If();
2344 
2345     if (!is_uncommon_trap_if_pattern(proj, Deoptimization::Reason_none)) {
2346       if (loop->is_loop_exit(iff)) {
2347         // stop processing the remaining projs in the list because the execution of them
2348         // depends on the condition of "iff" (iff->in(1)).
2349         break;
2350       } else {
2351         // Both arms are inside the loop. There are two cases:
2352         // (1) there is one backward branch. In this case, any remaining proj
2353         //     in the if_proj list post-dominates "iff". So, the condition of "iff"
2354         //     does not determine the execution the remining projs directly, and we
2355         //     can safely continue.
2356         // (2) both arms are forwarded, i.e. a diamond shape. In this case, "proj"
2357         //     does not dominate loop->tail(), so it can not be in the if_proj list.
2358         continue;
2359       }
2360     }
2361 
2362     Node*     test = iff->in(1);
2363     if (!test->is_Bool()){ //Conv2B, ...
2364       continue;
2365     }
2366     BoolNode* bol = test->as_Bool();
2367     if (invar.is_invariant(bol)) {
2368       // Invariant test
2369       new_predicate_proj = create_new_if_for_predicate(predicate_proj, NULL,
2370                                                        Deoptimization::Reason_predicate);
2371       Node* ctrl = new_predicate_proj->in(0)->as_If()->in(0);
2372       BoolNode* new_predicate_bol = invar.clone(bol, ctrl)->as_Bool();
2373 
2374       // Negate test if necessary
2375       bool negated = false;
2376       if (proj->_con != predicate_proj->_con) {
2377         new_predicate_bol = new (C, 2) BoolNode(new_predicate_bol->in(1), new_predicate_bol->_test.negate());
2378         register_new_node(new_predicate_bol, ctrl);
2379         negated = true;
2380       }
2381       IfNode* new_predicate_iff = new_predicate_proj->in(0)->as_If();
2382       _igvn.hash_delete(new_predicate_iff);
2383       new_predicate_iff->set_req(1, new_predicate_bol);
2384 #ifndef PRODUCT
2385       if (TraceLoopPredicate) {
2386         tty->print("Predicate invariant if%s: %d ", negated ? " negated" : "", new_predicate_iff->_idx);
2387         loop->dump_head();
2388       } else if (TraceLoopOpts) {
2389         tty->print("Predicate IC ");
2390         loop->dump_head();
2391       }
2392 #endif
2393     } else if (cl != NULL && loop->is_range_check_if(iff, this, invar)) {
2394       assert(proj->_con == predicate_proj->_con, "must match");
2395 
2396       // Range check for counted loops
2397       const Node*    cmp    = bol->in(1)->as_Cmp();
2398       Node*          idx    = cmp->in(1);
2399       assert(!invar.is_invariant(idx), "index is variant");
2400       assert(cmp->in(2)->Opcode() == Op_LoadRange || OptimizeFill, "must be");
2401       Node* rng = cmp->in(2);
2402       assert(invar.is_invariant(rng), "range must be invariant");
2403       int scale    = 1;
2404       Node* offset = zero;
2405       bool ok = is_scaled_iv_plus_offset(idx, cl->phi(), &scale, &offset);
2406       assert(ok, "must be index expression");
2407 
2408       Node* init    = cl->init_trip();
2409       Node* limit   = cl->limit();
2410       Node* stride  = cl->stride();
2411 
2412       // Build if's for the upper and lower bound tests.  The
2413       // lower_bound test will dominate the upper bound test and all
2414       // cloned or created nodes will use the lower bound test as
2415       // their declared control.
2416       ProjNode* lower_bound_proj = create_new_if_for_predicate(predicate_proj, NULL, Deoptimization::Reason_predicate);
2417       ProjNode* upper_bound_proj = create_new_if_for_predicate(predicate_proj, NULL, Deoptimization::Reason_predicate);
2418       assert(upper_bound_proj->in(0)->as_If()->in(0) == lower_bound_proj, "should dominate");
2419       Node *ctrl = lower_bound_proj->in(0)->as_If()->in(0);
2420 
2421       // Perform cloning to keep Invariance state correct since the
2422       // late schedule will place invariant things in the loop.
2423       rng = invar.clone(rng, ctrl);
2424       if (offset && offset != zero) {
2425         assert(invar.is_invariant(offset), "offset must be loop invariant");
2426         offset = invar.clone(offset, ctrl);
2427       }
2428 
2429       // Test the lower bound
2430       Node*  lower_bound_bol = rc_predicate(ctrl, scale, offset, init, limit, stride, rng, false);
2431       IfNode* lower_bound_iff = lower_bound_proj->in(0)->as_If();
2432       _igvn.hash_delete(lower_bound_iff);
2433       lower_bound_iff->set_req(1, lower_bound_bol);
2434       if (TraceLoopPredicate) tty->print_cr("lower bound check if: %d", lower_bound_iff->_idx);
2435 
2436       // Test the upper bound
2437       Node* upper_bound_bol = rc_predicate(ctrl, scale, offset, init, limit, stride, rng, true);
2438       IfNode* upper_bound_iff = upper_bound_proj->in(0)->as_If();
2439       _igvn.hash_delete(upper_bound_iff);
2440       upper_bound_iff->set_req(1, upper_bound_bol);
2441       if (TraceLoopPredicate) tty->print_cr("upper bound check if: %d", lower_bound_iff->_idx);
2442 
2443       // Fall through into rest of the clean up code which will move
2444       // any dependent nodes onto the upper bound test.
2445       new_predicate_proj = upper_bound_proj;
2446 
2447 #ifndef PRODUCT
2448       if (TraceLoopOpts && !TraceLoopPredicate) {
2449         tty->print("Predicate RC ");
2450         loop->dump_head();
2451       }
2452 #endif
2453     } else {
2454       // Loop variant check (for example, range check in non-counted loop)
2455       // with uncommon trap.
2456       continue;
2457     }
2458     assert(new_predicate_proj != NULL, "sanity");
2459     // Success - attach condition (new_predicate_bol) to predicate if
2460     invar.map_ctrl(proj, new_predicate_proj); // so that invariance test can be appropriate
2461 
2462     // Eliminate the old If in the loop body
2463     dominated_by( new_predicate_proj, iff, proj->_con != new_predicate_proj->_con );
2464 
2465     hoisted = true;
2466     C->set_major_progress();
2467   } // end while
2468 
2469 #ifndef PRODUCT
2470   // report that the loop predication has been actually performed
2471   // for this loop
2472   if (TraceLoopPredicate && hoisted) {
2473     tty->print("Loop Predication Performed:");
2474     loop->dump_head();
2475   }
2476 #endif
2477 
2478   return hoisted;
2479 }
2480 
2481 //------------------------------loop_predication--------------------------------
2482 // driver routine for loop predication optimization
2483 bool IdealLoopTree::loop_predication( PhaseIdealLoop *phase) {
2484   bool hoisted = false;
2485   // Recursively promote predicates
2486   if ( _child ) {
2487     hoisted = _child->loop_predication( phase);
2488   }
2489 
2490   // self
2491   if (!_irreducible && !tail()->is_top()) {
2492     hoisted |= phase->loop_predication_impl(this);
2493   }
2494 
2495   if ( _next ) { //sibling
2496     hoisted |= _next->loop_predication( phase);
2497   }
2498 
2499   return hoisted;
2500 }
2501 
2502 
2503 // Process all the loops in the loop tree and replace any fill
2504 // patterns with an intrisc version.
2505 bool PhaseIdealLoop::do_intrinsify_fill() {
2506   bool changed = false;
2507   for (LoopTreeIterator iter(_ltree_root); !iter.done(); iter.next()) {
2508     IdealLoopTree* lpt = iter.current();
2509     changed |= intrinsify_fill(lpt);
2510   }
2511   return changed;
2512 }
2513 
2514 
2515 // Examine an inner loop looking for a a single store of an invariant
2516 // value in a unit stride loop,
2517 bool PhaseIdealLoop::match_fill_loop(IdealLoopTree* lpt, Node*& store, Node*& store_value,
2518                                      Node*& shift, Node*& con) {
2519   const char* msg = NULL;
2520   Node* msg_node = NULL;
2521 
2522   store_value = NULL;
2523   con = NULL;
2524   shift = NULL;
2525 
2526   // Process the loop looking for stores.  If there are multiple
2527   // stores or extra control flow give at this point.
2528   CountedLoopNode* head = lpt->_head->as_CountedLoop();
2529   for (uint i = 0; msg == NULL && i < lpt->_body.size(); i++) {
2530     Node* n = lpt->_body.at(i);
2531     if (n->outcnt() == 0) continue; // Ignore dead
2532     if (n->is_Store()) {
2533       if (store != NULL) {
2534         msg = "multiple stores";
2535         break;
2536       }
2537       int opc = n->Opcode();
2538       if (opc == Op_StoreP || opc == Op_StoreN || opc == Op_StoreCM) {
2539         msg = "oop fills not handled";
2540         break;
2541       }
2542       Node* value = n->in(MemNode::ValueIn);
2543       if (!lpt->is_invariant(value)) {
2544         msg  = "variant store value";
2545       } else if (!_igvn.type(n->in(MemNode::Address))->isa_aryptr()) {
2546         msg = "not array address";
2547       }
2548       store = n;
2549       store_value = value;
2550     } else if (n->is_If() && n != head->loopexit()) {
2551       msg = "extra control flow";
2552       msg_node = n;
2553     }
2554   }
2555 
2556   if (store == NULL) {
2557     // No store in loop
2558     return false;
2559   }
2560 
2561   if (msg == NULL && head->stride_con() != 1) {
2562     // could handle negative strides too
2563     if (head->stride_con() < 0) {
2564       msg = "negative stride";
2565     } else {
2566       msg = "non-unit stride";
2567     }
2568   }
2569 
2570   if (msg == NULL && !store->in(MemNode::Address)->is_AddP()) {
2571     msg = "can't handle store address";
2572     msg_node = store->in(MemNode::Address);
2573   }
2574 
2575   if (msg == NULL &&
2576       (!store->in(MemNode::Memory)->is_Phi() ||
2577        store->in(MemNode::Memory)->in(LoopNode::LoopBackControl) != store)) {
2578     msg = "store memory isn't proper phi";
2579     msg_node = store->in(MemNode::Memory);
2580   }
2581 
2582   // Make sure there is an appropriate fill routine
2583   BasicType t = store->as_Mem()->memory_type();
2584   const char* fill_name;
2585   if (msg == NULL &&
2586       StubRoutines::select_fill_function(t, false, fill_name) == NULL) {
2587     msg = "unsupported store";
2588     msg_node = store;
2589   }
2590 
2591   if (msg != NULL) {
2592 #ifndef PRODUCT
2593     if (TraceOptimizeFill) {
2594       tty->print_cr("not fill intrinsic candidate: %s", msg);
2595       if (msg_node != NULL) msg_node->dump();
2596     }
2597 #endif
2598     return false;
2599   }
2600 
2601   // Make sure the address expression can be handled.  It should be
2602   // head->phi * elsize + con.  head->phi might have a ConvI2L.
2603   Node* elements[4];
2604   Node* conv = NULL;
2605   bool found_index = false;
2606   int count = store->in(MemNode::Address)->as_AddP()->unpack_offsets(elements, ARRAY_SIZE(elements));
2607   for (int e = 0; e < count; e++) {
2608     Node* n = elements[e];
2609     if (n->is_Con() && con == NULL) {
2610       con = n;
2611     } else if (n->Opcode() == Op_LShiftX && shift == NULL) {
2612       Node* value = n->in(1);
2613 #ifdef _LP64
2614       if (value->Opcode() == Op_ConvI2L) {
2615         conv = value;
2616         value = value->in(1);
2617       }
2618 #endif
2619       if (value != head->phi()) {
2620         msg = "unhandled shift in address";
2621       } else {
2622         found_index = true;
2623         shift = n;
2624         assert(type2aelembytes(store->as_Mem()->memory_type(), true) == 1 << shift->in(2)->get_int(), "scale should match");
2625       }
2626     } else if (n->Opcode() == Op_ConvI2L && conv == NULL) {
2627       if (n->in(1) == head->phi()) {
2628         found_index = true;
2629         conv = n;
2630       } else {
2631         msg = "unhandled input to ConvI2L";
2632       }
2633     } else if (n == head->phi()) {
2634       // no shift, check below for allowed cases
2635       found_index = true;
2636     } else {
2637       msg = "unhandled node in address";
2638       msg_node = n;
2639     }
2640   }
2641 
2642   if (count == -1) {
2643     msg = "malformed address expression";
2644     msg_node = store;
2645   }
2646 
2647   if (!found_index) {
2648     msg = "missing use of index";
2649   }
2650 
2651   // byte sized items won't have a shift
2652   if (msg == NULL && shift == NULL && t != T_BYTE && t != T_BOOLEAN) {
2653     msg = "can't find shift";
2654     msg_node = store;
2655   }
2656 
2657   if (msg != NULL) {
2658 #ifndef PRODUCT
2659     if (TraceOptimizeFill) {
2660       tty->print_cr("not fill intrinsic: %s", msg);
2661       if (msg_node != NULL) msg_node->dump();
2662     }
2663 #endif
2664     return false;
2665   }
2666 
2667   // No make sure all the other nodes in the loop can be handled
2668   VectorSet ok(Thread::current()->resource_area());
2669 
2670   // store related values are ok
2671   ok.set(store->_idx);
2672   ok.set(store->in(MemNode::Memory)->_idx);
2673 
2674   // Loop structure is ok
2675   ok.set(head->_idx);
2676   ok.set(head->loopexit()->_idx);
2677   ok.set(head->phi()->_idx);
2678   ok.set(head->incr()->_idx);
2679   ok.set(head->loopexit()->cmp_node()->_idx);
2680   ok.set(head->loopexit()->in(1)->_idx);
2681 
2682   // Address elements are ok
2683   if (con)   ok.set(con->_idx);
2684   if (shift) ok.set(shift->_idx);
2685   if (conv)  ok.set(conv->_idx);
2686 
2687   for (uint i = 0; msg == NULL && i < lpt->_body.size(); i++) {
2688     Node* n = lpt->_body.at(i);
2689     if (n->outcnt() == 0) continue; // Ignore dead
2690     if (ok.test(n->_idx)) continue;
2691     // Backedge projection is ok
2692     if (n->is_IfTrue() && n->in(0) == head->loopexit()) continue;
2693     if (!n->is_AddP()) {
2694       msg = "unhandled node";
2695       msg_node = n;
2696       break;
2697     }
2698   }
2699 
2700   // Make sure no unexpected values are used outside the loop
2701   for (uint i = 0; msg == NULL && i < lpt->_body.size(); i++) {
2702     Node* n = lpt->_body.at(i);
2703     // These values can be replaced with other nodes if they are used
2704     // outside the loop.
2705     if (n == store || n == head->loopexit() || n == head->incr() || n == store->in(MemNode::Memory)) continue;
2706     for (SimpleDUIterator iter(n); iter.has_next(); iter.next()) {
2707       Node* use = iter.get();
2708       if (!lpt->_body.contains(use)) {
2709         msg = "node is used outside loop";
2710         // lpt->_body.dump();
2711         msg_node = n;
2712         break;
2713       }
2714     }
2715   }
2716 
2717 #ifdef ASSERT
2718   if (TraceOptimizeFill) {
2719     if (msg != NULL) {
2720       tty->print_cr("no fill intrinsic: %s", msg);
2721       if (msg_node != NULL) msg_node->dump();
2722     } else {
2723       tty->print_cr("fill intrinsic for:");
2724     }
2725     store->dump();
2726     if (Verbose) {
2727       lpt->_body.dump();
2728     }
2729   }
2730 #endif
2731 
2732   return msg == NULL;
2733 }
2734 
2735 
2736 
2737 bool PhaseIdealLoop::intrinsify_fill(IdealLoopTree* lpt) {
2738   // Only for counted inner loops
2739   if (!lpt->is_counted() || !lpt->is_inner()) {
2740     return false;
2741   }
2742 
2743   // Must have constant stride
2744   CountedLoopNode* head = lpt->_head->as_CountedLoop();
2745   if (!head->stride_is_con() || !head->is_normal_loop()) {
2746     return false;
2747   }
2748 
2749   // Check that the body only contains a store of a loop invariant
2750   // value that is indexed by the loop phi.
2751   Node* store = NULL;
2752   Node* store_value = NULL;
2753   Node* shift = NULL;
2754   Node* offset = NULL;
2755   if (!match_fill_loop(lpt, store, store_value, shift, offset)) {
2756     return false;
2757   }
2758 
2759   // Now replace the whole loop body by a call to a fill routine that
2760   // covers the same region as the loop.
2761   Node* base = store->in(MemNode::Address)->as_AddP()->in(AddPNode::Base);
2762 
2763   // Build an expression for the beginning of the copy region
2764   Node* index = head->init_trip();
2765 #ifdef _LP64
2766   index = new (C, 2) ConvI2LNode(index);
2767   _igvn.register_new_node_with_optimizer(index);
2768 #endif
2769   if (shift != NULL) {
2770     // byte arrays don't require a shift but others do.
2771     index = new (C, 3) LShiftXNode(index, shift->in(2));
2772     _igvn.register_new_node_with_optimizer(index);
2773   }
2774   index = new (C, 4) AddPNode(base, base, index);
2775   _igvn.register_new_node_with_optimizer(index);
2776   Node* from = new (C, 4) AddPNode(base, index, offset);
2777   _igvn.register_new_node_with_optimizer(from);
2778   // Compute the number of elements to copy
2779   Node* len = new (C, 3) SubINode(head->limit(), head->init_trip());
2780   _igvn.register_new_node_with_optimizer(len);
2781 
2782   BasicType t = store->as_Mem()->memory_type();
2783   bool aligned = false;
2784   if (offset != NULL && head->init_trip()->is_Con()) {
2785     int element_size = type2aelembytes(t);
2786     aligned = (offset->find_intptr_t_type()->get_con() + head->init_trip()->get_int() * element_size) % HeapWordSize == 0;
2787   }
2788 
2789   // Build a call to the fill routine
2790   const char* fill_name;
2791   address fill = StubRoutines::select_fill_function(t, aligned, fill_name);
2792   assert(fill != NULL, "what?");
2793 
2794   // Convert float/double to int/long for fill routines
2795   if (t == T_FLOAT) {
2796     store_value = new (C, 2) MoveF2INode(store_value);
2797     _igvn.register_new_node_with_optimizer(store_value);
2798   } else if (t == T_DOUBLE) {
2799     store_value = new (C, 2) MoveD2LNode(store_value);
2800     _igvn.register_new_node_with_optimizer(store_value);
2801   }
2802 
2803   Node* mem_phi = store->in(MemNode::Memory);
2804   Node* result_ctrl;
2805   Node* result_mem;
2806   const TypeFunc* call_type = OptoRuntime::array_fill_Type();
2807   int size = call_type->domain()->cnt();
2808   CallLeafNode *call = new (C, size) CallLeafNoFPNode(call_type, fill,
2809                                                       fill_name, TypeAryPtr::get_array_body_type(t));
2810   call->init_req(TypeFunc::Parms+0, from);
2811   call->init_req(TypeFunc::Parms+1, store_value);
2812 #ifdef _LP64
2813   len = new (C, 2) ConvI2LNode(len);
2814   _igvn.register_new_node_with_optimizer(len);
2815 #endif
2816   call->init_req(TypeFunc::Parms+2, len);
2817 #ifdef _LP64
2818   call->init_req(TypeFunc::Parms+3, C->top());
2819 #endif
2820   call->init_req( TypeFunc::Control, head->init_control());
2821   call->init_req( TypeFunc::I_O    , C->top() )        ;   // does no i/o
2822   call->init_req( TypeFunc::Memory ,  mem_phi->in(LoopNode::EntryControl) );
2823   call->init_req( TypeFunc::ReturnAdr, C->start()->proj_out(TypeFunc::ReturnAdr) );
2824   call->init_req( TypeFunc::FramePtr, C->start()->proj_out(TypeFunc::FramePtr) );
2825   _igvn.register_new_node_with_optimizer(call);
2826   result_ctrl = new (C, 1) ProjNode(call,TypeFunc::Control);
2827   _igvn.register_new_node_with_optimizer(result_ctrl);
2828   result_mem = new (C, 1) ProjNode(call,TypeFunc::Memory);
2829   _igvn.register_new_node_with_optimizer(result_mem);
2830 
2831   // If this fill is tightly coupled to an allocation and overwrites
2832   // the whole body, allow it to take over the zeroing.
2833   AllocateNode* alloc = AllocateNode::Ideal_allocation(base, this);
2834   if (alloc != NULL && alloc->is_AllocateArray()) {
2835     Node* length = alloc->as_AllocateArray()->Ideal_length();
2836     if (head->limit() == length &&
2837         head->init_trip() == _igvn.intcon(0)) {
2838       if (TraceOptimizeFill) {
2839         tty->print_cr("Eliminated zeroing in allocation");
2840       }
2841       alloc->maybe_set_complete(&_igvn);
2842     } else {
2843 #ifdef ASSERT
2844       if (TraceOptimizeFill) {
2845         tty->print_cr("filling array but bounds don't match");
2846         alloc->dump();
2847         head->init_trip()->dump();
2848         head->limit()->dump();
2849         length->dump();
2850       }
2851 #endif
2852     }
2853   }
2854 
2855   // Redirect the old control and memory edges that are outside the loop.
2856   Node* exit = head->loopexit()->proj_out(0);
2857   // Sometimes the memory phi of the head is used as the outgoing
2858   // state of the loop.  It's safe in this case to replace it with the
2859   // result_mem.
2860   _igvn.replace_node(store->in(MemNode::Memory), result_mem);
2861   _igvn.replace_node(exit, result_ctrl);
2862   _igvn.replace_node(store, result_mem);
2863   // Any uses the increment outside of the loop become the loop limit.
2864   _igvn.replace_node(head->incr(), head->limit());
2865 
2866   // Disconnect the head from the loop.
2867   for (uint i = 0; i < lpt->_body.size(); i++) {
2868     Node* n = lpt->_body.at(i);
2869     _igvn.replace_node(n, C->top());
2870   }
2871 
2872   return true;
2873 }